1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.9.2.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25/************** Begin file sqliteInt.h ***************************************/
26/*
27** 2001 September 15
28**
29** The author disclaims copyright to this source code.  In place of
30** a legal notice, here is a blessing:
31**
32**    May you do good and not evil.
33**    May you find forgiveness for yourself and forgive others.
34**    May you share freely, never taking more than you give.
35**
36*************************************************************************
37** Internal interface definitions for SQLite.
38**
39*/
40#ifndef _SQLITEINT_H_
41#define _SQLITEINT_H_
42
43/*
44** Include the header file used to customize the compiler options for MSVC.
45** This should be done first so that it can successfully prevent spurious
46** compiler warnings due to subsequent content in this file and other files
47** that are included by this file.
48*/
49/************** Include msvc.h in the middle of sqliteInt.h ******************/
50/************** Begin file msvc.h ********************************************/
51/*
52** 2015 January 12
53**
54** The author disclaims copyright to this source code.  In place of
55** a legal notice, here is a blessing:
56**
57**    May you do good and not evil.
58**    May you find forgiveness for yourself and forgive others.
59**    May you share freely, never taking more than you give.
60**
61******************************************************************************
62**
63** This file contains code that is specific to MSVC.
64*/
65#ifndef _MSVC_H_
66#define _MSVC_H_
67
68#if defined(_MSC_VER)
69#pragma warning(disable : 4054)
70#pragma warning(disable : 4055)
71#pragma warning(disable : 4100)
72#pragma warning(disable : 4127)
73#pragma warning(disable : 4130)
74#pragma warning(disable : 4152)
75#pragma warning(disable : 4189)
76#pragma warning(disable : 4206)
77#pragma warning(disable : 4210)
78#pragma warning(disable : 4232)
79#pragma warning(disable : 4244)
80#pragma warning(disable : 4305)
81#pragma warning(disable : 4306)
82#pragma warning(disable : 4702)
83#pragma warning(disable : 4706)
84#endif /* defined(_MSC_VER) */
85
86#endif /* _MSVC_H_ */
87
88/************** End of msvc.h ************************************************/
89/************** Continuing where we left off in sqliteInt.h ******************/
90
91/*
92** Special setup for VxWorks
93*/
94/************** Include vxworks.h in the middle of sqliteInt.h ***************/
95/************** Begin file vxworks.h *****************************************/
96/*
97** 2015-03-02
98**
99** The author disclaims copyright to this source code.  In place of
100** a legal notice, here is a blessing:
101**
102**    May you do good and not evil.
103**    May you find forgiveness for yourself and forgive others.
104**    May you share freely, never taking more than you give.
105**
106******************************************************************************
107**
108** This file contains code that is specific to Wind River's VxWorks
109*/
110#if defined(__RTP__) || defined(_WRS_KERNEL)
111/* This is VxWorks.  Set up things specially for that OS
112*/
113#include <vxWorks.h>
114#include <pthread.h>  /* amalgamator: dontcache */
115#define OS_VXWORKS 1
116#define SQLITE_OS_OTHER 0
117#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
118#define SQLITE_OMIT_LOAD_EXTENSION 1
119#define SQLITE_ENABLE_LOCKING_STYLE 0
120#define HAVE_UTIME 1
121#else
122/* This is not VxWorks. */
123#define OS_VXWORKS 0
124#endif /* defined(_WRS_KERNEL) */
125
126/************** End of vxworks.h *********************************************/
127/************** Continuing where we left off in sqliteInt.h ******************/
128
129/*
130** These #defines should enable >2GB file support on POSIX if the
131** underlying operating system supports it.  If the OS lacks
132** large file support, or if the OS is windows, these should be no-ops.
133**
134** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
135** system #includes.  Hence, this block of code must be the very first
136** code in all source files.
137**
138** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
139** on the compiler command line.  This is necessary if you are compiling
140** on a recent machine (ex: Red Hat 7.2) but you want your code to work
141** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
142** without this option, LFS is enable.  But LFS does not exist in the kernel
143** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
144** portability you should omit LFS.
145**
146** The previous paragraph was written in 2005.  (This paragraph is written
147** on 2008-11-28.) These days, all Linux kernels support large files, so
148** you should probably leave LFS enabled.  But some embedded platforms might
149** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
150**
151** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
152*/
153#ifndef SQLITE_DISABLE_LFS
154# define _LARGE_FILE       1
155# ifndef _FILE_OFFSET_BITS
156#   define _FILE_OFFSET_BITS 64
157# endif
158# define _LARGEFILE_SOURCE 1
159#endif
160
161/* What version of GCC is being used.  0 means GCC is not being used */
162#ifdef __GNUC__
163# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
164#else
165# define GCC_VERSION 0
166#endif
167
168/* Needed for various definitions... */
169#if defined(__GNUC__) && !defined(_GNU_SOURCE)
170# define _GNU_SOURCE
171#endif
172
173#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
174# define _BSD_SOURCE
175#endif
176
177/*
178** For MinGW, check to see if we can include the header file containing its
179** version information, among other things.  Normally, this internal MinGW
180** header file would [only] be included automatically by other MinGW header
181** files; however, the contained version information is now required by this
182** header file to work around binary compatibility issues (see below) and
183** this is the only known way to reliably obtain it.  This entire #if block
184** would be completely unnecessary if there was any other way of detecting
185** MinGW via their preprocessor (e.g. if they customized their GCC to define
186** some MinGW-specific macros).  When compiling for MinGW, either the
187** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
188** defined; otherwise, detection of conditions specific to MinGW will be
189** disabled.
190*/
191#if defined(_HAVE_MINGW_H)
192# include "mingw.h"
193#elif defined(_HAVE__MINGW_H)
194# include "_mingw.h"
195#endif
196
197/*
198** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
199** define is required to maintain binary compatibility with the MSVC runtime
200** library in use (e.g. for Windows XP).
201*/
202#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
203    defined(_WIN32) && !defined(_WIN64) && \
204    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
205    defined(__MSVCRT__)
206# define _USE_32BIT_TIME_T
207#endif
208
209/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
210** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
211** MinGW.
212*/
213/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
214/************** Begin file sqlite3.h *****************************************/
215/*
216** 2001 September 15
217**
218** The author disclaims copyright to this source code.  In place of
219** a legal notice, here is a blessing:
220**
221**    May you do good and not evil.
222**    May you find forgiveness for yourself and forgive others.
223**    May you share freely, never taking more than you give.
224**
225*************************************************************************
226** This header file defines the interface that the SQLite library
227** presents to client programs.  If a C-function, structure, datatype,
228** or constant definition does not appear in this file, then it is
229** not a published API of SQLite, is subject to change without
230** notice, and should not be referenced by programs that use SQLite.
231**
232** Some of the definitions that are in this file are marked as
233** "experimental".  Experimental interfaces are normally new
234** features recently added to SQLite.  We do not anticipate changes
235** to experimental interfaces but reserve the right to make minor changes
236** if experience from use "in the wild" suggest such changes are prudent.
237**
238** The official C-language API documentation for SQLite is derived
239** from comments in this file.  This file is the authoritative source
240** on how SQLite interfaces are supposed to operate.
241**
242** The name of this file under configuration management is "sqlite.h.in".
243** The makefile makes some minor changes to this file (such as inserting
244** the version number) and changes its name to "sqlite3.h" as
245** part of the build process.
246*/
247#ifndef _SQLITE3_H_
248#define _SQLITE3_H_
249#include <stdarg.h>     /* Needed for the definition of va_list */
250
251/*
252** Make sure we can call this stuff from C++.
253*/
254#if 0
255extern "C" {
256#endif
257
258
259/*
260** Provide the ability to override linkage features of the interface.
261*/
262#ifndef SQLITE_EXTERN
263# define SQLITE_EXTERN extern
264#endif
265#ifndef SQLITE_API
266# define SQLITE_API
267#endif
268#ifndef SQLITE_CDECL
269# define SQLITE_CDECL
270#endif
271#ifndef SQLITE_STDCALL
272# define SQLITE_STDCALL
273#endif
274
275/*
276** These no-op macros are used in front of interfaces to mark those
277** interfaces as either deprecated or experimental.  New applications
278** should not use deprecated interfaces - they are supported for backwards
279** compatibility only.  Application writers should be aware that
280** experimental interfaces are subject to change in point releases.
281**
282** These macros used to resolve to various kinds of compiler magic that
283** would generate warning messages when they were used.  But that
284** compiler magic ended up generating such a flurry of bug reports
285** that we have taken it all out and gone back to using simple
286** noop macros.
287*/
288#define SQLITE_DEPRECATED
289#define SQLITE_EXPERIMENTAL
290
291/*
292** Ensure these symbols were not defined by some previous header file.
293*/
294#ifdef SQLITE_VERSION
295# undef SQLITE_VERSION
296#endif
297#ifdef SQLITE_VERSION_NUMBER
298# undef SQLITE_VERSION_NUMBER
299#endif
300
301/*
302** CAPI3REF: Compile-Time Library Version Numbers
303**
304** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
305** evaluates to a string literal that is the SQLite version in the
306** format "X.Y.Z" where X is the major version number (always 3 for
307** SQLite3) and Y is the minor version number and Z is the release number.)^
308** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
309** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
310** numbers used in [SQLITE_VERSION].)^
311** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
312** be larger than the release from which it is derived.  Either Y will
313** be held constant and Z will be incremented or else Y will be incremented
314** and Z will be reset to zero.
315**
316** Since version 3.6.18, SQLite source code has been stored in the
317** <a href="http://www.fossil-scm.org/">Fossil configuration management
318** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
319** a string which identifies a particular check-in of SQLite
320** within its configuration management system.  ^The SQLITE_SOURCE_ID
321** string contains the date and time of the check-in (UTC) and an SHA1
322** hash of the entire source tree.
323**
324** See also: [sqlite3_libversion()],
325** [sqlite3_libversion_number()], [sqlite3_sourceid()],
326** [sqlite_version()] and [sqlite_source_id()].
327*/
328#define SQLITE_VERSION        "3.9.2"
329#define SQLITE_VERSION_NUMBER 3009002
330#define SQLITE_SOURCE_ID      "2015-11-02 18:31:45 bda77dda9697c463c3d0704014d51627fceee328"
331
332/*
333** CAPI3REF: Run-Time Library Version Numbers
334** KEYWORDS: sqlite3_version, sqlite3_sourceid
335**
336** These interfaces provide the same information as the [SQLITE_VERSION],
337** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
338** but are associated with the library instead of the header file.  ^(Cautious
339** programmers might include assert() statements in their application to
340** verify that values returned by these interfaces match the macros in
341** the header, and thus ensure that the application is
342** compiled with matching library and header files.
343**
344** <blockquote><pre>
345** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
346** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
347** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
348** </pre></blockquote>)^
349**
350** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
351** macro.  ^The sqlite3_libversion() function returns a pointer to the
352** to the sqlite3_version[] string constant.  The sqlite3_libversion()
353** function is provided for use in DLLs since DLL users usually do not have
354** direct access to string constants within the DLL.  ^The
355** sqlite3_libversion_number() function returns an integer equal to
356** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
357** a pointer to a string constant whose value is the same as the
358** [SQLITE_SOURCE_ID] C preprocessor macro.
359**
360** See also: [sqlite_version()] and [sqlite_source_id()].
361*/
362SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
363SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
364SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
365SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
366
367/*
368** CAPI3REF: Run-Time Library Compilation Options Diagnostics
369**
370** ^The sqlite3_compileoption_used() function returns 0 or 1
371** indicating whether the specified option was defined at
372** compile time.  ^The SQLITE_ prefix may be omitted from the
373** option name passed to sqlite3_compileoption_used().
374**
375** ^The sqlite3_compileoption_get() function allows iterating
376** over the list of options that were defined at compile time by
377** returning the N-th compile time option string.  ^If N is out of range,
378** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
379** prefix is omitted from any strings returned by
380** sqlite3_compileoption_get().
381**
382** ^Support for the diagnostic functions sqlite3_compileoption_used()
383** and sqlite3_compileoption_get() may be omitted by specifying the
384** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
385**
386** See also: SQL functions [sqlite_compileoption_used()] and
387** [sqlite_compileoption_get()] and the [compile_options pragma].
388*/
389#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
390SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
391SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
392#endif
393
394/*
395** CAPI3REF: Test To See If The Library Is Threadsafe
396**
397** ^The sqlite3_threadsafe() function returns zero if and only if
398** SQLite was compiled with mutexing code omitted due to the
399** [SQLITE_THREADSAFE] compile-time option being set to 0.
400**
401** SQLite can be compiled with or without mutexes.  When
402** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
403** are enabled and SQLite is threadsafe.  When the
404** [SQLITE_THREADSAFE] macro is 0,
405** the mutexes are omitted.  Without the mutexes, it is not safe
406** to use SQLite concurrently from more than one thread.
407**
408** Enabling mutexes incurs a measurable performance penalty.
409** So if speed is of utmost importance, it makes sense to disable
410** the mutexes.  But for maximum safety, mutexes should be enabled.
411** ^The default behavior is for mutexes to be enabled.
412**
413** This interface can be used by an application to make sure that the
414** version of SQLite that it is linking against was compiled with
415** the desired setting of the [SQLITE_THREADSAFE] macro.
416**
417** This interface only reports on the compile-time mutex setting
418** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
419** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
420** can be fully or partially disabled using a call to [sqlite3_config()]
421** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
422** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
423** sqlite3_threadsafe() function shows only the compile-time setting of
424** thread safety, not any run-time changes to that setting made by
425** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
426** is unchanged by calls to sqlite3_config().)^
427**
428** See the [threading mode] documentation for additional information.
429*/
430SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
431
432/*
433** CAPI3REF: Database Connection Handle
434** KEYWORDS: {database connection} {database connections}
435**
436** Each open SQLite database is represented by a pointer to an instance of
437** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
438** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
439** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
440** and [sqlite3_close_v2()] are its destructors.  There are many other
441** interfaces (such as
442** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
443** [sqlite3_busy_timeout()] to name but three) that are methods on an
444** sqlite3 object.
445*/
446typedef struct sqlite3 sqlite3;
447
448/*
449** CAPI3REF: 64-Bit Integer Types
450** KEYWORDS: sqlite_int64 sqlite_uint64
451**
452** Because there is no cross-platform way to specify 64-bit integer types
453** SQLite includes typedefs for 64-bit signed and unsigned integers.
454**
455** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
456** The sqlite_int64 and sqlite_uint64 types are supported for backwards
457** compatibility only.
458**
459** ^The sqlite3_int64 and sqlite_int64 types can store integer values
460** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
461** sqlite3_uint64 and sqlite_uint64 types can store integer values
462** between 0 and +18446744073709551615 inclusive.
463*/
464#ifdef SQLITE_INT64_TYPE
465  typedef SQLITE_INT64_TYPE sqlite_int64;
466  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
467#elif defined(_MSC_VER) || defined(__BORLANDC__)
468  typedef __int64 sqlite_int64;
469  typedef unsigned __int64 sqlite_uint64;
470#else
471  typedef long long int sqlite_int64;
472  typedef unsigned long long int sqlite_uint64;
473#endif
474typedef sqlite_int64 sqlite3_int64;
475typedef sqlite_uint64 sqlite3_uint64;
476
477/*
478** If compiling for a processor that lacks floating point support,
479** substitute integer for floating-point.
480*/
481#ifdef SQLITE_OMIT_FLOATING_POINT
482# define double sqlite3_int64
483#endif
484
485/*
486** CAPI3REF: Closing A Database Connection
487** DESTRUCTOR: sqlite3
488**
489** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
490** for the [sqlite3] object.
491** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
492** the [sqlite3] object is successfully destroyed and all associated
493** resources are deallocated.
494**
495** ^If the database connection is associated with unfinalized prepared
496** statements or unfinished sqlite3_backup objects then sqlite3_close()
497** will leave the database connection open and return [SQLITE_BUSY].
498** ^If sqlite3_close_v2() is called with unfinalized prepared statements
499** and/or unfinished sqlite3_backups, then the database connection becomes
500** an unusable "zombie" which will automatically be deallocated when the
501** last prepared statement is finalized or the last sqlite3_backup is
502** finished.  The sqlite3_close_v2() interface is intended for use with
503** host languages that are garbage collected, and where the order in which
504** destructors are called is arbitrary.
505**
506** Applications should [sqlite3_finalize | finalize] all [prepared statements],
507** [sqlite3_blob_close | close] all [BLOB handles], and
508** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
509** with the [sqlite3] object prior to attempting to close the object.  ^If
510** sqlite3_close_v2() is called on a [database connection] that still has
511** outstanding [prepared statements], [BLOB handles], and/or
512** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
513** of resources is deferred until all [prepared statements], [BLOB handles],
514** and [sqlite3_backup] objects are also destroyed.
515**
516** ^If an [sqlite3] object is destroyed while a transaction is open,
517** the transaction is automatically rolled back.
518**
519** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
520** must be either a NULL
521** pointer or an [sqlite3] object pointer obtained
522** from [sqlite3_open()], [sqlite3_open16()], or
523** [sqlite3_open_v2()], and not previously closed.
524** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
525** argument is a harmless no-op.
526*/
527SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
528SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
529
530/*
531** The type for a callback function.
532** This is legacy and deprecated.  It is included for historical
533** compatibility and is not documented.
534*/
535typedef int (*sqlite3_callback)(void*,int,char**, char**);
536
537/*
538** CAPI3REF: One-Step Query Execution Interface
539** METHOD: sqlite3
540**
541** The sqlite3_exec() interface is a convenience wrapper around
542** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
543** that allows an application to run multiple statements of SQL
544** without having to use a lot of C code.
545**
546** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
547** semicolon-separate SQL statements passed into its 2nd argument,
548** in the context of the [database connection] passed in as its 1st
549** argument.  ^If the callback function of the 3rd argument to
550** sqlite3_exec() is not NULL, then it is invoked for each result row
551** coming out of the evaluated SQL statements.  ^The 4th argument to
552** sqlite3_exec() is relayed through to the 1st argument of each
553** callback invocation.  ^If the callback pointer to sqlite3_exec()
554** is NULL, then no callback is ever invoked and result rows are
555** ignored.
556**
557** ^If an error occurs while evaluating the SQL statements passed into
558** sqlite3_exec(), then execution of the current statement stops and
559** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
560** is not NULL then any error message is written into memory obtained
561** from [sqlite3_malloc()] and passed back through the 5th parameter.
562** To avoid memory leaks, the application should invoke [sqlite3_free()]
563** on error message strings returned through the 5th parameter of
564** of sqlite3_exec() after the error message string is no longer needed.
565** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
566** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
567** NULL before returning.
568**
569** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
570** routine returns SQLITE_ABORT without invoking the callback again and
571** without running any subsequent SQL statements.
572**
573** ^The 2nd argument to the sqlite3_exec() callback function is the
574** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
575** callback is an array of pointers to strings obtained as if from
576** [sqlite3_column_text()], one for each column.  ^If an element of a
577** result row is NULL then the corresponding string pointer for the
578** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
579** sqlite3_exec() callback is an array of pointers to strings where each
580** entry represents the name of corresponding result column as obtained
581** from [sqlite3_column_name()].
582**
583** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
584** to an empty string, or a pointer that contains only whitespace and/or
585** SQL comments, then no SQL statements are evaluated and the database
586** is not changed.
587**
588** Restrictions:
589**
590** <ul>
591** <li> The application must ensure that the 1st parameter to sqlite3_exec()
592**      is a valid and open [database connection].
593** <li> The application must not close the [database connection] specified by
594**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
595** <li> The application must not modify the SQL statement text passed into
596**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
597** </ul>
598*/
599SQLITE_API int SQLITE_STDCALL sqlite3_exec(
600  sqlite3*,                                  /* An open database */
601  const char *sql,                           /* SQL to be evaluated */
602  int (*callback)(void*,int,char**,char**),  /* Callback function */
603  void *,                                    /* 1st argument to callback */
604  char **errmsg                              /* Error msg written here */
605);
606
607/*
608** CAPI3REF: Result Codes
609** KEYWORDS: {result code definitions}
610**
611** Many SQLite functions return an integer result code from the set shown
612** here in order to indicate success or failure.
613**
614** New error codes may be added in future versions of SQLite.
615**
616** See also: [extended result code definitions]
617*/
618#define SQLITE_OK           0   /* Successful result */
619/* beginning-of-error-codes */
620#define SQLITE_ERROR        1   /* SQL error or missing database */
621#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
622#define SQLITE_PERM         3   /* Access permission denied */
623#define SQLITE_ABORT        4   /* Callback routine requested an abort */
624#define SQLITE_BUSY         5   /* The database file is locked */
625#define SQLITE_LOCKED       6   /* A table in the database is locked */
626#define SQLITE_NOMEM        7   /* A malloc() failed */
627#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
628#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
629#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
630#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
631#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
632#define SQLITE_FULL        13   /* Insertion failed because database is full */
633#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
634#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
635#define SQLITE_EMPTY       16   /* Database is empty */
636#define SQLITE_SCHEMA      17   /* The database schema changed */
637#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
638#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
639#define SQLITE_MISMATCH    20   /* Data type mismatch */
640#define SQLITE_MISUSE      21   /* Library used incorrectly */
641#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
642#define SQLITE_AUTH        23   /* Authorization denied */
643#define SQLITE_FORMAT      24   /* Auxiliary database format error */
644#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
645#define SQLITE_NOTADB      26   /* File opened that is not a database file */
646#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
647#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
648#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
649#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
650/* end-of-error-codes */
651
652/*
653** CAPI3REF: Extended Result Codes
654** KEYWORDS: {extended result code definitions}
655**
656** In its default configuration, SQLite API routines return one of 30 integer
657** [result codes].  However, experience has shown that many of
658** these result codes are too coarse-grained.  They do not provide as
659** much information about problems as programmers might like.  In an effort to
660** address this, newer versions of SQLite (version 3.3.8 and later) include
661** support for additional result codes that provide more detailed information
662** about errors. These [extended result codes] are enabled or disabled
663** on a per database connection basis using the
664** [sqlite3_extended_result_codes()] API.  Or, the extended code for
665** the most recent error can be obtained using
666** [sqlite3_extended_errcode()].
667*/
668#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
669#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
670#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
671#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
672#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
673#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
674#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
675#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
676#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
677#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
678#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
679#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
680#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
681#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
682#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
683#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
684#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
685#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
686#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
687#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
688#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
689#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
690#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
691#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
692#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
693#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
694#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
695#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
696#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
697#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
698#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
699#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
700#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
701#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
702#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
703#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
704#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
705#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
706#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
707#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
708#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
709#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
710#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
711#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
712#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
713#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
714#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
715#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
716#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
717#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
718#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
719#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
720#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
721#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
722
723/*
724** CAPI3REF: Flags For File Open Operations
725**
726** These bit values are intended for use in the
727** 3rd parameter to the [sqlite3_open_v2()] interface and
728** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
729*/
730#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
731#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
732#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
733#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
734#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
735#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
736#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
737#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
738#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
739#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
740#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
741#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
742#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
743#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
744#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
745#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
746#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
747#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
748#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
749#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
750
751/* Reserved:                         0x00F00000 */
752
753/*
754** CAPI3REF: Device Characteristics
755**
756** The xDeviceCharacteristics method of the [sqlite3_io_methods]
757** object returns an integer which is a vector of these
758** bit values expressing I/O characteristics of the mass storage
759** device that holds the file that the [sqlite3_io_methods]
760** refers to.
761**
762** The SQLITE_IOCAP_ATOMIC property means that all writes of
763** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
764** mean that writes of blocks that are nnn bytes in size and
765** are aligned to an address which is an integer multiple of
766** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
767** that when data is appended to a file, the data is appended
768** first then the size of the file is extended, never the other
769** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
770** information is written to disk in the same order as calls
771** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
772** after reboot following a crash or power loss, the only bytes in a
773** file that were written at the application level might have changed
774** and that adjacent bytes, even bytes within the same sector are
775** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
776** flag indicate that a file cannot be deleted when open.  The
777** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
778** read-only media and cannot be changed even by processes with
779** elevated privileges.
780*/
781#define SQLITE_IOCAP_ATOMIC                 0x00000001
782#define SQLITE_IOCAP_ATOMIC512              0x00000002
783#define SQLITE_IOCAP_ATOMIC1K               0x00000004
784#define SQLITE_IOCAP_ATOMIC2K               0x00000008
785#define SQLITE_IOCAP_ATOMIC4K               0x00000010
786#define SQLITE_IOCAP_ATOMIC8K               0x00000020
787#define SQLITE_IOCAP_ATOMIC16K              0x00000040
788#define SQLITE_IOCAP_ATOMIC32K              0x00000080
789#define SQLITE_IOCAP_ATOMIC64K              0x00000100
790#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
791#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
792#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
793#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
794#define SQLITE_IOCAP_IMMUTABLE              0x00002000
795
796/*
797** CAPI3REF: File Locking Levels
798**
799** SQLite uses one of these integer values as the second
800** argument to calls it makes to the xLock() and xUnlock() methods
801** of an [sqlite3_io_methods] object.
802*/
803#define SQLITE_LOCK_NONE          0
804#define SQLITE_LOCK_SHARED        1
805#define SQLITE_LOCK_RESERVED      2
806#define SQLITE_LOCK_PENDING       3
807#define SQLITE_LOCK_EXCLUSIVE     4
808
809/*
810** CAPI3REF: Synchronization Type Flags
811**
812** When SQLite invokes the xSync() method of an
813** [sqlite3_io_methods] object it uses a combination of
814** these integer values as the second argument.
815**
816** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
817** sync operation only needs to flush data to mass storage.  Inode
818** information need not be flushed. If the lower four bits of the flag
819** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
820** If the lower four bits equal SQLITE_SYNC_FULL, that means
821** to use Mac OS X style fullsync instead of fsync().
822**
823** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
824** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
825** settings.  The [synchronous pragma] determines when calls to the
826** xSync VFS method occur and applies uniformly across all platforms.
827** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
828** energetic or rigorous or forceful the sync operations are and
829** only make a difference on Mac OSX for the default SQLite code.
830** (Third-party VFS implementations might also make the distinction
831** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
832** operating systems natively supported by SQLite, only Mac OSX
833** cares about the difference.)
834*/
835#define SQLITE_SYNC_NORMAL        0x00002
836#define SQLITE_SYNC_FULL          0x00003
837#define SQLITE_SYNC_DATAONLY      0x00010
838
839/*
840** CAPI3REF: OS Interface Open File Handle
841**
842** An [sqlite3_file] object represents an open file in the
843** [sqlite3_vfs | OS interface layer].  Individual OS interface
844** implementations will
845** want to subclass this object by appending additional fields
846** for their own use.  The pMethods entry is a pointer to an
847** [sqlite3_io_methods] object that defines methods for performing
848** I/O operations on the open file.
849*/
850typedef struct sqlite3_file sqlite3_file;
851struct sqlite3_file {
852  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
853};
854
855/*
856** CAPI3REF: OS Interface File Virtual Methods Object
857**
858** Every file opened by the [sqlite3_vfs.xOpen] method populates an
859** [sqlite3_file] object (or, more commonly, a subclass of the
860** [sqlite3_file] object) with a pointer to an instance of this object.
861** This object defines the methods used to perform various operations
862** against the open file represented by the [sqlite3_file] object.
863**
864** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
865** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
866** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
867** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
868** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
869** to NULL.
870**
871** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
872** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
873** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
874** flag may be ORed in to indicate that only the data of the file
875** and not its inode needs to be synced.
876**
877** The integer values to xLock() and xUnlock() are one of
878** <ul>
879** <li> [SQLITE_LOCK_NONE],
880** <li> [SQLITE_LOCK_SHARED],
881** <li> [SQLITE_LOCK_RESERVED],
882** <li> [SQLITE_LOCK_PENDING], or
883** <li> [SQLITE_LOCK_EXCLUSIVE].
884** </ul>
885** xLock() increases the lock. xUnlock() decreases the lock.
886** The xCheckReservedLock() method checks whether any database connection,
887** either in this process or in some other process, is holding a RESERVED,
888** PENDING, or EXCLUSIVE lock on the file.  It returns true
889** if such a lock exists and false otherwise.
890**
891** The xFileControl() method is a generic interface that allows custom
892** VFS implementations to directly control an open file using the
893** [sqlite3_file_control()] interface.  The second "op" argument is an
894** integer opcode.  The third argument is a generic pointer intended to
895** point to a structure that may contain arguments or space in which to
896** write return values.  Potential uses for xFileControl() might be
897** functions to enable blocking locks with timeouts, to change the
898** locking strategy (for example to use dot-file locks), to inquire
899** about the status of a lock, or to break stale locks.  The SQLite
900** core reserves all opcodes less than 100 for its own use.
901** A [file control opcodes | list of opcodes] less than 100 is available.
902** Applications that define a custom xFileControl method should use opcodes
903** greater than 100 to avoid conflicts.  VFS implementations should
904** return [SQLITE_NOTFOUND] for file control opcodes that they do not
905** recognize.
906**
907** The xSectorSize() method returns the sector size of the
908** device that underlies the file.  The sector size is the
909** minimum write that can be performed without disturbing
910** other bytes in the file.  The xDeviceCharacteristics()
911** method returns a bit vector describing behaviors of the
912** underlying device:
913**
914** <ul>
915** <li> [SQLITE_IOCAP_ATOMIC]
916** <li> [SQLITE_IOCAP_ATOMIC512]
917** <li> [SQLITE_IOCAP_ATOMIC1K]
918** <li> [SQLITE_IOCAP_ATOMIC2K]
919** <li> [SQLITE_IOCAP_ATOMIC4K]
920** <li> [SQLITE_IOCAP_ATOMIC8K]
921** <li> [SQLITE_IOCAP_ATOMIC16K]
922** <li> [SQLITE_IOCAP_ATOMIC32K]
923** <li> [SQLITE_IOCAP_ATOMIC64K]
924** <li> [SQLITE_IOCAP_SAFE_APPEND]
925** <li> [SQLITE_IOCAP_SEQUENTIAL]
926** </ul>
927**
928** The SQLITE_IOCAP_ATOMIC property means that all writes of
929** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
930** mean that writes of blocks that are nnn bytes in size and
931** are aligned to an address which is an integer multiple of
932** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
933** that when data is appended to a file, the data is appended
934** first then the size of the file is extended, never the other
935** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
936** information is written to disk in the same order as calls
937** to xWrite().
938**
939** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
940** in the unread portions of the buffer with zeros.  A VFS that
941** fails to zero-fill short reads might seem to work.  However,
942** failure to zero-fill short reads will eventually lead to
943** database corruption.
944*/
945typedef struct sqlite3_io_methods sqlite3_io_methods;
946struct sqlite3_io_methods {
947  int iVersion;
948  int (*xClose)(sqlite3_file*);
949  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
950  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
951  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
952  int (*xSync)(sqlite3_file*, int flags);
953  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
954  int (*xLock)(sqlite3_file*, int);
955  int (*xUnlock)(sqlite3_file*, int);
956  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
957  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
958  int (*xSectorSize)(sqlite3_file*);
959  int (*xDeviceCharacteristics)(sqlite3_file*);
960  /* Methods above are valid for version 1 */
961  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
962  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
963  void (*xShmBarrier)(sqlite3_file*);
964  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
965  /* Methods above are valid for version 2 */
966  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
967  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
968  /* Methods above are valid for version 3 */
969  /* Additional methods may be added in future releases */
970};
971
972/*
973** CAPI3REF: Standard File Control Opcodes
974** KEYWORDS: {file control opcodes} {file control opcode}
975**
976** These integer constants are opcodes for the xFileControl method
977** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
978** interface.
979**
980** <ul>
981** <li>[[SQLITE_FCNTL_LOCKSTATE]]
982** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
983** opcode causes the xFileControl method to write the current state of
984** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
985** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
986** into an integer that the pArg argument points to. This capability
987** is used during testing and is only available when the SQLITE_TEST
988** compile-time option is used.
989**
990** <li>[[SQLITE_FCNTL_SIZE_HINT]]
991** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
992** layer a hint of how large the database file will grow to be during the
993** current transaction.  This hint is not guaranteed to be accurate but it
994** is often close.  The underlying VFS might choose to preallocate database
995** file space based on this hint in order to help writes to the database
996** file run faster.
997**
998** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
999** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1000** extends and truncates the database file in chunks of a size specified
1001** by the user. The fourth argument to [sqlite3_file_control()] should
1002** point to an integer (type int) containing the new chunk-size to use
1003** for the nominated database. Allocating database file space in large
1004** chunks (say 1MB at a time), may reduce file-system fragmentation and
1005** improve performance on some systems.
1006**
1007** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1008** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1009** to the [sqlite3_file] object associated with a particular database
1010** connection.  See the [sqlite3_file_control()] documentation for
1011** additional information.
1012**
1013** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1014** No longer in use.
1015**
1016** <li>[[SQLITE_FCNTL_SYNC]]
1017** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1018** sent to the VFS immediately before the xSync method is invoked on a
1019** database file descriptor. Or, if the xSync method is not invoked
1020** because the user has configured SQLite with
1021** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1022** of the xSync method. In most cases, the pointer argument passed with
1023** this file-control is NULL. However, if the database file is being synced
1024** as part of a multi-database commit, the argument points to a nul-terminated
1025** string containing the transactions master-journal file name. VFSes that
1026** do not need this signal should silently ignore this opcode. Applications
1027** should not call [sqlite3_file_control()] with this opcode as doing so may
1028** disrupt the operation of the specialized VFSes that do require it.
1029**
1030** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1031** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1032** and sent to the VFS after a transaction has been committed immediately
1033** but before the database is unlocked. VFSes that do not need this signal
1034** should silently ignore this opcode. Applications should not call
1035** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1036** operation of the specialized VFSes that do require it.
1037**
1038** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1039** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1040** retry counts and intervals for certain disk I/O operations for the
1041** windows [VFS] in order to provide robustness in the presence of
1042** anti-virus programs.  By default, the windows VFS will retry file read,
1043** file write, and file delete operations up to 10 times, with a delay
1044** of 25 milliseconds before the first retry and with the delay increasing
1045** by an additional 25 milliseconds with each subsequent retry.  This
1046** opcode allows these two values (10 retries and 25 milliseconds of delay)
1047** to be adjusted.  The values are changed for all database connections
1048** within the same process.  The argument is a pointer to an array of two
1049** integers where the first integer i the new retry count and the second
1050** integer is the delay.  If either integer is negative, then the setting
1051** is not changed but instead the prior value of that setting is written
1052** into the array entry, allowing the current retry settings to be
1053** interrogated.  The zDbName parameter is ignored.
1054**
1055** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1056** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1057** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1058** write ahead log and shared memory files used for transaction control
1059** are automatically deleted when the latest connection to the database
1060** closes.  Setting persistent WAL mode causes those files to persist after
1061** close.  Persisting the files is useful when other processes that do not
1062** have write permission on the directory containing the database file want
1063** to read the database file, as the WAL and shared memory files must exist
1064** in order for the database to be readable.  The fourth parameter to
1065** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1066** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1067** WAL mode.  If the integer is -1, then it is overwritten with the current
1068** WAL persistence setting.
1069**
1070** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1071** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1072** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1073** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1074** xDeviceCharacteristics methods. The fourth parameter to
1075** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1076** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1077** mode.  If the integer is -1, then it is overwritten with the current
1078** zero-damage mode setting.
1079**
1080** <li>[[SQLITE_FCNTL_OVERWRITE]]
1081** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1082** a write transaction to indicate that, unless it is rolled back for some
1083** reason, the entire database file will be overwritten by the current
1084** transaction. This is used by VACUUM operations.
1085**
1086** <li>[[SQLITE_FCNTL_VFSNAME]]
1087** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1088** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1089** final bottom-level VFS are written into memory obtained from
1090** [sqlite3_malloc()] and the result is stored in the char* variable
1091** that the fourth parameter of [sqlite3_file_control()] points to.
1092** The caller is responsible for freeing the memory when done.  As with
1093** all file-control actions, there is no guarantee that this will actually
1094** do anything.  Callers should initialize the char* variable to a NULL
1095** pointer in case this file-control is not implemented.  This file-control
1096** is intended for diagnostic use only.
1097**
1098** <li>[[SQLITE_FCNTL_PRAGMA]]
1099** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1100** file control is sent to the open [sqlite3_file] object corresponding
1101** to the database file to which the pragma statement refers. ^The argument
1102** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1103** pointers to strings (char**) in which the second element of the array
1104** is the name of the pragma and the third element is the argument to the
1105** pragma or NULL if the pragma has no argument.  ^The handler for an
1106** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1107** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1108** or the equivalent and that string will become the result of the pragma or
1109** the error message if the pragma fails. ^If the
1110** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1111** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1112** file control returns [SQLITE_OK], then the parser assumes that the
1113** VFS has handled the PRAGMA itself and the parser generates a no-op
1114** prepared statement if result string is NULL, or that returns a copy
1115** of the result string if the string is non-NULL.
1116** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1117** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1118** that the VFS encountered an error while handling the [PRAGMA] and the
1119** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1120** file control occurs at the beginning of pragma statement analysis and so
1121** it is able to override built-in [PRAGMA] statements.
1122**
1123** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1124** ^The [SQLITE_FCNTL_BUSYHANDLER]
1125** file-control may be invoked by SQLite on the database file handle
1126** shortly after it is opened in order to provide a custom VFS with access
1127** to the connections busy-handler callback. The argument is of type (void **)
1128** - an array of two (void *) values. The first (void *) actually points
1129** to a function of type (int (*)(void *)). In order to invoke the connections
1130** busy-handler, this function should be invoked with the second (void *) in
1131** the array as the only argument. If it returns non-zero, then the operation
1132** should be retried. If it returns zero, the custom VFS should abandon the
1133** current operation.
1134**
1135** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1136** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1137** to have SQLite generate a
1138** temporary filename using the same algorithm that is followed to generate
1139** temporary filenames for TEMP tables and other internal uses.  The
1140** argument should be a char** which will be filled with the filename
1141** written into memory obtained from [sqlite3_malloc()].  The caller should
1142** invoke [sqlite3_free()] on the result to avoid a memory leak.
1143**
1144** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1145** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1146** maximum number of bytes that will be used for memory-mapped I/O.
1147** The argument is a pointer to a value of type sqlite3_int64 that
1148** is an advisory maximum number of bytes in the file to memory map.  The
1149** pointer is overwritten with the old value.  The limit is not changed if
1150** the value originally pointed to is negative, and so the current limit
1151** can be queried by passing in a pointer to a negative number.  This
1152** file-control is used internally to implement [PRAGMA mmap_size].
1153**
1154** <li>[[SQLITE_FCNTL_TRACE]]
1155** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1156** to the VFS about what the higher layers of the SQLite stack are doing.
1157** This file control is used by some VFS activity tracing [shims].
1158** The argument is a zero-terminated string.  Higher layers in the
1159** SQLite stack may generate instances of this file control if
1160** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1161**
1162** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1163** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1164** pointer to an integer and it writes a boolean into that integer depending
1165** on whether or not the file has been renamed, moved, or deleted since it
1166** was first opened.
1167**
1168** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1169** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1170** opcode causes the xFileControl method to swap the file handle with the one
1171** pointed to by the pArg argument.  This capability is used during testing
1172** and only needs to be supported when SQLITE_TEST is defined.
1173**
1174** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1175** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1176** be advantageous to block on the next WAL lock if the lock is not immediately
1177** available.  The WAL subsystem issues this signal during rare
1178** circumstances in order to fix a problem with priority inversion.
1179** Applications should <em>not</em> use this file-control.
1180**
1181** <li>[[SQLITE_FCNTL_ZIPVFS]]
1182** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1183** VFS should return SQLITE_NOTFOUND for this opcode.
1184**
1185** <li>[[SQLITE_FCNTL_RBU]]
1186** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1187** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
1188** this opcode.
1189** </ul>
1190*/
1191#define SQLITE_FCNTL_LOCKSTATE               1
1192#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1193#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1194#define SQLITE_FCNTL_LAST_ERRNO              4
1195#define SQLITE_FCNTL_SIZE_HINT               5
1196#define SQLITE_FCNTL_CHUNK_SIZE              6
1197#define SQLITE_FCNTL_FILE_POINTER            7
1198#define SQLITE_FCNTL_SYNC_OMITTED            8
1199#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1200#define SQLITE_FCNTL_PERSIST_WAL            10
1201#define SQLITE_FCNTL_OVERWRITE              11
1202#define SQLITE_FCNTL_VFSNAME                12
1203#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1204#define SQLITE_FCNTL_PRAGMA                 14
1205#define SQLITE_FCNTL_BUSYHANDLER            15
1206#define SQLITE_FCNTL_TEMPFILENAME           16
1207#define SQLITE_FCNTL_MMAP_SIZE              18
1208#define SQLITE_FCNTL_TRACE                  19
1209#define SQLITE_FCNTL_HAS_MOVED              20
1210#define SQLITE_FCNTL_SYNC                   21
1211#define SQLITE_FCNTL_COMMIT_PHASETWO        22
1212#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1213#define SQLITE_FCNTL_WAL_BLOCK              24
1214#define SQLITE_FCNTL_ZIPVFS                 25
1215#define SQLITE_FCNTL_RBU                    26
1216
1217/* deprecated names */
1218#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1219#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1220#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1221
1222
1223/*
1224** CAPI3REF: Mutex Handle
1225**
1226** The mutex module within SQLite defines [sqlite3_mutex] to be an
1227** abstract type for a mutex object.  The SQLite core never looks
1228** at the internal representation of an [sqlite3_mutex].  It only
1229** deals with pointers to the [sqlite3_mutex] object.
1230**
1231** Mutexes are created using [sqlite3_mutex_alloc()].
1232*/
1233typedef struct sqlite3_mutex sqlite3_mutex;
1234
1235/*
1236** CAPI3REF: OS Interface Object
1237**
1238** An instance of the sqlite3_vfs object defines the interface between
1239** the SQLite core and the underlying operating system.  The "vfs"
1240** in the name of the object stands for "virtual file system".  See
1241** the [VFS | VFS documentation] for further information.
1242**
1243** The value of the iVersion field is initially 1 but may be larger in
1244** future versions of SQLite.  Additional fields may be appended to this
1245** object when the iVersion value is increased.  Note that the structure
1246** of the sqlite3_vfs object changes in the transaction between
1247** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1248** modified.
1249**
1250** The szOsFile field is the size of the subclassed [sqlite3_file]
1251** structure used by this VFS.  mxPathname is the maximum length of
1252** a pathname in this VFS.
1253**
1254** Registered sqlite3_vfs objects are kept on a linked list formed by
1255** the pNext pointer.  The [sqlite3_vfs_register()]
1256** and [sqlite3_vfs_unregister()] interfaces manage this list
1257** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1258** searches the list.  Neither the application code nor the VFS
1259** implementation should use the pNext pointer.
1260**
1261** The pNext field is the only field in the sqlite3_vfs
1262** structure that SQLite will ever modify.  SQLite will only access
1263** or modify this field while holding a particular static mutex.
1264** The application should never modify anything within the sqlite3_vfs
1265** object once the object has been registered.
1266**
1267** The zName field holds the name of the VFS module.  The name must
1268** be unique across all VFS modules.
1269**
1270** [[sqlite3_vfs.xOpen]]
1271** ^SQLite guarantees that the zFilename parameter to xOpen
1272** is either a NULL pointer or string obtained
1273** from xFullPathname() with an optional suffix added.
1274** ^If a suffix is added to the zFilename parameter, it will
1275** consist of a single "-" character followed by no more than
1276** 11 alphanumeric and/or "-" characters.
1277** ^SQLite further guarantees that
1278** the string will be valid and unchanged until xClose() is
1279** called. Because of the previous sentence,
1280** the [sqlite3_file] can safely store a pointer to the
1281** filename if it needs to remember the filename for some reason.
1282** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1283** must invent its own temporary name for the file.  ^Whenever the
1284** xFilename parameter is NULL it will also be the case that the
1285** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1286**
1287** The flags argument to xOpen() includes all bits set in
1288** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1289** or [sqlite3_open16()] is used, then flags includes at least
1290** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1291** If xOpen() opens a file read-only then it sets *pOutFlags to
1292** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1293**
1294** ^(SQLite will also add one of the following flags to the xOpen()
1295** call, depending on the object being opened:
1296**
1297** <ul>
1298** <li>  [SQLITE_OPEN_MAIN_DB]
1299** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1300** <li>  [SQLITE_OPEN_TEMP_DB]
1301** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1302** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1303** <li>  [SQLITE_OPEN_SUBJOURNAL]
1304** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1305** <li>  [SQLITE_OPEN_WAL]
1306** </ul>)^
1307**
1308** The file I/O implementation can use the object type flags to
1309** change the way it deals with files.  For example, an application
1310** that does not care about crash recovery or rollback might make
1311** the open of a journal file a no-op.  Writes to this journal would
1312** also be no-ops, and any attempt to read the journal would return
1313** SQLITE_IOERR.  Or the implementation might recognize that a database
1314** file will be doing page-aligned sector reads and writes in a random
1315** order and set up its I/O subsystem accordingly.
1316**
1317** SQLite might also add one of the following flags to the xOpen method:
1318**
1319** <ul>
1320** <li> [SQLITE_OPEN_DELETEONCLOSE]
1321** <li> [SQLITE_OPEN_EXCLUSIVE]
1322** </ul>
1323**
1324** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1325** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1326** will be set for TEMP databases and their journals, transient
1327** databases, and subjournals.
1328**
1329** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1330** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1331** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1332** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1333** SQLITE_OPEN_CREATE, is used to indicate that file should always
1334** be created, and that it is an error if it already exists.
1335** It is <i>not</i> used to indicate the file should be opened
1336** for exclusive access.
1337**
1338** ^At least szOsFile bytes of memory are allocated by SQLite
1339** to hold the  [sqlite3_file] structure passed as the third
1340** argument to xOpen.  The xOpen method does not have to
1341** allocate the structure; it should just fill it in.  Note that
1342** the xOpen method must set the sqlite3_file.pMethods to either
1343** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1344** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1345** element will be valid after xOpen returns regardless of the success
1346** or failure of the xOpen call.
1347**
1348** [[sqlite3_vfs.xAccess]]
1349** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1350** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1351** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1352** to test whether a file is at least readable.   The file can be a
1353** directory.
1354**
1355** ^SQLite will always allocate at least mxPathname+1 bytes for the
1356** output buffer xFullPathname.  The exact size of the output buffer
1357** is also passed as a parameter to both  methods. If the output buffer
1358** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1359** handled as a fatal error by SQLite, vfs implementations should endeavor
1360** to prevent this by setting mxPathname to a sufficiently large value.
1361**
1362** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1363** interfaces are not strictly a part of the filesystem, but they are
1364** included in the VFS structure for completeness.
1365** The xRandomness() function attempts to return nBytes bytes
1366** of good-quality randomness into zOut.  The return value is
1367** the actual number of bytes of randomness obtained.
1368** The xSleep() method causes the calling thread to sleep for at
1369** least the number of microseconds given.  ^The xCurrentTime()
1370** method returns a Julian Day Number for the current date and time as
1371** a floating point value.
1372** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1373** Day Number multiplied by 86400000 (the number of milliseconds in
1374** a 24-hour day).
1375** ^SQLite will use the xCurrentTimeInt64() method to get the current
1376** date and time if that method is available (if iVersion is 2 or
1377** greater and the function pointer is not NULL) and will fall back
1378** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1379**
1380** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1381** are not used by the SQLite core.  These optional interfaces are provided
1382** by some VFSes to facilitate testing of the VFS code. By overriding
1383** system calls with functions under its control, a test program can
1384** simulate faults and error conditions that would otherwise be difficult
1385** or impossible to induce.  The set of system calls that can be overridden
1386** varies from one VFS to another, and from one version of the same VFS to the
1387** next.  Applications that use these interfaces must be prepared for any
1388** or all of these interfaces to be NULL or for their behavior to change
1389** from one release to the next.  Applications must not attempt to access
1390** any of these methods if the iVersion of the VFS is less than 3.
1391*/
1392typedef struct sqlite3_vfs sqlite3_vfs;
1393typedef void (*sqlite3_syscall_ptr)(void);
1394struct sqlite3_vfs {
1395  int iVersion;            /* Structure version number (currently 3) */
1396  int szOsFile;            /* Size of subclassed sqlite3_file */
1397  int mxPathname;          /* Maximum file pathname length */
1398  sqlite3_vfs *pNext;      /* Next registered VFS */
1399  const char *zName;       /* Name of this virtual file system */
1400  void *pAppData;          /* Pointer to application-specific data */
1401  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1402               int flags, int *pOutFlags);
1403  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1404  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1405  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1406  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1407  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1408  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1409  void (*xDlClose)(sqlite3_vfs*, void*);
1410  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1411  int (*xSleep)(sqlite3_vfs*, int microseconds);
1412  int (*xCurrentTime)(sqlite3_vfs*, double*);
1413  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1414  /*
1415  ** The methods above are in version 1 of the sqlite_vfs object
1416  ** definition.  Those that follow are added in version 2 or later
1417  */
1418  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1419  /*
1420  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1421  ** Those below are for version 3 and greater.
1422  */
1423  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1424  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1425  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1426  /*
1427  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1428  ** New fields may be appended in figure versions.  The iVersion
1429  ** value will increment whenever this happens.
1430  */
1431};
1432
1433/*
1434** CAPI3REF: Flags for the xAccess VFS method
1435**
1436** These integer constants can be used as the third parameter to
1437** the xAccess method of an [sqlite3_vfs] object.  They determine
1438** what kind of permissions the xAccess method is looking for.
1439** With SQLITE_ACCESS_EXISTS, the xAccess method
1440** simply checks whether the file exists.
1441** With SQLITE_ACCESS_READWRITE, the xAccess method
1442** checks whether the named directory is both readable and writable
1443** (in other words, if files can be added, removed, and renamed within
1444** the directory).
1445** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1446** [temp_store_directory pragma], though this could change in a future
1447** release of SQLite.
1448** With SQLITE_ACCESS_READ, the xAccess method
1449** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1450** currently unused, though it might be used in a future release of
1451** SQLite.
1452*/
1453#define SQLITE_ACCESS_EXISTS    0
1454#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1455#define SQLITE_ACCESS_READ      2   /* Unused */
1456
1457/*
1458** CAPI3REF: Flags for the xShmLock VFS method
1459**
1460** These integer constants define the various locking operations
1461** allowed by the xShmLock method of [sqlite3_io_methods].  The
1462** following are the only legal combinations of flags to the
1463** xShmLock method:
1464**
1465** <ul>
1466** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1467** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1468** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1469** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1470** </ul>
1471**
1472** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1473** was given on the corresponding lock.
1474**
1475** The xShmLock method can transition between unlocked and SHARED or
1476** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1477** and EXCLUSIVE.
1478*/
1479#define SQLITE_SHM_UNLOCK       1
1480#define SQLITE_SHM_LOCK         2
1481#define SQLITE_SHM_SHARED       4
1482#define SQLITE_SHM_EXCLUSIVE    8
1483
1484/*
1485** CAPI3REF: Maximum xShmLock index
1486**
1487** The xShmLock method on [sqlite3_io_methods] may use values
1488** between 0 and this upper bound as its "offset" argument.
1489** The SQLite core will never attempt to acquire or release a
1490** lock outside of this range
1491*/
1492#define SQLITE_SHM_NLOCK        8
1493
1494
1495/*
1496** CAPI3REF: Initialize The SQLite Library
1497**
1498** ^The sqlite3_initialize() routine initializes the
1499** SQLite library.  ^The sqlite3_shutdown() routine
1500** deallocates any resources that were allocated by sqlite3_initialize().
1501** These routines are designed to aid in process initialization and
1502** shutdown on embedded systems.  Workstation applications using
1503** SQLite normally do not need to invoke either of these routines.
1504**
1505** A call to sqlite3_initialize() is an "effective" call if it is
1506** the first time sqlite3_initialize() is invoked during the lifetime of
1507** the process, or if it is the first time sqlite3_initialize() is invoked
1508** following a call to sqlite3_shutdown().  ^(Only an effective call
1509** of sqlite3_initialize() does any initialization.  All other calls
1510** are harmless no-ops.)^
1511**
1512** A call to sqlite3_shutdown() is an "effective" call if it is the first
1513** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1514** an effective call to sqlite3_shutdown() does any deinitialization.
1515** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1516**
1517** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1518** is not.  The sqlite3_shutdown() interface must only be called from a
1519** single thread.  All open [database connections] must be closed and all
1520** other SQLite resources must be deallocated prior to invoking
1521** sqlite3_shutdown().
1522**
1523** Among other things, ^sqlite3_initialize() will invoke
1524** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1525** will invoke sqlite3_os_end().
1526**
1527** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1528** ^If for some reason, sqlite3_initialize() is unable to initialize
1529** the library (perhaps it is unable to allocate a needed resource such
1530** as a mutex) it returns an [error code] other than [SQLITE_OK].
1531**
1532** ^The sqlite3_initialize() routine is called internally by many other
1533** SQLite interfaces so that an application usually does not need to
1534** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1535** calls sqlite3_initialize() so the SQLite library will be automatically
1536** initialized when [sqlite3_open()] is called if it has not be initialized
1537** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1538** compile-time option, then the automatic calls to sqlite3_initialize()
1539** are omitted and the application must call sqlite3_initialize() directly
1540** prior to using any other SQLite interface.  For maximum portability,
1541** it is recommended that applications always invoke sqlite3_initialize()
1542** directly prior to using any other SQLite interface.  Future releases
1543** of SQLite may require this.  In other words, the behavior exhibited
1544** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1545** default behavior in some future release of SQLite.
1546**
1547** The sqlite3_os_init() routine does operating-system specific
1548** initialization of the SQLite library.  The sqlite3_os_end()
1549** routine undoes the effect of sqlite3_os_init().  Typical tasks
1550** performed by these routines include allocation or deallocation
1551** of static resources, initialization of global variables,
1552** setting up a default [sqlite3_vfs] module, or setting up
1553** a default configuration using [sqlite3_config()].
1554**
1555** The application should never invoke either sqlite3_os_init()
1556** or sqlite3_os_end() directly.  The application should only invoke
1557** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1558** interface is called automatically by sqlite3_initialize() and
1559** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1560** implementations for sqlite3_os_init() and sqlite3_os_end()
1561** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1562** When [custom builds | built for other platforms]
1563** (using the [SQLITE_OS_OTHER=1] compile-time
1564** option) the application must supply a suitable implementation for
1565** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1566** implementation of sqlite3_os_init() or sqlite3_os_end()
1567** must return [SQLITE_OK] on success and some other [error code] upon
1568** failure.
1569*/
1570SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1571SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1572SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1573SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1574
1575/*
1576** CAPI3REF: Configuring The SQLite Library
1577**
1578** The sqlite3_config() interface is used to make global configuration
1579** changes to SQLite in order to tune SQLite to the specific needs of
1580** the application.  The default configuration is recommended for most
1581** applications and so this routine is usually not necessary.  It is
1582** provided to support rare applications with unusual needs.
1583**
1584** <b>The sqlite3_config() interface is not threadsafe. The application
1585** must ensure that no other SQLite interfaces are invoked by other
1586** threads while sqlite3_config() is running.</b>
1587**
1588** The sqlite3_config() interface
1589** may only be invoked prior to library initialization using
1590** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1591** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1592** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1593** Note, however, that ^sqlite3_config() can be called as part of the
1594** implementation of an application-defined [sqlite3_os_init()].
1595**
1596** The first argument to sqlite3_config() is an integer
1597** [configuration option] that determines
1598** what property of SQLite is to be configured.  Subsequent arguments
1599** vary depending on the [configuration option]
1600** in the first argument.
1601**
1602** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1603** ^If the option is unknown or SQLite is unable to set the option
1604** then this routine returns a non-zero [error code].
1605*/
1606SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1607
1608/*
1609** CAPI3REF: Configure database connections
1610** METHOD: sqlite3
1611**
1612** The sqlite3_db_config() interface is used to make configuration
1613** changes to a [database connection].  The interface is similar to
1614** [sqlite3_config()] except that the changes apply to a single
1615** [database connection] (specified in the first argument).
1616**
1617** The second argument to sqlite3_db_config(D,V,...)  is the
1618** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1619** that indicates what aspect of the [database connection] is being configured.
1620** Subsequent arguments vary depending on the configuration verb.
1621**
1622** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1623** the call is considered successful.
1624*/
1625SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1626
1627/*
1628** CAPI3REF: Memory Allocation Routines
1629**
1630** An instance of this object defines the interface between SQLite
1631** and low-level memory allocation routines.
1632**
1633** This object is used in only one place in the SQLite interface.
1634** A pointer to an instance of this object is the argument to
1635** [sqlite3_config()] when the configuration option is
1636** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1637** By creating an instance of this object
1638** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1639** during configuration, an application can specify an alternative
1640** memory allocation subsystem for SQLite to use for all of its
1641** dynamic memory needs.
1642**
1643** Note that SQLite comes with several [built-in memory allocators]
1644** that are perfectly adequate for the overwhelming majority of applications
1645** and that this object is only useful to a tiny minority of applications
1646** with specialized memory allocation requirements.  This object is
1647** also used during testing of SQLite in order to specify an alternative
1648** memory allocator that simulates memory out-of-memory conditions in
1649** order to verify that SQLite recovers gracefully from such
1650** conditions.
1651**
1652** The xMalloc, xRealloc, and xFree methods must work like the
1653** malloc(), realloc() and free() functions from the standard C library.
1654** ^SQLite guarantees that the second argument to
1655** xRealloc is always a value returned by a prior call to xRoundup.
1656**
1657** xSize should return the allocated size of a memory allocation
1658** previously obtained from xMalloc or xRealloc.  The allocated size
1659** is always at least as big as the requested size but may be larger.
1660**
1661** The xRoundup method returns what would be the allocated size of
1662** a memory allocation given a particular requested size.  Most memory
1663** allocators round up memory allocations at least to the next multiple
1664** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1665** Every memory allocation request coming in through [sqlite3_malloc()]
1666** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1667** that causes the corresponding memory allocation to fail.
1668**
1669** The xInit method initializes the memory allocator.  For example,
1670** it might allocate any require mutexes or initialize internal data
1671** structures.  The xShutdown method is invoked (indirectly) by
1672** [sqlite3_shutdown()] and should deallocate any resources acquired
1673** by xInit.  The pAppData pointer is used as the only parameter to
1674** xInit and xShutdown.
1675**
1676** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1677** the xInit method, so the xInit method need not be threadsafe.  The
1678** xShutdown method is only called from [sqlite3_shutdown()] so it does
1679** not need to be threadsafe either.  For all other methods, SQLite
1680** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1681** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1682** it is by default) and so the methods are automatically serialized.
1683** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1684** methods must be threadsafe or else make their own arrangements for
1685** serialization.
1686**
1687** SQLite will never invoke xInit() more than once without an intervening
1688** call to xShutdown().
1689*/
1690typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1691struct sqlite3_mem_methods {
1692  void *(*xMalloc)(int);         /* Memory allocation function */
1693  void (*xFree)(void*);          /* Free a prior allocation */
1694  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1695  int (*xSize)(void*);           /* Return the size of an allocation */
1696  int (*xRoundup)(int);          /* Round up request size to allocation size */
1697  int (*xInit)(void*);           /* Initialize the memory allocator */
1698  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1699  void *pAppData;                /* Argument to xInit() and xShutdown() */
1700};
1701
1702/*
1703** CAPI3REF: Configuration Options
1704** KEYWORDS: {configuration option}
1705**
1706** These constants are the available integer configuration options that
1707** can be passed as the first argument to the [sqlite3_config()] interface.
1708**
1709** New configuration options may be added in future releases of SQLite.
1710** Existing configuration options might be discontinued.  Applications
1711** should check the return code from [sqlite3_config()] to make sure that
1712** the call worked.  The [sqlite3_config()] interface will return a
1713** non-zero [error code] if a discontinued or unsupported configuration option
1714** is invoked.
1715**
1716** <dl>
1717** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1718** <dd>There are no arguments to this option.  ^This option sets the
1719** [threading mode] to Single-thread.  In other words, it disables
1720** all mutexing and puts SQLite into a mode where it can only be used
1721** by a single thread.   ^If SQLite is compiled with
1722** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1723** it is not possible to change the [threading mode] from its default
1724** value of Single-thread and so [sqlite3_config()] will return
1725** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1726** configuration option.</dd>
1727**
1728** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1729** <dd>There are no arguments to this option.  ^This option sets the
1730** [threading mode] to Multi-thread.  In other words, it disables
1731** mutexing on [database connection] and [prepared statement] objects.
1732** The application is responsible for serializing access to
1733** [database connections] and [prepared statements].  But other mutexes
1734** are enabled so that SQLite will be safe to use in a multi-threaded
1735** environment as long as no two threads attempt to use the same
1736** [database connection] at the same time.  ^If SQLite is compiled with
1737** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1738** it is not possible to set the Multi-thread [threading mode] and
1739** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1740** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1741**
1742** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1743** <dd>There are no arguments to this option.  ^This option sets the
1744** [threading mode] to Serialized. In other words, this option enables
1745** all mutexes including the recursive
1746** mutexes on [database connection] and [prepared statement] objects.
1747** In this mode (which is the default when SQLite is compiled with
1748** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1749** to [database connections] and [prepared statements] so that the
1750** application is free to use the same [database connection] or the
1751** same [prepared statement] in different threads at the same time.
1752** ^If SQLite is compiled with
1753** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1754** it is not possible to set the Serialized [threading mode] and
1755** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1756** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1757**
1758** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1759** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1760** a pointer to an instance of the [sqlite3_mem_methods] structure.
1761** The argument specifies
1762** alternative low-level memory allocation routines to be used in place of
1763** the memory allocation routines built into SQLite.)^ ^SQLite makes
1764** its own private copy of the content of the [sqlite3_mem_methods] structure
1765** before the [sqlite3_config()] call returns.</dd>
1766**
1767** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1768** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1769** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1770** The [sqlite3_mem_methods]
1771** structure is filled with the currently defined memory allocation routines.)^
1772** This option can be used to overload the default memory allocation
1773** routines with a wrapper that simulations memory allocation failure or
1774** tracks memory usage, for example. </dd>
1775**
1776** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1777** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1778** interpreted as a boolean, which enables or disables the collection of
1779** memory allocation statistics. ^(When memory allocation statistics are
1780** disabled, the following SQLite interfaces become non-operational:
1781**   <ul>
1782**   <li> [sqlite3_memory_used()]
1783**   <li> [sqlite3_memory_highwater()]
1784**   <li> [sqlite3_soft_heap_limit64()]
1785**   <li> [sqlite3_status64()]
1786**   </ul>)^
1787** ^Memory allocation statistics are enabled by default unless SQLite is
1788** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1789** allocation statistics are disabled by default.
1790** </dd>
1791**
1792** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1793** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1794** that SQLite can use for scratch memory.  ^(There are three arguments
1795** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
1796** aligned memory buffer from which the scratch allocations will be
1797** drawn, the size of each scratch allocation (sz),
1798** and the maximum number of scratch allocations (N).)^
1799** The first argument must be a pointer to an 8-byte aligned buffer
1800** of at least sz*N bytes of memory.
1801** ^SQLite will not use more than one scratch buffers per thread.
1802** ^SQLite will never request a scratch buffer that is more than 6
1803** times the database page size.
1804** ^If SQLite needs needs additional
1805** scratch memory beyond what is provided by this configuration option, then
1806** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1807** ^When the application provides any amount of scratch memory using
1808** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1809** [sqlite3_malloc|heap allocations].
1810** This can help [Robson proof|prevent memory allocation failures] due to heap
1811** fragmentation in low-memory embedded systems.
1812** </dd>
1813**
1814** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1815** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
1816** that SQLite can use for the database page cache with the default page
1817** cache implementation.
1818** This configuration should not be used if an application-define page
1819** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
1820** configuration option.
1821** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1822** 8-byte aligned
1823** memory, the size of each page buffer (sz), and the number of pages (N).
1824** The sz argument should be the size of the largest database page
1825** (a power of two between 512 and 65536) plus some extra bytes for each
1826** page header.  ^The number of extra bytes needed by the page header
1827** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option
1828** to [sqlite3_config()].
1829** ^It is harmless, apart from the wasted memory,
1830** for the sz parameter to be larger than necessary.  The first
1831** argument should pointer to an 8-byte aligned block of memory that
1832** is at least sz*N bytes of memory, otherwise subsequent behavior is
1833** undefined.
1834** ^SQLite will use the memory provided by the first argument to satisfy its
1835** memory needs for the first N pages that it adds to cache.  ^If additional
1836** page cache memory is needed beyond what is provided by this option, then
1837** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
1838**
1839** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1840** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1841** that SQLite will use for all of its dynamic memory allocation needs
1842** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1843** [SQLITE_CONFIG_PAGECACHE].
1844** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1845** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1846** [SQLITE_ERROR] if invoked otherwise.
1847** ^There are three arguments to SQLITE_CONFIG_HEAP:
1848** An 8-byte aligned pointer to the memory,
1849** the number of bytes in the memory buffer, and the minimum allocation size.
1850** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1851** to using its default memory allocator (the system malloc() implementation),
1852** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1853** memory pointer is not NULL then the alternative memory
1854** allocator is engaged to handle all of SQLites memory allocation needs.
1855** The first pointer (the memory pointer) must be aligned to an 8-byte
1856** boundary or subsequent behavior of SQLite will be undefined.
1857** The minimum allocation size is capped at 2**12. Reasonable values
1858** for the minimum allocation size are 2**5 through 2**8.</dd>
1859**
1860** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1861** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1862** pointer to an instance of the [sqlite3_mutex_methods] structure.
1863** The argument specifies alternative low-level mutex routines to be used
1864** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
1865** the content of the [sqlite3_mutex_methods] structure before the call to
1866** [sqlite3_config()] returns. ^If SQLite is compiled with
1867** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1868** the entire mutexing subsystem is omitted from the build and hence calls to
1869** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1870** return [SQLITE_ERROR].</dd>
1871**
1872** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1873** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1874** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
1875** [sqlite3_mutex_methods]
1876** structure is filled with the currently defined mutex routines.)^
1877** This option can be used to overload the default mutex allocation
1878** routines with a wrapper used to track mutex usage for performance
1879** profiling or testing, for example.   ^If SQLite is compiled with
1880** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1881** the entire mutexing subsystem is omitted from the build and hence calls to
1882** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1883** return [SQLITE_ERROR].</dd>
1884**
1885** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1886** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1887** the default size of lookaside memory on each [database connection].
1888** The first argument is the
1889** size of each lookaside buffer slot and the second is the number of
1890** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
1891** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1892** option to [sqlite3_db_config()] can be used to change the lookaside
1893** configuration on individual connections.)^ </dd>
1894**
1895** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1896** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1897** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
1898** the interface to a custom page cache implementation.)^
1899** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1900**
1901** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1902** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1903** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
1904** the current page cache implementation into that object.)^ </dd>
1905**
1906** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1907** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1908** global [error log].
1909** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1910** function with a call signature of void(*)(void*,int,const char*),
1911** and a pointer to void. ^If the function pointer is not NULL, it is
1912** invoked by [sqlite3_log()] to process each logging event.  ^If the
1913** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1914** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1915** passed through as the first parameter to the application-defined logger
1916** function whenever that function is invoked.  ^The second parameter to
1917** the logger function is a copy of the first parameter to the corresponding
1918** [sqlite3_log()] call and is intended to be a [result code] or an
1919** [extended result code].  ^The third parameter passed to the logger is
1920** log message after formatting via [sqlite3_snprintf()].
1921** The SQLite logging interface is not reentrant; the logger function
1922** supplied by the application must not invoke any SQLite interface.
1923** In a multi-threaded application, the application-defined logger
1924** function must be threadsafe. </dd>
1925**
1926** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1927** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
1928** If non-zero, then URI handling is globally enabled. If the parameter is zero,
1929** then URI handling is globally disabled.)^ ^If URI handling is globally
1930** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
1931** [sqlite3_open16()] or
1932** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1933** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1934** connection is opened. ^If it is globally disabled, filenames are
1935** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1936** database connection is opened. ^(By default, URI handling is globally
1937** disabled. The default value may be changed by compiling with the
1938** [SQLITE_USE_URI] symbol defined.)^
1939**
1940** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1941** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
1942** argument which is interpreted as a boolean in order to enable or disable
1943** the use of covering indices for full table scans in the query optimizer.
1944** ^The default setting is determined
1945** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1946** if that compile-time option is omitted.
1947** The ability to disable the use of covering indices for full table scans
1948** is because some incorrectly coded legacy applications might malfunction
1949** when the optimization is enabled.  Providing the ability to
1950** disable the optimization allows the older, buggy application code to work
1951** without change even with newer versions of SQLite.
1952**
1953** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1954** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1955** <dd> These options are obsolete and should not be used by new code.
1956** They are retained for backwards compatibility but are now no-ops.
1957** </dd>
1958**
1959** [[SQLITE_CONFIG_SQLLOG]]
1960** <dt>SQLITE_CONFIG_SQLLOG
1961** <dd>This option is only available if sqlite is compiled with the
1962** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1963** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1964** The second should be of type (void*). The callback is invoked by the library
1965** in three separate circumstances, identified by the value passed as the
1966** fourth parameter. If the fourth parameter is 0, then the database connection
1967** passed as the second argument has just been opened. The third argument
1968** points to a buffer containing the name of the main database file. If the
1969** fourth parameter is 1, then the SQL statement that the third parameter
1970** points to has just been executed. Or, if the fourth parameter is 2, then
1971** the connection being passed as the second parameter is being closed. The
1972** third parameter is passed NULL In this case.  An example of using this
1973** configuration option can be seen in the "test_sqllog.c" source file in
1974** the canonical SQLite source tree.</dd>
1975**
1976** [[SQLITE_CONFIG_MMAP_SIZE]]
1977** <dt>SQLITE_CONFIG_MMAP_SIZE
1978** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1979** that are the default mmap size limit (the default setting for
1980** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1981** ^The default setting can be overridden by each database connection using
1982** either the [PRAGMA mmap_size] command, or by using the
1983** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
1984** will be silently truncated if necessary so that it does not exceed the
1985** compile-time maximum mmap size set by the
1986** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1987** ^If either argument to this option is negative, then that argument is
1988** changed to its compile-time default.
1989**
1990** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1991** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1992** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
1993** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
1994** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1995** that specifies the maximum size of the created heap.
1996**
1997** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
1998** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
1999** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2000** is a pointer to an integer and writes into that integer the number of extra
2001** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2002** The amount of extra space required can change depending on the compiler,
2003** target platform, and SQLite version.
2004**
2005** [[SQLITE_CONFIG_PMASZ]]
2006** <dt>SQLITE_CONFIG_PMASZ
2007** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2008** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2009** sorter to that integer.  The default minimum PMA Size is set by the
2010** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
2011** to help with sort operations when multithreaded sorting
2012** is enabled (using the [PRAGMA threads] command) and the amount of content
2013** to be sorted exceeds the page size times the minimum of the
2014** [PRAGMA cache_size] setting and this value.
2015** </dl>
2016*/
2017#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2018#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2019#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2020#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2021#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2022#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2023#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2024#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2025#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2026#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2027#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2028/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2029#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2030#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2031#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2032#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2033#define SQLITE_CONFIG_URI          17  /* int */
2034#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2035#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2036#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2037#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2038#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2039#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2040#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2041#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2042
2043/*
2044** CAPI3REF: Database Connection Configuration Options
2045**
2046** These constants are the available integer configuration options that
2047** can be passed as the second argument to the [sqlite3_db_config()] interface.
2048**
2049** New configuration options may be added in future releases of SQLite.
2050** Existing configuration options might be discontinued.  Applications
2051** should check the return code from [sqlite3_db_config()] to make sure that
2052** the call worked.  ^The [sqlite3_db_config()] interface will return a
2053** non-zero [error code] if a discontinued or unsupported configuration option
2054** is invoked.
2055**
2056** <dl>
2057** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2058** <dd> ^This option takes three additional arguments that determine the
2059** [lookaside memory allocator] configuration for the [database connection].
2060** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2061** pointer to a memory buffer to use for lookaside memory.
2062** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2063** may be NULL in which case SQLite will allocate the
2064** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2065** size of each lookaside buffer slot.  ^The third argument is the number of
2066** slots.  The size of the buffer in the first argument must be greater than
2067** or equal to the product of the second and third arguments.  The buffer
2068** must be aligned to an 8-byte boundary.  ^If the second argument to
2069** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2070** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2071** configuration for a database connection can only be changed when that
2072** connection is not currently using lookaside memory, or in other words
2073** when the "current value" returned by
2074** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2075** Any attempt to change the lookaside memory configuration when lookaside
2076** memory is in use leaves the configuration unchanged and returns
2077** [SQLITE_BUSY].)^</dd>
2078**
2079** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2080** <dd> ^This option is used to enable or disable the enforcement of
2081** [foreign key constraints].  There should be two additional arguments.
2082** The first argument is an integer which is 0 to disable FK enforcement,
2083** positive to enable FK enforcement or negative to leave FK enforcement
2084** unchanged.  The second parameter is a pointer to an integer into which
2085** is written 0 or 1 to indicate whether FK enforcement is off or on
2086** following this call.  The second parameter may be a NULL pointer, in
2087** which case the FK enforcement setting is not reported back. </dd>
2088**
2089** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2090** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2091** There should be two additional arguments.
2092** The first argument is an integer which is 0 to disable triggers,
2093** positive to enable triggers or negative to leave the setting unchanged.
2094** The second parameter is a pointer to an integer into which
2095** is written 0 or 1 to indicate whether triggers are disabled or enabled
2096** following this call.  The second parameter may be a NULL pointer, in
2097** which case the trigger setting is not reported back. </dd>
2098**
2099** </dl>
2100*/
2101#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2102#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2103#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2104
2105
2106/*
2107** CAPI3REF: Enable Or Disable Extended Result Codes
2108** METHOD: sqlite3
2109**
2110** ^The sqlite3_extended_result_codes() routine enables or disables the
2111** [extended result codes] feature of SQLite. ^The extended result
2112** codes are disabled by default for historical compatibility.
2113*/
2114SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
2115
2116/*
2117** CAPI3REF: Last Insert Rowid
2118** METHOD: sqlite3
2119**
2120** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2121** has a unique 64-bit signed
2122** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2123** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2124** names are not also used by explicitly declared columns. ^If
2125** the table has a column of type [INTEGER PRIMARY KEY] then that column
2126** is another alias for the rowid.
2127**
2128** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2129** most recent successful [INSERT] into a rowid table or [virtual table]
2130** on database connection D.
2131** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2132** ^If no successful [INSERT]s into rowid tables
2133** have ever occurred on the database connection D,
2134** then sqlite3_last_insert_rowid(D) returns zero.
2135**
2136** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2137** method, then this routine will return the [rowid] of the inserted
2138** row as long as the trigger or virtual table method is running.
2139** But once the trigger or virtual table method ends, the value returned
2140** by this routine reverts to what it was before the trigger or virtual
2141** table method began.)^
2142**
2143** ^An [INSERT] that fails due to a constraint violation is not a
2144** successful [INSERT] and does not change the value returned by this
2145** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2146** and INSERT OR ABORT make no changes to the return value of this
2147** routine when their insertion fails.  ^(When INSERT OR REPLACE
2148** encounters a constraint violation, it does not fail.  The
2149** INSERT continues to completion after deleting rows that caused
2150** the constraint problem so INSERT OR REPLACE will always change
2151** the return value of this interface.)^
2152**
2153** ^For the purposes of this routine, an [INSERT] is considered to
2154** be successful even if it is subsequently rolled back.
2155**
2156** This function is accessible to SQL statements via the
2157** [last_insert_rowid() SQL function].
2158**
2159** If a separate thread performs a new [INSERT] on the same
2160** database connection while the [sqlite3_last_insert_rowid()]
2161** function is running and thus changes the last insert [rowid],
2162** then the value returned by [sqlite3_last_insert_rowid()] is
2163** unpredictable and might not equal either the old or the new
2164** last insert [rowid].
2165*/
2166SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2167
2168/*
2169** CAPI3REF: Count The Number Of Rows Modified
2170** METHOD: sqlite3
2171**
2172** ^This function returns the number of rows modified, inserted or
2173** deleted by the most recently completed INSERT, UPDATE or DELETE
2174** statement on the database connection specified by the only parameter.
2175** ^Executing any other type of SQL statement does not modify the value
2176** returned by this function.
2177**
2178** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2179** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2180** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2181**
2182** Changes to a view that are intercepted by
2183** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2184** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2185** DELETE statement run on a view is always zero. Only changes made to real
2186** tables are counted.
2187**
2188** Things are more complicated if the sqlite3_changes() function is
2189** executed while a trigger program is running. This may happen if the
2190** program uses the [changes() SQL function], or if some other callback
2191** function invokes sqlite3_changes() directly. Essentially:
2192**
2193** <ul>
2194**   <li> ^(Before entering a trigger program the value returned by
2195**        sqlite3_changes() function is saved. After the trigger program
2196**        has finished, the original value is restored.)^
2197**
2198**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2199**        statement sets the value returned by sqlite3_changes()
2200**        upon completion as normal. Of course, this value will not include
2201**        any changes performed by sub-triggers, as the sqlite3_changes()
2202**        value will be saved and restored after each sub-trigger has run.)^
2203** </ul>
2204**
2205** ^This means that if the changes() SQL function (or similar) is used
2206** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2207** returns the value as set when the calling statement began executing.
2208** ^If it is used by the second or subsequent such statement within a trigger
2209** program, the value returned reflects the number of rows modified by the
2210** previous INSERT, UPDATE or DELETE statement within the same trigger.
2211**
2212** See also the [sqlite3_total_changes()] interface, the
2213** [count_changes pragma], and the [changes() SQL function].
2214**
2215** If a separate thread makes changes on the same database connection
2216** while [sqlite3_changes()] is running then the value returned
2217** is unpredictable and not meaningful.
2218*/
2219SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2220
2221/*
2222** CAPI3REF: Total Number Of Rows Modified
2223** METHOD: sqlite3
2224**
2225** ^This function returns the total number of rows inserted, modified or
2226** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2227** since the database connection was opened, including those executed as
2228** part of trigger programs. ^Executing any other type of SQL statement
2229** does not affect the value returned by sqlite3_total_changes().
2230**
2231** ^Changes made as part of [foreign key actions] are included in the
2232** count, but those made as part of REPLACE constraint resolution are
2233** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2234** are not counted.
2235**
2236** See also the [sqlite3_changes()] interface, the
2237** [count_changes pragma], and the [total_changes() SQL function].
2238**
2239** If a separate thread makes changes on the same database connection
2240** while [sqlite3_total_changes()] is running then the value
2241** returned is unpredictable and not meaningful.
2242*/
2243SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2244
2245/*
2246** CAPI3REF: Interrupt A Long-Running Query
2247** METHOD: sqlite3
2248**
2249** ^This function causes any pending database operation to abort and
2250** return at its earliest opportunity. This routine is typically
2251** called in response to a user action such as pressing "Cancel"
2252** or Ctrl-C where the user wants a long query operation to halt
2253** immediately.
2254**
2255** ^It is safe to call this routine from a thread different from the
2256** thread that is currently running the database operation.  But it
2257** is not safe to call this routine with a [database connection] that
2258** is closed or might close before sqlite3_interrupt() returns.
2259**
2260** ^If an SQL operation is very nearly finished at the time when
2261** sqlite3_interrupt() is called, then it might not have an opportunity
2262** to be interrupted and might continue to completion.
2263**
2264** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2265** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2266** that is inside an explicit transaction, then the entire transaction
2267** will be rolled back automatically.
2268**
2269** ^The sqlite3_interrupt(D) call is in effect until all currently running
2270** SQL statements on [database connection] D complete.  ^Any new SQL statements
2271** that are started after the sqlite3_interrupt() call and before the
2272** running statements reaches zero are interrupted as if they had been
2273** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2274** that are started after the running statement count reaches zero are
2275** not effected by the sqlite3_interrupt().
2276** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2277** SQL statements is a no-op and has no effect on SQL statements
2278** that are started after the sqlite3_interrupt() call returns.
2279**
2280** If the database connection closes while [sqlite3_interrupt()]
2281** is running then bad things will likely happen.
2282*/
2283SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2284
2285/*
2286** CAPI3REF: Determine If An SQL Statement Is Complete
2287**
2288** These routines are useful during command-line input to determine if the
2289** currently entered text seems to form a complete SQL statement or
2290** if additional input is needed before sending the text into
2291** SQLite for parsing.  ^These routines return 1 if the input string
2292** appears to be a complete SQL statement.  ^A statement is judged to be
2293** complete if it ends with a semicolon token and is not a prefix of a
2294** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2295** string literals or quoted identifier names or comments are not
2296** independent tokens (they are part of the token in which they are
2297** embedded) and thus do not count as a statement terminator.  ^Whitespace
2298** and comments that follow the final semicolon are ignored.
2299**
2300** ^These routines return 0 if the statement is incomplete.  ^If a
2301** memory allocation fails, then SQLITE_NOMEM is returned.
2302**
2303** ^These routines do not parse the SQL statements thus
2304** will not detect syntactically incorrect SQL.
2305**
2306** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2307** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2308** automatically by sqlite3_complete16().  If that initialization fails,
2309** then the return value from sqlite3_complete16() will be non-zero
2310** regardless of whether or not the input SQL is complete.)^
2311**
2312** The input to [sqlite3_complete()] must be a zero-terminated
2313** UTF-8 string.
2314**
2315** The input to [sqlite3_complete16()] must be a zero-terminated
2316** UTF-16 string in native byte order.
2317*/
2318SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2319SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2320
2321/*
2322** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2323** KEYWORDS: {busy-handler callback} {busy handler}
2324** METHOD: sqlite3
2325**
2326** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2327** that might be invoked with argument P whenever
2328** an attempt is made to access a database table associated with
2329** [database connection] D when another thread
2330** or process has the table locked.
2331** The sqlite3_busy_handler() interface is used to implement
2332** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2333**
2334** ^If the busy callback is NULL, then [SQLITE_BUSY]
2335** is returned immediately upon encountering the lock.  ^If the busy callback
2336** is not NULL, then the callback might be invoked with two arguments.
2337**
2338** ^The first argument to the busy handler is a copy of the void* pointer which
2339** is the third argument to sqlite3_busy_handler().  ^The second argument to
2340** the busy handler callback is the number of times that the busy handler has
2341** been invoked previously for the same locking event.  ^If the
2342** busy callback returns 0, then no additional attempts are made to
2343** access the database and [SQLITE_BUSY] is returned
2344** to the application.
2345** ^If the callback returns non-zero, then another attempt
2346** is made to access the database and the cycle repeats.
2347**
2348** The presence of a busy handler does not guarantee that it will be invoked
2349** when there is lock contention. ^If SQLite determines that invoking the busy
2350** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2351** to the application instead of invoking the
2352** busy handler.
2353** Consider a scenario where one process is holding a read lock that
2354** it is trying to promote to a reserved lock and
2355** a second process is holding a reserved lock that it is trying
2356** to promote to an exclusive lock.  The first process cannot proceed
2357** because it is blocked by the second and the second process cannot
2358** proceed because it is blocked by the first.  If both processes
2359** invoke the busy handlers, neither will make any progress.  Therefore,
2360** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2361** will induce the first process to release its read lock and allow
2362** the second process to proceed.
2363**
2364** ^The default busy callback is NULL.
2365**
2366** ^(There can only be a single busy handler defined for each
2367** [database connection].  Setting a new busy handler clears any
2368** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2369** or evaluating [PRAGMA busy_timeout=N] will change the
2370** busy handler and thus clear any previously set busy handler.
2371**
2372** The busy callback should not take any actions which modify the
2373** database connection that invoked the busy handler.  In other words,
2374** the busy handler is not reentrant.  Any such actions
2375** result in undefined behavior.
2376**
2377** A busy handler must not close the database connection
2378** or [prepared statement] that invoked the busy handler.
2379*/
2380SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2381
2382/*
2383** CAPI3REF: Set A Busy Timeout
2384** METHOD: sqlite3
2385**
2386** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2387** for a specified amount of time when a table is locked.  ^The handler
2388** will sleep multiple times until at least "ms" milliseconds of sleeping
2389** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2390** the handler returns 0 which causes [sqlite3_step()] to return
2391** [SQLITE_BUSY].
2392**
2393** ^Calling this routine with an argument less than or equal to zero
2394** turns off all busy handlers.
2395**
2396** ^(There can only be a single busy handler for a particular
2397** [database connection] at any given moment.  If another busy handler
2398** was defined  (using [sqlite3_busy_handler()]) prior to calling
2399** this routine, that other busy handler is cleared.)^
2400**
2401** See also:  [PRAGMA busy_timeout]
2402*/
2403SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2404
2405/*
2406** CAPI3REF: Convenience Routines For Running Queries
2407** METHOD: sqlite3
2408**
2409** This is a legacy interface that is preserved for backwards compatibility.
2410** Use of this interface is not recommended.
2411**
2412** Definition: A <b>result table</b> is memory data structure created by the
2413** [sqlite3_get_table()] interface.  A result table records the
2414** complete query results from one or more queries.
2415**
2416** The table conceptually has a number of rows and columns.  But
2417** these numbers are not part of the result table itself.  These
2418** numbers are obtained separately.  Let N be the number of rows
2419** and M be the number of columns.
2420**
2421** A result table is an array of pointers to zero-terminated UTF-8 strings.
2422** There are (N+1)*M elements in the array.  The first M pointers point
2423** to zero-terminated strings that  contain the names of the columns.
2424** The remaining entries all point to query results.  NULL values result
2425** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2426** string representation as returned by [sqlite3_column_text()].
2427**
2428** A result table might consist of one or more memory allocations.
2429** It is not safe to pass a result table directly to [sqlite3_free()].
2430** A result table should be deallocated using [sqlite3_free_table()].
2431**
2432** ^(As an example of the result table format, suppose a query result
2433** is as follows:
2434**
2435** <blockquote><pre>
2436**        Name        | Age
2437**        -----------------------
2438**        Alice       | 43
2439**        Bob         | 28
2440**        Cindy       | 21
2441** </pre></blockquote>
2442**
2443** There are two column (M==2) and three rows (N==3).  Thus the
2444** result table has 8 entries.  Suppose the result table is stored
2445** in an array names azResult.  Then azResult holds this content:
2446**
2447** <blockquote><pre>
2448**        azResult&#91;0] = "Name";
2449**        azResult&#91;1] = "Age";
2450**        azResult&#91;2] = "Alice";
2451**        azResult&#91;3] = "43";
2452**        azResult&#91;4] = "Bob";
2453**        azResult&#91;5] = "28";
2454**        azResult&#91;6] = "Cindy";
2455**        azResult&#91;7] = "21";
2456** </pre></blockquote>)^
2457**
2458** ^The sqlite3_get_table() function evaluates one or more
2459** semicolon-separated SQL statements in the zero-terminated UTF-8
2460** string of its 2nd parameter and returns a result table to the
2461** pointer given in its 3rd parameter.
2462**
2463** After the application has finished with the result from sqlite3_get_table(),
2464** it must pass the result table pointer to sqlite3_free_table() in order to
2465** release the memory that was malloced.  Because of the way the
2466** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2467** function must not try to call [sqlite3_free()] directly.  Only
2468** [sqlite3_free_table()] is able to release the memory properly and safely.
2469**
2470** The sqlite3_get_table() interface is implemented as a wrapper around
2471** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2472** to any internal data structures of SQLite.  It uses only the public
2473** interface defined here.  As a consequence, errors that occur in the
2474** wrapper layer outside of the internal [sqlite3_exec()] call are not
2475** reflected in subsequent calls to [sqlite3_errcode()] or
2476** [sqlite3_errmsg()].
2477*/
2478SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2479  sqlite3 *db,          /* An open database */
2480  const char *zSql,     /* SQL to be evaluated */
2481  char ***pazResult,    /* Results of the query */
2482  int *pnRow,           /* Number of result rows written here */
2483  int *pnColumn,        /* Number of result columns written here */
2484  char **pzErrmsg       /* Error msg written here */
2485);
2486SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2487
2488/*
2489** CAPI3REF: Formatted String Printing Functions
2490**
2491** These routines are work-alikes of the "printf()" family of functions
2492** from the standard C library.
2493** These routines understand most of the common K&R formatting options,
2494** plus some additional non-standard formats, detailed below.
2495** Note that some of the more obscure formatting options from recent
2496** C-library standards are omitted from this implementation.
2497**
2498** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2499** results into memory obtained from [sqlite3_malloc()].
2500** The strings returned by these two routines should be
2501** released by [sqlite3_free()].  ^Both routines return a
2502** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2503** memory to hold the resulting string.
2504**
2505** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2506** the standard C library.  The result is written into the
2507** buffer supplied as the second parameter whose size is given by
2508** the first parameter. Note that the order of the
2509** first two parameters is reversed from snprintf().)^  This is an
2510** historical accident that cannot be fixed without breaking
2511** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2512** returns a pointer to its buffer instead of the number of
2513** characters actually written into the buffer.)^  We admit that
2514** the number of characters written would be a more useful return
2515** value but we cannot change the implementation of sqlite3_snprintf()
2516** now without breaking compatibility.
2517**
2518** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2519** guarantees that the buffer is always zero-terminated.  ^The first
2520** parameter "n" is the total size of the buffer, including space for
2521** the zero terminator.  So the longest string that can be completely
2522** written will be n-1 characters.
2523**
2524** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2525**
2526** These routines all implement some additional formatting
2527** options that are useful for constructing SQL statements.
2528** All of the usual printf() formatting options apply.  In addition, there
2529** is are "%q", "%Q", "%w" and "%z" options.
2530**
2531** ^(The %q option works like %s in that it substitutes a nul-terminated
2532** string from the argument list.  But %q also doubles every '\'' character.
2533** %q is designed for use inside a string literal.)^  By doubling each '\''
2534** character it escapes that character and allows it to be inserted into
2535** the string.
2536**
2537** For example, assume the string variable zText contains text as follows:
2538**
2539** <blockquote><pre>
2540**  char *zText = "It's a happy day!";
2541** </pre></blockquote>
2542**
2543** One can use this text in an SQL statement as follows:
2544**
2545** <blockquote><pre>
2546**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2547**  sqlite3_exec(db, zSQL, 0, 0, 0);
2548**  sqlite3_free(zSQL);
2549** </pre></blockquote>
2550**
2551** Because the %q format string is used, the '\'' character in zText
2552** is escaped and the SQL generated is as follows:
2553**
2554** <blockquote><pre>
2555**  INSERT INTO table1 VALUES('It''s a happy day!')
2556** </pre></blockquote>
2557**
2558** This is correct.  Had we used %s instead of %q, the generated SQL
2559** would have looked like this:
2560**
2561** <blockquote><pre>
2562**  INSERT INTO table1 VALUES('It's a happy day!');
2563** </pre></blockquote>
2564**
2565** This second example is an SQL syntax error.  As a general rule you should
2566** always use %q instead of %s when inserting text into a string literal.
2567**
2568** ^(The %Q option works like %q except it also adds single quotes around
2569** the outside of the total string.  Additionally, if the parameter in the
2570** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2571** single quotes).)^  So, for example, one could say:
2572**
2573** <blockquote><pre>
2574**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2575**  sqlite3_exec(db, zSQL, 0, 0, 0);
2576**  sqlite3_free(zSQL);
2577** </pre></blockquote>
2578**
2579** The code above will render a correct SQL statement in the zSQL
2580** variable even if the zText variable is a NULL pointer.
2581**
2582** ^(The "%w" formatting option is like "%q" except that it expects to
2583** be contained within double-quotes instead of single quotes, and it
2584** escapes the double-quote character instead of the single-quote
2585** character.)^  The "%w" formatting option is intended for safely inserting
2586** table and column names into a constructed SQL statement.
2587**
2588** ^(The "%z" formatting option works like "%s" but with the
2589** addition that after the string has been read and copied into
2590** the result, [sqlite3_free()] is called on the input string.)^
2591*/
2592SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2593SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2594SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2595SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2596
2597/*
2598** CAPI3REF: Memory Allocation Subsystem
2599**
2600** The SQLite core uses these three routines for all of its own
2601** internal memory allocation needs. "Core" in the previous sentence
2602** does not include operating-system specific VFS implementation.  The
2603** Windows VFS uses native malloc() and free() for some operations.
2604**
2605** ^The sqlite3_malloc() routine returns a pointer to a block
2606** of memory at least N bytes in length, where N is the parameter.
2607** ^If sqlite3_malloc() is unable to obtain sufficient free
2608** memory, it returns a NULL pointer.  ^If the parameter N to
2609** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2610** a NULL pointer.
2611**
2612** ^The sqlite3_malloc64(N) routine works just like
2613** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2614** of a signed 32-bit integer.
2615**
2616** ^Calling sqlite3_free() with a pointer previously returned
2617** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2618** that it might be reused.  ^The sqlite3_free() routine is
2619** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2620** to sqlite3_free() is harmless.  After being freed, memory
2621** should neither be read nor written.  Even reading previously freed
2622** memory might result in a segmentation fault or other severe error.
2623** Memory corruption, a segmentation fault, or other severe error
2624** might result if sqlite3_free() is called with a non-NULL pointer that
2625** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2626**
2627** ^The sqlite3_realloc(X,N) interface attempts to resize a
2628** prior memory allocation X to be at least N bytes.
2629** ^If the X parameter to sqlite3_realloc(X,N)
2630** is a NULL pointer then its behavior is identical to calling
2631** sqlite3_malloc(N).
2632** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2633** negative then the behavior is exactly the same as calling
2634** sqlite3_free(X).
2635** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2636** of at least N bytes in size or NULL if insufficient memory is available.
2637** ^If M is the size of the prior allocation, then min(N,M) bytes
2638** of the prior allocation are copied into the beginning of buffer returned
2639** by sqlite3_realloc(X,N) and the prior allocation is freed.
2640** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2641** prior allocation is not freed.
2642**
2643** ^The sqlite3_realloc64(X,N) interfaces works the same as
2644** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2645** of a 32-bit signed integer.
2646**
2647** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2648** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2649** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2650** ^The value returned by sqlite3_msize(X) might be larger than the number
2651** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2652** sqlite3_msize(X) returns zero.  If X points to something that is not
2653** the beginning of memory allocation, or if it points to a formerly
2654** valid memory allocation that has now been freed, then the behavior
2655** of sqlite3_msize(X) is undefined and possibly harmful.
2656**
2657** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2658** sqlite3_malloc64(), and sqlite3_realloc64()
2659** is always aligned to at least an 8 byte boundary, or to a
2660** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2661** option is used.
2662**
2663** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2664** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2665** implementation of these routines to be omitted.  That capability
2666** is no longer provided.  Only built-in memory allocators can be used.
2667**
2668** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2669** the system malloc() and free() directly when converting
2670** filenames between the UTF-8 encoding used by SQLite
2671** and whatever filename encoding is used by the particular Windows
2672** installation.  Memory allocation errors were detected, but
2673** they were reported back as [SQLITE_CANTOPEN] or
2674** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2675**
2676** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2677** must be either NULL or else pointers obtained from a prior
2678** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2679** not yet been released.
2680**
2681** The application must not read or write any part of
2682** a block of memory after it has been released using
2683** [sqlite3_free()] or [sqlite3_realloc()].
2684*/
2685SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2686SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2687SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2688SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2689SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2690SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2691
2692/*
2693** CAPI3REF: Memory Allocator Statistics
2694**
2695** SQLite provides these two interfaces for reporting on the status
2696** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2697** routines, which form the built-in memory allocation subsystem.
2698**
2699** ^The [sqlite3_memory_used()] routine returns the number of bytes
2700** of memory currently outstanding (malloced but not freed).
2701** ^The [sqlite3_memory_highwater()] routine returns the maximum
2702** value of [sqlite3_memory_used()] since the high-water mark
2703** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2704** [sqlite3_memory_highwater()] include any overhead
2705** added by SQLite in its implementation of [sqlite3_malloc()],
2706** but not overhead added by the any underlying system library
2707** routines that [sqlite3_malloc()] may call.
2708**
2709** ^The memory high-water mark is reset to the current value of
2710** [sqlite3_memory_used()] if and only if the parameter to
2711** [sqlite3_memory_highwater()] is true.  ^The value returned
2712** by [sqlite3_memory_highwater(1)] is the high-water mark
2713** prior to the reset.
2714*/
2715SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2716SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2717
2718/*
2719** CAPI3REF: Pseudo-Random Number Generator
2720**
2721** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2722** select random [ROWID | ROWIDs] when inserting new records into a table that
2723** already uses the largest possible [ROWID].  The PRNG is also used for
2724** the build-in random() and randomblob() SQL functions.  This interface allows
2725** applications to access the same PRNG for other purposes.
2726**
2727** ^A call to this routine stores N bytes of randomness into buffer P.
2728** ^The P parameter can be a NULL pointer.
2729**
2730** ^If this routine has not been previously called or if the previous
2731** call had N less than one or a NULL pointer for P, then the PRNG is
2732** seeded using randomness obtained from the xRandomness method of
2733** the default [sqlite3_vfs] object.
2734** ^If the previous call to this routine had an N of 1 or more and a
2735** non-NULL P then the pseudo-randomness is generated
2736** internally and without recourse to the [sqlite3_vfs] xRandomness
2737** method.
2738*/
2739SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2740
2741/*
2742** CAPI3REF: Compile-Time Authorization Callbacks
2743** METHOD: sqlite3
2744**
2745** ^This routine registers an authorizer callback with a particular
2746** [database connection], supplied in the first argument.
2747** ^The authorizer callback is invoked as SQL statements are being compiled
2748** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2749** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2750** points during the compilation process, as logic is being created
2751** to perform various actions, the authorizer callback is invoked to
2752** see if those actions are allowed.  ^The authorizer callback should
2753** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2754** specific action but allow the SQL statement to continue to be
2755** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2756** rejected with an error.  ^If the authorizer callback returns
2757** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2758** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2759** the authorizer will fail with an error message.
2760**
2761** When the callback returns [SQLITE_OK], that means the operation
2762** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2763** [sqlite3_prepare_v2()] or equivalent call that triggered the
2764** authorizer will fail with an error message explaining that
2765** access is denied.
2766**
2767** ^The first parameter to the authorizer callback is a copy of the third
2768** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2769** to the callback is an integer [SQLITE_COPY | action code] that specifies
2770** the particular action to be authorized. ^The third through sixth parameters
2771** to the callback are zero-terminated strings that contain additional
2772** details about the action to be authorized.
2773**
2774** ^If the action code is [SQLITE_READ]
2775** and the callback returns [SQLITE_IGNORE] then the
2776** [prepared statement] statement is constructed to substitute
2777** a NULL value in place of the table column that would have
2778** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2779** return can be used to deny an untrusted user access to individual
2780** columns of a table.
2781** ^If the action code is [SQLITE_DELETE] and the callback returns
2782** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2783** [truncate optimization] is disabled and all rows are deleted individually.
2784**
2785** An authorizer is used when [sqlite3_prepare | preparing]
2786** SQL statements from an untrusted source, to ensure that the SQL statements
2787** do not try to access data they are not allowed to see, or that they do not
2788** try to execute malicious statements that damage the database.  For
2789** example, an application may allow a user to enter arbitrary
2790** SQL queries for evaluation by a database.  But the application does
2791** not want the user to be able to make arbitrary changes to the
2792** database.  An authorizer could then be put in place while the
2793** user-entered SQL is being [sqlite3_prepare | prepared] that
2794** disallows everything except [SELECT] statements.
2795**
2796** Applications that need to process SQL from untrusted sources
2797** might also consider lowering resource limits using [sqlite3_limit()]
2798** and limiting database size using the [max_page_count] [PRAGMA]
2799** in addition to using an authorizer.
2800**
2801** ^(Only a single authorizer can be in place on a database connection
2802** at a time.  Each call to sqlite3_set_authorizer overrides the
2803** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2804** The authorizer is disabled by default.
2805**
2806** The authorizer callback must not do anything that will modify
2807** the database connection that invoked the authorizer callback.
2808** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2809** database connections for the meaning of "modify" in this paragraph.
2810**
2811** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2812** statement might be re-prepared during [sqlite3_step()] due to a
2813** schema change.  Hence, the application should ensure that the
2814** correct authorizer callback remains in place during the [sqlite3_step()].
2815**
2816** ^Note that the authorizer callback is invoked only during
2817** [sqlite3_prepare()] or its variants.  Authorization is not
2818** performed during statement evaluation in [sqlite3_step()], unless
2819** as stated in the previous paragraph, sqlite3_step() invokes
2820** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2821*/
2822SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2823  sqlite3*,
2824  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2825  void *pUserData
2826);
2827
2828/*
2829** CAPI3REF: Authorizer Return Codes
2830**
2831** The [sqlite3_set_authorizer | authorizer callback function] must
2832** return either [SQLITE_OK] or one of these two constants in order
2833** to signal SQLite whether or not the action is permitted.  See the
2834** [sqlite3_set_authorizer | authorizer documentation] for additional
2835** information.
2836**
2837** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2838** returned from the [sqlite3_vtab_on_conflict()] interface.
2839*/
2840#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2841#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2842
2843/*
2844** CAPI3REF: Authorizer Action Codes
2845**
2846** The [sqlite3_set_authorizer()] interface registers a callback function
2847** that is invoked to authorize certain SQL statement actions.  The
2848** second parameter to the callback is an integer code that specifies
2849** what action is being authorized.  These are the integer action codes that
2850** the authorizer callback may be passed.
2851**
2852** These action code values signify what kind of operation is to be
2853** authorized.  The 3rd and 4th parameters to the authorization
2854** callback function will be parameters or NULL depending on which of these
2855** codes is used as the second parameter.  ^(The 5th parameter to the
2856** authorizer callback is the name of the database ("main", "temp",
2857** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2858** is the name of the inner-most trigger or view that is responsible for
2859** the access attempt or NULL if this access attempt is directly from
2860** top-level SQL code.
2861*/
2862/******************************************* 3rd ************ 4th ***********/
2863#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2864#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2865#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2866#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2867#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2868#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2869#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2870#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2871#define SQLITE_DELETE                9   /* Table Name      NULL            */
2872#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2873#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2874#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2875#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2876#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2877#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2878#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2879#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2880#define SQLITE_INSERT               18   /* Table Name      NULL            */
2881#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2882#define SQLITE_READ                 20   /* Table Name      Column Name     */
2883#define SQLITE_SELECT               21   /* NULL            NULL            */
2884#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2885#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2886#define SQLITE_ATTACH               24   /* Filename        NULL            */
2887#define SQLITE_DETACH               25   /* Database Name   NULL            */
2888#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2889#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2890#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2891#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2892#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2893#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2894#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2895#define SQLITE_COPY                  0   /* No longer used */
2896#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
2897
2898/*
2899** CAPI3REF: Tracing And Profiling Functions
2900** METHOD: sqlite3
2901**
2902** These routines register callback functions that can be used for
2903** tracing and profiling the execution of SQL statements.
2904**
2905** ^The callback function registered by sqlite3_trace() is invoked at
2906** various times when an SQL statement is being run by [sqlite3_step()].
2907** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2908** SQL statement text as the statement first begins executing.
2909** ^(Additional sqlite3_trace() callbacks might occur
2910** as each triggered subprogram is entered.  The callbacks for triggers
2911** contain a UTF-8 SQL comment that identifies the trigger.)^
2912**
2913** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2914** the length of [bound parameter] expansion in the output of sqlite3_trace().
2915**
2916** ^The callback function registered by sqlite3_profile() is invoked
2917** as each SQL statement finishes.  ^The profile callback contains
2918** the original statement text and an estimate of wall-clock time
2919** of how long that statement took to run.  ^The profile callback
2920** time is in units of nanoseconds, however the current implementation
2921** is only capable of millisecond resolution so the six least significant
2922** digits in the time are meaningless.  Future versions of SQLite
2923** might provide greater resolution on the profiler callback.  The
2924** sqlite3_profile() function is considered experimental and is
2925** subject to change in future versions of SQLite.
2926*/
2927SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2928SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
2929   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2930
2931/*
2932** CAPI3REF: Query Progress Callbacks
2933** METHOD: sqlite3
2934**
2935** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2936** function X to be invoked periodically during long running calls to
2937** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2938** database connection D.  An example use for this
2939** interface is to keep a GUI updated during a large query.
2940**
2941** ^The parameter P is passed through as the only parameter to the
2942** callback function X.  ^The parameter N is the approximate number of
2943** [virtual machine instructions] that are evaluated between successive
2944** invocations of the callback X.  ^If N is less than one then the progress
2945** handler is disabled.
2946**
2947** ^Only a single progress handler may be defined at one time per
2948** [database connection]; setting a new progress handler cancels the
2949** old one.  ^Setting parameter X to NULL disables the progress handler.
2950** ^The progress handler is also disabled by setting N to a value less
2951** than 1.
2952**
2953** ^If the progress callback returns non-zero, the operation is
2954** interrupted.  This feature can be used to implement a
2955** "Cancel" button on a GUI progress dialog box.
2956**
2957** The progress handler callback must not do anything that will modify
2958** the database connection that invoked the progress handler.
2959** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2960** database connections for the meaning of "modify" in this paragraph.
2961**
2962*/
2963SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2964
2965/*
2966** CAPI3REF: Opening A New Database Connection
2967** CONSTRUCTOR: sqlite3
2968**
2969** ^These routines open an SQLite database file as specified by the
2970** filename argument. ^The filename argument is interpreted as UTF-8 for
2971** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2972** order for sqlite3_open16(). ^(A [database connection] handle is usually
2973** returned in *ppDb, even if an error occurs.  The only exception is that
2974** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2975** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2976** object.)^ ^(If the database is opened (and/or created) successfully, then
2977** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2978** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2979** an English language description of the error following a failure of any
2980** of the sqlite3_open() routines.
2981**
2982** ^The default encoding will be UTF-8 for databases created using
2983** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
2984** created using sqlite3_open16() will be UTF-16 in the native byte order.
2985**
2986** Whether or not an error occurs when it is opened, resources
2987** associated with the [database connection] handle should be released by
2988** passing it to [sqlite3_close()] when it is no longer required.
2989**
2990** The sqlite3_open_v2() interface works like sqlite3_open()
2991** except that it accepts two additional parameters for additional control
2992** over the new database connection.  ^(The flags parameter to
2993** sqlite3_open_v2() can take one of
2994** the following three values, optionally combined with the
2995** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2996** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2997**
2998** <dl>
2999** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3000** <dd>The database is opened in read-only mode.  If the database does not
3001** already exist, an error is returned.</dd>)^
3002**
3003** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3004** <dd>The database is opened for reading and writing if possible, or reading
3005** only if the file is write protected by the operating system.  In either
3006** case the database must already exist, otherwise an error is returned.</dd>)^
3007**
3008** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3009** <dd>The database is opened for reading and writing, and is created if
3010** it does not already exist. This is the behavior that is always used for
3011** sqlite3_open() and sqlite3_open16().</dd>)^
3012** </dl>
3013**
3014** If the 3rd parameter to sqlite3_open_v2() is not one of the
3015** combinations shown above optionally combined with other
3016** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3017** then the behavior is undefined.
3018**
3019** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3020** opens in the multi-thread [threading mode] as long as the single-thread
3021** mode has not been set at compile-time or start-time.  ^If the
3022** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3023** in the serialized [threading mode] unless single-thread was
3024** previously selected at compile-time or start-time.
3025** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3026** eligible to use [shared cache mode], regardless of whether or not shared
3027** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3028** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3029** participate in [shared cache mode] even if it is enabled.
3030**
3031** ^The fourth parameter to sqlite3_open_v2() is the name of the
3032** [sqlite3_vfs] object that defines the operating system interface that
3033** the new database connection should use.  ^If the fourth parameter is
3034** a NULL pointer then the default [sqlite3_vfs] object is used.
3035**
3036** ^If the filename is ":memory:", then a private, temporary in-memory database
3037** is created for the connection.  ^This in-memory database will vanish when
3038** the database connection is closed.  Future versions of SQLite might
3039** make use of additional special filenames that begin with the ":" character.
3040** It is recommended that when a database filename actually does begin with
3041** a ":" character you should prefix the filename with a pathname such as
3042** "./" to avoid ambiguity.
3043**
3044** ^If the filename is an empty string, then a private, temporary
3045** on-disk database will be created.  ^This private database will be
3046** automatically deleted as soon as the database connection is closed.
3047**
3048** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3049**
3050** ^If [URI filename] interpretation is enabled, and the filename argument
3051** begins with "file:", then the filename is interpreted as a URI. ^URI
3052** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3053** set in the fourth argument to sqlite3_open_v2(), or if it has
3054** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3055** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3056** As of SQLite version 3.7.7, URI filename interpretation is turned off
3057** by default, but future releases of SQLite might enable URI filename
3058** interpretation by default.  See "[URI filenames]" for additional
3059** information.
3060**
3061** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3062** authority, then it must be either an empty string or the string
3063** "localhost". ^If the authority is not an empty string or "localhost", an
3064** error is returned to the caller. ^The fragment component of a URI, if
3065** present, is ignored.
3066**
3067** ^SQLite uses the path component of the URI as the name of the disk file
3068** which contains the database. ^If the path begins with a '/' character,
3069** then it is interpreted as an absolute path. ^If the path does not begin
3070** with a '/' (meaning that the authority section is omitted from the URI)
3071** then the path is interpreted as a relative path.
3072** ^(On windows, the first component of an absolute path
3073** is a drive specification (e.g. "C:").)^
3074**
3075** [[core URI query parameters]]
3076** The query component of a URI may contain parameters that are interpreted
3077** either by SQLite itself, or by a [VFS | custom VFS implementation].
3078** SQLite and its built-in [VFSes] interpret the
3079** following query parameters:
3080**
3081** <ul>
3082**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3083**     a VFS object that provides the operating system interface that should
3084**     be used to access the database file on disk. ^If this option is set to
3085**     an empty string the default VFS object is used. ^Specifying an unknown
3086**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3087**     present, then the VFS specified by the option takes precedence over
3088**     the value passed as the fourth parameter to sqlite3_open_v2().
3089**
3090**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3091**     "rwc", or "memory". Attempting to set it to any other value is
3092**     an error)^.
3093**     ^If "ro" is specified, then the database is opened for read-only
3094**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3095**     third argument to sqlite3_open_v2(). ^If the mode option is set to
3096**     "rw", then the database is opened for read-write (but not create)
3097**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3098**     been set. ^Value "rwc" is equivalent to setting both
3099**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3100**     set to "memory" then a pure [in-memory database] that never reads
3101**     or writes from disk is used. ^It is an error to specify a value for
3102**     the mode parameter that is less restrictive than that specified by
3103**     the flags passed in the third parameter to sqlite3_open_v2().
3104**
3105**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3106**     "private". ^Setting it to "shared" is equivalent to setting the
3107**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3108**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3109**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3110**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3111**     a URI filename, its value overrides any behavior requested by setting
3112**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3113**
3114**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3115**     [powersafe overwrite] property does or does not apply to the
3116**     storage media on which the database file resides.
3117**
3118**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3119**     which if set disables file locking in rollback journal modes.  This
3120**     is useful for accessing a database on a filesystem that does not
3121**     support locking.  Caution:  Database corruption might result if two
3122**     or more processes write to the same database and any one of those
3123**     processes uses nolock=1.
3124**
3125**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3126**     parameter that indicates that the database file is stored on
3127**     read-only media.  ^When immutable is set, SQLite assumes that the
3128**     database file cannot be changed, even by a process with higher
3129**     privilege, and so the database is opened read-only and all locking
3130**     and change detection is disabled.  Caution: Setting the immutable
3131**     property on a database file that does in fact change can result
3132**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
3133**     See also: [SQLITE_IOCAP_IMMUTABLE].
3134**
3135** </ul>
3136**
3137** ^Specifying an unknown parameter in the query component of a URI is not an
3138** error.  Future versions of SQLite might understand additional query
3139** parameters.  See "[query parameters with special meaning to SQLite]" for
3140** additional information.
3141**
3142** [[URI filename examples]] <h3>URI filename examples</h3>
3143**
3144** <table border="1" align=center cellpadding=5>
3145** <tr><th> URI filenames <th> Results
3146** <tr><td> file:data.db <td>
3147**          Open the file "data.db" in the current directory.
3148** <tr><td> file:/home/fred/data.db<br>
3149**          file:///home/fred/data.db <br>
3150**          file://localhost/home/fred/data.db <br> <td>
3151**          Open the database file "/home/fred/data.db".
3152** <tr><td> file://darkstar/home/fred/data.db <td>
3153**          An error. "darkstar" is not a recognized authority.
3154** <tr><td style="white-space:nowrap">
3155**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3156**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3157**          C:. Note that the %20 escaping in this example is not strictly
3158**          necessary - space characters can be used literally
3159**          in URI filenames.
3160** <tr><td> file:data.db?mode=ro&cache=private <td>
3161**          Open file "data.db" in the current directory for read-only access.
3162**          Regardless of whether or not shared-cache mode is enabled by
3163**          default, use a private cache.
3164** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3165**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3166**          that uses dot-files in place of posix advisory locking.
3167** <tr><td> file:data.db?mode=readonly <td>
3168**          An error. "readonly" is not a valid option for the "mode" parameter.
3169** </table>
3170**
3171** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3172** query components of a URI. A hexadecimal escape sequence consists of a
3173** percent sign - "%" - followed by exactly two hexadecimal digits
3174** specifying an octet value. ^Before the path or query components of a
3175** URI filename are interpreted, they are encoded using UTF-8 and all
3176** hexadecimal escape sequences replaced by a single byte containing the
3177** corresponding octet. If this process generates an invalid UTF-8 encoding,
3178** the results are undefined.
3179**
3180** <b>Note to Windows users:</b>  The encoding used for the filename argument
3181** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3182** codepage is currently defined.  Filenames containing international
3183** characters must be converted to UTF-8 prior to passing them into
3184** sqlite3_open() or sqlite3_open_v2().
3185**
3186** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3187** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3188** features that require the use of temporary files may fail.
3189**
3190** See also: [sqlite3_temp_directory]
3191*/
3192SQLITE_API int SQLITE_STDCALL sqlite3_open(
3193  const char *filename,   /* Database filename (UTF-8) */
3194  sqlite3 **ppDb          /* OUT: SQLite db handle */
3195);
3196SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3197  const void *filename,   /* Database filename (UTF-16) */
3198  sqlite3 **ppDb          /* OUT: SQLite db handle */
3199);
3200SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3201  const char *filename,   /* Database filename (UTF-8) */
3202  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3203  int flags,              /* Flags */
3204  const char *zVfs        /* Name of VFS module to use */
3205);
3206
3207/*
3208** CAPI3REF: Obtain Values For URI Parameters
3209**
3210** These are utility routines, useful to VFS implementations, that check
3211** to see if a database file was a URI that contained a specific query
3212** parameter, and if so obtains the value of that query parameter.
3213**
3214** If F is the database filename pointer passed into the xOpen() method of
3215** a VFS implementation when the flags parameter to xOpen() has one or
3216** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3217** P is the name of the query parameter, then
3218** sqlite3_uri_parameter(F,P) returns the value of the P
3219** parameter if it exists or a NULL pointer if P does not appear as a
3220** query parameter on F.  If P is a query parameter of F
3221** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3222** a pointer to an empty string.
3223**
3224** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3225** parameter and returns true (1) or false (0) according to the value
3226** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3227** value of query parameter P is one of "yes", "true", or "on" in any
3228** case or if the value begins with a non-zero number.  The
3229** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3230** query parameter P is one of "no", "false", or "off" in any case or
3231** if the value begins with a numeric zero.  If P is not a query
3232** parameter on F or if the value of P is does not match any of the
3233** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3234**
3235** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3236** 64-bit signed integer and returns that integer, or D if P does not
3237** exist.  If the value of P is something other than an integer, then
3238** zero is returned.
3239**
3240** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3241** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3242** is not a database file pathname pointer that SQLite passed into the xOpen
3243** VFS method, then the behavior of this routine is undefined and probably
3244** undesirable.
3245*/
3246SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3247SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3248SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3249
3250
3251/*
3252** CAPI3REF: Error Codes And Messages
3253** METHOD: sqlite3
3254**
3255** ^If the most recent sqlite3_* API call associated with
3256** [database connection] D failed, then the sqlite3_errcode(D) interface
3257** returns the numeric [result code] or [extended result code] for that
3258** API call.
3259** If the most recent API call was successful,
3260** then the return value from sqlite3_errcode() is undefined.
3261** ^The sqlite3_extended_errcode()
3262** interface is the same except that it always returns the
3263** [extended result code] even when extended result codes are
3264** disabled.
3265**
3266** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3267** text that describes the error, as either UTF-8 or UTF-16 respectively.
3268** ^(Memory to hold the error message string is managed internally.
3269** The application does not need to worry about freeing the result.
3270** However, the error string might be overwritten or deallocated by
3271** subsequent calls to other SQLite interface functions.)^
3272**
3273** ^The sqlite3_errstr() interface returns the English-language text
3274** that describes the [result code], as UTF-8.
3275** ^(Memory to hold the error message string is managed internally
3276** and must not be freed by the application)^.
3277**
3278** When the serialized [threading mode] is in use, it might be the
3279** case that a second error occurs on a separate thread in between
3280** the time of the first error and the call to these interfaces.
3281** When that happens, the second error will be reported since these
3282** interfaces always report the most recent result.  To avoid
3283** this, each thread can obtain exclusive use of the [database connection] D
3284** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3285** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3286** all calls to the interfaces listed here are completed.
3287**
3288** If an interface fails with SQLITE_MISUSE, that means the interface
3289** was invoked incorrectly by the application.  In that case, the
3290** error code and message may or may not be set.
3291*/
3292SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3293SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3294SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3295SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3296SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3297
3298/*
3299** CAPI3REF: Prepared Statement Object
3300** KEYWORDS: {prepared statement} {prepared statements}
3301**
3302** An instance of this object represents a single SQL statement that
3303** has been compiled into binary form and is ready to be evaluated.
3304**
3305** Think of each SQL statement as a separate computer program.  The
3306** original SQL text is source code.  A prepared statement object
3307** is the compiled object code.  All SQL must be converted into a
3308** prepared statement before it can be run.
3309**
3310** The life-cycle of a prepared statement object usually goes like this:
3311**
3312** <ol>
3313** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3314** <li> Bind values to [parameters] using the sqlite3_bind_*()
3315**      interfaces.
3316** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3317** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3318**      to step 2.  Do this zero or more times.
3319** <li> Destroy the object using [sqlite3_finalize()].
3320** </ol>
3321*/
3322typedef struct sqlite3_stmt sqlite3_stmt;
3323
3324/*
3325** CAPI3REF: Run-time Limits
3326** METHOD: sqlite3
3327**
3328** ^(This interface allows the size of various constructs to be limited
3329** on a connection by connection basis.  The first parameter is the
3330** [database connection] whose limit is to be set or queried.  The
3331** second parameter is one of the [limit categories] that define a
3332** class of constructs to be size limited.  The third parameter is the
3333** new limit for that construct.)^
3334**
3335** ^If the new limit is a negative number, the limit is unchanged.
3336** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3337** [limits | hard upper bound]
3338** set at compile-time by a C preprocessor macro called
3339** [limits | SQLITE_MAX_<i>NAME</i>].
3340** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3341** ^Attempts to increase a limit above its hard upper bound are
3342** silently truncated to the hard upper bound.
3343**
3344** ^Regardless of whether or not the limit was changed, the
3345** [sqlite3_limit()] interface returns the prior value of the limit.
3346** ^Hence, to find the current value of a limit without changing it,
3347** simply invoke this interface with the third parameter set to -1.
3348**
3349** Run-time limits are intended for use in applications that manage
3350** both their own internal database and also databases that are controlled
3351** by untrusted external sources.  An example application might be a
3352** web browser that has its own databases for storing history and
3353** separate databases controlled by JavaScript applications downloaded
3354** off the Internet.  The internal databases can be given the
3355** large, default limits.  Databases managed by external sources can
3356** be given much smaller limits designed to prevent a denial of service
3357** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3358** interface to further control untrusted SQL.  The size of the database
3359** created by an untrusted script can be contained using the
3360** [max_page_count] [PRAGMA].
3361**
3362** New run-time limit categories may be added in future releases.
3363*/
3364SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3365
3366/*
3367** CAPI3REF: Run-Time Limit Categories
3368** KEYWORDS: {limit category} {*limit categories}
3369**
3370** These constants define various performance limits
3371** that can be lowered at run-time using [sqlite3_limit()].
3372** The synopsis of the meanings of the various limits is shown below.
3373** Additional information is available at [limits | Limits in SQLite].
3374**
3375** <dl>
3376** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3377** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3378**
3379** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3380** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3381**
3382** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3383** <dd>The maximum number of columns in a table definition or in the
3384** result set of a [SELECT] or the maximum number of columns in an index
3385** or in an ORDER BY or GROUP BY clause.</dd>)^
3386**
3387** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3388** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3389**
3390** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3391** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3392**
3393** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3394** <dd>The maximum number of instructions in a virtual machine program
3395** used to implement an SQL statement.  This limit is not currently
3396** enforced, though that might be added in some future release of
3397** SQLite.</dd>)^
3398**
3399** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3400** <dd>The maximum number of arguments on a function.</dd>)^
3401**
3402** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3403** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3404**
3405** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3406** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3407** <dd>The maximum length of the pattern argument to the [LIKE] or
3408** [GLOB] operators.</dd>)^
3409**
3410** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3411** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3412** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3413**
3414** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3415** <dd>The maximum depth of recursion for triggers.</dd>)^
3416**
3417** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3418** <dd>The maximum number of auxiliary worker threads that a single
3419** [prepared statement] may start.</dd>)^
3420** </dl>
3421*/
3422#define SQLITE_LIMIT_LENGTH                    0
3423#define SQLITE_LIMIT_SQL_LENGTH                1
3424#define SQLITE_LIMIT_COLUMN                    2
3425#define SQLITE_LIMIT_EXPR_DEPTH                3
3426#define SQLITE_LIMIT_COMPOUND_SELECT           4
3427#define SQLITE_LIMIT_VDBE_OP                   5
3428#define SQLITE_LIMIT_FUNCTION_ARG              6
3429#define SQLITE_LIMIT_ATTACHED                  7
3430#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3431#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3432#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3433#define SQLITE_LIMIT_WORKER_THREADS           11
3434
3435/*
3436** CAPI3REF: Compiling An SQL Statement
3437** KEYWORDS: {SQL statement compiler}
3438** METHOD: sqlite3
3439** CONSTRUCTOR: sqlite3_stmt
3440**
3441** To execute an SQL query, it must first be compiled into a byte-code
3442** program using one of these routines.
3443**
3444** The first argument, "db", is a [database connection] obtained from a
3445** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3446** [sqlite3_open16()].  The database connection must not have been closed.
3447**
3448** The second argument, "zSql", is the statement to be compiled, encoded
3449** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3450** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3451** use UTF-16.
3452**
3453** ^If the nByte argument is negative, then zSql is read up to the
3454** first zero terminator. ^If nByte is positive, then it is the
3455** number of bytes read from zSql.  ^If nByte is zero, then no prepared
3456** statement is generated.
3457** If the caller knows that the supplied string is nul-terminated, then
3458** there is a small performance advantage to passing an nByte parameter that
3459** is the number of bytes in the input string <i>including</i>
3460** the nul-terminator.
3461**
3462** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3463** past the end of the first SQL statement in zSql.  These routines only
3464** compile the first statement in zSql, so *pzTail is left pointing to
3465** what remains uncompiled.
3466**
3467** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3468** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3469** to NULL.  ^If the input text contains no SQL (if the input is an empty
3470** string or a comment) then *ppStmt is set to NULL.
3471** The calling procedure is responsible for deleting the compiled
3472** SQL statement using [sqlite3_finalize()] after it has finished with it.
3473** ppStmt may not be NULL.
3474**
3475** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3476** otherwise an [error code] is returned.
3477**
3478** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3479** recommended for all new programs. The two older interfaces are retained
3480** for backwards compatibility, but their use is discouraged.
3481** ^In the "v2" interfaces, the prepared statement
3482** that is returned (the [sqlite3_stmt] object) contains a copy of the
3483** original SQL text. This causes the [sqlite3_step()] interface to
3484** behave differently in three ways:
3485**
3486** <ol>
3487** <li>
3488** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3489** always used to do, [sqlite3_step()] will automatically recompile the SQL
3490** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3491** retries will occur before sqlite3_step() gives up and returns an error.
3492** </li>
3493**
3494** <li>
3495** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3496** [error codes] or [extended error codes].  ^The legacy behavior was that
3497** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3498** and the application would have to make a second call to [sqlite3_reset()]
3499** in order to find the underlying cause of the problem. With the "v2" prepare
3500** interfaces, the underlying reason for the error is returned immediately.
3501** </li>
3502**
3503** <li>
3504** ^If the specific value bound to [parameter | host parameter] in the
3505** WHERE clause might influence the choice of query plan for a statement,
3506** then the statement will be automatically recompiled, as if there had been
3507** a schema change, on the first  [sqlite3_step()] call following any change
3508** to the [sqlite3_bind_text | bindings] of that [parameter].
3509** ^The specific value of WHERE-clause [parameter] might influence the
3510** choice of query plan if the parameter is the left-hand side of a [LIKE]
3511** or [GLOB] operator or if the parameter is compared to an indexed column
3512** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3513** </li>
3514** </ol>
3515*/
3516SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3517  sqlite3 *db,            /* Database handle */
3518  const char *zSql,       /* SQL statement, UTF-8 encoded */
3519  int nByte,              /* Maximum length of zSql in bytes. */
3520  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3521  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3522);
3523SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3524  sqlite3 *db,            /* Database handle */
3525  const char *zSql,       /* SQL statement, UTF-8 encoded */
3526  int nByte,              /* Maximum length of zSql in bytes. */
3527  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3528  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3529);
3530SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3531  sqlite3 *db,            /* Database handle */
3532  const void *zSql,       /* SQL statement, UTF-16 encoded */
3533  int nByte,              /* Maximum length of zSql in bytes. */
3534  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3535  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3536);
3537SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3538  sqlite3 *db,            /* Database handle */
3539  const void *zSql,       /* SQL statement, UTF-16 encoded */
3540  int nByte,              /* Maximum length of zSql in bytes. */
3541  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3542  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3543);
3544
3545/*
3546** CAPI3REF: Retrieving Statement SQL
3547** METHOD: sqlite3_stmt
3548**
3549** ^This interface can be used to retrieve a saved copy of the original
3550** SQL text used to create a [prepared statement] if that statement was
3551** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3552*/
3553SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3554
3555/*
3556** CAPI3REF: Determine If An SQL Statement Writes The Database
3557** METHOD: sqlite3_stmt
3558**
3559** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3560** and only if the [prepared statement] X makes no direct changes to
3561** the content of the database file.
3562**
3563** Note that [application-defined SQL functions] or
3564** [virtual tables] might change the database indirectly as a side effect.
3565** ^(For example, if an application defines a function "eval()" that
3566** calls [sqlite3_exec()], then the following SQL statement would
3567** change the database file through side-effects:
3568**
3569** <blockquote><pre>
3570**    SELECT eval('DELETE FROM t1') FROM t2;
3571** </pre></blockquote>
3572**
3573** But because the [SELECT] statement does not change the database file
3574** directly, sqlite3_stmt_readonly() would still return true.)^
3575**
3576** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3577** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3578** since the statements themselves do not actually modify the database but
3579** rather they control the timing of when other statements modify the
3580** database.  ^The [ATTACH] and [DETACH] statements also cause
3581** sqlite3_stmt_readonly() to return true since, while those statements
3582** change the configuration of a database connection, they do not make
3583** changes to the content of the database files on disk.
3584*/
3585SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3586
3587/*
3588** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3589** METHOD: sqlite3_stmt
3590**
3591** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3592** [prepared statement] S has been stepped at least once using
3593** [sqlite3_step(S)] but has neither run to completion (returned
3594** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3595** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3596** interface returns false if S is a NULL pointer.  If S is not a
3597** NULL pointer and is not a pointer to a valid [prepared statement]
3598** object, then the behavior is undefined and probably undesirable.
3599**
3600** This interface can be used in combination [sqlite3_next_stmt()]
3601** to locate all prepared statements associated with a database
3602** connection that are in need of being reset.  This can be used,
3603** for example, in diagnostic routines to search for prepared
3604** statements that are holding a transaction open.
3605*/
3606SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3607
3608/*
3609** CAPI3REF: Dynamically Typed Value Object
3610** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3611**
3612** SQLite uses the sqlite3_value object to represent all values
3613** that can be stored in a database table. SQLite uses dynamic typing
3614** for the values it stores.  ^Values stored in sqlite3_value objects
3615** can be integers, floating point values, strings, BLOBs, or NULL.
3616**
3617** An sqlite3_value object may be either "protected" or "unprotected".
3618** Some interfaces require a protected sqlite3_value.  Other interfaces
3619** will accept either a protected or an unprotected sqlite3_value.
3620** Every interface that accepts sqlite3_value arguments specifies
3621** whether or not it requires a protected sqlite3_value.  The
3622** [sqlite3_value_dup()] interface can be used to construct a new
3623** protected sqlite3_value from an unprotected sqlite3_value.
3624**
3625** The terms "protected" and "unprotected" refer to whether or not
3626** a mutex is held.  An internal mutex is held for a protected
3627** sqlite3_value object but no mutex is held for an unprotected
3628** sqlite3_value object.  If SQLite is compiled to be single-threaded
3629** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3630** or if SQLite is run in one of reduced mutex modes
3631** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3632** then there is no distinction between protected and unprotected
3633** sqlite3_value objects and they can be used interchangeably.  However,
3634** for maximum code portability it is recommended that applications
3635** still make the distinction between protected and unprotected
3636** sqlite3_value objects even when not strictly required.
3637**
3638** ^The sqlite3_value objects that are passed as parameters into the
3639** implementation of [application-defined SQL functions] are protected.
3640** ^The sqlite3_value object returned by
3641** [sqlite3_column_value()] is unprotected.
3642** Unprotected sqlite3_value objects may only be used with
3643** [sqlite3_result_value()] and [sqlite3_bind_value()].
3644** The [sqlite3_value_blob | sqlite3_value_type()] family of
3645** interfaces require protected sqlite3_value objects.
3646*/
3647typedef struct Mem sqlite3_value;
3648
3649/*
3650** CAPI3REF: SQL Function Context Object
3651**
3652** The context in which an SQL function executes is stored in an
3653** sqlite3_context object.  ^A pointer to an sqlite3_context object
3654** is always first parameter to [application-defined SQL functions].
3655** The application-defined SQL function implementation will pass this
3656** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3657** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3658** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3659** and/or [sqlite3_set_auxdata()].
3660*/
3661typedef struct sqlite3_context sqlite3_context;
3662
3663/*
3664** CAPI3REF: Binding Values To Prepared Statements
3665** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3666** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3667** METHOD: sqlite3_stmt
3668**
3669** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3670** literals may be replaced by a [parameter] that matches one of following
3671** templates:
3672**
3673** <ul>
3674** <li>  ?
3675** <li>  ?NNN
3676** <li>  :VVV
3677** <li>  @VVV
3678** <li>  $VVV
3679** </ul>
3680**
3681** In the templates above, NNN represents an integer literal,
3682** and VVV represents an alphanumeric identifier.)^  ^The values of these
3683** parameters (also called "host parameter names" or "SQL parameters")
3684** can be set using the sqlite3_bind_*() routines defined here.
3685**
3686** ^The first argument to the sqlite3_bind_*() routines is always
3687** a pointer to the [sqlite3_stmt] object returned from
3688** [sqlite3_prepare_v2()] or its variants.
3689**
3690** ^The second argument is the index of the SQL parameter to be set.
3691** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3692** SQL parameter is used more than once, second and subsequent
3693** occurrences have the same index as the first occurrence.
3694** ^The index for named parameters can be looked up using the
3695** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3696** for "?NNN" parameters is the value of NNN.
3697** ^The NNN value must be between 1 and the [sqlite3_limit()]
3698** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3699**
3700** ^The third argument is the value to bind to the parameter.
3701** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3702** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3703** is ignored and the end result is the same as sqlite3_bind_null().
3704**
3705** ^(In those routines that have a fourth argument, its value is the
3706** number of bytes in the parameter.  To be clear: the value is the
3707** number of <u>bytes</u> in the value, not the number of characters.)^
3708** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3709** is negative, then the length of the string is
3710** the number of bytes up to the first zero terminator.
3711** If the fourth parameter to sqlite3_bind_blob() is negative, then
3712** the behavior is undefined.
3713** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3714** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3715** that parameter must be the byte offset
3716** where the NUL terminator would occur assuming the string were NUL
3717** terminated.  If any NUL characters occur at byte offsets less than
3718** the value of the fourth parameter then the resulting string value will
3719** contain embedded NULs.  The result of expressions involving strings
3720** with embedded NULs is undefined.
3721**
3722** ^The fifth argument to the BLOB and string binding interfaces
3723** is a destructor used to dispose of the BLOB or
3724** string after SQLite has finished with it.  ^The destructor is called
3725** to dispose of the BLOB or string even if the call to bind API fails.
3726** ^If the fifth argument is
3727** the special value [SQLITE_STATIC], then SQLite assumes that the
3728** information is in static, unmanaged space and does not need to be freed.
3729** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3730** SQLite makes its own private copy of the data immediately, before
3731** the sqlite3_bind_*() routine returns.
3732**
3733** ^The sixth argument to sqlite3_bind_text64() must be one of
3734** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3735** to specify the encoding of the text in the third parameter.  If
3736** the sixth argument to sqlite3_bind_text64() is not one of the
3737** allowed values shown above, or if the text encoding is different
3738** from the encoding specified by the sixth parameter, then the behavior
3739** is undefined.
3740**
3741** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3742** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3743** (just an integer to hold its size) while it is being processed.
3744** Zeroblobs are intended to serve as placeholders for BLOBs whose
3745** content is later written using
3746** [sqlite3_blob_open | incremental BLOB I/O] routines.
3747** ^A negative value for the zeroblob results in a zero-length BLOB.
3748**
3749** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3750** for the [prepared statement] or with a prepared statement for which
3751** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3752** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3753** routine is passed a [prepared statement] that has been finalized, the
3754** result is undefined and probably harmful.
3755**
3756** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3757** ^Unbound parameters are interpreted as NULL.
3758**
3759** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3760** [error code] if anything goes wrong.
3761** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3762** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3763** [SQLITE_MAX_LENGTH].
3764** ^[SQLITE_RANGE] is returned if the parameter
3765** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3766**
3767** See also: [sqlite3_bind_parameter_count()],
3768** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3769*/
3770SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3771SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3772                        void(*)(void*));
3773SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
3774SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
3775SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3776SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
3777SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3778SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3779SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3780                         void(*)(void*), unsigned char encoding);
3781SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3782SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3783SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
3784
3785/*
3786** CAPI3REF: Number Of SQL Parameters
3787** METHOD: sqlite3_stmt
3788**
3789** ^This routine can be used to find the number of [SQL parameters]
3790** in a [prepared statement].  SQL parameters are tokens of the
3791** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3792** placeholders for values that are [sqlite3_bind_blob | bound]
3793** to the parameters at a later time.
3794**
3795** ^(This routine actually returns the index of the largest (rightmost)
3796** parameter. For all forms except ?NNN, this will correspond to the
3797** number of unique parameters.  If parameters of the ?NNN form are used,
3798** there may be gaps in the list.)^
3799**
3800** See also: [sqlite3_bind_blob|sqlite3_bind()],
3801** [sqlite3_bind_parameter_name()], and
3802** [sqlite3_bind_parameter_index()].
3803*/
3804SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
3805
3806/*
3807** CAPI3REF: Name Of A Host Parameter
3808** METHOD: sqlite3_stmt
3809**
3810** ^The sqlite3_bind_parameter_name(P,N) interface returns
3811** the name of the N-th [SQL parameter] in the [prepared statement] P.
3812** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3813** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3814** respectively.
3815** In other words, the initial ":" or "$" or "@" or "?"
3816** is included as part of the name.)^
3817** ^Parameters of the form "?" without a following integer have no name
3818** and are referred to as "nameless" or "anonymous parameters".
3819**
3820** ^The first host parameter has an index of 1, not 0.
3821**
3822** ^If the value N is out of range or if the N-th parameter is
3823** nameless, then NULL is returned.  ^The returned string is
3824** always in UTF-8 encoding even if the named parameter was
3825** originally specified as UTF-16 in [sqlite3_prepare16()] or
3826** [sqlite3_prepare16_v2()].
3827**
3828** See also: [sqlite3_bind_blob|sqlite3_bind()],
3829** [sqlite3_bind_parameter_count()], and
3830** [sqlite3_bind_parameter_index()].
3831*/
3832SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3833
3834/*
3835** CAPI3REF: Index Of A Parameter With A Given Name
3836** METHOD: sqlite3_stmt
3837**
3838** ^Return the index of an SQL parameter given its name.  ^The
3839** index value returned is suitable for use as the second
3840** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3841** is returned if no matching parameter is found.  ^The parameter
3842** name must be given in UTF-8 even if the original statement
3843** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3844**
3845** See also: [sqlite3_bind_blob|sqlite3_bind()],
3846** [sqlite3_bind_parameter_count()], and
3847** [sqlite3_bind_parameter_name()].
3848*/
3849SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3850
3851/*
3852** CAPI3REF: Reset All Bindings On A Prepared Statement
3853** METHOD: sqlite3_stmt
3854**
3855** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3856** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3857** ^Use this routine to reset all host parameters to NULL.
3858*/
3859SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
3860
3861/*
3862** CAPI3REF: Number Of Columns In A Result Set
3863** METHOD: sqlite3_stmt
3864**
3865** ^Return the number of columns in the result set returned by the
3866** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3867** statement that does not return data (for example an [UPDATE]).
3868**
3869** See also: [sqlite3_data_count()]
3870*/
3871SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
3872
3873/*
3874** CAPI3REF: Column Names In A Result Set
3875** METHOD: sqlite3_stmt
3876**
3877** ^These routines return the name assigned to a particular column
3878** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3879** interface returns a pointer to a zero-terminated UTF-8 string
3880** and sqlite3_column_name16() returns a pointer to a zero-terminated
3881** UTF-16 string.  ^The first parameter is the [prepared statement]
3882** that implements the [SELECT] statement. ^The second parameter is the
3883** column number.  ^The leftmost column is number 0.
3884**
3885** ^The returned string pointer is valid until either the [prepared statement]
3886** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3887** reprepared by the first call to [sqlite3_step()] for a particular run
3888** or until the next call to
3889** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3890**
3891** ^If sqlite3_malloc() fails during the processing of either routine
3892** (for example during a conversion from UTF-8 to UTF-16) then a
3893** NULL pointer is returned.
3894**
3895** ^The name of a result column is the value of the "AS" clause for
3896** that column, if there is an AS clause.  If there is no AS clause
3897** then the name of the column is unspecified and may change from
3898** one release of SQLite to the next.
3899*/
3900SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
3901SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
3902
3903/*
3904** CAPI3REF: Source Of Data In A Query Result
3905** METHOD: sqlite3_stmt
3906**
3907** ^These routines provide a means to determine the database, table, and
3908** table column that is the origin of a particular result column in
3909** [SELECT] statement.
3910** ^The name of the database or table or column can be returned as
3911** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3912** the database name, the _table_ routines return the table name, and
3913** the origin_ routines return the column name.
3914** ^The returned string is valid until the [prepared statement] is destroyed
3915** using [sqlite3_finalize()] or until the statement is automatically
3916** reprepared by the first call to [sqlite3_step()] for a particular run
3917** or until the same information is requested
3918** again in a different encoding.
3919**
3920** ^The names returned are the original un-aliased names of the
3921** database, table, and column.
3922**
3923** ^The first argument to these interfaces is a [prepared statement].
3924** ^These functions return information about the Nth result column returned by
3925** the statement, where N is the second function argument.
3926** ^The left-most column is column 0 for these routines.
3927**
3928** ^If the Nth column returned by the statement is an expression or
3929** subquery and is not a column value, then all of these functions return
3930** NULL.  ^These routine might also return NULL if a memory allocation error
3931** occurs.  ^Otherwise, they return the name of the attached database, table,
3932** or column that query result column was extracted from.
3933**
3934** ^As with all other SQLite APIs, those whose names end with "16" return
3935** UTF-16 encoded strings and the other functions return UTF-8.
3936**
3937** ^These APIs are only available if the library was compiled with the
3938** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3939**
3940** If two or more threads call one or more of these routines against the same
3941** prepared statement and column at the same time then the results are
3942** undefined.
3943**
3944** If two or more threads call one or more
3945** [sqlite3_column_database_name | column metadata interfaces]
3946** for the same [prepared statement] and result column
3947** at the same time then the results are undefined.
3948*/
3949SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
3950SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
3951SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
3952SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
3953SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
3954SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
3955
3956/*
3957** CAPI3REF: Declared Datatype Of A Query Result
3958** METHOD: sqlite3_stmt
3959**
3960** ^(The first parameter is a [prepared statement].
3961** If this statement is a [SELECT] statement and the Nth column of the
3962** returned result set of that [SELECT] is a table column (not an
3963** expression or subquery) then the declared type of the table
3964** column is returned.)^  ^If the Nth column of the result set is an
3965** expression or subquery, then a NULL pointer is returned.
3966** ^The returned string is always UTF-8 encoded.
3967**
3968** ^(For example, given the database schema:
3969**
3970** CREATE TABLE t1(c1 VARIANT);
3971**
3972** and the following statement to be compiled:
3973**
3974** SELECT c1 + 1, c1 FROM t1;
3975**
3976** this routine would return the string "VARIANT" for the second result
3977** column (i==1), and a NULL pointer for the first result column (i==0).)^
3978**
3979** ^SQLite uses dynamic run-time typing.  ^So just because a column
3980** is declared to contain a particular type does not mean that the
3981** data stored in that column is of the declared type.  SQLite is
3982** strongly typed, but the typing is dynamic not static.  ^Type
3983** is associated with individual values, not with the containers
3984** used to hold those values.
3985*/
3986SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
3987SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
3988
3989/*
3990** CAPI3REF: Evaluate An SQL Statement
3991** METHOD: sqlite3_stmt
3992**
3993** After a [prepared statement] has been prepared using either
3994** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3995** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3996** must be called one or more times to evaluate the statement.
3997**
3998** The details of the behavior of the sqlite3_step() interface depend
3999** on whether the statement was prepared using the newer "v2" interface
4000** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4001** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4002** new "v2" interface is recommended for new applications but the legacy
4003** interface will continue to be supported.
4004**
4005** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4006** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4007** ^With the "v2" interface, any of the other [result codes] or
4008** [extended result codes] might be returned as well.
4009**
4010** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4011** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4012** or occurs outside of an explicit transaction, then you can retry the
4013** statement.  If the statement is not a [COMMIT] and occurs within an
4014** explicit transaction then you should rollback the transaction before
4015** continuing.
4016**
4017** ^[SQLITE_DONE] means that the statement has finished executing
4018** successfully.  sqlite3_step() should not be called again on this virtual
4019** machine without first calling [sqlite3_reset()] to reset the virtual
4020** machine back to its initial state.
4021**
4022** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4023** is returned each time a new row of data is ready for processing by the
4024** caller. The values may be accessed using the [column access functions].
4025** sqlite3_step() is called again to retrieve the next row of data.
4026**
4027** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4028** violation) has occurred.  sqlite3_step() should not be called again on
4029** the VM. More information may be found by calling [sqlite3_errmsg()].
4030** ^With the legacy interface, a more specific error code (for example,
4031** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4032** can be obtained by calling [sqlite3_reset()] on the
4033** [prepared statement].  ^In the "v2" interface,
4034** the more specific error code is returned directly by sqlite3_step().
4035**
4036** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4037** Perhaps it was called on a [prepared statement] that has
4038** already been [sqlite3_finalize | finalized] or on one that had
4039** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4040** be the case that the same database connection is being used by two or
4041** more threads at the same moment in time.
4042**
4043** For all versions of SQLite up to and including 3.6.23.1, a call to
4044** [sqlite3_reset()] was required after sqlite3_step() returned anything
4045** other than [SQLITE_ROW] before any subsequent invocation of
4046** sqlite3_step().  Failure to reset the prepared statement using
4047** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4048** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4049** calling [sqlite3_reset()] automatically in this circumstance rather
4050** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4051** break because any application that ever receives an SQLITE_MISUSE error
4052** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4053** can be used to restore the legacy behavior.
4054**
4055** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4056** API always returns a generic error code, [SQLITE_ERROR], following any
4057** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4058** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4059** specific [error codes] that better describes the error.
4060** We admit that this is a goofy design.  The problem has been fixed
4061** with the "v2" interface.  If you prepare all of your SQL statements
4062** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4063** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4064** then the more specific [error codes] are returned directly
4065** by sqlite3_step().  The use of the "v2" interface is recommended.
4066*/
4067SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4068
4069/*
4070** CAPI3REF: Number of columns in a result set
4071** METHOD: sqlite3_stmt
4072**
4073** ^The sqlite3_data_count(P) interface returns the number of columns in the
4074** current row of the result set of [prepared statement] P.
4075** ^If prepared statement P does not have results ready to return
4076** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4077** interfaces) then sqlite3_data_count(P) returns 0.
4078** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4079** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4080** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4081** will return non-zero if previous call to [sqlite3_step](P) returned
4082** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4083** where it always returns zero since each step of that multi-step
4084** pragma returns 0 columns of data.
4085**
4086** See also: [sqlite3_column_count()]
4087*/
4088SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4089
4090/*
4091** CAPI3REF: Fundamental Datatypes
4092** KEYWORDS: SQLITE_TEXT
4093**
4094** ^(Every value in SQLite has one of five fundamental datatypes:
4095**
4096** <ul>
4097** <li> 64-bit signed integer
4098** <li> 64-bit IEEE floating point number
4099** <li> string
4100** <li> BLOB
4101** <li> NULL
4102** </ul>)^
4103**
4104** These constants are codes for each of those types.
4105**
4106** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4107** for a completely different meaning.  Software that links against both
4108** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4109** SQLITE_TEXT.
4110*/
4111#define SQLITE_INTEGER  1
4112#define SQLITE_FLOAT    2
4113#define SQLITE_BLOB     4
4114#define SQLITE_NULL     5
4115#ifdef SQLITE_TEXT
4116# undef SQLITE_TEXT
4117#else
4118# define SQLITE_TEXT     3
4119#endif
4120#define SQLITE3_TEXT     3
4121
4122/*
4123** CAPI3REF: Result Values From A Query
4124** KEYWORDS: {column access functions}
4125** METHOD: sqlite3_stmt
4126**
4127** ^These routines return information about a single column of the current
4128** result row of a query.  ^In every case the first argument is a pointer
4129** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4130** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4131** and the second argument is the index of the column for which information
4132** should be returned. ^The leftmost column of the result set has the index 0.
4133** ^The number of columns in the result can be determined using
4134** [sqlite3_column_count()].
4135**
4136** If the SQL statement does not currently point to a valid row, or if the
4137** column index is out of range, the result is undefined.
4138** These routines may only be called when the most recent call to
4139** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4140** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4141** If any of these routines are called after [sqlite3_reset()] or
4142** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4143** something other than [SQLITE_ROW], the results are undefined.
4144** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4145** are called from a different thread while any of these routines
4146** are pending, then the results are undefined.
4147**
4148** ^The sqlite3_column_type() routine returns the
4149** [SQLITE_INTEGER | datatype code] for the initial data type
4150** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4151** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4152** returned by sqlite3_column_type() is only meaningful if no type
4153** conversions have occurred as described below.  After a type conversion,
4154** the value returned by sqlite3_column_type() is undefined.  Future
4155** versions of SQLite may change the behavior of sqlite3_column_type()
4156** following a type conversion.
4157**
4158** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4159** routine returns the number of bytes in that BLOB or string.
4160** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4161** the string to UTF-8 and then returns the number of bytes.
4162** ^If the result is a numeric value then sqlite3_column_bytes() uses
4163** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4164** the number of bytes in that string.
4165** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4166**
4167** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4168** routine returns the number of bytes in that BLOB or string.
4169** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4170** the string to UTF-16 and then returns the number of bytes.
4171** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4172** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4173** the number of bytes in that string.
4174** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4175**
4176** ^The values returned by [sqlite3_column_bytes()] and
4177** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4178** of the string.  ^For clarity: the values returned by
4179** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4180** bytes in the string, not the number of characters.
4181**
4182** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4183** even empty strings, are always zero-terminated.  ^The return
4184** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4185**
4186** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4187** [unprotected sqlite3_value] object.  In a multithreaded environment,
4188** an unprotected sqlite3_value object may only be used safely with
4189** [sqlite3_bind_value()] and [sqlite3_result_value()].
4190** If the [unprotected sqlite3_value] object returned by
4191** [sqlite3_column_value()] is used in any other way, including calls
4192** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4193** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4194**
4195** These routines attempt to convert the value where appropriate.  ^For
4196** example, if the internal representation is FLOAT and a text result
4197** is requested, [sqlite3_snprintf()] is used internally to perform the
4198** conversion automatically.  ^(The following table details the conversions
4199** that are applied:
4200**
4201** <blockquote>
4202** <table border="1">
4203** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4204**
4205** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4206** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4207** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4208** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4209** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4210** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4211** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4212** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4213** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4214** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4215** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4216** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4217** <tr><td>  TEXT    <td>   BLOB    <td> No change
4218** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4219** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4220** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4221** </table>
4222** </blockquote>)^
4223**
4224** Note that when type conversions occur, pointers returned by prior
4225** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4226** sqlite3_column_text16() may be invalidated.
4227** Type conversions and pointer invalidations might occur
4228** in the following cases:
4229**
4230** <ul>
4231** <li> The initial content is a BLOB and sqlite3_column_text() or
4232**      sqlite3_column_text16() is called.  A zero-terminator might
4233**      need to be added to the string.</li>
4234** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4235**      sqlite3_column_text16() is called.  The content must be converted
4236**      to UTF-16.</li>
4237** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4238**      sqlite3_column_text() is called.  The content must be converted
4239**      to UTF-8.</li>
4240** </ul>
4241**
4242** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4243** not invalidate a prior pointer, though of course the content of the buffer
4244** that the prior pointer references will have been modified.  Other kinds
4245** of conversion are done in place when it is possible, but sometimes they
4246** are not possible and in those cases prior pointers are invalidated.
4247**
4248** The safest policy is to invoke these routines
4249** in one of the following ways:
4250**
4251** <ul>
4252**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4253**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4254**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4255** </ul>
4256**
4257** In other words, you should call sqlite3_column_text(),
4258** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4259** into the desired format, then invoke sqlite3_column_bytes() or
4260** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4261** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4262** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4263** with calls to sqlite3_column_bytes().
4264**
4265** ^The pointers returned are valid until a type conversion occurs as
4266** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4267** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4268** and BLOBs is freed automatically.  Do <em>not</em> pass the pointers returned
4269** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4270** [sqlite3_free()].
4271**
4272** ^(If a memory allocation error occurs during the evaluation of any
4273** of these routines, a default value is returned.  The default value
4274** is either the integer 0, the floating point number 0.0, or a NULL
4275** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4276** [SQLITE_NOMEM].)^
4277*/
4278SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
4279SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4280SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4281SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4282SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4283SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4284SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4285SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
4286SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4287SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4288
4289/*
4290** CAPI3REF: Destroy A Prepared Statement Object
4291** DESTRUCTOR: sqlite3_stmt
4292**
4293** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4294** ^If the most recent evaluation of the statement encountered no errors
4295** or if the statement is never been evaluated, then sqlite3_finalize() returns
4296** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4297** sqlite3_finalize(S) returns the appropriate [error code] or
4298** [extended error code].
4299**
4300** ^The sqlite3_finalize(S) routine can be called at any point during
4301** the life cycle of [prepared statement] S:
4302** before statement S is ever evaluated, after
4303** one or more calls to [sqlite3_reset()], or after any call
4304** to [sqlite3_step()] regardless of whether or not the statement has
4305** completed execution.
4306**
4307** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4308**
4309** The application must finalize every [prepared statement] in order to avoid
4310** resource leaks.  It is a grievous error for the application to try to use
4311** a prepared statement after it has been finalized.  Any use of a prepared
4312** statement after it has been finalized can result in undefined and
4313** undesirable behavior such as segfaults and heap corruption.
4314*/
4315SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4316
4317/*
4318** CAPI3REF: Reset A Prepared Statement Object
4319** METHOD: sqlite3_stmt
4320**
4321** The sqlite3_reset() function is called to reset a [prepared statement]
4322** object back to its initial state, ready to be re-executed.
4323** ^Any SQL statement variables that had values bound to them using
4324** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4325** Use [sqlite3_clear_bindings()] to reset the bindings.
4326**
4327** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4328** back to the beginning of its program.
4329**
4330** ^If the most recent call to [sqlite3_step(S)] for the
4331** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4332** or if [sqlite3_step(S)] has never before been called on S,
4333** then [sqlite3_reset(S)] returns [SQLITE_OK].
4334**
4335** ^If the most recent call to [sqlite3_step(S)] for the
4336** [prepared statement] S indicated an error, then
4337** [sqlite3_reset(S)] returns an appropriate [error code].
4338**
4339** ^The [sqlite3_reset(S)] interface does not change the values
4340** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4341*/
4342SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4343
4344/*
4345** CAPI3REF: Create Or Redefine SQL Functions
4346** KEYWORDS: {function creation routines}
4347** KEYWORDS: {application-defined SQL function}
4348** KEYWORDS: {application-defined SQL functions}
4349** METHOD: sqlite3
4350**
4351** ^These functions (collectively known as "function creation routines")
4352** are used to add SQL functions or aggregates or to redefine the behavior
4353** of existing SQL functions or aggregates.  The only differences between
4354** these routines are the text encoding expected for
4355** the second parameter (the name of the function being created)
4356** and the presence or absence of a destructor callback for
4357** the application data pointer.
4358**
4359** ^The first parameter is the [database connection] to which the SQL
4360** function is to be added.  ^If an application uses more than one database
4361** connection then application-defined SQL functions must be added
4362** to each database connection separately.
4363**
4364** ^The second parameter is the name of the SQL function to be created or
4365** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4366** representation, exclusive of the zero-terminator.  ^Note that the name
4367** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4368** ^Any attempt to create a function with a longer name
4369** will result in [SQLITE_MISUSE] being returned.
4370**
4371** ^The third parameter (nArg)
4372** is the number of arguments that the SQL function or
4373** aggregate takes. ^If this parameter is -1, then the SQL function or
4374** aggregate may take any number of arguments between 0 and the limit
4375** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4376** parameter is less than -1 or greater than 127 then the behavior is
4377** undefined.
4378**
4379** ^The fourth parameter, eTextRep, specifies what
4380** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4381** its parameters.  The application should set this parameter to
4382** [SQLITE_UTF16LE] if the function implementation invokes
4383** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4384** implementation invokes [sqlite3_value_text16be()] on an input, or
4385** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4386** otherwise.  ^The same SQL function may be registered multiple times using
4387** different preferred text encodings, with different implementations for
4388** each encoding.
4389** ^When multiple implementations of the same function are available, SQLite
4390** will pick the one that involves the least amount of data conversion.
4391**
4392** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4393** to signal that the function will always return the same result given
4394** the same inputs within a single SQL statement.  Most SQL functions are
4395** deterministic.  The built-in [random()] SQL function is an example of a
4396** function that is not deterministic.  The SQLite query planner is able to
4397** perform additional optimizations on deterministic functions, so use
4398** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4399**
4400** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4401** function can gain access to this pointer using [sqlite3_user_data()].)^
4402**
4403** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4404** pointers to C-language functions that implement the SQL function or
4405** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4406** callback only; NULL pointers must be passed as the xStep and xFinal
4407** parameters. ^An aggregate SQL function requires an implementation of xStep
4408** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4409** SQL function or aggregate, pass NULL pointers for all three function
4410** callbacks.
4411**
4412** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4413** then it is destructor for the application data pointer.
4414** The destructor is invoked when the function is deleted, either by being
4415** overloaded or when the database connection closes.)^
4416** ^The destructor is also invoked if the call to
4417** sqlite3_create_function_v2() fails.
4418** ^When the destructor callback of the tenth parameter is invoked, it
4419** is passed a single argument which is a copy of the application data
4420** pointer which was the fifth parameter to sqlite3_create_function_v2().
4421**
4422** ^It is permitted to register multiple implementations of the same
4423** functions with the same name but with either differing numbers of
4424** arguments or differing preferred text encodings.  ^SQLite will use
4425** the implementation that most closely matches the way in which the
4426** SQL function is used.  ^A function implementation with a non-negative
4427** nArg parameter is a better match than a function implementation with
4428** a negative nArg.  ^A function where the preferred text encoding
4429** matches the database encoding is a better
4430** match than a function where the encoding is different.
4431** ^A function where the encoding difference is between UTF16le and UTF16be
4432** is a closer match than a function where the encoding difference is
4433** between UTF8 and UTF16.
4434**
4435** ^Built-in functions may be overloaded by new application-defined functions.
4436**
4437** ^An application-defined function is permitted to call other
4438** SQLite interfaces.  However, such calls must not
4439** close the database connection nor finalize or reset the prepared
4440** statement in which the function is running.
4441*/
4442SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4443  sqlite3 *db,
4444  const char *zFunctionName,
4445  int nArg,
4446  int eTextRep,
4447  void *pApp,
4448  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4449  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4450  void (*xFinal)(sqlite3_context*)
4451);
4452SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4453  sqlite3 *db,
4454  const void *zFunctionName,
4455  int nArg,
4456  int eTextRep,
4457  void *pApp,
4458  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4459  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4460  void (*xFinal)(sqlite3_context*)
4461);
4462SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4463  sqlite3 *db,
4464  const char *zFunctionName,
4465  int nArg,
4466  int eTextRep,
4467  void *pApp,
4468  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4469  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4470  void (*xFinal)(sqlite3_context*),
4471  void(*xDestroy)(void*)
4472);
4473
4474/*
4475** CAPI3REF: Text Encodings
4476**
4477** These constant define integer codes that represent the various
4478** text encodings supported by SQLite.
4479*/
4480#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
4481#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
4482#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
4483#define SQLITE_UTF16          4    /* Use native byte order */
4484#define SQLITE_ANY            5    /* Deprecated */
4485#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4486
4487/*
4488** CAPI3REF: Function Flags
4489**
4490** These constants may be ORed together with the
4491** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4492** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4493** [sqlite3_create_function_v2()].
4494*/
4495#define SQLITE_DETERMINISTIC    0x800
4496
4497/*
4498** CAPI3REF: Deprecated Functions
4499** DEPRECATED
4500**
4501** These functions are [deprecated].  In order to maintain
4502** backwards compatibility with older code, these functions continue
4503** to be supported.  However, new applications should avoid
4504** the use of these functions.  To encourage programmers to avoid
4505** these functions, we will not explain what they do.
4506*/
4507#ifndef SQLITE_OMIT_DEPRECATED
4508SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
4509SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4510SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4511SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4512SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4513SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4514                      void*,sqlite3_int64);
4515#endif
4516
4517/*
4518** CAPI3REF: Obtaining SQL Values
4519** METHOD: sqlite3_value
4520**
4521** The C-language implementation of SQL functions and aggregates uses
4522** this set of interface routines to access the parameter values on
4523** the function or aggregate.
4524**
4525** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4526** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4527** define callbacks that implement the SQL functions and aggregates.
4528** The 3rd parameter to these callbacks is an array of pointers to
4529** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4530** each parameter to the SQL function.  These routines are used to
4531** extract values from the [sqlite3_value] objects.
4532**
4533** These routines work only with [protected sqlite3_value] objects.
4534** Any attempt to use these routines on an [unprotected sqlite3_value]
4535** object results in undefined behavior.
4536**
4537** ^These routines work just like the corresponding [column access functions]
4538** except that these routines take a single [protected sqlite3_value] object
4539** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4540**
4541** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4542** in the native byte-order of the host machine.  ^The
4543** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4544** extract UTF-16 strings as big-endian and little-endian respectively.
4545**
4546** ^(The sqlite3_value_numeric_type() interface attempts to apply
4547** numeric affinity to the value.  This means that an attempt is
4548** made to convert the value to an integer or floating point.  If
4549** such a conversion is possible without loss of information (in other
4550** words, if the value is a string that looks like a number)
4551** then the conversion is performed.  Otherwise no conversion occurs.
4552** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4553**
4554** Please pay particular attention to the fact that the pointer returned
4555** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4556** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4557** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4558** or [sqlite3_value_text16()].
4559**
4560** These routines must be called from the same thread as
4561** the SQL function that supplied the [sqlite3_value*] parameters.
4562*/
4563SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4564SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4565SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4566SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4567SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4568SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4569SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
4570SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4571SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4572SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4573SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4574SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4575
4576/*
4577** CAPI3REF: Finding The Subtype Of SQL Values
4578** METHOD: sqlite3_value
4579**
4580** The sqlite3_value_subtype(V) function returns the subtype for
4581** an [application-defined SQL function] argument V.  The subtype
4582** information can be used to pass a limited amount of context from
4583** one SQL function to another.  Use the [sqlite3_result_subtype()]
4584** routine to set the subtype for the return value of an SQL function.
4585**
4586** SQLite makes no use of subtype itself.  It merely passes the subtype
4587** from the result of one [application-defined SQL function] into the
4588** input of another.
4589*/
4590SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
4591
4592/*
4593** CAPI3REF: Copy And Free SQL Values
4594** METHOD: sqlite3_value
4595**
4596** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4597** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
4598** is a [protected sqlite3_value] object even if the input is not.
4599** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4600** memory allocation fails.
4601**
4602** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4603** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
4604** then sqlite3_value_free(V) is a harmless no-op.
4605*/
4606SQLITE_API SQLITE_EXPERIMENTAL sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
4607SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
4608
4609/*
4610** CAPI3REF: Obtain Aggregate Function Context
4611** METHOD: sqlite3_context
4612**
4613** Implementations of aggregate SQL functions use this
4614** routine to allocate memory for storing their state.
4615**
4616** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4617** for a particular aggregate function, SQLite
4618** allocates N of memory, zeroes out that memory, and returns a pointer
4619** to the new memory. ^On second and subsequent calls to
4620** sqlite3_aggregate_context() for the same aggregate function instance,
4621** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4622** called once for each invocation of the xStep callback and then one
4623** last time when the xFinal callback is invoked.  ^(When no rows match
4624** an aggregate query, the xStep() callback of the aggregate function
4625** implementation is never called and xFinal() is called exactly once.
4626** In those cases, sqlite3_aggregate_context() might be called for the
4627** first time from within xFinal().)^
4628**
4629** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4630** when first called if N is less than or equal to zero or if a memory
4631** allocate error occurs.
4632**
4633** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4634** determined by the N parameter on first successful call.  Changing the
4635** value of N in subsequent call to sqlite3_aggregate_context() within
4636** the same aggregate function instance will not resize the memory
4637** allocation.)^  Within the xFinal callback, it is customary to set
4638** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4639** pointless memory allocations occur.
4640**
4641** ^SQLite automatically frees the memory allocated by
4642** sqlite3_aggregate_context() when the aggregate query concludes.
4643**
4644** The first parameter must be a copy of the
4645** [sqlite3_context | SQL function context] that is the first parameter
4646** to the xStep or xFinal callback routine that implements the aggregate
4647** function.
4648**
4649** This routine must be called from the same thread in which
4650** the aggregate SQL function is running.
4651*/
4652SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4653
4654/*
4655** CAPI3REF: User Data For Functions
4656** METHOD: sqlite3_context
4657**
4658** ^The sqlite3_user_data() interface returns a copy of
4659** the pointer that was the pUserData parameter (the 5th parameter)
4660** of the [sqlite3_create_function()]
4661** and [sqlite3_create_function16()] routines that originally
4662** registered the application defined function.
4663**
4664** This routine must be called from the same thread in which
4665** the application-defined function is running.
4666*/
4667SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4668
4669/*
4670** CAPI3REF: Database Connection For Functions
4671** METHOD: sqlite3_context
4672**
4673** ^The sqlite3_context_db_handle() interface returns a copy of
4674** the pointer to the [database connection] (the 1st parameter)
4675** of the [sqlite3_create_function()]
4676** and [sqlite3_create_function16()] routines that originally
4677** registered the application defined function.
4678*/
4679SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4680
4681/*
4682** CAPI3REF: Function Auxiliary Data
4683** METHOD: sqlite3_context
4684**
4685** These functions may be used by (non-aggregate) SQL functions to
4686** associate metadata with argument values. If the same value is passed to
4687** multiple invocations of the same SQL function during query execution, under
4688** some circumstances the associated metadata may be preserved.  An example
4689** of where this might be useful is in a regular-expression matching
4690** function. The compiled version of the regular expression can be stored as
4691** metadata associated with the pattern string.
4692** Then as long as the pattern string remains the same,
4693** the compiled regular expression can be reused on multiple
4694** invocations of the same function.
4695**
4696** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4697** associated by the sqlite3_set_auxdata() function with the Nth argument
4698** value to the application-defined function. ^If there is no metadata
4699** associated with the function argument, this sqlite3_get_auxdata() interface
4700** returns a NULL pointer.
4701**
4702** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4703** argument of the application-defined function.  ^Subsequent
4704** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4705** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4706** NULL if the metadata has been discarded.
4707** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4708** SQLite will invoke the destructor function X with parameter P exactly
4709** once, when the metadata is discarded.
4710** SQLite is free to discard the metadata at any time, including: <ul>
4711** <li> when the corresponding function parameter changes, or
4712** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4713**      SQL statement, or
4714** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4715** <li> during the original sqlite3_set_auxdata() call when a memory
4716**      allocation error occurs. </ul>)^
4717**
4718** Note the last bullet in particular.  The destructor X in
4719** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4720** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4721** should be called near the end of the function implementation and the
4722** function implementation should not make any use of P after
4723** sqlite3_set_auxdata() has been called.
4724**
4725** ^(In practice, metadata is preserved between function calls for
4726** function parameters that are compile-time constants, including literal
4727** values and [parameters] and expressions composed from the same.)^
4728**
4729** These routines must be called from the same thread in which
4730** the SQL function is running.
4731*/
4732SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4733SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4734
4735
4736/*
4737** CAPI3REF: Constants Defining Special Destructor Behavior
4738**
4739** These are special values for the destructor that is passed in as the
4740** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4741** argument is SQLITE_STATIC, it means that the content pointer is constant
4742** and will never change.  It does not need to be destroyed.  ^The
4743** SQLITE_TRANSIENT value means that the content will likely change in
4744** the near future and that SQLite should make its own private copy of
4745** the content before returning.
4746**
4747** The typedef is necessary to work around problems in certain
4748** C++ compilers.
4749*/
4750typedef void (*sqlite3_destructor_type)(void*);
4751#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4752#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4753
4754/*
4755** CAPI3REF: Setting The Result Of An SQL Function
4756** METHOD: sqlite3_context
4757**
4758** These routines are used by the xFunc or xFinal callbacks that
4759** implement SQL functions and aggregates.  See
4760** [sqlite3_create_function()] and [sqlite3_create_function16()]
4761** for additional information.
4762**
4763** These functions work very much like the [parameter binding] family of
4764** functions used to bind values to host parameters in prepared statements.
4765** Refer to the [SQL parameter] documentation for additional information.
4766**
4767** ^The sqlite3_result_blob() interface sets the result from
4768** an application-defined function to be the BLOB whose content is pointed
4769** to by the second parameter and which is N bytes long where N is the
4770** third parameter.
4771**
4772** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
4773** interfaces set the result of the application-defined function to be
4774** a BLOB containing all zero bytes and N bytes in size.
4775**
4776** ^The sqlite3_result_double() interface sets the result from
4777** an application-defined function to be a floating point value specified
4778** by its 2nd argument.
4779**
4780** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4781** cause the implemented SQL function to throw an exception.
4782** ^SQLite uses the string pointed to by the
4783** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4784** as the text of an error message.  ^SQLite interprets the error
4785** message string from sqlite3_result_error() as UTF-8. ^SQLite
4786** interprets the string from sqlite3_result_error16() as UTF-16 in native
4787** byte order.  ^If the third parameter to sqlite3_result_error()
4788** or sqlite3_result_error16() is negative then SQLite takes as the error
4789** message all text up through the first zero character.
4790** ^If the third parameter to sqlite3_result_error() or
4791** sqlite3_result_error16() is non-negative then SQLite takes that many
4792** bytes (not characters) from the 2nd parameter as the error message.
4793** ^The sqlite3_result_error() and sqlite3_result_error16()
4794** routines make a private copy of the error message text before
4795** they return.  Hence, the calling function can deallocate or
4796** modify the text after they return without harm.
4797** ^The sqlite3_result_error_code() function changes the error code
4798** returned by SQLite as a result of an error in a function.  ^By default,
4799** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4800** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4801**
4802** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4803** error indicating that a string or BLOB is too long to represent.
4804**
4805** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4806** error indicating that a memory allocation failed.
4807**
4808** ^The sqlite3_result_int() interface sets the return value
4809** of the application-defined function to be the 32-bit signed integer
4810** value given in the 2nd argument.
4811** ^The sqlite3_result_int64() interface sets the return value
4812** of the application-defined function to be the 64-bit signed integer
4813** value given in the 2nd argument.
4814**
4815** ^The sqlite3_result_null() interface sets the return value
4816** of the application-defined function to be NULL.
4817**
4818** ^The sqlite3_result_text(), sqlite3_result_text16(),
4819** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4820** set the return value of the application-defined function to be
4821** a text string which is represented as UTF-8, UTF-16 native byte order,
4822** UTF-16 little endian, or UTF-16 big endian, respectively.
4823** ^The sqlite3_result_text64() interface sets the return value of an
4824** application-defined function to be a text string in an encoding
4825** specified by the fifth (and last) parameter, which must be one
4826** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4827** ^SQLite takes the text result from the application from
4828** the 2nd parameter of the sqlite3_result_text* interfaces.
4829** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4830** is negative, then SQLite takes result text from the 2nd parameter
4831** through the first zero character.
4832** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4833** is non-negative, then as many bytes (not characters) of the text
4834** pointed to by the 2nd parameter are taken as the application-defined
4835** function result.  If the 3rd parameter is non-negative, then it
4836** must be the byte offset into the string where the NUL terminator would
4837** appear if the string where NUL terminated.  If any NUL characters occur
4838** in the string at a byte offset that is less than the value of the 3rd
4839** parameter, then the resulting string will contain embedded NULs and the
4840** result of expressions operating on strings with embedded NULs is undefined.
4841** ^If the 4th parameter to the sqlite3_result_text* interfaces
4842** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4843** function as the destructor on the text or BLOB result when it has
4844** finished using that result.
4845** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4846** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4847** assumes that the text or BLOB result is in constant space and does not
4848** copy the content of the parameter nor call a destructor on the content
4849** when it has finished using that result.
4850** ^If the 4th parameter to the sqlite3_result_text* interfaces
4851** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4852** then SQLite makes a copy of the result into space obtained from
4853** from [sqlite3_malloc()] before it returns.
4854**
4855** ^The sqlite3_result_value() interface sets the result of
4856** the application-defined function to be a copy of the
4857** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4858** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4859** so that the [sqlite3_value] specified in the parameter may change or
4860** be deallocated after sqlite3_result_value() returns without harm.
4861** ^A [protected sqlite3_value] object may always be used where an
4862** [unprotected sqlite3_value] object is required, so either
4863** kind of [sqlite3_value] object can be used with this interface.
4864**
4865** If these routines are called from within the different thread
4866** than the one containing the application-defined function that received
4867** the [sqlite3_context] pointer, the results are undefined.
4868*/
4869SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4870SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
4871                           sqlite3_uint64,void(*)(void*));
4872SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
4873SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
4874SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
4875SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
4876SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
4877SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
4878SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
4879SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4880SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
4881SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4882SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4883                           void(*)(void*), unsigned char encoding);
4884SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4885SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4886SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4887SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4888SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
4889SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
4890
4891
4892/*
4893** CAPI3REF: Setting The Subtype Of An SQL Function
4894** METHOD: sqlite3_context
4895**
4896** The sqlite3_result_subtype(C,T) function causes the subtype of
4897** the result from the [application-defined SQL function] with
4898** [sqlite3_context] C to be the value T.  Only the lower 8 bits
4899** of the subtype T are preserved in current versions of SQLite;
4900** higher order bits are discarded.
4901** The number of subtype bytes preserved by SQLite might increase
4902** in future releases of SQLite.
4903*/
4904SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
4905
4906/*
4907** CAPI3REF: Define New Collating Sequences
4908** METHOD: sqlite3
4909**
4910** ^These functions add, remove, or modify a [collation] associated
4911** with the [database connection] specified as the first argument.
4912**
4913** ^The name of the collation is a UTF-8 string
4914** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4915** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4916** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4917** considered to be the same name.
4918**
4919** ^(The third argument (eTextRep) must be one of the constants:
4920** <ul>
4921** <li> [SQLITE_UTF8],
4922** <li> [SQLITE_UTF16LE],
4923** <li> [SQLITE_UTF16BE],
4924** <li> [SQLITE_UTF16], or
4925** <li> [SQLITE_UTF16_ALIGNED].
4926** </ul>)^
4927** ^The eTextRep argument determines the encoding of strings passed
4928** to the collating function callback, xCallback.
4929** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4930** force strings to be UTF16 with native byte order.
4931** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4932** on an even byte address.
4933**
4934** ^The fourth argument, pArg, is an application data pointer that is passed
4935** through as the first argument to the collating function callback.
4936**
4937** ^The fifth argument, xCallback, is a pointer to the collating function.
4938** ^Multiple collating functions can be registered using the same name but
4939** with different eTextRep parameters and SQLite will use whichever
4940** function requires the least amount of data transformation.
4941** ^If the xCallback argument is NULL then the collating function is
4942** deleted.  ^When all collating functions having the same name are deleted,
4943** that collation is no longer usable.
4944**
4945** ^The collating function callback is invoked with a copy of the pArg
4946** application data pointer and with two strings in the encoding specified
4947** by the eTextRep argument.  The collating function must return an
4948** integer that is negative, zero, or positive
4949** if the first string is less than, equal to, or greater than the second,
4950** respectively.  A collating function must always return the same answer
4951** given the same inputs.  If two or more collating functions are registered
4952** to the same collation name (using different eTextRep values) then all
4953** must give an equivalent answer when invoked with equivalent strings.
4954** The collating function must obey the following properties for all
4955** strings A, B, and C:
4956**
4957** <ol>
4958** <li> If A==B then B==A.
4959** <li> If A==B and B==C then A==C.
4960** <li> If A&lt;B THEN B&gt;A.
4961** <li> If A&lt;B and B&lt;C then A&lt;C.
4962** </ol>
4963**
4964** If a collating function fails any of the above constraints and that
4965** collating function is  registered and used, then the behavior of SQLite
4966** is undefined.
4967**
4968** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4969** with the addition that the xDestroy callback is invoked on pArg when
4970** the collating function is deleted.
4971** ^Collating functions are deleted when they are overridden by later
4972** calls to the collation creation functions or when the
4973** [database connection] is closed using [sqlite3_close()].
4974**
4975** ^The xDestroy callback is <u>not</u> called if the
4976** sqlite3_create_collation_v2() function fails.  Applications that invoke
4977** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4978** check the return code and dispose of the application data pointer
4979** themselves rather than expecting SQLite to deal with it for them.
4980** This is different from every other SQLite interface.  The inconsistency
4981** is unfortunate but cannot be changed without breaking backwards
4982** compatibility.
4983**
4984** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4985*/
4986SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
4987  sqlite3*,
4988  const char *zName,
4989  int eTextRep,
4990  void *pArg,
4991  int(*xCompare)(void*,int,const void*,int,const void*)
4992);
4993SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
4994  sqlite3*,
4995  const char *zName,
4996  int eTextRep,
4997  void *pArg,
4998  int(*xCompare)(void*,int,const void*,int,const void*),
4999  void(*xDestroy)(void*)
5000);
5001SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
5002  sqlite3*,
5003  const void *zName,
5004  int eTextRep,
5005  void *pArg,
5006  int(*xCompare)(void*,int,const void*,int,const void*)
5007);
5008
5009/*
5010** CAPI3REF: Collation Needed Callbacks
5011** METHOD: sqlite3
5012**
5013** ^To avoid having to register all collation sequences before a database
5014** can be used, a single callback function may be registered with the
5015** [database connection] to be invoked whenever an undefined collation
5016** sequence is required.
5017**
5018** ^If the function is registered using the sqlite3_collation_needed() API,
5019** then it is passed the names of undefined collation sequences as strings
5020** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5021** the names are passed as UTF-16 in machine native byte order.
5022** ^A call to either function replaces the existing collation-needed callback.
5023**
5024** ^(When the callback is invoked, the first argument passed is a copy
5025** of the second argument to sqlite3_collation_needed() or
5026** sqlite3_collation_needed16().  The second argument is the database
5027** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5028** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5029** sequence function required.  The fourth parameter is the name of the
5030** required collation sequence.)^
5031**
5032** The callback function should register the desired collation using
5033** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5034** [sqlite3_create_collation_v2()].
5035*/
5036SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
5037  sqlite3*,
5038  void*,
5039  void(*)(void*,sqlite3*,int eTextRep,const char*)
5040);
5041SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
5042  sqlite3*,
5043  void*,
5044  void(*)(void*,sqlite3*,int eTextRep,const void*)
5045);
5046
5047#ifdef SQLITE_HAS_CODEC
5048/*
5049** Specify the key for an encrypted database.  This routine should be
5050** called right after sqlite3_open().
5051**
5052** The code to implement this API is not available in the public release
5053** of SQLite.
5054*/
5055SQLITE_API int SQLITE_STDCALL sqlite3_key(
5056  sqlite3 *db,                   /* Database to be rekeyed */
5057  const void *pKey, int nKey     /* The key */
5058);
5059SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
5060  sqlite3 *db,                   /* Database to be rekeyed */
5061  const char *zDbName,           /* Name of the database */
5062  const void *pKey, int nKey     /* The key */
5063);
5064
5065/*
5066** Change the key on an open database.  If the current database is not
5067** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5068** database is decrypted.
5069**
5070** The code to implement this API is not available in the public release
5071** of SQLite.
5072*/
5073SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5074  sqlite3 *db,                   /* Database to be rekeyed */
5075  const void *pKey, int nKey     /* The new key */
5076);
5077SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5078  sqlite3 *db,                   /* Database to be rekeyed */
5079  const char *zDbName,           /* Name of the database */
5080  const void *pKey, int nKey     /* The new key */
5081);
5082
5083/*
5084** Specify the activation key for a SEE database.  Unless
5085** activated, none of the SEE routines will work.
5086*/
5087SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5088  const char *zPassPhrase        /* Activation phrase */
5089);
5090#endif
5091
5092#ifdef SQLITE_ENABLE_CEROD
5093/*
5094** Specify the activation key for a CEROD database.  Unless
5095** activated, none of the CEROD routines will work.
5096*/
5097SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5098  const char *zPassPhrase        /* Activation phrase */
5099);
5100#endif
5101
5102/*
5103** CAPI3REF: Suspend Execution For A Short Time
5104**
5105** The sqlite3_sleep() function causes the current thread to suspend execution
5106** for at least a number of milliseconds specified in its parameter.
5107**
5108** If the operating system does not support sleep requests with
5109** millisecond time resolution, then the time will be rounded up to
5110** the nearest second. The number of milliseconds of sleep actually
5111** requested from the operating system is returned.
5112**
5113** ^SQLite implements this interface by calling the xSleep()
5114** method of the default [sqlite3_vfs] object.  If the xSleep() method
5115** of the default VFS is not implemented correctly, or not implemented at
5116** all, then the behavior of sqlite3_sleep() may deviate from the description
5117** in the previous paragraphs.
5118*/
5119SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5120
5121/*
5122** CAPI3REF: Name Of The Folder Holding Temporary Files
5123**
5124** ^(If this global variable is made to point to a string which is
5125** the name of a folder (a.k.a. directory), then all temporary files
5126** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5127** will be placed in that directory.)^  ^If this variable
5128** is a NULL pointer, then SQLite performs a search for an appropriate
5129** temporary file directory.
5130**
5131** Applications are strongly discouraged from using this global variable.
5132** It is required to set a temporary folder on Windows Runtime (WinRT).
5133** But for all other platforms, it is highly recommended that applications
5134** neither read nor write this variable.  This global variable is a relic
5135** that exists for backwards compatibility of legacy applications and should
5136** be avoided in new projects.
5137**
5138** It is not safe to read or modify this variable in more than one
5139** thread at a time.  It is not safe to read or modify this variable
5140** if a [database connection] is being used at the same time in a separate
5141** thread.
5142** It is intended that this variable be set once
5143** as part of process initialization and before any SQLite interface
5144** routines have been called and that this variable remain unchanged
5145** thereafter.
5146**
5147** ^The [temp_store_directory pragma] may modify this variable and cause
5148** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5149** the [temp_store_directory pragma] always assumes that any string
5150** that this variable points to is held in memory obtained from
5151** [sqlite3_malloc] and the pragma may attempt to free that memory
5152** using [sqlite3_free].
5153** Hence, if this variable is modified directly, either it should be
5154** made NULL or made to point to memory obtained from [sqlite3_malloc]
5155** or else the use of the [temp_store_directory pragma] should be avoided.
5156** Except when requested by the [temp_store_directory pragma], SQLite
5157** does not free the memory that sqlite3_temp_directory points to.  If
5158** the application wants that memory to be freed, it must do
5159** so itself, taking care to only do so after all [database connection]
5160** objects have been destroyed.
5161**
5162** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5163** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5164** features that require the use of temporary files may fail.  Here is an
5165** example of how to do this using C++ with the Windows Runtime:
5166**
5167** <blockquote><pre>
5168** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5169** &nbsp;     TemporaryFolder->Path->Data();
5170** char zPathBuf&#91;MAX_PATH + 1&#93;;
5171** memset(zPathBuf, 0, sizeof(zPathBuf));
5172** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5173** &nbsp;     NULL, NULL);
5174** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5175** </pre></blockquote>
5176*/
5177SQLITE_API char *sqlite3_temp_directory;
5178
5179/*
5180** CAPI3REF: Name Of The Folder Holding Database Files
5181**
5182** ^(If this global variable is made to point to a string which is
5183** the name of a folder (a.k.a. directory), then all database files
5184** specified with a relative pathname and created or accessed by
5185** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5186** to be relative to that directory.)^ ^If this variable is a NULL
5187** pointer, then SQLite assumes that all database files specified
5188** with a relative pathname are relative to the current directory
5189** for the process.  Only the windows VFS makes use of this global
5190** variable; it is ignored by the unix VFS.
5191**
5192** Changing the value of this variable while a database connection is
5193** open can result in a corrupt database.
5194**
5195** It is not safe to read or modify this variable in more than one
5196** thread at a time.  It is not safe to read or modify this variable
5197** if a [database connection] is being used at the same time in a separate
5198** thread.
5199** It is intended that this variable be set once
5200** as part of process initialization and before any SQLite interface
5201** routines have been called and that this variable remain unchanged
5202** thereafter.
5203**
5204** ^The [data_store_directory pragma] may modify this variable and cause
5205** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5206** the [data_store_directory pragma] always assumes that any string
5207** that this variable points to is held in memory obtained from
5208** [sqlite3_malloc] and the pragma may attempt to free that memory
5209** using [sqlite3_free].
5210** Hence, if this variable is modified directly, either it should be
5211** made NULL or made to point to memory obtained from [sqlite3_malloc]
5212** or else the use of the [data_store_directory pragma] should be avoided.
5213*/
5214SQLITE_API char *sqlite3_data_directory;
5215
5216/*
5217** CAPI3REF: Test For Auto-Commit Mode
5218** KEYWORDS: {autocommit mode}
5219** METHOD: sqlite3
5220**
5221** ^The sqlite3_get_autocommit() interface returns non-zero or
5222** zero if the given database connection is or is not in autocommit mode,
5223** respectively.  ^Autocommit mode is on by default.
5224** ^Autocommit mode is disabled by a [BEGIN] statement.
5225** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5226**
5227** If certain kinds of errors occur on a statement within a multi-statement
5228** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5229** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5230** transaction might be rolled back automatically.  The only way to
5231** find out whether SQLite automatically rolled back the transaction after
5232** an error is to use this function.
5233**
5234** If another thread changes the autocommit status of the database
5235** connection while this routine is running, then the return value
5236** is undefined.
5237*/
5238SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5239
5240/*
5241** CAPI3REF: Find The Database Handle Of A Prepared Statement
5242** METHOD: sqlite3_stmt
5243**
5244** ^The sqlite3_db_handle interface returns the [database connection] handle
5245** to which a [prepared statement] belongs.  ^The [database connection]
5246** returned by sqlite3_db_handle is the same [database connection]
5247** that was the first argument
5248** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5249** create the statement in the first place.
5250*/
5251SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5252
5253/*
5254** CAPI3REF: Return The Filename For A Database Connection
5255** METHOD: sqlite3
5256**
5257** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5258** associated with database N of connection D.  ^The main database file
5259** has the name "main".  If there is no attached database N on the database
5260** connection D, or if database N is a temporary or in-memory database, then
5261** a NULL pointer is returned.
5262**
5263** ^The filename returned by this function is the output of the
5264** xFullPathname method of the [VFS].  ^In other words, the filename
5265** will be an absolute pathname, even if the filename used
5266** to open the database originally was a URI or relative pathname.
5267*/
5268SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5269
5270/*
5271** CAPI3REF: Determine if a database is read-only
5272** METHOD: sqlite3
5273**
5274** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5275** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5276** the name of a database on connection D.
5277*/
5278SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5279
5280/*
5281** CAPI3REF: Find the next prepared statement
5282** METHOD: sqlite3
5283**
5284** ^This interface returns a pointer to the next [prepared statement] after
5285** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5286** then this interface returns a pointer to the first prepared statement
5287** associated with the database connection pDb.  ^If no prepared statement
5288** satisfies the conditions of this routine, it returns NULL.
5289**
5290** The [database connection] pointer D in a call to
5291** [sqlite3_next_stmt(D,S)] must refer to an open database
5292** connection and in particular must not be a NULL pointer.
5293*/
5294SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5295
5296/*
5297** CAPI3REF: Commit And Rollback Notification Callbacks
5298** METHOD: sqlite3
5299**
5300** ^The sqlite3_commit_hook() interface registers a callback
5301** function to be invoked whenever a transaction is [COMMIT | committed].
5302** ^Any callback set by a previous call to sqlite3_commit_hook()
5303** for the same database connection is overridden.
5304** ^The sqlite3_rollback_hook() interface registers a callback
5305** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5306** ^Any callback set by a previous call to sqlite3_rollback_hook()
5307** for the same database connection is overridden.
5308** ^The pArg argument is passed through to the callback.
5309** ^If the callback on a commit hook function returns non-zero,
5310** then the commit is converted into a rollback.
5311**
5312** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5313** return the P argument from the previous call of the same function
5314** on the same [database connection] D, or NULL for
5315** the first call for each function on D.
5316**
5317** The commit and rollback hook callbacks are not reentrant.
5318** The callback implementation must not do anything that will modify
5319** the database connection that invoked the callback.  Any actions
5320** to modify the database connection must be deferred until after the
5321** completion of the [sqlite3_step()] call that triggered the commit
5322** or rollback hook in the first place.
5323** Note that running any other SQL statements, including SELECT statements,
5324** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5325** the database connections for the meaning of "modify" in this paragraph.
5326**
5327** ^Registering a NULL function disables the callback.
5328**
5329** ^When the commit hook callback routine returns zero, the [COMMIT]
5330** operation is allowed to continue normally.  ^If the commit hook
5331** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5332** ^The rollback hook is invoked on a rollback that results from a commit
5333** hook returning non-zero, just as it would be with any other rollback.
5334**
5335** ^For the purposes of this API, a transaction is said to have been
5336** rolled back if an explicit "ROLLBACK" statement is executed, or
5337** an error or constraint causes an implicit rollback to occur.
5338** ^The rollback callback is not invoked if a transaction is
5339** automatically rolled back because the database connection is closed.
5340**
5341** See also the [sqlite3_update_hook()] interface.
5342*/
5343SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5344SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5345
5346/*
5347** CAPI3REF: Data Change Notification Callbacks
5348** METHOD: sqlite3
5349**
5350** ^The sqlite3_update_hook() interface registers a callback function
5351** with the [database connection] identified by the first argument
5352** to be invoked whenever a row is updated, inserted or deleted in
5353** a rowid table.
5354** ^Any callback set by a previous call to this function
5355** for the same database connection is overridden.
5356**
5357** ^The second argument is a pointer to the function to invoke when a
5358** row is updated, inserted or deleted in a rowid table.
5359** ^The first argument to the callback is a copy of the third argument
5360** to sqlite3_update_hook().
5361** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5362** or [SQLITE_UPDATE], depending on the operation that caused the callback
5363** to be invoked.
5364** ^The third and fourth arguments to the callback contain pointers to the
5365** database and table name containing the affected row.
5366** ^The final callback parameter is the [rowid] of the row.
5367** ^In the case of an update, this is the [rowid] after the update takes place.
5368**
5369** ^(The update hook is not invoked when internal system tables are
5370** modified (i.e. sqlite_master and sqlite_sequence).)^
5371** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5372**
5373** ^In the current implementation, the update hook
5374** is not invoked when duplication rows are deleted because of an
5375** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5376** invoked when rows are deleted using the [truncate optimization].
5377** The exceptions defined in this paragraph might change in a future
5378** release of SQLite.
5379**
5380** The update hook implementation must not do anything that will modify
5381** the database connection that invoked the update hook.  Any actions
5382** to modify the database connection must be deferred until after the
5383** completion of the [sqlite3_step()] call that triggered the update hook.
5384** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5385** database connections for the meaning of "modify" in this paragraph.
5386**
5387** ^The sqlite3_update_hook(D,C,P) function
5388** returns the P argument from the previous call
5389** on the same [database connection] D, or NULL for
5390** the first call on D.
5391**
5392** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5393** interfaces.
5394*/
5395SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5396  sqlite3*,
5397  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5398  void*
5399);
5400
5401/*
5402** CAPI3REF: Enable Or Disable Shared Pager Cache
5403**
5404** ^(This routine enables or disables the sharing of the database cache
5405** and schema data structures between [database connection | connections]
5406** to the same database. Sharing is enabled if the argument is true
5407** and disabled if the argument is false.)^
5408**
5409** ^Cache sharing is enabled and disabled for an entire process.
5410** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5411** sharing was enabled or disabled for each thread separately.
5412**
5413** ^(The cache sharing mode set by this interface effects all subsequent
5414** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5415** Existing database connections continue use the sharing mode
5416** that was in effect at the time they were opened.)^
5417**
5418** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5419** successfully.  An [error code] is returned otherwise.)^
5420**
5421** ^Shared cache is disabled by default. But this might change in
5422** future releases of SQLite.  Applications that care about shared
5423** cache setting should set it explicitly.
5424**
5425** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5426** and will always return SQLITE_MISUSE. On those systems,
5427** shared cache mode should be enabled per-database connection via
5428** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5429**
5430** This interface is threadsafe on processors where writing a
5431** 32-bit integer is atomic.
5432**
5433** See Also:  [SQLite Shared-Cache Mode]
5434*/
5435SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5436
5437/*
5438** CAPI3REF: Attempt To Free Heap Memory
5439**
5440** ^The sqlite3_release_memory() interface attempts to free N bytes
5441** of heap memory by deallocating non-essential memory allocations
5442** held by the database library.   Memory used to cache database
5443** pages to improve performance is an example of non-essential memory.
5444** ^sqlite3_release_memory() returns the number of bytes actually freed,
5445** which might be more or less than the amount requested.
5446** ^The sqlite3_release_memory() routine is a no-op returning zero
5447** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5448**
5449** See also: [sqlite3_db_release_memory()]
5450*/
5451SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5452
5453/*
5454** CAPI3REF: Free Memory Used By A Database Connection
5455** METHOD: sqlite3
5456**
5457** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5458** memory as possible from database connection D. Unlike the
5459** [sqlite3_release_memory()] interface, this interface is in effect even
5460** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5461** omitted.
5462**
5463** See also: [sqlite3_release_memory()]
5464*/
5465SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5466
5467/*
5468** CAPI3REF: Impose A Limit On Heap Size
5469**
5470** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5471** soft limit on the amount of heap memory that may be allocated by SQLite.
5472** ^SQLite strives to keep heap memory utilization below the soft heap
5473** limit by reducing the number of pages held in the page cache
5474** as heap memory usages approaches the limit.
5475** ^The soft heap limit is "soft" because even though SQLite strives to stay
5476** below the limit, it will exceed the limit rather than generate
5477** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5478** is advisory only.
5479**
5480** ^The return value from sqlite3_soft_heap_limit64() is the size of
5481** the soft heap limit prior to the call, or negative in the case of an
5482** error.  ^If the argument N is negative
5483** then no change is made to the soft heap limit.  Hence, the current
5484** size of the soft heap limit can be determined by invoking
5485** sqlite3_soft_heap_limit64() with a negative argument.
5486**
5487** ^If the argument N is zero then the soft heap limit is disabled.
5488**
5489** ^(The soft heap limit is not enforced in the current implementation
5490** if one or more of following conditions are true:
5491**
5492** <ul>
5493** <li> The soft heap limit is set to zero.
5494** <li> Memory accounting is disabled using a combination of the
5495**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5496**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5497** <li> An alternative page cache implementation is specified using
5498**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5499** <li> The page cache allocates from its own memory pool supplied
5500**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5501**      from the heap.
5502** </ul>)^
5503**
5504** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5505** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5506** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5507** the soft heap limit is enforced on every memory allocation.  Without
5508** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5509** when memory is allocated by the page cache.  Testing suggests that because
5510** the page cache is the predominate memory user in SQLite, most
5511** applications will achieve adequate soft heap limit enforcement without
5512** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5513**
5514** The circumstances under which SQLite will enforce the soft heap limit may
5515** changes in future releases of SQLite.
5516*/
5517SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5518
5519/*
5520** CAPI3REF: Deprecated Soft Heap Limit Interface
5521** DEPRECATED
5522**
5523** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5524** interface.  This routine is provided for historical compatibility
5525** only.  All new applications should use the
5526** [sqlite3_soft_heap_limit64()] interface rather than this one.
5527*/
5528SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5529
5530
5531/*
5532** CAPI3REF: Extract Metadata About A Column Of A Table
5533** METHOD: sqlite3
5534**
5535** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5536** information about column C of table T in database D
5537** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
5538** interface returns SQLITE_OK and fills in the non-NULL pointers in
5539** the final five arguments with appropriate values if the specified
5540** column exists.  ^The sqlite3_table_column_metadata() interface returns
5541** SQLITE_ERROR and if the specified column does not exist.
5542** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5543** NULL pointer, then this routine simply checks for the existance of the
5544** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5545** does not.
5546**
5547** ^The column is identified by the second, third and fourth parameters to
5548** this function. ^(The second parameter is either the name of the database
5549** (i.e. "main", "temp", or an attached database) containing the specified
5550** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5551** for the table using the same algorithm used by the database engine to
5552** resolve unqualified table references.
5553**
5554** ^The third and fourth parameters to this function are the table and column
5555** name of the desired column, respectively.
5556**
5557** ^Metadata is returned by writing to the memory locations passed as the 5th
5558** and subsequent parameters to this function. ^Any of these arguments may be
5559** NULL, in which case the corresponding element of metadata is omitted.
5560**
5561** ^(<blockquote>
5562** <table border="1">
5563** <tr><th> Parameter <th> Output<br>Type <th>  Description
5564**
5565** <tr><td> 5th <td> const char* <td> Data type
5566** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5567** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5568** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5569** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5570** </table>
5571** </blockquote>)^
5572**
5573** ^The memory pointed to by the character pointers returned for the
5574** declaration type and collation sequence is valid until the next
5575** call to any SQLite API function.
5576**
5577** ^If the specified table is actually a view, an [error code] is returned.
5578**
5579** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5580** is not a [WITHOUT ROWID] table and an
5581** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5582** parameters are set for the explicitly declared column. ^(If there is no
5583** [INTEGER PRIMARY KEY] column, then the outputs
5584** for the [rowid] are set as follows:
5585**
5586** <pre>
5587**     data type: "INTEGER"
5588**     collation sequence: "BINARY"
5589**     not null: 0
5590**     primary key: 1
5591**     auto increment: 0
5592** </pre>)^
5593**
5594** ^This function causes all database schemas to be read from disk and
5595** parsed, if that has not already been done, and returns an error if
5596** any errors are encountered while loading the schema.
5597*/
5598SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5599  sqlite3 *db,                /* Connection handle */
5600  const char *zDbName,        /* Database name or NULL */
5601  const char *zTableName,     /* Table name */
5602  const char *zColumnName,    /* Column name */
5603  char const **pzDataType,    /* OUTPUT: Declared data type */
5604  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5605  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5606  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5607  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5608);
5609
5610/*
5611** CAPI3REF: Load An Extension
5612** METHOD: sqlite3
5613**
5614** ^This interface loads an SQLite extension library from the named file.
5615**
5616** ^The sqlite3_load_extension() interface attempts to load an
5617** [SQLite extension] library contained in the file zFile.  If
5618** the file cannot be loaded directly, attempts are made to load
5619** with various operating-system specific extensions added.
5620** So for example, if "samplelib" cannot be loaded, then names like
5621** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5622** be tried also.
5623**
5624** ^The entry point is zProc.
5625** ^(zProc may be 0, in which case SQLite will try to come up with an
5626** entry point name on its own.  It first tries "sqlite3_extension_init".
5627** If that does not work, it constructs a name "sqlite3_X_init" where the
5628** X is consists of the lower-case equivalent of all ASCII alphabetic
5629** characters in the filename from the last "/" to the first following
5630** "." and omitting any initial "lib".)^
5631** ^The sqlite3_load_extension() interface returns
5632** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5633** ^If an error occurs and pzErrMsg is not 0, then the
5634** [sqlite3_load_extension()] interface shall attempt to
5635** fill *pzErrMsg with error message text stored in memory
5636** obtained from [sqlite3_malloc()]. The calling function
5637** should free this memory by calling [sqlite3_free()].
5638**
5639** ^Extension loading must be enabled using
5640** [sqlite3_enable_load_extension()] prior to calling this API,
5641** otherwise an error will be returned.
5642**
5643** See also the [load_extension() SQL function].
5644*/
5645SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5646  sqlite3 *db,          /* Load the extension into this database connection */
5647  const char *zFile,    /* Name of the shared library containing extension */
5648  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5649  char **pzErrMsg       /* Put error message here if not 0 */
5650);
5651
5652/*
5653** CAPI3REF: Enable Or Disable Extension Loading
5654** METHOD: sqlite3
5655**
5656** ^So as not to open security holes in older applications that are
5657** unprepared to deal with [extension loading], and as a means of disabling
5658** [extension loading] while evaluating user-entered SQL, the following API
5659** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5660**
5661** ^Extension loading is off by default.
5662** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5663** to turn extension loading on and call it with onoff==0 to turn
5664** it back off again.
5665*/
5666SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5667
5668/*
5669** CAPI3REF: Automatically Load Statically Linked Extensions
5670**
5671** ^This interface causes the xEntryPoint() function to be invoked for
5672** each new [database connection] that is created.  The idea here is that
5673** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5674** that is to be automatically loaded into all new database connections.
5675**
5676** ^(Even though the function prototype shows that xEntryPoint() takes
5677** no arguments and returns void, SQLite invokes xEntryPoint() with three
5678** arguments and expects and integer result as if the signature of the
5679** entry point where as follows:
5680**
5681** <blockquote><pre>
5682** &nbsp;  int xEntryPoint(
5683** &nbsp;    sqlite3 *db,
5684** &nbsp;    const char **pzErrMsg,
5685** &nbsp;    const struct sqlite3_api_routines *pThunk
5686** &nbsp;  );
5687** </pre></blockquote>)^
5688**
5689** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5690** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5691** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5692** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5693** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5694** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5695** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5696**
5697** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5698** on the list of automatic extensions is a harmless no-op. ^No entry point
5699** will be called more than once for each database connection that is opened.
5700**
5701** See also: [sqlite3_reset_auto_extension()]
5702** and [sqlite3_cancel_auto_extension()]
5703*/
5704SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
5705
5706/*
5707** CAPI3REF: Cancel Automatic Extension Loading
5708**
5709** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5710** initialization routine X that was registered using a prior call to
5711** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5712** routine returns 1 if initialization routine X was successfully
5713** unregistered and it returns 0 if X was not on the list of initialization
5714** routines.
5715*/
5716SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5717
5718/*
5719** CAPI3REF: Reset Automatic Extension Loading
5720**
5721** ^This interface disables all automatic extensions previously
5722** registered using [sqlite3_auto_extension()].
5723*/
5724SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
5725
5726/*
5727** The interface to the virtual-table mechanism is currently considered
5728** to be experimental.  The interface might change in incompatible ways.
5729** If this is a problem for you, do not use the interface at this time.
5730**
5731** When the virtual-table mechanism stabilizes, we will declare the
5732** interface fixed, support it indefinitely, and remove this comment.
5733*/
5734
5735/*
5736** Structures used by the virtual table interface
5737*/
5738typedef struct sqlite3_vtab sqlite3_vtab;
5739typedef struct sqlite3_index_info sqlite3_index_info;
5740typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5741typedef struct sqlite3_module sqlite3_module;
5742
5743/*
5744** CAPI3REF: Virtual Table Object
5745** KEYWORDS: sqlite3_module {virtual table module}
5746**
5747** This structure, sometimes called a "virtual table module",
5748** defines the implementation of a [virtual tables].
5749** This structure consists mostly of methods for the module.
5750**
5751** ^A virtual table module is created by filling in a persistent
5752** instance of this structure and passing a pointer to that instance
5753** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5754** ^The registration remains valid until it is replaced by a different
5755** module or until the [database connection] closes.  The content
5756** of this structure must not change while it is registered with
5757** any database connection.
5758*/
5759struct sqlite3_module {
5760  int iVersion;
5761  int (*xCreate)(sqlite3*, void *pAux,
5762               int argc, const char *const*argv,
5763               sqlite3_vtab **ppVTab, char**);
5764  int (*xConnect)(sqlite3*, void *pAux,
5765               int argc, const char *const*argv,
5766               sqlite3_vtab **ppVTab, char**);
5767  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5768  int (*xDisconnect)(sqlite3_vtab *pVTab);
5769  int (*xDestroy)(sqlite3_vtab *pVTab);
5770  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5771  int (*xClose)(sqlite3_vtab_cursor*);
5772  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5773                int argc, sqlite3_value **argv);
5774  int (*xNext)(sqlite3_vtab_cursor*);
5775  int (*xEof)(sqlite3_vtab_cursor*);
5776  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5777  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5778  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5779  int (*xBegin)(sqlite3_vtab *pVTab);
5780  int (*xSync)(sqlite3_vtab *pVTab);
5781  int (*xCommit)(sqlite3_vtab *pVTab);
5782  int (*xRollback)(sqlite3_vtab *pVTab);
5783  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5784                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5785                       void **ppArg);
5786  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5787  /* The methods above are in version 1 of the sqlite_module object. Those
5788  ** below are for version 2 and greater. */
5789  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5790  int (*xRelease)(sqlite3_vtab *pVTab, int);
5791  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5792};
5793
5794/*
5795** CAPI3REF: Virtual Table Indexing Information
5796** KEYWORDS: sqlite3_index_info
5797**
5798** The sqlite3_index_info structure and its substructures is used as part
5799** of the [virtual table] interface to
5800** pass information into and receive the reply from the [xBestIndex]
5801** method of a [virtual table module].  The fields under **Inputs** are the
5802** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5803** results into the **Outputs** fields.
5804**
5805** ^(The aConstraint[] array records WHERE clause constraints of the form:
5806**
5807** <blockquote>column OP expr</blockquote>
5808**
5809** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5810** stored in aConstraint[].op using one of the
5811** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5812** ^(The index of the column is stored in
5813** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5814** expr on the right-hand side can be evaluated (and thus the constraint
5815** is usable) and false if it cannot.)^
5816**
5817** ^The optimizer automatically inverts terms of the form "expr OP column"
5818** and makes other simplifications to the WHERE clause in an attempt to
5819** get as many WHERE clause terms into the form shown above as possible.
5820** ^The aConstraint[] array only reports WHERE clause terms that are
5821** relevant to the particular virtual table being queried.
5822**
5823** ^Information about the ORDER BY clause is stored in aOrderBy[].
5824** ^Each term of aOrderBy records a column of the ORDER BY clause.
5825**
5826** The [xBestIndex] method must fill aConstraintUsage[] with information
5827** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5828** the right-hand side of the corresponding aConstraint[] is evaluated
5829** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5830** is true, then the constraint is assumed to be fully handled by the
5831** virtual table and is not checked again by SQLite.)^
5832**
5833** ^The idxNum and idxPtr values are recorded and passed into the
5834** [xFilter] method.
5835** ^[sqlite3_free()] is used to free idxPtr if and only if
5836** needToFreeIdxPtr is true.
5837**
5838** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5839** the correct order to satisfy the ORDER BY clause so that no separate
5840** sorting step is required.
5841**
5842** ^The estimatedCost value is an estimate of the cost of a particular
5843** strategy. A cost of N indicates that the cost of the strategy is similar
5844** to a linear scan of an SQLite table with N rows. A cost of log(N)
5845** indicates that the expense of the operation is similar to that of a
5846** binary search on a unique indexed field of an SQLite table with N rows.
5847**
5848** ^The estimatedRows value is an estimate of the number of rows that
5849** will be returned by the strategy.
5850**
5851** The xBestIndex method may optionally populate the idxFlags field with a
5852** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
5853** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
5854** assumes that the strategy may visit at most one row.
5855**
5856** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
5857** SQLite also assumes that if a call to the xUpdate() method is made as
5858** part of the same statement to delete or update a virtual table row and the
5859** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
5860** any database changes. In other words, if the xUpdate() returns
5861** SQLITE_CONSTRAINT, the database contents must be exactly as they were
5862** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
5863** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
5864** the xUpdate method are automatically rolled back by SQLite.
5865**
5866** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5867** structure for SQLite version 3.8.2. If a virtual table extension is
5868** used with an SQLite version earlier than 3.8.2, the results of attempting
5869** to read or write the estimatedRows field are undefined (but are likely
5870** to included crashing the application). The estimatedRows field should
5871** therefore only be used if [sqlite3_libversion_number()] returns a
5872** value greater than or equal to 3008002. Similarly, the idxFlags field
5873** was added for version 3.9.0. It may therefore only be used if
5874** sqlite3_libversion_number() returns a value greater than or equal to
5875** 3009000.
5876*/
5877struct sqlite3_index_info {
5878  /* Inputs */
5879  int nConstraint;           /* Number of entries in aConstraint */
5880  struct sqlite3_index_constraint {
5881     int iColumn;              /* Column on left-hand side of constraint */
5882     unsigned char op;         /* Constraint operator */
5883     unsigned char usable;     /* True if this constraint is usable */
5884     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5885  } *aConstraint;            /* Table of WHERE clause constraints */
5886  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5887  struct sqlite3_index_orderby {
5888     int iColumn;              /* Column number */
5889     unsigned char desc;       /* True for DESC.  False for ASC. */
5890  } *aOrderBy;               /* The ORDER BY clause */
5891  /* Outputs */
5892  struct sqlite3_index_constraint_usage {
5893    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5894    unsigned char omit;      /* Do not code a test for this constraint */
5895  } *aConstraintUsage;
5896  int idxNum;                /* Number used to identify the index */
5897  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5898  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5899  int orderByConsumed;       /* True if output is already ordered */
5900  double estimatedCost;           /* Estimated cost of using this index */
5901  /* Fields below are only available in SQLite 3.8.2 and later */
5902  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
5903  /* Fields below are only available in SQLite 3.9.0 and later */
5904  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
5905};
5906
5907/*
5908** CAPI3REF: Virtual Table Scan Flags
5909*/
5910#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
5911
5912/*
5913** CAPI3REF: Virtual Table Constraint Operator Codes
5914**
5915** These macros defined the allowed values for the
5916** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5917** an operator that is part of a constraint term in the wHERE clause of
5918** a query that uses a [virtual table].
5919*/
5920#define SQLITE_INDEX_CONSTRAINT_EQ    2
5921#define SQLITE_INDEX_CONSTRAINT_GT    4
5922#define SQLITE_INDEX_CONSTRAINT_LE    8
5923#define SQLITE_INDEX_CONSTRAINT_LT    16
5924#define SQLITE_INDEX_CONSTRAINT_GE    32
5925#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5926
5927/*
5928** CAPI3REF: Register A Virtual Table Implementation
5929** METHOD: sqlite3
5930**
5931** ^These routines are used to register a new [virtual table module] name.
5932** ^Module names must be registered before
5933** creating a new [virtual table] using the module and before using a
5934** preexisting [virtual table] for the module.
5935**
5936** ^The module name is registered on the [database connection] specified
5937** by the first parameter.  ^The name of the module is given by the
5938** second parameter.  ^The third parameter is a pointer to
5939** the implementation of the [virtual table module].   ^The fourth
5940** parameter is an arbitrary client data pointer that is passed through
5941** into the [xCreate] and [xConnect] methods of the virtual table module
5942** when a new virtual table is be being created or reinitialized.
5943**
5944** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5945** is a pointer to a destructor for the pClientData.  ^SQLite will
5946** invoke the destructor function (if it is not NULL) when SQLite
5947** no longer needs the pClientData pointer.  ^The destructor will also
5948** be invoked if the call to sqlite3_create_module_v2() fails.
5949** ^The sqlite3_create_module()
5950** interface is equivalent to sqlite3_create_module_v2() with a NULL
5951** destructor.
5952*/
5953SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
5954  sqlite3 *db,               /* SQLite connection to register module with */
5955  const char *zName,         /* Name of the module */
5956  const sqlite3_module *p,   /* Methods for the module */
5957  void *pClientData          /* Client data for xCreate/xConnect */
5958);
5959SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
5960  sqlite3 *db,               /* SQLite connection to register module with */
5961  const char *zName,         /* Name of the module */
5962  const sqlite3_module *p,   /* Methods for the module */
5963  void *pClientData,         /* Client data for xCreate/xConnect */
5964  void(*xDestroy)(void*)     /* Module destructor function */
5965);
5966
5967/*
5968** CAPI3REF: Virtual Table Instance Object
5969** KEYWORDS: sqlite3_vtab
5970**
5971** Every [virtual table module] implementation uses a subclass
5972** of this object to describe a particular instance
5973** of the [virtual table].  Each subclass will
5974** be tailored to the specific needs of the module implementation.
5975** The purpose of this superclass is to define certain fields that are
5976** common to all module implementations.
5977**
5978** ^Virtual tables methods can set an error message by assigning a
5979** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5980** take care that any prior string is freed by a call to [sqlite3_free()]
5981** prior to assigning a new string to zErrMsg.  ^After the error message
5982** is delivered up to the client application, the string will be automatically
5983** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5984*/
5985struct sqlite3_vtab {
5986  const sqlite3_module *pModule;  /* The module for this virtual table */
5987  int nRef;                       /* Number of open cursors */
5988  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5989  /* Virtual table implementations will typically add additional fields */
5990};
5991
5992/*
5993** CAPI3REF: Virtual Table Cursor Object
5994** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5995**
5996** Every [virtual table module] implementation uses a subclass of the
5997** following structure to describe cursors that point into the
5998** [virtual table] and are used
5999** to loop through the virtual table.  Cursors are created using the
6000** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6001** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
6002** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6003** of the module.  Each module implementation will define
6004** the content of a cursor structure to suit its own needs.
6005**
6006** This superclass exists in order to define fields of the cursor that
6007** are common to all implementations.
6008*/
6009struct sqlite3_vtab_cursor {
6010  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6011  /* Virtual table implementations will typically add additional fields */
6012};
6013
6014/*
6015** CAPI3REF: Declare The Schema Of A Virtual Table
6016**
6017** ^The [xCreate] and [xConnect] methods of a
6018** [virtual table module] call this interface
6019** to declare the format (the names and datatypes of the columns) of
6020** the virtual tables they implement.
6021*/
6022SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6023
6024/*
6025** CAPI3REF: Overload A Function For A Virtual Table
6026** METHOD: sqlite3
6027**
6028** ^(Virtual tables can provide alternative implementations of functions
6029** using the [xFindFunction] method of the [virtual table module].
6030** But global versions of those functions
6031** must exist in order to be overloaded.)^
6032**
6033** ^(This API makes sure a global version of a function with a particular
6034** name and number of parameters exists.  If no such function exists
6035** before this API is called, a new function is created.)^  ^The implementation
6036** of the new function always causes an exception to be thrown.  So
6037** the new function is not good for anything by itself.  Its only
6038** purpose is to be a placeholder function that can be overloaded
6039** by a [virtual table].
6040*/
6041SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6042
6043/*
6044** The interface to the virtual-table mechanism defined above (back up
6045** to a comment remarkably similar to this one) is currently considered
6046** to be experimental.  The interface might change in incompatible ways.
6047** If this is a problem for you, do not use the interface at this time.
6048**
6049** When the virtual-table mechanism stabilizes, we will declare the
6050** interface fixed, support it indefinitely, and remove this comment.
6051*/
6052
6053/*
6054** CAPI3REF: A Handle To An Open BLOB
6055** KEYWORDS: {BLOB handle} {BLOB handles}
6056**
6057** An instance of this object represents an open BLOB on which
6058** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6059** ^Objects of this type are created by [sqlite3_blob_open()]
6060** and destroyed by [sqlite3_blob_close()].
6061** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6062** can be used to read or write small subsections of the BLOB.
6063** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6064*/
6065typedef struct sqlite3_blob sqlite3_blob;
6066
6067/*
6068** CAPI3REF: Open A BLOB For Incremental I/O
6069** METHOD: sqlite3
6070** CONSTRUCTOR: sqlite3_blob
6071**
6072** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6073** in row iRow, column zColumn, table zTable in database zDb;
6074** in other words, the same BLOB that would be selected by:
6075**
6076** <pre>
6077**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6078** </pre>)^
6079**
6080** ^(Parameter zDb is not the filename that contains the database, but
6081** rather the symbolic name of the database. For attached databases, this is
6082** the name that appears after the AS keyword in the [ATTACH] statement.
6083** For the main database file, the database name is "main". For TEMP
6084** tables, the database name is "temp".)^
6085**
6086** ^If the flags parameter is non-zero, then the BLOB is opened for read
6087** and write access. ^If the flags parameter is zero, the BLOB is opened for
6088** read-only access.
6089**
6090** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6091** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6092** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6093** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6094** on *ppBlob after this function it returns.
6095**
6096** This function fails with SQLITE_ERROR if any of the following are true:
6097** <ul>
6098**   <li> ^(Database zDb does not exist)^,
6099**   <li> ^(Table zTable does not exist within database zDb)^,
6100**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
6101**   <li> ^(Column zColumn does not exist)^,
6102**   <li> ^(Row iRow is not present in the table)^,
6103**   <li> ^(The specified column of row iRow contains a value that is not
6104**         a TEXT or BLOB value)^,
6105**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6106**         constraint and the blob is being opened for read/write access)^,
6107**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6108**         column zColumn is part of a [child key] definition and the blob is
6109**         being opened for read/write access)^.
6110** </ul>
6111**
6112** ^Unless it returns SQLITE_MISUSE, this function sets the
6113** [database connection] error code and message accessible via
6114** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6115**
6116**
6117** ^(If the row that a BLOB handle points to is modified by an
6118** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6119** then the BLOB handle is marked as "expired".
6120** This is true if any column of the row is changed, even a column
6121** other than the one the BLOB handle is open on.)^
6122** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6123** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6124** ^(Changes written into a BLOB prior to the BLOB expiring are not
6125** rolled back by the expiration of the BLOB.  Such changes will eventually
6126** commit if the transaction continues to completion.)^
6127**
6128** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6129** the opened blob.  ^The size of a blob may not be changed by this
6130** interface.  Use the [UPDATE] SQL command to change the size of a
6131** blob.
6132**
6133** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6134** and the built-in [zeroblob] SQL function may be used to create a
6135** zero-filled blob to read or write using the incremental-blob interface.
6136**
6137** To avoid a resource leak, every open [BLOB handle] should eventually
6138** be released by a call to [sqlite3_blob_close()].
6139*/
6140SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
6141  sqlite3*,
6142  const char *zDb,
6143  const char *zTable,
6144  const char *zColumn,
6145  sqlite3_int64 iRow,
6146  int flags,
6147  sqlite3_blob **ppBlob
6148);
6149
6150/*
6151** CAPI3REF: Move a BLOB Handle to a New Row
6152** METHOD: sqlite3_blob
6153**
6154** ^This function is used to move an existing blob handle so that it points
6155** to a different row of the same database table. ^The new row is identified
6156** by the rowid value passed as the second argument. Only the row can be
6157** changed. ^The database, table and column on which the blob handle is open
6158** remain the same. Moving an existing blob handle to a new row can be
6159** faster than closing the existing handle and opening a new one.
6160**
6161** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6162** it must exist and there must be either a blob or text value stored in
6163** the nominated column.)^ ^If the new row is not present in the table, or if
6164** it does not contain a blob or text value, or if another error occurs, an
6165** SQLite error code is returned and the blob handle is considered aborted.
6166** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6167** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6168** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6169** always returns zero.
6170**
6171** ^This function sets the database handle error code and message.
6172*/
6173SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6174
6175/*
6176** CAPI3REF: Close A BLOB Handle
6177** DESTRUCTOR: sqlite3_blob
6178**
6179** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6180** unconditionally.  Even if this routine returns an error code, the
6181** handle is still closed.)^
6182**
6183** ^If the blob handle being closed was opened for read-write access, and if
6184** the database is in auto-commit mode and there are no other open read-write
6185** blob handles or active write statements, the current transaction is
6186** committed. ^If an error occurs while committing the transaction, an error
6187** code is returned and the transaction rolled back.
6188**
6189** Calling this function with an argument that is not a NULL pointer or an
6190** open blob handle results in undefined behaviour. ^Calling this routine
6191** with a null pointer (such as would be returned by a failed call to
6192** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6193** is passed a valid open blob handle, the values returned by the
6194** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6195*/
6196SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6197
6198/*
6199** CAPI3REF: Return The Size Of An Open BLOB
6200** METHOD: sqlite3_blob
6201**
6202** ^Returns the size in bytes of the BLOB accessible via the
6203** successfully opened [BLOB handle] in its only argument.  ^The
6204** incremental blob I/O routines can only read or overwriting existing
6205** blob content; they cannot change the size of a blob.
6206**
6207** This routine only works on a [BLOB handle] which has been created
6208** by a prior successful call to [sqlite3_blob_open()] and which has not
6209** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6210** to this routine results in undefined and probably undesirable behavior.
6211*/
6212SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6213
6214/*
6215** CAPI3REF: Read Data From A BLOB Incrementally
6216** METHOD: sqlite3_blob
6217**
6218** ^(This function is used to read data from an open [BLOB handle] into a
6219** caller-supplied buffer. N bytes of data are copied into buffer Z
6220** from the open BLOB, starting at offset iOffset.)^
6221**
6222** ^If offset iOffset is less than N bytes from the end of the BLOB,
6223** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6224** less than zero, [SQLITE_ERROR] is returned and no data is read.
6225** ^The size of the blob (and hence the maximum value of N+iOffset)
6226** can be determined using the [sqlite3_blob_bytes()] interface.
6227**
6228** ^An attempt to read from an expired [BLOB handle] fails with an
6229** error code of [SQLITE_ABORT].
6230**
6231** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6232** Otherwise, an [error code] or an [extended error code] is returned.)^
6233**
6234** This routine only works on a [BLOB handle] which has been created
6235** by a prior successful call to [sqlite3_blob_open()] and which has not
6236** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6237** to this routine results in undefined and probably undesirable behavior.
6238**
6239** See also: [sqlite3_blob_write()].
6240*/
6241SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6242
6243/*
6244** CAPI3REF: Write Data Into A BLOB Incrementally
6245** METHOD: sqlite3_blob
6246**
6247** ^(This function is used to write data into an open [BLOB handle] from a
6248** caller-supplied buffer. N bytes of data are copied from the buffer Z
6249** into the open BLOB, starting at offset iOffset.)^
6250**
6251** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6252** Otherwise, an  [error code] or an [extended error code] is returned.)^
6253** ^Unless SQLITE_MISUSE is returned, this function sets the
6254** [database connection] error code and message accessible via
6255** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6256**
6257** ^If the [BLOB handle] passed as the first argument was not opened for
6258** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6259** this function returns [SQLITE_READONLY].
6260**
6261** This function may only modify the contents of the BLOB; it is
6262** not possible to increase the size of a BLOB using this API.
6263** ^If offset iOffset is less than N bytes from the end of the BLOB,
6264** [SQLITE_ERROR] is returned and no data is written. The size of the
6265** BLOB (and hence the maximum value of N+iOffset) can be determined
6266** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6267** than zero [SQLITE_ERROR] is returned and no data is written.
6268**
6269** ^An attempt to write to an expired [BLOB handle] fails with an
6270** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6271** before the [BLOB handle] expired are not rolled back by the
6272** expiration of the handle, though of course those changes might
6273** have been overwritten by the statement that expired the BLOB handle
6274** or by other independent statements.
6275**
6276** This routine only works on a [BLOB handle] which has been created
6277** by a prior successful call to [sqlite3_blob_open()] and which has not
6278** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6279** to this routine results in undefined and probably undesirable behavior.
6280**
6281** See also: [sqlite3_blob_read()].
6282*/
6283SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6284
6285/*
6286** CAPI3REF: Virtual File System Objects
6287**
6288** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6289** that SQLite uses to interact
6290** with the underlying operating system.  Most SQLite builds come with a
6291** single default VFS that is appropriate for the host computer.
6292** New VFSes can be registered and existing VFSes can be unregistered.
6293** The following interfaces are provided.
6294**
6295** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6296** ^Names are case sensitive.
6297** ^Names are zero-terminated UTF-8 strings.
6298** ^If there is no match, a NULL pointer is returned.
6299** ^If zVfsName is NULL then the default VFS is returned.
6300**
6301** ^New VFSes are registered with sqlite3_vfs_register().
6302** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6303** ^The same VFS can be registered multiple times without injury.
6304** ^To make an existing VFS into the default VFS, register it again
6305** with the makeDflt flag set.  If two different VFSes with the
6306** same name are registered, the behavior is undefined.  If a
6307** VFS is registered with a name that is NULL or an empty string,
6308** then the behavior is undefined.
6309**
6310** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6311** ^(If the default VFS is unregistered, another VFS is chosen as
6312** the default.  The choice for the new VFS is arbitrary.)^
6313*/
6314SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6315SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6316SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6317
6318/*
6319** CAPI3REF: Mutexes
6320**
6321** The SQLite core uses these routines for thread
6322** synchronization. Though they are intended for internal
6323** use by SQLite, code that links against SQLite is
6324** permitted to use any of these routines.
6325**
6326** The SQLite source code contains multiple implementations
6327** of these mutex routines.  An appropriate implementation
6328** is selected automatically at compile-time.  The following
6329** implementations are available in the SQLite core:
6330**
6331** <ul>
6332** <li>   SQLITE_MUTEX_PTHREADS
6333** <li>   SQLITE_MUTEX_W32
6334** <li>   SQLITE_MUTEX_NOOP
6335** </ul>
6336**
6337** The SQLITE_MUTEX_NOOP implementation is a set of routines
6338** that does no real locking and is appropriate for use in
6339** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
6340** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6341** and Windows.
6342**
6343** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6344** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6345** implementation is included with the library. In this case the
6346** application must supply a custom mutex implementation using the
6347** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6348** before calling sqlite3_initialize() or any other public sqlite3_
6349** function that calls sqlite3_initialize().
6350**
6351** ^The sqlite3_mutex_alloc() routine allocates a new
6352** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6353** routine returns NULL if it is unable to allocate the requested
6354** mutex.  The argument to sqlite3_mutex_alloc() must one of these
6355** integer constants:
6356**
6357** <ul>
6358** <li>  SQLITE_MUTEX_FAST
6359** <li>  SQLITE_MUTEX_RECURSIVE
6360** <li>  SQLITE_MUTEX_STATIC_MASTER
6361** <li>  SQLITE_MUTEX_STATIC_MEM
6362** <li>  SQLITE_MUTEX_STATIC_OPEN
6363** <li>  SQLITE_MUTEX_STATIC_PRNG
6364** <li>  SQLITE_MUTEX_STATIC_LRU
6365** <li>  SQLITE_MUTEX_STATIC_PMEM
6366** <li>  SQLITE_MUTEX_STATIC_APP1
6367** <li>  SQLITE_MUTEX_STATIC_APP2
6368** <li>  SQLITE_MUTEX_STATIC_APP3
6369** <li>  SQLITE_MUTEX_STATIC_VFS1
6370** <li>  SQLITE_MUTEX_STATIC_VFS2
6371** <li>  SQLITE_MUTEX_STATIC_VFS3
6372** </ul>
6373**
6374** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6375** cause sqlite3_mutex_alloc() to create
6376** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6377** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6378** The mutex implementation does not need to make a distinction
6379** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6380** not want to.  SQLite will only request a recursive mutex in
6381** cases where it really needs one.  If a faster non-recursive mutex
6382** implementation is available on the host platform, the mutex subsystem
6383** might return such a mutex in response to SQLITE_MUTEX_FAST.
6384**
6385** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6386** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6387** a pointer to a static preexisting mutex.  ^Nine static mutexes are
6388** used by the current version of SQLite.  Future versions of SQLite
6389** may add additional static mutexes.  Static mutexes are for internal
6390** use by SQLite only.  Applications that use SQLite mutexes should
6391** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6392** SQLITE_MUTEX_RECURSIVE.
6393**
6394** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6395** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6396** returns a different mutex on every call.  ^For the static
6397** mutex types, the same mutex is returned on every call that has
6398** the same type number.
6399**
6400** ^The sqlite3_mutex_free() routine deallocates a previously
6401** allocated dynamic mutex.  Attempting to deallocate a static
6402** mutex results in undefined behavior.
6403**
6404** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6405** to enter a mutex.  ^If another thread is already within the mutex,
6406** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6407** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6408** upon successful entry.  ^(Mutexes created using
6409** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6410** In such cases, the
6411** mutex must be exited an equal number of times before another thread
6412** can enter.)^  If the same thread tries to enter any mutex other
6413** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6414**
6415** ^(Some systems (for example, Windows 95) do not support the operation
6416** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6417** will always return SQLITE_BUSY. The SQLite core only ever uses
6418** sqlite3_mutex_try() as an optimization so this is acceptable
6419** behavior.)^
6420**
6421** ^The sqlite3_mutex_leave() routine exits a mutex that was
6422** previously entered by the same thread.   The behavior
6423** is undefined if the mutex is not currently entered by the
6424** calling thread or is not currently allocated.
6425**
6426** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6427** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6428** behave as no-ops.
6429**
6430** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6431*/
6432SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6433SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6434SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6435SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6436SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6437
6438/*
6439** CAPI3REF: Mutex Methods Object
6440**
6441** An instance of this structure defines the low-level routines
6442** used to allocate and use mutexes.
6443**
6444** Usually, the default mutex implementations provided by SQLite are
6445** sufficient, however the application has the option of substituting a custom
6446** implementation for specialized deployments or systems for which SQLite
6447** does not provide a suitable implementation. In this case, the application
6448** creates and populates an instance of this structure to pass
6449** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6450** Additionally, an instance of this structure can be used as an
6451** output variable when querying the system for the current mutex
6452** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6453**
6454** ^The xMutexInit method defined by this structure is invoked as
6455** part of system initialization by the sqlite3_initialize() function.
6456** ^The xMutexInit routine is called by SQLite exactly once for each
6457** effective call to [sqlite3_initialize()].
6458**
6459** ^The xMutexEnd method defined by this structure is invoked as
6460** part of system shutdown by the sqlite3_shutdown() function. The
6461** implementation of this method is expected to release all outstanding
6462** resources obtained by the mutex methods implementation, especially
6463** those obtained by the xMutexInit method.  ^The xMutexEnd()
6464** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6465**
6466** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6467** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6468** xMutexNotheld) implement the following interfaces (respectively):
6469**
6470** <ul>
6471**   <li>  [sqlite3_mutex_alloc()] </li>
6472**   <li>  [sqlite3_mutex_free()] </li>
6473**   <li>  [sqlite3_mutex_enter()] </li>
6474**   <li>  [sqlite3_mutex_try()] </li>
6475**   <li>  [sqlite3_mutex_leave()] </li>
6476**   <li>  [sqlite3_mutex_held()] </li>
6477**   <li>  [sqlite3_mutex_notheld()] </li>
6478** </ul>)^
6479**
6480** The only difference is that the public sqlite3_XXX functions enumerated
6481** above silently ignore any invocations that pass a NULL pointer instead
6482** of a valid mutex handle. The implementations of the methods defined
6483** by this structure are not required to handle this case, the results
6484** of passing a NULL pointer instead of a valid mutex handle are undefined
6485** (i.e. it is acceptable to provide an implementation that segfaults if
6486** it is passed a NULL pointer).
6487**
6488** The xMutexInit() method must be threadsafe.  It must be harmless to
6489** invoke xMutexInit() multiple times within the same process and without
6490** intervening calls to xMutexEnd().  Second and subsequent calls to
6491** xMutexInit() must be no-ops.
6492**
6493** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6494** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
6495** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6496** memory allocation for a fast or recursive mutex.
6497**
6498** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6499** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6500** If xMutexInit fails in any way, it is expected to clean up after itself
6501** prior to returning.
6502*/
6503typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6504struct sqlite3_mutex_methods {
6505  int (*xMutexInit)(void);
6506  int (*xMutexEnd)(void);
6507  sqlite3_mutex *(*xMutexAlloc)(int);
6508  void (*xMutexFree)(sqlite3_mutex *);
6509  void (*xMutexEnter)(sqlite3_mutex *);
6510  int (*xMutexTry)(sqlite3_mutex *);
6511  void (*xMutexLeave)(sqlite3_mutex *);
6512  int (*xMutexHeld)(sqlite3_mutex *);
6513  int (*xMutexNotheld)(sqlite3_mutex *);
6514};
6515
6516/*
6517** CAPI3REF: Mutex Verification Routines
6518**
6519** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6520** are intended for use inside assert() statements.  The SQLite core
6521** never uses these routines except inside an assert() and applications
6522** are advised to follow the lead of the core.  The SQLite core only
6523** provides implementations for these routines when it is compiled
6524** with the SQLITE_DEBUG flag.  External mutex implementations
6525** are only required to provide these routines if SQLITE_DEBUG is
6526** defined and if NDEBUG is not defined.
6527**
6528** These routines should return true if the mutex in their argument
6529** is held or not held, respectively, by the calling thread.
6530**
6531** The implementation is not required to provide versions of these
6532** routines that actually work. If the implementation does not provide working
6533** versions of these routines, it should at least provide stubs that always
6534** return true so that one does not get spurious assertion failures.
6535**
6536** If the argument to sqlite3_mutex_held() is a NULL pointer then
6537** the routine should return 1.   This seems counter-intuitive since
6538** clearly the mutex cannot be held if it does not exist.  But
6539** the reason the mutex does not exist is because the build is not
6540** using mutexes.  And we do not want the assert() containing the
6541** call to sqlite3_mutex_held() to fail, so a non-zero return is
6542** the appropriate thing to do.  The sqlite3_mutex_notheld()
6543** interface should also return 1 when given a NULL pointer.
6544*/
6545#ifndef NDEBUG
6546SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6547SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6548#endif
6549
6550/*
6551** CAPI3REF: Mutex Types
6552**
6553** The [sqlite3_mutex_alloc()] interface takes a single argument
6554** which is one of these integer constants.
6555**
6556** The set of static mutexes may change from one SQLite release to the
6557** next.  Applications that override the built-in mutex logic must be
6558** prepared to accommodate additional static mutexes.
6559*/
6560#define SQLITE_MUTEX_FAST             0
6561#define SQLITE_MUTEX_RECURSIVE        1
6562#define SQLITE_MUTEX_STATIC_MASTER    2
6563#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6564#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6565#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6566#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6567#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6568#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6569#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6570#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6571#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6572#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6573#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
6574#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
6575#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
6576
6577/*
6578** CAPI3REF: Retrieve the mutex for a database connection
6579** METHOD: sqlite3
6580**
6581** ^This interface returns a pointer the [sqlite3_mutex] object that
6582** serializes access to the [database connection] given in the argument
6583** when the [threading mode] is Serialized.
6584** ^If the [threading mode] is Single-thread or Multi-thread then this
6585** routine returns a NULL pointer.
6586*/
6587SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6588
6589/*
6590** CAPI3REF: Low-Level Control Of Database Files
6591** METHOD: sqlite3
6592**
6593** ^The [sqlite3_file_control()] interface makes a direct call to the
6594** xFileControl method for the [sqlite3_io_methods] object associated
6595** with a particular database identified by the second argument. ^The
6596** name of the database is "main" for the main database or "temp" for the
6597** TEMP database, or the name that appears after the AS keyword for
6598** databases that are added using the [ATTACH] SQL command.
6599** ^A NULL pointer can be used in place of "main" to refer to the
6600** main database file.
6601** ^The third and fourth parameters to this routine
6602** are passed directly through to the second and third parameters of
6603** the xFileControl method.  ^The return value of the xFileControl
6604** method becomes the return value of this routine.
6605**
6606** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6607** a pointer to the underlying [sqlite3_file] object to be written into
6608** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6609** case is a short-circuit path which does not actually invoke the
6610** underlying sqlite3_io_methods.xFileControl method.
6611**
6612** ^If the second parameter (zDbName) does not match the name of any
6613** open database file, then SQLITE_ERROR is returned.  ^This error
6614** code is not remembered and will not be recalled by [sqlite3_errcode()]
6615** or [sqlite3_errmsg()].  The underlying xFileControl method might
6616** also return SQLITE_ERROR.  There is no way to distinguish between
6617** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6618** xFileControl method.
6619**
6620** See also: [SQLITE_FCNTL_LOCKSTATE]
6621*/
6622SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6623
6624/*
6625** CAPI3REF: Testing Interface
6626**
6627** ^The sqlite3_test_control() interface is used to read out internal
6628** state of SQLite and to inject faults into SQLite for testing
6629** purposes.  ^The first parameter is an operation code that determines
6630** the number, meaning, and operation of all subsequent parameters.
6631**
6632** This interface is not for use by applications.  It exists solely
6633** for verifying the correct operation of the SQLite library.  Depending
6634** on how the SQLite library is compiled, this interface might not exist.
6635**
6636** The details of the operation codes, their meanings, the parameters
6637** they take, and what they do are all subject to change without notice.
6638** Unlike most of the SQLite API, this function is not guaranteed to
6639** operate consistently from one release to the next.
6640*/
6641SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6642
6643/*
6644** CAPI3REF: Testing Interface Operation Codes
6645**
6646** These constants are the valid operation code parameters used
6647** as the first argument to [sqlite3_test_control()].
6648**
6649** These parameters and their meanings are subject to change
6650** without notice.  These values are for testing purposes only.
6651** Applications should not use any of these parameters or the
6652** [sqlite3_test_control()] interface.
6653*/
6654#define SQLITE_TESTCTRL_FIRST                    5
6655#define SQLITE_TESTCTRL_PRNG_SAVE                5
6656#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6657#define SQLITE_TESTCTRL_PRNG_RESET               7
6658#define SQLITE_TESTCTRL_BITVEC_TEST              8
6659#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6660#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6661#define SQLITE_TESTCTRL_PENDING_BYTE            11
6662#define SQLITE_TESTCTRL_ASSERT                  12
6663#define SQLITE_TESTCTRL_ALWAYS                  13
6664#define SQLITE_TESTCTRL_RESERVE                 14
6665#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6666#define SQLITE_TESTCTRL_ISKEYWORD               16
6667#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6668#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6669#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
6670#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6671#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6672#define SQLITE_TESTCTRL_BYTEORDER               22
6673#define SQLITE_TESTCTRL_ISINIT                  23
6674#define SQLITE_TESTCTRL_SORTER_MMAP             24
6675#define SQLITE_TESTCTRL_IMPOSTER                25
6676#define SQLITE_TESTCTRL_LAST                    25
6677
6678/*
6679** CAPI3REF: SQLite Runtime Status
6680**
6681** ^These interfaces are used to retrieve runtime status information
6682** about the performance of SQLite, and optionally to reset various
6683** highwater marks.  ^The first argument is an integer code for
6684** the specific parameter to measure.  ^(Recognized integer codes
6685** are of the form [status parameters | SQLITE_STATUS_...].)^
6686** ^The current value of the parameter is returned into *pCurrent.
6687** ^The highest recorded value is returned in *pHighwater.  ^If the
6688** resetFlag is true, then the highest record value is reset after
6689** *pHighwater is written.  ^(Some parameters do not record the highest
6690** value.  For those parameters
6691** nothing is written into *pHighwater and the resetFlag is ignored.)^
6692** ^(Other parameters record only the highwater mark and not the current
6693** value.  For these latter parameters nothing is written into *pCurrent.)^
6694**
6695** ^The sqlite3_status() and sqlite3_status64() routines return
6696** SQLITE_OK on success and a non-zero [error code] on failure.
6697**
6698** If either the current value or the highwater mark is too large to
6699** be represented by a 32-bit integer, then the values returned by
6700** sqlite3_status() are undefined.
6701**
6702** See also: [sqlite3_db_status()]
6703*/
6704SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6705SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6706  int op,
6707  sqlite3_int64 *pCurrent,
6708  sqlite3_int64 *pHighwater,
6709  int resetFlag
6710);
6711
6712
6713/*
6714** CAPI3REF: Status Parameters
6715** KEYWORDS: {status parameters}
6716**
6717** These integer constants designate various run-time status parameters
6718** that can be returned by [sqlite3_status()].
6719**
6720** <dl>
6721** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6722** <dd>This parameter is the current amount of memory checked out
6723** using [sqlite3_malloc()], either directly or indirectly.  The
6724** figure includes calls made to [sqlite3_malloc()] by the application
6725** and internal memory usage by the SQLite library.  Scratch memory
6726** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6727** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6728** this parameter.  The amount returned is the sum of the allocation
6729** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6730**
6731** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6732** <dd>This parameter records the largest memory allocation request
6733** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6734** internal equivalents).  Only the value returned in the
6735** *pHighwater parameter to [sqlite3_status()] is of interest.
6736** The value written into the *pCurrent parameter is undefined.</dd>)^
6737**
6738** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6739** <dd>This parameter records the number of separate memory allocations
6740** currently checked out.</dd>)^
6741**
6742** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6743** <dd>This parameter returns the number of pages used out of the
6744** [pagecache memory allocator] that was configured using
6745** [SQLITE_CONFIG_PAGECACHE].  The
6746** value returned is in pages, not in bytes.</dd>)^
6747**
6748** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6749** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6750** <dd>This parameter returns the number of bytes of page cache
6751** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6752** buffer and where forced to overflow to [sqlite3_malloc()].  The
6753** returned value includes allocations that overflowed because they
6754** where too large (they were larger than the "sz" parameter to
6755** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6756** no space was left in the page cache.</dd>)^
6757**
6758** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6759** <dd>This parameter records the largest memory allocation request
6760** handed to [pagecache memory allocator].  Only the value returned in the
6761** *pHighwater parameter to [sqlite3_status()] is of interest.
6762** The value written into the *pCurrent parameter is undefined.</dd>)^
6763**
6764** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6765** <dd>This parameter returns the number of allocations used out of the
6766** [scratch memory allocator] configured using
6767** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6768** in bytes.  Since a single thread may only have one scratch allocation
6769** outstanding at time, this parameter also reports the number of threads
6770** using scratch memory at the same time.</dd>)^
6771**
6772** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6773** <dd>This parameter returns the number of bytes of scratch memory
6774** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6775** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6776** returned include overflows because the requested allocation was too
6777** larger (that is, because the requested allocation was larger than the
6778** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6779** slots were available.
6780** </dd>)^
6781**
6782** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6783** <dd>This parameter records the largest memory allocation request
6784** handed to [scratch memory allocator].  Only the value returned in the
6785** *pHighwater parameter to [sqlite3_status()] is of interest.
6786** The value written into the *pCurrent parameter is undefined.</dd>)^
6787**
6788** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6789** <dd>This parameter records the deepest parser stack.  It is only
6790** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6791** </dl>
6792**
6793** New status parameters may be added from time to time.
6794*/
6795#define SQLITE_STATUS_MEMORY_USED          0
6796#define SQLITE_STATUS_PAGECACHE_USED       1
6797#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6798#define SQLITE_STATUS_SCRATCH_USED         3
6799#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6800#define SQLITE_STATUS_MALLOC_SIZE          5
6801#define SQLITE_STATUS_PARSER_STACK         6
6802#define SQLITE_STATUS_PAGECACHE_SIZE       7
6803#define SQLITE_STATUS_SCRATCH_SIZE         8
6804#define SQLITE_STATUS_MALLOC_COUNT         9
6805
6806/*
6807** CAPI3REF: Database Connection Status
6808** METHOD: sqlite3
6809**
6810** ^This interface is used to retrieve runtime status information
6811** about a single [database connection].  ^The first argument is the
6812** database connection object to be interrogated.  ^The second argument
6813** is an integer constant, taken from the set of
6814** [SQLITE_DBSTATUS options], that
6815** determines the parameter to interrogate.  The set of
6816** [SQLITE_DBSTATUS options] is likely
6817** to grow in future releases of SQLite.
6818**
6819** ^The current value of the requested parameter is written into *pCur
6820** and the highest instantaneous value is written into *pHiwtr.  ^If
6821** the resetFlg is true, then the highest instantaneous value is
6822** reset back down to the current value.
6823**
6824** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6825** non-zero [error code] on failure.
6826**
6827** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6828*/
6829SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6830
6831/*
6832** CAPI3REF: Status Parameters for database connections
6833** KEYWORDS: {SQLITE_DBSTATUS options}
6834**
6835** These constants are the available integer "verbs" that can be passed as
6836** the second argument to the [sqlite3_db_status()] interface.
6837**
6838** New verbs may be added in future releases of SQLite. Existing verbs
6839** might be discontinued. Applications should check the return code from
6840** [sqlite3_db_status()] to make sure that the call worked.
6841** The [sqlite3_db_status()] interface will return a non-zero error code
6842** if a discontinued or unsupported verb is invoked.
6843**
6844** <dl>
6845** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6846** <dd>This parameter returns the number of lookaside memory slots currently
6847** checked out.</dd>)^
6848**
6849** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6850** <dd>This parameter returns the number malloc attempts that were
6851** satisfied using lookaside memory. Only the high-water value is meaningful;
6852** the current value is always zero.)^
6853**
6854** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6855** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6856** <dd>This parameter returns the number malloc attempts that might have
6857** been satisfied using lookaside memory but failed due to the amount of
6858** memory requested being larger than the lookaside slot size.
6859** Only the high-water value is meaningful;
6860** the current value is always zero.)^
6861**
6862** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6863** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6864** <dd>This parameter returns the number malloc attempts that might have
6865** been satisfied using lookaside memory but failed due to all lookaside
6866** memory already being in use.
6867** Only the high-water value is meaningful;
6868** the current value is always zero.)^
6869**
6870** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6871** <dd>This parameter returns the approximate number of bytes of heap
6872** memory used by all pager caches associated with the database connection.)^
6873** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6874**
6875** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6876** <dd>This parameter returns the approximate number of bytes of heap
6877** memory used to store the schema for all databases associated
6878** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6879** ^The full amount of memory used by the schemas is reported, even if the
6880** schema memory is shared with other database connections due to
6881** [shared cache mode] being enabled.
6882** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6883**
6884** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6885** <dd>This parameter returns the approximate number of bytes of heap
6886** and lookaside memory used by all prepared statements associated with
6887** the database connection.)^
6888** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6889** </dd>
6890**
6891** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6892** <dd>This parameter returns the number of pager cache hits that have
6893** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6894** is always 0.
6895** </dd>
6896**
6897** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6898** <dd>This parameter returns the number of pager cache misses that have
6899** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6900** is always 0.
6901** </dd>
6902**
6903** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6904** <dd>This parameter returns the number of dirty cache entries that have
6905** been written to disk. Specifically, the number of pages written to the
6906** wal file in wal mode databases, or the number of pages written to the
6907** database file in rollback mode databases. Any pages written as part of
6908** transaction rollback or database recovery operations are not included.
6909** If an IO or other error occurs while writing a page to disk, the effect
6910** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6911** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6912** </dd>
6913**
6914** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6915** <dd>This parameter returns zero for the current value if and only if
6916** all foreign key constraints (deferred or immediate) have been
6917** resolved.)^  ^The highwater mark is always 0.
6918** </dd>
6919** </dl>
6920*/
6921#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6922#define SQLITE_DBSTATUS_CACHE_USED           1
6923#define SQLITE_DBSTATUS_SCHEMA_USED          2
6924#define SQLITE_DBSTATUS_STMT_USED            3
6925#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6926#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6927#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6928#define SQLITE_DBSTATUS_CACHE_HIT            7
6929#define SQLITE_DBSTATUS_CACHE_MISS           8
6930#define SQLITE_DBSTATUS_CACHE_WRITE          9
6931#define SQLITE_DBSTATUS_DEFERRED_FKS        10
6932#define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
6933
6934
6935/*
6936** CAPI3REF: Prepared Statement Status
6937** METHOD: sqlite3_stmt
6938**
6939** ^(Each prepared statement maintains various
6940** [SQLITE_STMTSTATUS counters] that measure the number
6941** of times it has performed specific operations.)^  These counters can
6942** be used to monitor the performance characteristics of the prepared
6943** statements.  For example, if the number of table steps greatly exceeds
6944** the number of table searches or result rows, that would tend to indicate
6945** that the prepared statement is using a full table scan rather than
6946** an index.
6947**
6948** ^(This interface is used to retrieve and reset counter values from
6949** a [prepared statement].  The first argument is the prepared statement
6950** object to be interrogated.  The second argument
6951** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6952** to be interrogated.)^
6953** ^The current value of the requested counter is returned.
6954** ^If the resetFlg is true, then the counter is reset to zero after this
6955** interface call returns.
6956**
6957** See also: [sqlite3_status()] and [sqlite3_db_status()].
6958*/
6959SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6960
6961/*
6962** CAPI3REF: Status Parameters for prepared statements
6963** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6964**
6965** These preprocessor macros define integer codes that name counter
6966** values associated with the [sqlite3_stmt_status()] interface.
6967** The meanings of the various counters are as follows:
6968**
6969** <dl>
6970** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6971** <dd>^This is the number of times that SQLite has stepped forward in
6972** a table as part of a full table scan.  Large numbers for this counter
6973** may indicate opportunities for performance improvement through
6974** careful use of indices.</dd>
6975**
6976** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6977** <dd>^This is the number of sort operations that have occurred.
6978** A non-zero value in this counter may indicate an opportunity to
6979** improvement performance through careful use of indices.</dd>
6980**
6981** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6982** <dd>^This is the number of rows inserted into transient indices that
6983** were created automatically in order to help joins run faster.
6984** A non-zero value in this counter may indicate an opportunity to
6985** improvement performance by adding permanent indices that do not
6986** need to be reinitialized each time the statement is run.</dd>
6987**
6988** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6989** <dd>^This is the number of virtual machine operations executed
6990** by the prepared statement if that number is less than or equal
6991** to 2147483647.  The number of virtual machine operations can be
6992** used as a proxy for the total work done by the prepared statement.
6993** If the number of virtual machine operations exceeds 2147483647
6994** then the value returned by this statement status code is undefined.
6995** </dd>
6996** </dl>
6997*/
6998#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6999#define SQLITE_STMTSTATUS_SORT              2
7000#define SQLITE_STMTSTATUS_AUTOINDEX         3
7001#define SQLITE_STMTSTATUS_VM_STEP           4
7002
7003/*
7004** CAPI3REF: Custom Page Cache Object
7005**
7006** The sqlite3_pcache type is opaque.  It is implemented by
7007** the pluggable module.  The SQLite core has no knowledge of
7008** its size or internal structure and never deals with the
7009** sqlite3_pcache object except by holding and passing pointers
7010** to the object.
7011**
7012** See [sqlite3_pcache_methods2] for additional information.
7013*/
7014typedef struct sqlite3_pcache sqlite3_pcache;
7015
7016/*
7017** CAPI3REF: Custom Page Cache Object
7018**
7019** The sqlite3_pcache_page object represents a single page in the
7020** page cache.  The page cache will allocate instances of this
7021** object.  Various methods of the page cache use pointers to instances
7022** of this object as parameters or as their return value.
7023**
7024** See [sqlite3_pcache_methods2] for additional information.
7025*/
7026typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7027struct sqlite3_pcache_page {
7028  void *pBuf;        /* The content of the page */
7029  void *pExtra;      /* Extra information associated with the page */
7030};
7031
7032/*
7033** CAPI3REF: Application Defined Page Cache.
7034** KEYWORDS: {page cache}
7035**
7036** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7037** register an alternative page cache implementation by passing in an
7038** instance of the sqlite3_pcache_methods2 structure.)^
7039** In many applications, most of the heap memory allocated by
7040** SQLite is used for the page cache.
7041** By implementing a
7042** custom page cache using this API, an application can better control
7043** the amount of memory consumed by SQLite, the way in which
7044** that memory is allocated and released, and the policies used to
7045** determine exactly which parts of a database file are cached and for
7046** how long.
7047**
7048** The alternative page cache mechanism is an
7049** extreme measure that is only needed by the most demanding applications.
7050** The built-in page cache is recommended for most uses.
7051**
7052** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7053** internal buffer by SQLite within the call to [sqlite3_config].  Hence
7054** the application may discard the parameter after the call to
7055** [sqlite3_config()] returns.)^
7056**
7057** [[the xInit() page cache method]]
7058** ^(The xInit() method is called once for each effective
7059** call to [sqlite3_initialize()])^
7060** (usually only once during the lifetime of the process). ^(The xInit()
7061** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7062** The intent of the xInit() method is to set up global data structures
7063** required by the custom page cache implementation.
7064** ^(If the xInit() method is NULL, then the
7065** built-in default page cache is used instead of the application defined
7066** page cache.)^
7067**
7068** [[the xShutdown() page cache method]]
7069** ^The xShutdown() method is called by [sqlite3_shutdown()].
7070** It can be used to clean up
7071** any outstanding resources before process shutdown, if required.
7072** ^The xShutdown() method may be NULL.
7073**
7074** ^SQLite automatically serializes calls to the xInit method,
7075** so the xInit method need not be threadsafe.  ^The
7076** xShutdown method is only called from [sqlite3_shutdown()] so it does
7077** not need to be threadsafe either.  All other methods must be threadsafe
7078** in multithreaded applications.
7079**
7080** ^SQLite will never invoke xInit() more than once without an intervening
7081** call to xShutdown().
7082**
7083** [[the xCreate() page cache methods]]
7084** ^SQLite invokes the xCreate() method to construct a new cache instance.
7085** SQLite will typically create one cache instance for each open database file,
7086** though this is not guaranteed. ^The
7087** first parameter, szPage, is the size in bytes of the pages that must
7088** be allocated by the cache.  ^szPage will always a power of two.  ^The
7089** second parameter szExtra is a number of bytes of extra storage
7090** associated with each page cache entry.  ^The szExtra parameter will
7091** a number less than 250.  SQLite will use the
7092** extra szExtra bytes on each page to store metadata about the underlying
7093** database page on disk.  The value passed into szExtra depends
7094** on the SQLite version, the target platform, and how SQLite was compiled.
7095** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7096** created will be used to cache database pages of a file stored on disk, or
7097** false if it is used for an in-memory database. The cache implementation
7098** does not have to do anything special based with the value of bPurgeable;
7099** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
7100** never invoke xUnpin() except to deliberately delete a page.
7101** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7102** false will always have the "discard" flag set to true.
7103** ^Hence, a cache created with bPurgeable false will
7104** never contain any unpinned pages.
7105**
7106** [[the xCachesize() page cache method]]
7107** ^(The xCachesize() method may be called at any time by SQLite to set the
7108** suggested maximum cache-size (number of pages stored by) the cache
7109** instance passed as the first argument. This is the value configured using
7110** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
7111** parameter, the implementation is not required to do anything with this
7112** value; it is advisory only.
7113**
7114** [[the xPagecount() page cache methods]]
7115** The xPagecount() method must return the number of pages currently
7116** stored in the cache, both pinned and unpinned.
7117**
7118** [[the xFetch() page cache methods]]
7119** The xFetch() method locates a page in the cache and returns a pointer to
7120** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7121** The pBuf element of the returned sqlite3_pcache_page object will be a
7122** pointer to a buffer of szPage bytes used to store the content of a
7123** single database page.  The pExtra element of sqlite3_pcache_page will be
7124** a pointer to the szExtra bytes of extra storage that SQLite has requested
7125** for each entry in the page cache.
7126**
7127** The page to be fetched is determined by the key. ^The minimum key value
7128** is 1.  After it has been retrieved using xFetch, the page is considered
7129** to be "pinned".
7130**
7131** If the requested page is already in the page cache, then the page cache
7132** implementation must return a pointer to the page buffer with its content
7133** intact.  If the requested page is not already in the cache, then the
7134** cache implementation should use the value of the createFlag
7135** parameter to help it determined what action to take:
7136**
7137** <table border=1 width=85% align=center>
7138** <tr><th> createFlag <th> Behavior when page is not already in cache
7139** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7140** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7141**                 Otherwise return NULL.
7142** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7143**                 NULL if allocating a new page is effectively impossible.
7144** </table>
7145**
7146** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7147** will only use a createFlag of 2 after a prior call with a createFlag of 1
7148** failed.)^  In between the to xFetch() calls, SQLite may
7149** attempt to unpin one or more cache pages by spilling the content of
7150** pinned pages to disk and synching the operating system disk cache.
7151**
7152** [[the xUnpin() page cache method]]
7153** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7154** as its second argument.  If the third parameter, discard, is non-zero,
7155** then the page must be evicted from the cache.
7156** ^If the discard parameter is
7157** zero, then the page may be discarded or retained at the discretion of
7158** page cache implementation. ^The page cache implementation
7159** may choose to evict unpinned pages at any time.
7160**
7161** The cache must not perform any reference counting. A single
7162** call to xUnpin() unpins the page regardless of the number of prior calls
7163** to xFetch().
7164**
7165** [[the xRekey() page cache methods]]
7166** The xRekey() method is used to change the key value associated with the
7167** page passed as the second argument. If the cache
7168** previously contains an entry associated with newKey, it must be
7169** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7170** to be pinned.
7171**
7172** When SQLite calls the xTruncate() method, the cache must discard all
7173** existing cache entries with page numbers (keys) greater than or equal
7174** to the value of the iLimit parameter passed to xTruncate(). If any
7175** of these pages are pinned, they are implicitly unpinned, meaning that
7176** they can be safely discarded.
7177**
7178** [[the xDestroy() page cache method]]
7179** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7180** All resources associated with the specified cache should be freed. ^After
7181** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7182** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7183** functions.
7184**
7185** [[the xShrink() page cache method]]
7186** ^SQLite invokes the xShrink() method when it wants the page cache to
7187** free up as much of heap memory as possible.  The page cache implementation
7188** is not obligated to free any memory, but well-behaved implementations should
7189** do their best.
7190*/
7191typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7192struct sqlite3_pcache_methods2 {
7193  int iVersion;
7194  void *pArg;
7195  int (*xInit)(void*);
7196  void (*xShutdown)(void*);
7197  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7198  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7199  int (*xPagecount)(sqlite3_pcache*);
7200  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7201  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7202  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7203      unsigned oldKey, unsigned newKey);
7204  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7205  void (*xDestroy)(sqlite3_pcache*);
7206  void (*xShrink)(sqlite3_pcache*);
7207};
7208
7209/*
7210** This is the obsolete pcache_methods object that has now been replaced
7211** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7212** retained in the header file for backwards compatibility only.
7213*/
7214typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7215struct sqlite3_pcache_methods {
7216  void *pArg;
7217  int (*xInit)(void*);
7218  void (*xShutdown)(void*);
7219  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7220  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7221  int (*xPagecount)(sqlite3_pcache*);
7222  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7223  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7224  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7225  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7226  void (*xDestroy)(sqlite3_pcache*);
7227};
7228
7229
7230/*
7231** CAPI3REF: Online Backup Object
7232**
7233** The sqlite3_backup object records state information about an ongoing
7234** online backup operation.  ^The sqlite3_backup object is created by
7235** a call to [sqlite3_backup_init()] and is destroyed by a call to
7236** [sqlite3_backup_finish()].
7237**
7238** See Also: [Using the SQLite Online Backup API]
7239*/
7240typedef struct sqlite3_backup sqlite3_backup;
7241
7242/*
7243** CAPI3REF: Online Backup API.
7244**
7245** The backup API copies the content of one database into another.
7246** It is useful either for creating backups of databases or
7247** for copying in-memory databases to or from persistent files.
7248**
7249** See Also: [Using the SQLite Online Backup API]
7250**
7251** ^SQLite holds a write transaction open on the destination database file
7252** for the duration of the backup operation.
7253** ^The source database is read-locked only while it is being read;
7254** it is not locked continuously for the entire backup operation.
7255** ^Thus, the backup may be performed on a live source database without
7256** preventing other database connections from
7257** reading or writing to the source database while the backup is underway.
7258**
7259** ^(To perform a backup operation:
7260**   <ol>
7261**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7262**         backup,
7263**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7264**         the data between the two databases, and finally
7265**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7266**         associated with the backup operation.
7267**   </ol>)^
7268** There should be exactly one call to sqlite3_backup_finish() for each
7269** successful call to sqlite3_backup_init().
7270**
7271** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7272**
7273** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7274** [database connection] associated with the destination database
7275** and the database name, respectively.
7276** ^The database name is "main" for the main database, "temp" for the
7277** temporary database, or the name specified after the AS keyword in
7278** an [ATTACH] statement for an attached database.
7279** ^The S and M arguments passed to
7280** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7281** and database name of the source database, respectively.
7282** ^The source and destination [database connections] (parameters S and D)
7283** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7284** an error.
7285**
7286** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7287** there is already a read or read-write transaction open on the
7288** destination database.
7289**
7290** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7291** returned and an error code and error message are stored in the
7292** destination [database connection] D.
7293** ^The error code and message for the failed call to sqlite3_backup_init()
7294** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7295** [sqlite3_errmsg16()] functions.
7296** ^A successful call to sqlite3_backup_init() returns a pointer to an
7297** [sqlite3_backup] object.
7298** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7299** sqlite3_backup_finish() functions to perform the specified backup
7300** operation.
7301**
7302** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7303**
7304** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7305** the source and destination databases specified by [sqlite3_backup] object B.
7306** ^If N is negative, all remaining source pages are copied.
7307** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7308** are still more pages to be copied, then the function returns [SQLITE_OK].
7309** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7310** from source to destination, then it returns [SQLITE_DONE].
7311** ^If an error occurs while running sqlite3_backup_step(B,N),
7312** then an [error code] is returned. ^As well as [SQLITE_OK] and
7313** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7314** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7315** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7316**
7317** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7318** <ol>
7319** <li> the destination database was opened read-only, or
7320** <li> the destination database is using write-ahead-log journaling
7321** and the destination and source page sizes differ, or
7322** <li> the destination database is an in-memory database and the
7323** destination and source page sizes differ.
7324** </ol>)^
7325**
7326** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7327** the [sqlite3_busy_handler | busy-handler function]
7328** is invoked (if one is specified). ^If the
7329** busy-handler returns non-zero before the lock is available, then
7330** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7331** sqlite3_backup_step() can be retried later. ^If the source
7332** [database connection]
7333** is being used to write to the source database when sqlite3_backup_step()
7334** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7335** case the call to sqlite3_backup_step() can be retried later on. ^(If
7336** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7337** [SQLITE_READONLY] is returned, then
7338** there is no point in retrying the call to sqlite3_backup_step(). These
7339** errors are considered fatal.)^  The application must accept
7340** that the backup operation has failed and pass the backup operation handle
7341** to the sqlite3_backup_finish() to release associated resources.
7342**
7343** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7344** on the destination file. ^The exclusive lock is not released until either
7345** sqlite3_backup_finish() is called or the backup operation is complete
7346** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7347** sqlite3_backup_step() obtains a [shared lock] on the source database that
7348** lasts for the duration of the sqlite3_backup_step() call.
7349** ^Because the source database is not locked between calls to
7350** sqlite3_backup_step(), the source database may be modified mid-way
7351** through the backup process.  ^If the source database is modified by an
7352** external process or via a database connection other than the one being
7353** used by the backup operation, then the backup will be automatically
7354** restarted by the next call to sqlite3_backup_step(). ^If the source
7355** database is modified by the using the same database connection as is used
7356** by the backup operation, then the backup database is automatically
7357** updated at the same time.
7358**
7359** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7360**
7361** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7362** application wishes to abandon the backup operation, the application
7363** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7364** ^The sqlite3_backup_finish() interfaces releases all
7365** resources associated with the [sqlite3_backup] object.
7366** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7367** active write-transaction on the destination database is rolled back.
7368** The [sqlite3_backup] object is invalid
7369** and may not be used following a call to sqlite3_backup_finish().
7370**
7371** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7372** sqlite3_backup_step() errors occurred, regardless or whether or not
7373** sqlite3_backup_step() completed.
7374** ^If an out-of-memory condition or IO error occurred during any prior
7375** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7376** sqlite3_backup_finish() returns the corresponding [error code].
7377**
7378** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7379** is not a permanent error and does not affect the return value of
7380** sqlite3_backup_finish().
7381**
7382** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7383** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7384**
7385** ^The sqlite3_backup_remaining() routine returns the number of pages still
7386** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7387** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7388** in the source database at the conclusion of the most recent
7389** sqlite3_backup_step().
7390** ^(The values returned by these functions are only updated by
7391** sqlite3_backup_step(). If the source database is modified in a way that
7392** changes the size of the source database or the number of pages remaining,
7393** those changes are not reflected in the output of sqlite3_backup_pagecount()
7394** and sqlite3_backup_remaining() until after the next
7395** sqlite3_backup_step().)^
7396**
7397** <b>Concurrent Usage of Database Handles</b>
7398**
7399** ^The source [database connection] may be used by the application for other
7400** purposes while a backup operation is underway or being initialized.
7401** ^If SQLite is compiled and configured to support threadsafe database
7402** connections, then the source database connection may be used concurrently
7403** from within other threads.
7404**
7405** However, the application must guarantee that the destination
7406** [database connection] is not passed to any other API (by any thread) after
7407** sqlite3_backup_init() is called and before the corresponding call to
7408** sqlite3_backup_finish().  SQLite does not currently check to see
7409** if the application incorrectly accesses the destination [database connection]
7410** and so no error code is reported, but the operations may malfunction
7411** nevertheless.  Use of the destination database connection while a
7412** backup is in progress might also also cause a mutex deadlock.
7413**
7414** If running in [shared cache mode], the application must
7415** guarantee that the shared cache used by the destination database
7416** is not accessed while the backup is running. In practice this means
7417** that the application must guarantee that the disk file being
7418** backed up to is not accessed by any connection within the process,
7419** not just the specific connection that was passed to sqlite3_backup_init().
7420**
7421** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7422** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7423** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7424** APIs are not strictly speaking threadsafe. If they are invoked at the
7425** same time as another thread is invoking sqlite3_backup_step() it is
7426** possible that they return invalid values.
7427*/
7428SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7429  sqlite3 *pDest,                        /* Destination database handle */
7430  const char *zDestName,                 /* Destination database name */
7431  sqlite3 *pSource,                      /* Source database handle */
7432  const char *zSourceName                /* Source database name */
7433);
7434SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7435SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7436SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7437SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7438
7439/*
7440** CAPI3REF: Unlock Notification
7441** METHOD: sqlite3
7442**
7443** ^When running in shared-cache mode, a database operation may fail with
7444** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7445** individual tables within the shared-cache cannot be obtained. See
7446** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7447** ^This API may be used to register a callback that SQLite will invoke
7448** when the connection currently holding the required lock relinquishes it.
7449** ^This API is only available if the library was compiled with the
7450** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7451**
7452** See Also: [Using the SQLite Unlock Notification Feature].
7453**
7454** ^Shared-cache locks are released when a database connection concludes
7455** its current transaction, either by committing it or rolling it back.
7456**
7457** ^When a connection (known as the blocked connection) fails to obtain a
7458** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7459** identity of the database connection (the blocking connection) that
7460** has locked the required resource is stored internally. ^After an
7461** application receives an SQLITE_LOCKED error, it may call the
7462** sqlite3_unlock_notify() method with the blocked connection handle as
7463** the first argument to register for a callback that will be invoked
7464** when the blocking connections current transaction is concluded. ^The
7465** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7466** call that concludes the blocking connections transaction.
7467**
7468** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7469** there is a chance that the blocking connection will have already
7470** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7471** If this happens, then the specified callback is invoked immediately,
7472** from within the call to sqlite3_unlock_notify().)^
7473**
7474** ^If the blocked connection is attempting to obtain a write-lock on a
7475** shared-cache table, and more than one other connection currently holds
7476** a read-lock on the same table, then SQLite arbitrarily selects one of
7477** the other connections to use as the blocking connection.
7478**
7479** ^(There may be at most one unlock-notify callback registered by a
7480** blocked connection. If sqlite3_unlock_notify() is called when the
7481** blocked connection already has a registered unlock-notify callback,
7482** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7483** called with a NULL pointer as its second argument, then any existing
7484** unlock-notify callback is canceled. ^The blocked connections
7485** unlock-notify callback may also be canceled by closing the blocked
7486** connection using [sqlite3_close()].
7487**
7488** The unlock-notify callback is not reentrant. If an application invokes
7489** any sqlite3_xxx API functions from within an unlock-notify callback, a
7490** crash or deadlock may be the result.
7491**
7492** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7493** returns SQLITE_OK.
7494**
7495** <b>Callback Invocation Details</b>
7496**
7497** When an unlock-notify callback is registered, the application provides a
7498** single void* pointer that is passed to the callback when it is invoked.
7499** However, the signature of the callback function allows SQLite to pass
7500** it an array of void* context pointers. The first argument passed to
7501** an unlock-notify callback is a pointer to an array of void* pointers,
7502** and the second is the number of entries in the array.
7503**
7504** When a blocking connections transaction is concluded, there may be
7505** more than one blocked connection that has registered for an unlock-notify
7506** callback. ^If two or more such blocked connections have specified the
7507** same callback function, then instead of invoking the callback function
7508** multiple times, it is invoked once with the set of void* context pointers
7509** specified by the blocked connections bundled together into an array.
7510** This gives the application an opportunity to prioritize any actions
7511** related to the set of unblocked database connections.
7512**
7513** <b>Deadlock Detection</b>
7514**
7515** Assuming that after registering for an unlock-notify callback a
7516** database waits for the callback to be issued before taking any further
7517** action (a reasonable assumption), then using this API may cause the
7518** application to deadlock. For example, if connection X is waiting for
7519** connection Y's transaction to be concluded, and similarly connection
7520** Y is waiting on connection X's transaction, then neither connection
7521** will proceed and the system may remain deadlocked indefinitely.
7522**
7523** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7524** detection. ^If a given call to sqlite3_unlock_notify() would put the
7525** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7526** unlock-notify callback is registered. The system is said to be in
7527** a deadlocked state if connection A has registered for an unlock-notify
7528** callback on the conclusion of connection B's transaction, and connection
7529** B has itself registered for an unlock-notify callback when connection
7530** A's transaction is concluded. ^Indirect deadlock is also detected, so
7531** the system is also considered to be deadlocked if connection B has
7532** registered for an unlock-notify callback on the conclusion of connection
7533** C's transaction, where connection C is waiting on connection A. ^Any
7534** number of levels of indirection are allowed.
7535**
7536** <b>The "DROP TABLE" Exception</b>
7537**
7538** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7539** always appropriate to call sqlite3_unlock_notify(). There is however,
7540** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7541** SQLite checks if there are any currently executing SELECT statements
7542** that belong to the same connection. If there are, SQLITE_LOCKED is
7543** returned. In this case there is no "blocking connection", so invoking
7544** sqlite3_unlock_notify() results in the unlock-notify callback being
7545** invoked immediately. If the application then re-attempts the "DROP TABLE"
7546** or "DROP INDEX" query, an infinite loop might be the result.
7547**
7548** One way around this problem is to check the extended error code returned
7549** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7550** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7551** the special "DROP TABLE/INDEX" case, the extended error code is just
7552** SQLITE_LOCKED.)^
7553*/
7554SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7555  sqlite3 *pBlocked,                          /* Waiting connection */
7556  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7557  void *pNotifyArg                            /* Argument to pass to xNotify */
7558);
7559
7560
7561/*
7562** CAPI3REF: String Comparison
7563**
7564** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7565** and extensions to compare the contents of two buffers containing UTF-8
7566** strings in a case-independent fashion, using the same definition of "case
7567** independence" that SQLite uses internally when comparing identifiers.
7568*/
7569SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7570SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7571
7572/*
7573** CAPI3REF: String Globbing
7574*
7575** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7576** the glob pattern P, and it returns non-zero if string X does not match
7577** the glob pattern P.  ^The definition of glob pattern matching used in
7578** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7579** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7580** sensitive.
7581**
7582** Note that this routine returns zero on a match and non-zero if the strings
7583** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7584*/
7585SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7586
7587/*
7588** CAPI3REF: Error Logging Interface
7589**
7590** ^The [sqlite3_log()] interface writes a message into the [error log]
7591** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7592** ^If logging is enabled, the zFormat string and subsequent arguments are
7593** used with [sqlite3_snprintf()] to generate the final output string.
7594**
7595** The sqlite3_log() interface is intended for use by extensions such as
7596** virtual tables, collating functions, and SQL functions.  While there is
7597** nothing to prevent an application from calling sqlite3_log(), doing so
7598** is considered bad form.
7599**
7600** The zFormat string must not be NULL.
7601**
7602** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7603** will not use dynamically allocated memory.  The log message is stored in
7604** a fixed-length buffer on the stack.  If the log message is longer than
7605** a few hundred characters, it will be truncated to the length of the
7606** buffer.
7607*/
7608SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7609
7610/*
7611** CAPI3REF: Write-Ahead Log Commit Hook
7612** METHOD: sqlite3
7613**
7614** ^The [sqlite3_wal_hook()] function is used to register a callback that
7615** is invoked each time data is committed to a database in wal mode.
7616**
7617** ^(The callback is invoked by SQLite after the commit has taken place and
7618** the associated write-lock on the database released)^, so the implementation
7619** may read, write or [checkpoint] the database as required.
7620**
7621** ^The first parameter passed to the callback function when it is invoked
7622** is a copy of the third parameter passed to sqlite3_wal_hook() when
7623** registering the callback. ^The second is a copy of the database handle.
7624** ^The third parameter is the name of the database that was written to -
7625** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7626** is the number of pages currently in the write-ahead log file,
7627** including those that were just committed.
7628**
7629** The callback function should normally return [SQLITE_OK].  ^If an error
7630** code is returned, that error will propagate back up through the
7631** SQLite code base to cause the statement that provoked the callback
7632** to report an error, though the commit will have still occurred. If the
7633** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7634** that does not correspond to any valid SQLite error code, the results
7635** are undefined.
7636**
7637** A single database handle may have at most a single write-ahead log callback
7638** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7639** previously registered write-ahead log callback. ^Note that the
7640** [sqlite3_wal_autocheckpoint()] interface and the
7641** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7642** those overwrite any prior [sqlite3_wal_hook()] settings.
7643*/
7644SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7645  sqlite3*,
7646  int(*)(void *,sqlite3*,const char*,int),
7647  void*
7648);
7649
7650/*
7651** CAPI3REF: Configure an auto-checkpoint
7652** METHOD: sqlite3
7653**
7654** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7655** [sqlite3_wal_hook()] that causes any database on [database connection] D
7656** to automatically [checkpoint]
7657** after committing a transaction if there are N or
7658** more frames in the [write-ahead log] file.  ^Passing zero or
7659** a negative value as the nFrame parameter disables automatic
7660** checkpoints entirely.
7661**
7662** ^The callback registered by this function replaces any existing callback
7663** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7664** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7665** configured by this function.
7666**
7667** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7668** from SQL.
7669**
7670** ^Checkpoints initiated by this mechanism are
7671** [sqlite3_wal_checkpoint_v2|PASSIVE].
7672**
7673** ^Every new [database connection] defaults to having the auto-checkpoint
7674** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7675** pages.  The use of this interface
7676** is only necessary if the default setting is found to be suboptimal
7677** for a particular application.
7678*/
7679SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7680
7681/*
7682** CAPI3REF: Checkpoint a database
7683** METHOD: sqlite3
7684**
7685** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
7686** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
7687**
7688** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
7689** [write-ahead log] for database X on [database connection] D to be
7690** transferred into the database file and for the write-ahead log to
7691** be reset.  See the [checkpointing] documentation for addition
7692** information.
7693**
7694** This interface used to be the only way to cause a checkpoint to
7695** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
7696** interface was added.  This interface is retained for backwards
7697** compatibility and as a convenience for applications that need to manually
7698** start a callback but which do not need the full power (and corresponding
7699** complication) of [sqlite3_wal_checkpoint_v2()].
7700*/
7701SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7702
7703/*
7704** CAPI3REF: Checkpoint a database
7705** METHOD: sqlite3
7706**
7707** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
7708** operation on database X of [database connection] D in mode M.  Status
7709** information is written back into integers pointed to by L and C.)^
7710** ^(The M parameter must be a valid [checkpoint mode]:)^
7711**
7712** <dl>
7713** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7714**   ^Checkpoint as many frames as possible without waiting for any database
7715**   readers or writers to finish, then sync the database file if all frames
7716**   in the log were checkpointed. ^The [busy-handler callback]
7717**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
7718**   ^On the other hand, passive mode might leave the checkpoint unfinished
7719**   if there are concurrent readers or writers.
7720**
7721** <dt>SQLITE_CHECKPOINT_FULL<dd>
7722**   ^This mode blocks (it invokes the
7723**   [sqlite3_busy_handler|busy-handler callback]) until there is no
7724**   database writer and all readers are reading from the most recent database
7725**   snapshot. ^It then checkpoints all frames in the log file and syncs the
7726**   database file. ^This mode blocks new database writers while it is pending,
7727**   but new database readers are allowed to continue unimpeded.
7728**
7729** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7730**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
7731**   that after checkpointing the log file it blocks (calls the
7732**   [busy-handler callback])
7733**   until all readers are reading from the database file only. ^This ensures
7734**   that the next writer will restart the log file from the beginning.
7735**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
7736**   database writer attempts while it is pending, but does not impede readers.
7737**
7738** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
7739**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
7740**   addition that it also truncates the log file to zero bytes just prior
7741**   to a successful return.
7742** </dl>
7743**
7744** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
7745** the log file or to -1 if the checkpoint could not run because
7746** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
7747** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
7748** log file (including any that were already checkpointed before the function
7749** was called) or to -1 if the checkpoint could not run due to an error or
7750** because the database is not in WAL mode. ^Note that upon successful
7751** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
7752** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
7753**
7754** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
7755** any other process is running a checkpoint operation at the same time, the
7756** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
7757** busy-handler configured, it will not be invoked in this case.
7758**
7759** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
7760** exclusive "writer" lock on the database file. ^If the writer lock cannot be
7761** obtained immediately, and a busy-handler is configured, it is invoked and
7762** the writer lock retried until either the busy-handler returns 0 or the lock
7763** is successfully obtained. ^The busy-handler is also invoked while waiting for
7764** database readers as described above. ^If the busy-handler returns 0 before
7765** the writer lock is obtained or while waiting for database readers, the
7766** checkpoint operation proceeds from that point in the same way as
7767** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7768** without blocking any further. ^SQLITE_BUSY is returned in this case.
7769**
7770** ^If parameter zDb is NULL or points to a zero length string, then the
7771** specified operation is attempted on all WAL databases [attached] to
7772** [database connection] db.  In this case the
7773** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
7774** an SQLITE_BUSY error is encountered when processing one or more of the
7775** attached WAL databases, the operation is still attempted on any remaining
7776** attached databases and SQLITE_BUSY is returned at the end. ^If any other
7777** error occurs while processing an attached database, processing is abandoned
7778** and the error code is returned to the caller immediately. ^If no error
7779** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7780** databases, SQLITE_OK is returned.
7781**
7782** ^If database zDb is the name of an attached database that is not in WAL
7783** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
7784** zDb is not NULL (or a zero length string) and is not the name of any
7785** attached database, SQLITE_ERROR is returned to the caller.
7786**
7787** ^Unless it returns SQLITE_MISUSE,
7788** the sqlite3_wal_checkpoint_v2() interface
7789** sets the error information that is queried by
7790** [sqlite3_errcode()] and [sqlite3_errmsg()].
7791**
7792** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
7793** from SQL.
7794*/
7795SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
7796  sqlite3 *db,                    /* Database handle */
7797  const char *zDb,                /* Name of attached database (or NULL) */
7798  int eMode,                      /* SQLITE_CHECKPOINT_* value */
7799  int *pnLog,                     /* OUT: Size of WAL log in frames */
7800  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7801);
7802
7803/*
7804** CAPI3REF: Checkpoint Mode Values
7805** KEYWORDS: {checkpoint mode}
7806**
7807** These constants define all valid values for the "checkpoint mode" passed
7808** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
7809** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
7810** meaning of each of these checkpoint modes.
7811*/
7812#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
7813#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
7814#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
7815#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
7816
7817/*
7818** CAPI3REF: Virtual Table Interface Configuration
7819**
7820** This function may be called by either the [xConnect] or [xCreate] method
7821** of a [virtual table] implementation to configure
7822** various facets of the virtual table interface.
7823**
7824** If this interface is invoked outside the context of an xConnect or
7825** xCreate virtual table method then the behavior is undefined.
7826**
7827** At present, there is only one option that may be configured using
7828** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7829** may be added in the future.
7830*/
7831SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
7832
7833/*
7834** CAPI3REF: Virtual Table Configuration Options
7835**
7836** These macros define the various options to the
7837** [sqlite3_vtab_config()] interface that [virtual table] implementations
7838** can use to customize and optimize their behavior.
7839**
7840** <dl>
7841** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7842** <dd>Calls of the form
7843** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7844** where X is an integer.  If X is zero, then the [virtual table] whose
7845** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7846** support constraints.  In this configuration (which is the default) if
7847** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7848** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7849** specified as part of the users SQL statement, regardless of the actual
7850** ON CONFLICT mode specified.
7851**
7852** If X is non-zero, then the virtual table implementation guarantees
7853** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7854** any modifications to internal or persistent data structures have been made.
7855** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7856** is able to roll back a statement or database transaction, and abandon
7857** or continue processing the current SQL statement as appropriate.
7858** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7859** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7860** had been ABORT.
7861**
7862** Virtual table implementations that are required to handle OR REPLACE
7863** must do so within the [xUpdate] method. If a call to the
7864** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7865** CONFLICT policy is REPLACE, the virtual table implementation should
7866** silently replace the appropriate rows within the xUpdate callback and
7867** return SQLITE_OK. Or, if this is not possible, it may return
7868** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7869** constraint handling.
7870** </dl>
7871*/
7872#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7873
7874/*
7875** CAPI3REF: Determine The Virtual Table Conflict Policy
7876**
7877** This function may only be called from within a call to the [xUpdate] method
7878** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7879** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7880** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7881** of the SQL statement that triggered the call to the [xUpdate] method of the
7882** [virtual table].
7883*/
7884SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
7885
7886/*
7887** CAPI3REF: Conflict resolution modes
7888** KEYWORDS: {conflict resolution mode}
7889**
7890** These constants are returned by [sqlite3_vtab_on_conflict()] to
7891** inform a [virtual table] implementation what the [ON CONFLICT] mode
7892** is for the SQL statement being evaluated.
7893**
7894** Note that the [SQLITE_IGNORE] constant is also used as a potential
7895** return value from the [sqlite3_set_authorizer()] callback and that
7896** [SQLITE_ABORT] is also a [result code].
7897*/
7898#define SQLITE_ROLLBACK 1
7899/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7900#define SQLITE_FAIL     3
7901/* #define SQLITE_ABORT 4  // Also an error code */
7902#define SQLITE_REPLACE  5
7903
7904/*
7905** CAPI3REF: Prepared Statement Scan Status Opcodes
7906** KEYWORDS: {scanstatus options}
7907**
7908** The following constants can be used for the T parameter to the
7909** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
7910** different metric for sqlite3_stmt_scanstatus() to return.
7911**
7912** When the value returned to V is a string, space to hold that string is
7913** managed by the prepared statement S and will be automatically freed when
7914** S is finalized.
7915**
7916** <dl>
7917** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
7918** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
7919** set to the total number of times that the X-th loop has run.</dd>
7920**
7921** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
7922** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
7923** to the total number of rows examined by all iterations of the X-th loop.</dd>
7924**
7925** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
7926** <dd>^The "double" variable pointed to by the T parameter will be set to the
7927** query planner's estimate for the average number of rows output from each
7928** iteration of the X-th loop.  If the query planner's estimates was accurate,
7929** then this value will approximate the quotient NVISIT/NLOOP and the
7930** product of this value for all prior loops with the same SELECTID will
7931** be the NLOOP value for the current loop.
7932**
7933** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
7934** <dd>^The "const char *" variable pointed to by the T parameter will be set
7935** to a zero-terminated UTF-8 string containing the name of the index or table
7936** used for the X-th loop.
7937**
7938** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
7939** <dd>^The "const char *" variable pointed to by the T parameter will be set
7940** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
7941** description for the X-th loop.
7942**
7943** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
7944** <dd>^The "int" variable pointed to by the T parameter will be set to the
7945** "select-id" for the X-th loop.  The select-id identifies which query or
7946** subquery the loop is part of.  The main query has a select-id of zero.
7947** The select-id is the same value as is output in the first column
7948** of an [EXPLAIN QUERY PLAN] query.
7949** </dl>
7950*/
7951#define SQLITE_SCANSTAT_NLOOP    0
7952#define SQLITE_SCANSTAT_NVISIT   1
7953#define SQLITE_SCANSTAT_EST      2
7954#define SQLITE_SCANSTAT_NAME     3
7955#define SQLITE_SCANSTAT_EXPLAIN  4
7956#define SQLITE_SCANSTAT_SELECTID 5
7957
7958/*
7959** CAPI3REF: Prepared Statement Scan Status
7960** METHOD: sqlite3_stmt
7961**
7962** This interface returns information about the predicted and measured
7963** performance for pStmt.  Advanced applications can use this
7964** interface to compare the predicted and the measured performance and
7965** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
7966**
7967** Since this interface is expected to be rarely used, it is only
7968** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
7969** compile-time option.
7970**
7971** The "iScanStatusOp" parameter determines which status information to return.
7972** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
7973** of this interface is undefined.
7974** ^The requested measurement is written into a variable pointed to by
7975** the "pOut" parameter.
7976** Parameter "idx" identifies the specific loop to retrieve statistics for.
7977** Loops are numbered starting from zero. ^If idx is out of range - less than
7978** zero or greater than or equal to the total number of loops used to implement
7979** the statement - a non-zero value is returned and the variable that pOut
7980** points to is unchanged.
7981**
7982** ^Statistics might not be available for all loops in all statements. ^In cases
7983** where there exist loops with no available statistics, this function behaves
7984** as if the loop did not exist - it returns non-zero and leave the variable
7985** that pOut points to unchanged.
7986**
7987** See also: [sqlite3_stmt_scanstatus_reset()]
7988*/
7989SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
7990  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
7991  int idx,                  /* Index of loop to report on */
7992  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
7993  void *pOut                /* Result written here */
7994);
7995
7996/*
7997** CAPI3REF: Zero Scan-Status Counters
7998** METHOD: sqlite3_stmt
7999**
8000** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8001**
8002** This API is only available if the library is built with pre-processor
8003** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8004*/
8005SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8006
8007
8008/*
8009** Undo the hack that converts floating point types to integer for
8010** builds on processors without floating point support.
8011*/
8012#ifdef SQLITE_OMIT_FLOATING_POINT
8013# undef double
8014#endif
8015
8016#if 0
8017}  /* End of the 'extern "C"' block */
8018#endif
8019#endif /* _SQLITE3_H_ */
8020
8021/*
8022** 2010 August 30
8023**
8024** The author disclaims copyright to this source code.  In place of
8025** a legal notice, here is a blessing:
8026**
8027**    May you do good and not evil.
8028**    May you find forgiveness for yourself and forgive others.
8029**    May you share freely, never taking more than you give.
8030**
8031*************************************************************************
8032*/
8033
8034#ifndef _SQLITE3RTREE_H_
8035#define _SQLITE3RTREE_H_
8036
8037
8038#if 0
8039extern "C" {
8040#endif
8041
8042typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8043typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8044
8045/* The double-precision datatype used by RTree depends on the
8046** SQLITE_RTREE_INT_ONLY compile-time option.
8047*/
8048#ifdef SQLITE_RTREE_INT_ONLY
8049  typedef sqlite3_int64 sqlite3_rtree_dbl;
8050#else
8051  typedef double sqlite3_rtree_dbl;
8052#endif
8053
8054/*
8055** Register a geometry callback named zGeom that can be used as part of an
8056** R-Tree geometry query as follows:
8057**
8058**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8059*/
8060SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
8061  sqlite3 *db,
8062  const char *zGeom,
8063  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8064  void *pContext
8065);
8066
8067
8068/*
8069** A pointer to a structure of the following type is passed as the first
8070** argument to callbacks registered using rtree_geometry_callback().
8071*/
8072struct sqlite3_rtree_geometry {
8073  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
8074  int nParam;                     /* Size of array aParam[] */
8075  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
8076  void *pUser;                    /* Callback implementation user data */
8077  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
8078};
8079
8080/*
8081** Register a 2nd-generation geometry callback named zScore that can be
8082** used as part of an R-Tree geometry query as follows:
8083**
8084**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8085*/
8086SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
8087  sqlite3 *db,
8088  const char *zQueryFunc,
8089  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8090  void *pContext,
8091  void (*xDestructor)(void*)
8092);
8093
8094
8095/*
8096** A pointer to a structure of the following type is passed as the
8097** argument to scored geometry callback registered using
8098** sqlite3_rtree_query_callback().
8099**
8100** Note that the first 5 fields of this structure are identical to
8101** sqlite3_rtree_geometry.  This structure is a subclass of
8102** sqlite3_rtree_geometry.
8103*/
8104struct sqlite3_rtree_query_info {
8105  void *pContext;                   /* pContext from when function registered */
8106  int nParam;                       /* Number of function parameters */
8107  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
8108  void *pUser;                      /* callback can use this, if desired */
8109  void (*xDelUser)(void*);          /* function to free pUser */
8110  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
8111  unsigned int *anQueue;            /* Number of pending entries in the queue */
8112  int nCoord;                       /* Number of coordinates */
8113  int iLevel;                       /* Level of current node or entry */
8114  int mxLevel;                      /* The largest iLevel value in the tree */
8115  sqlite3_int64 iRowid;             /* Rowid for current entry */
8116  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
8117  int eParentWithin;                /* Visibility of parent node */
8118  int eWithin;                      /* OUT: Visiblity */
8119  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
8120  /* The following fields are only available in 3.8.11 and later */
8121  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
8122};
8123
8124/*
8125** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8126*/
8127#define NOT_WITHIN       0   /* Object completely outside of query region */
8128#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
8129#define FULLY_WITHIN     2   /* Object fully contained within query region */
8130
8131
8132#if 0
8133}  /* end of the 'extern "C"' block */
8134#endif
8135
8136#endif  /* ifndef _SQLITE3RTREE_H_ */
8137
8138/*
8139** 2014 May 31
8140**
8141** The author disclaims copyright to this source code.  In place of
8142** a legal notice, here is a blessing:
8143**
8144**    May you do good and not evil.
8145**    May you find forgiveness for yourself and forgive others.
8146**    May you share freely, never taking more than you give.
8147**
8148******************************************************************************
8149**
8150** Interfaces to extend FTS5. Using the interfaces defined in this file,
8151** FTS5 may be extended with:
8152**
8153**     * custom tokenizers, and
8154**     * custom auxiliary functions.
8155*/
8156
8157
8158#ifndef _FTS5_H
8159#define _FTS5_H
8160
8161
8162#if 0
8163extern "C" {
8164#endif
8165
8166/*************************************************************************
8167** CUSTOM AUXILIARY FUNCTIONS
8168**
8169** Virtual table implementations may overload SQL functions by implementing
8170** the sqlite3_module.xFindFunction() method.
8171*/
8172
8173typedef struct Fts5ExtensionApi Fts5ExtensionApi;
8174typedef struct Fts5Context Fts5Context;
8175typedef struct Fts5PhraseIter Fts5PhraseIter;
8176
8177typedef void (*fts5_extension_function)(
8178  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
8179  Fts5Context *pFts,              /* First arg to pass to pApi functions */
8180  sqlite3_context *pCtx,          /* Context for returning result/error */
8181  int nVal,                       /* Number of values in apVal[] array */
8182  sqlite3_value **apVal           /* Array of trailing arguments */
8183);
8184
8185struct Fts5PhraseIter {
8186  const unsigned char *a;
8187  const unsigned char *b;
8188};
8189
8190/*
8191** EXTENSION API FUNCTIONS
8192**
8193** xUserData(pFts):
8194**   Return a copy of the context pointer the extension function was
8195**   registered with.
8196**
8197** xColumnTotalSize(pFts, iCol, pnToken):
8198**   If parameter iCol is less than zero, set output variable *pnToken
8199**   to the total number of tokens in the FTS5 table. Or, if iCol is
8200**   non-negative but less than the number of columns in the table, return
8201**   the total number of tokens in column iCol, considering all rows in
8202**   the FTS5 table.
8203**
8204**   If parameter iCol is greater than or equal to the number of columns
8205**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
8206**   an OOM condition or IO error), an appropriate SQLite error code is
8207**   returned.
8208**
8209** xColumnCount(pFts):
8210**   Return the number of columns in the table.
8211**
8212** xColumnSize(pFts, iCol, pnToken):
8213**   If parameter iCol is less than zero, set output variable *pnToken
8214**   to the total number of tokens in the current row. Or, if iCol is
8215**   non-negative but less than the number of columns in the table, set
8216**   *pnToken to the number of tokens in column iCol of the current row.
8217**
8218**   If parameter iCol is greater than or equal to the number of columns
8219**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
8220**   an OOM condition or IO error), an appropriate SQLite error code is
8221**   returned.
8222**
8223** xColumnText:
8224**   This function attempts to retrieve the text of column iCol of the
8225**   current document. If successful, (*pz) is set to point to a buffer
8226**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
8227**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
8228**   if an error occurs, an SQLite error code is returned and the final values
8229**   of (*pz) and (*pn) are undefined.
8230**
8231** xPhraseCount:
8232**   Returns the number of phrases in the current query expression.
8233**
8234** xPhraseSize:
8235**   Returns the number of tokens in phrase iPhrase of the query. Phrases
8236**   are numbered starting from zero.
8237**
8238** xInstCount:
8239**   Set *pnInst to the total number of occurrences of all phrases within
8240**   the query within the current row. Return SQLITE_OK if successful, or
8241**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
8242**
8243** xInst:
8244**   Query for the details of phrase match iIdx within the current row.
8245**   Phrase matches are numbered starting from zero, so the iIdx argument
8246**   should be greater than or equal to zero and smaller than the value
8247**   output by xInstCount().
8248**
8249**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
8250**   if an error occurs.
8251**
8252** xRowid:
8253**   Returns the rowid of the current row.
8254**
8255** xTokenize:
8256**   Tokenize text using the tokenizer belonging to the FTS5 table.
8257**
8258** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
8259**   This API function is used to query the FTS table for phrase iPhrase
8260**   of the current query. Specifically, a query equivalent to:
8261**
8262**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
8263**
8264**   with $p set to a phrase equivalent to the phrase iPhrase of the
8265**   current query is executed. For each row visited, the callback function
8266**   passed as the fourth argument is invoked. The context and API objects
8267**   passed to the callback function may be used to access the properties of
8268**   each matched row. Invoking Api.xUserData() returns a copy of the pointer
8269**   passed as the third argument to pUserData.
8270**
8271**   If the callback function returns any value other than SQLITE_OK, the
8272**   query is abandoned and the xQueryPhrase function returns immediately.
8273**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
8274**   Otherwise, the error code is propagated upwards.
8275**
8276**   If the query runs to completion without incident, SQLITE_OK is returned.
8277**   Or, if some error occurs before the query completes or is aborted by
8278**   the callback, an SQLite error code is returned.
8279**
8280**
8281** xSetAuxdata(pFts5, pAux, xDelete)
8282**
8283**   Save the pointer passed as the second argument as the extension functions
8284**   "auxiliary data". The pointer may then be retrieved by the current or any
8285**   future invocation of the same fts5 extension function made as part of
8286**   of the same MATCH query using the xGetAuxdata() API.
8287**
8288**   Each extension function is allocated a single auxiliary data slot for
8289**   each FTS query (MATCH expression). If the extension function is invoked
8290**   more than once for a single FTS query, then all invocations share a
8291**   single auxiliary data context.
8292**
8293**   If there is already an auxiliary data pointer when this function is
8294**   invoked, then it is replaced by the new pointer. If an xDelete callback
8295**   was specified along with the original pointer, it is invoked at this
8296**   point.
8297**
8298**   The xDelete callback, if one is specified, is also invoked on the
8299**   auxiliary data pointer after the FTS5 query has finished.
8300**
8301**   If an error (e.g. an OOM condition) occurs within this function, an
8302**   the auxiliary data is set to NULL and an error code returned. If the
8303**   xDelete parameter was not NULL, it is invoked on the auxiliary data
8304**   pointer before returning.
8305**
8306**
8307** xGetAuxdata(pFts5, bClear)
8308**
8309**   Returns the current auxiliary data pointer for the fts5 extension
8310**   function. See the xSetAuxdata() method for details.
8311**
8312**   If the bClear argument is non-zero, then the auxiliary data is cleared
8313**   (set to NULL) before this function returns. In this case the xDelete,
8314**   if any, is not invoked.
8315**
8316**
8317** xRowCount(pFts5, pnRow)
8318**
8319**   This function is used to retrieve the total number of rows in the table.
8320**   In other words, the same value that would be returned by:
8321**
8322**        SELECT count(*) FROM ftstable;
8323**
8324** xPhraseFirst()
8325**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
8326**   method, to iterate through all instances of a single query phrase within
8327**   the current row. This is the same information as is accessible via the
8328**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
8329**   to use, this API may be faster under some circumstances. To iterate
8330**   through instances of phrase iPhrase, use the following code:
8331**
8332**       Fts5PhraseIter iter;
8333**       int iCol, iOff;
8334**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
8335**           iOff>=0;
8336**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
8337**       ){
8338**         // An instance of phrase iPhrase at offset iOff of column iCol
8339**       }
8340**
8341**   The Fts5PhraseIter structure is defined above. Applications should not
8342**   modify this structure directly - it should only be used as shown above
8343**   with the xPhraseFirst() and xPhraseNext() API methods.
8344**
8345** xPhraseNext()
8346**   See xPhraseFirst above.
8347*/
8348struct Fts5ExtensionApi {
8349  int iVersion;                   /* Currently always set to 1 */
8350
8351  void *(*xUserData)(Fts5Context*);
8352
8353  int (*xColumnCount)(Fts5Context*);
8354  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
8355  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
8356
8357  int (*xTokenize)(Fts5Context*,
8358    const char *pText, int nText, /* Text to tokenize */
8359    void *pCtx,                   /* Context passed to xToken() */
8360    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
8361  );
8362
8363  int (*xPhraseCount)(Fts5Context*);
8364  int (*xPhraseSize)(Fts5Context*, int iPhrase);
8365
8366  int (*xInstCount)(Fts5Context*, int *pnInst);
8367  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
8368
8369  sqlite3_int64 (*xRowid)(Fts5Context*);
8370  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
8371  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
8372
8373  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
8374    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
8375  );
8376  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
8377  void *(*xGetAuxdata)(Fts5Context*, int bClear);
8378
8379  void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
8380  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
8381};
8382
8383/*
8384** CUSTOM AUXILIARY FUNCTIONS
8385*************************************************************************/
8386
8387/*************************************************************************
8388** CUSTOM TOKENIZERS
8389**
8390** Applications may also register custom tokenizer types. A tokenizer
8391** is registered by providing fts5 with a populated instance of the
8392** following structure. All structure methods must be defined, setting
8393** any member of the fts5_tokenizer struct to NULL leads to undefined
8394** behaviour. The structure methods are expected to function as follows:
8395**
8396** xCreate:
8397**   This function is used to allocate and inititalize a tokenizer instance.
8398**   A tokenizer instance is required to actually tokenize text.
8399**
8400**   The first argument passed to this function is a copy of the (void*)
8401**   pointer provided by the application when the fts5_tokenizer object
8402**   was registered with FTS5 (the third argument to xCreateTokenizer()).
8403**   The second and third arguments are an array of nul-terminated strings
8404**   containing the tokenizer arguments, if any, specified following the
8405**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
8406**   to create the FTS5 table.
8407**
8408**   The final argument is an output variable. If successful, (*ppOut)
8409**   should be set to point to the new tokenizer handle and SQLITE_OK
8410**   returned. If an error occurs, some value other than SQLITE_OK should
8411**   be returned. In this case, fts5 assumes that the final value of *ppOut
8412**   is undefined.
8413**
8414** xDelete:
8415**   This function is invoked to delete a tokenizer handle previously
8416**   allocated using xCreate(). Fts5 guarantees that this function will
8417**   be invoked exactly once for each successful call to xCreate().
8418**
8419** xTokenize:
8420**   This function is expected to tokenize the nText byte string indicated
8421**   by argument pText. pText may or may not be nul-terminated. The first
8422**   argument passed to this function is a pointer to an Fts5Tokenizer object
8423**   returned by an earlier call to xCreate().
8424**
8425**   The second argument indicates the reason that FTS5 is requesting
8426**   tokenization of the supplied text. This is always one of the following
8427**   four values:
8428**
8429**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
8430**            or removed from the FTS table. The tokenizer is being invoked to
8431**            determine the set of tokens to add to (or delete from) the
8432**            FTS index.
8433**
8434**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
8435**            against the FTS index. The tokenizer is being called to tokenize
8436**            a bareword or quoted string specified as part of the query.
8437**
8438**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
8439**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
8440**            followed by a "*" character, indicating that the last token
8441**            returned by the tokenizer will be treated as a token prefix.
8442**
8443**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
8444**            satisfy an fts5_api.xTokenize() request made by an auxiliary
8445**            function. Or an fts5_api.xColumnSize() request made by the same
8446**            on a columnsize=0 database.
8447**   </ul>
8448**
8449**   For each token in the input string, the supplied callback xToken() must
8450**   be invoked. The first argument to it should be a copy of the pointer
8451**   passed as the second argument to xTokenize(). The third and fourth
8452**   arguments are a pointer to a buffer containing the token text, and the
8453**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
8454**   of the first byte of and first byte immediately following the text from
8455**   which the token is derived within the input.
8456**
8457**   The second argument passed to the xToken() callback ("tflags") should
8458**   normally be set to 0. The exception is if the tokenizer supports
8459**   synonyms. In this case see the discussion below for details.
8460**
8461**   FTS5 assumes the xToken() callback is invoked for each token in the
8462**   order that they occur within the input text.
8463**
8464**   If an xToken() callback returns any value other than SQLITE_OK, then
8465**   the tokenization should be abandoned and the xTokenize() method should
8466**   immediately return a copy of the xToken() return value. Or, if the
8467**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
8468**   if an error occurs with the xTokenize() implementation itself, it
8469**   may abandon the tokenization and return any error code other than
8470**   SQLITE_OK or SQLITE_DONE.
8471**
8472** SYNONYM SUPPORT
8473**
8474**   Custom tokenizers may also support synonyms. Consider a case in which a
8475**   user wishes to query for a phrase such as "first place". Using the
8476**   built-in tokenizers, the FTS5 query 'first + place' will match instances
8477**   of "first place" within the document set, but not alternative forms
8478**   such as "1st place". In some applications, it would be better to match
8479**   all instances of "first place" or "1st place" regardless of which form
8480**   the user specified in the MATCH query text.
8481**
8482**   There are several ways to approach this in FTS5:
8483**
8484**   <ol><li> By mapping all synonyms to a single token. In this case, the
8485**            In the above example, this means that the tokenizer returns the
8486**            same token for inputs "first" and "1st". Say that token is in
8487**            fact "first", so that when the user inserts the document "I won
8488**            1st place" entries are added to the index for tokens "i", "won",
8489**            "first" and "place". If the user then queries for '1st + place',
8490**            the tokenizer substitutes "first" for "1st" and the query works
8491**            as expected.
8492**
8493**       <li> By adding multiple synonyms for a single term to the FTS index.
8494**            In this case, when tokenizing query text, the tokenizer may
8495**            provide multiple synonyms for a single term within the document.
8496**            FTS5 then queries the index for each synonym individually. For
8497**            example, faced with the query:
8498**
8499**   <codeblock>
8500**     ... MATCH 'first place'</codeblock>
8501**
8502**            the tokenizer offers both "1st" and "first" as synonyms for the
8503**            first token in the MATCH query and FTS5 effectively runs a query
8504**            similar to:
8505**
8506**   <codeblock>
8507**     ... MATCH '(first OR 1st) place'</codeblock>
8508**
8509**            except that, for the purposes of auxiliary functions, the query
8510**            still appears to contain just two phrases - "(first OR 1st)"
8511**            being treated as a single phrase.
8512**
8513**       <li> By adding multiple synonyms for a single term to the FTS index.
8514**            Using this method, when tokenizing document text, the tokenizer
8515**            provides multiple synonyms for each token. So that when a
8516**            document such as "I won first place" is tokenized, entries are
8517**            added to the FTS index for "i", "won", "first", "1st" and
8518**            "place".
8519**
8520**            This way, even if the tokenizer does not provide synonyms
8521**            when tokenizing query text (it should not - to do would be
8522**            inefficient), it doesn't matter if the user queries for
8523**            'first + place' or '1st + place', as there are entires in the
8524**            FTS index corresponding to both forms of the first token.
8525**   </ol>
8526**
8527**   Whether it is parsing document or query text, any call to xToken that
8528**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
8529**   is considered to supply a synonym for the previous token. For example,
8530**   when parsing the document "I won first place", a tokenizer that supports
8531**   synonyms would call xToken() 5 times, as follows:
8532**
8533**   <codeblock>
8534**       xToken(pCtx, 0, "i",                      1,  0,  1);
8535**       xToken(pCtx, 0, "won",                    3,  2,  5);
8536**       xToken(pCtx, 0, "first",                  5,  6, 11);
8537**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
8538**       xToken(pCtx, 0, "place",                  5, 12, 17);
8539**</codeblock>
8540**
8541**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
8542**   xToken() is called. Multiple synonyms may be specified for a single token
8543**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
8544**   There is no limit to the number of synonyms that may be provided for a
8545**   single token.
8546**
8547**   In many cases, method (1) above is the best approach. It does not add
8548**   extra data to the FTS index or require FTS5 to query for multiple terms,
8549**   so it is efficient in terms of disk space and query speed. However, it
8550**   does not support prefix queries very well. If, as suggested above, the
8551**   token "first" is subsituted for "1st" by the tokenizer, then the query:
8552**
8553**   <codeblock>
8554**     ... MATCH '1s*'</codeblock>
8555**
8556**   will not match documents that contain the token "1st" (as the tokenizer
8557**   will probably not map "1s" to any prefix of "first").
8558**
8559**   For full prefix support, method (3) may be preferred. In this case,
8560**   because the index contains entries for both "first" and "1st", prefix
8561**   queries such as 'fi*' or '1s*' will match correctly. However, because
8562**   extra entries are added to the FTS index, this method uses more space
8563**   within the database.
8564**
8565**   Method (2) offers a midpoint between (1) and (3). Using this method,
8566**   a query such as '1s*' will match documents that contain the literal
8567**   token "1st", but not "first" (assuming the tokenizer is not able to
8568**   provide synonyms for prefixes). However, a non-prefix query like '1st'
8569**   will match against "1st" and "first". This method does not require
8570**   extra disk space, as no extra entries are added to the FTS index.
8571**   On the other hand, it may require more CPU cycles to run MATCH queries,
8572**   as separate queries of the FTS index are required for each synonym.
8573**
8574**   When using methods (2) or (3), it is important that the tokenizer only
8575**   provide synonyms when tokenizing document text (method (2)) or query
8576**   text (method (3)), not both. Doing so will not cause any errors, but is
8577**   inefficient.
8578*/
8579typedef struct Fts5Tokenizer Fts5Tokenizer;
8580typedef struct fts5_tokenizer fts5_tokenizer;
8581struct fts5_tokenizer {
8582  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
8583  void (*xDelete)(Fts5Tokenizer*);
8584  int (*xTokenize)(Fts5Tokenizer*,
8585      void *pCtx,
8586      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
8587      const char *pText, int nText,
8588      int (*xToken)(
8589        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
8590        int tflags,         /* Mask of FTS5_TOKEN_* flags */
8591        const char *pToken, /* Pointer to buffer containing token */
8592        int nToken,         /* Size of token in bytes */
8593        int iStart,         /* Byte offset of token within input text */
8594        int iEnd            /* Byte offset of end of token within input text */
8595      )
8596  );
8597};
8598
8599/* Flags that may be passed as the third argument to xTokenize() */
8600#define FTS5_TOKENIZE_QUERY     0x0001
8601#define FTS5_TOKENIZE_PREFIX    0x0002
8602#define FTS5_TOKENIZE_DOCUMENT  0x0004
8603#define FTS5_TOKENIZE_AUX       0x0008
8604
8605/* Flags that may be passed by the tokenizer implementation back to FTS5
8606** as the third argument to the supplied xToken callback. */
8607#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
8608
8609/*
8610** END OF CUSTOM TOKENIZERS
8611*************************************************************************/
8612
8613/*************************************************************************
8614** FTS5 EXTENSION REGISTRATION API
8615*/
8616typedef struct fts5_api fts5_api;
8617struct fts5_api {
8618  int iVersion;                   /* Currently always set to 2 */
8619
8620  /* Create a new tokenizer */
8621  int (*xCreateTokenizer)(
8622    fts5_api *pApi,
8623    const char *zName,
8624    void *pContext,
8625    fts5_tokenizer *pTokenizer,
8626    void (*xDestroy)(void*)
8627  );
8628
8629  /* Find an existing tokenizer */
8630  int (*xFindTokenizer)(
8631    fts5_api *pApi,
8632    const char *zName,
8633    void **ppContext,
8634    fts5_tokenizer *pTokenizer
8635  );
8636
8637  /* Create a new auxiliary function */
8638  int (*xCreateFunction)(
8639    fts5_api *pApi,
8640    const char *zName,
8641    void *pContext,
8642    fts5_extension_function xFunction,
8643    void (*xDestroy)(void*)
8644  );
8645};
8646
8647/*
8648** END OF REGISTRATION API
8649*************************************************************************/
8650
8651#if 0
8652}  /* end of the 'extern "C"' block */
8653#endif
8654
8655#endif /* _FTS5_H */
8656
8657
8658
8659/************** End of sqlite3.h *********************************************/
8660/************** Continuing where we left off in sqliteInt.h ******************/
8661
8662/*
8663** Include the configuration header output by 'configure' if we're using the
8664** autoconf-based build
8665*/
8666#ifdef _HAVE_SQLITE_CONFIG_H
8667#include "config.h"
8668#endif
8669
8670/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
8671/************** Begin file sqliteLimit.h *************************************/
8672/*
8673** 2007 May 7
8674**
8675** The author disclaims copyright to this source code.  In place of
8676** a legal notice, here is a blessing:
8677**
8678**    May you do good and not evil.
8679**    May you find forgiveness for yourself and forgive others.
8680**    May you share freely, never taking more than you give.
8681**
8682*************************************************************************
8683**
8684** This file defines various limits of what SQLite can process.
8685*/
8686
8687/*
8688** The maximum length of a TEXT or BLOB in bytes.   This also
8689** limits the size of a row in a table or index.
8690**
8691** The hard limit is the ability of a 32-bit signed integer
8692** to count the size: 2^31-1 or 2147483647.
8693*/
8694#ifndef SQLITE_MAX_LENGTH
8695# define SQLITE_MAX_LENGTH 1000000000
8696#endif
8697
8698/*
8699** This is the maximum number of
8700**
8701**    * Columns in a table
8702**    * Columns in an index
8703**    * Columns in a view
8704**    * Terms in the SET clause of an UPDATE statement
8705**    * Terms in the result set of a SELECT statement
8706**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
8707**    * Terms in the VALUES clause of an INSERT statement
8708**
8709** The hard upper limit here is 32676.  Most database people will
8710** tell you that in a well-normalized database, you usually should
8711** not have more than a dozen or so columns in any table.  And if
8712** that is the case, there is no point in having more than a few
8713** dozen values in any of the other situations described above.
8714*/
8715#ifndef SQLITE_MAX_COLUMN
8716# define SQLITE_MAX_COLUMN 2000
8717#endif
8718
8719/*
8720** The maximum length of a single SQL statement in bytes.
8721**
8722** It used to be the case that setting this value to zero would
8723** turn the limit off.  That is no longer true.  It is not possible
8724** to turn this limit off.
8725*/
8726#ifndef SQLITE_MAX_SQL_LENGTH
8727# define SQLITE_MAX_SQL_LENGTH 1000000000
8728#endif
8729
8730/*
8731** The maximum depth of an expression tree. This is limited to
8732** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
8733** want to place more severe limits on the complexity of an
8734** expression.
8735**
8736** A value of 0 used to mean that the limit was not enforced.
8737** But that is no longer true.  The limit is now strictly enforced
8738** at all times.
8739*/
8740#ifndef SQLITE_MAX_EXPR_DEPTH
8741# define SQLITE_MAX_EXPR_DEPTH 1000
8742#endif
8743
8744/*
8745** The maximum number of terms in a compound SELECT statement.
8746** The code generator for compound SELECT statements does one
8747** level of recursion for each term.  A stack overflow can result
8748** if the number of terms is too large.  In practice, most SQL
8749** never has more than 3 or 4 terms.  Use a value of 0 to disable
8750** any limit on the number of terms in a compount SELECT.
8751*/
8752#ifndef SQLITE_MAX_COMPOUND_SELECT
8753# define SQLITE_MAX_COMPOUND_SELECT 500
8754#endif
8755
8756/*
8757** The maximum number of opcodes in a VDBE program.
8758** Not currently enforced.
8759*/
8760#ifndef SQLITE_MAX_VDBE_OP
8761# define SQLITE_MAX_VDBE_OP 25000
8762#endif
8763
8764/*
8765** The maximum number of arguments to an SQL function.
8766*/
8767#ifndef SQLITE_MAX_FUNCTION_ARG
8768# define SQLITE_MAX_FUNCTION_ARG 127
8769#endif
8770
8771/*
8772** The suggested maximum number of in-memory pages to use for
8773** the main database table and for temporary tables.
8774**
8775** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
8776** is 2000 pages.
8777** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
8778** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
8779*/
8780#ifndef SQLITE_DEFAULT_CACHE_SIZE
8781# define SQLITE_DEFAULT_CACHE_SIZE  2000
8782#endif
8783
8784/*
8785** The default number of frames to accumulate in the log file before
8786** checkpointing the database in WAL mode.
8787*/
8788#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
8789# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
8790#endif
8791
8792/*
8793** The maximum number of attached databases.  This must be between 0
8794** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
8795** is used internally to track attached databases.
8796*/
8797#ifndef SQLITE_MAX_ATTACHED
8798# define SQLITE_MAX_ATTACHED 10
8799#endif
8800
8801
8802/*
8803** The maximum value of a ?nnn wildcard that the parser will accept.
8804*/
8805#ifndef SQLITE_MAX_VARIABLE_NUMBER
8806# define SQLITE_MAX_VARIABLE_NUMBER 999
8807#endif
8808
8809/* Maximum page size.  The upper bound on this value is 65536.  This a limit
8810** imposed by the use of 16-bit offsets within each page.
8811**
8812** Earlier versions of SQLite allowed the user to change this value at
8813** compile time. This is no longer permitted, on the grounds that it creates
8814** a library that is technically incompatible with an SQLite library
8815** compiled with a different limit. If a process operating on a database
8816** with a page-size of 65536 bytes crashes, then an instance of SQLite
8817** compiled with the default page-size limit will not be able to rollback
8818** the aborted transaction. This could lead to database corruption.
8819*/
8820#ifdef SQLITE_MAX_PAGE_SIZE
8821# undef SQLITE_MAX_PAGE_SIZE
8822#endif
8823#define SQLITE_MAX_PAGE_SIZE 65536
8824
8825
8826/*
8827** The default size of a database page.
8828*/
8829#ifndef SQLITE_DEFAULT_PAGE_SIZE
8830# define SQLITE_DEFAULT_PAGE_SIZE 1024
8831#endif
8832#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8833# undef SQLITE_DEFAULT_PAGE_SIZE
8834# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8835#endif
8836
8837/*
8838** Ordinarily, if no value is explicitly provided, SQLite creates databases
8839** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
8840** device characteristics (sector-size and atomic write() support),
8841** SQLite may choose a larger value. This constant is the maximum value
8842** SQLite will choose on its own.
8843*/
8844#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
8845# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
8846#endif
8847#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8848# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
8849# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8850#endif
8851
8852
8853/*
8854** Maximum number of pages in one database file.
8855**
8856** This is really just the default value for the max_page_count pragma.
8857** This value can be lowered (or raised) at run-time using that the
8858** max_page_count macro.
8859*/
8860#ifndef SQLITE_MAX_PAGE_COUNT
8861# define SQLITE_MAX_PAGE_COUNT 1073741823
8862#endif
8863
8864/*
8865** Maximum length (in bytes) of the pattern in a LIKE or GLOB
8866** operator.
8867*/
8868#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
8869# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
8870#endif
8871
8872/*
8873** Maximum depth of recursion for triggers.
8874**
8875** A value of 1 means that a trigger program will not be able to itself
8876** fire any triggers. A value of 0 means that no trigger programs at all
8877** may be executed.
8878*/
8879#ifndef SQLITE_MAX_TRIGGER_DEPTH
8880# define SQLITE_MAX_TRIGGER_DEPTH 1000
8881#endif
8882
8883/************** End of sqliteLimit.h *****************************************/
8884/************** Continuing where we left off in sqliteInt.h ******************/
8885
8886/* Disable nuisance warnings on Borland compilers */
8887#if defined(__BORLANDC__)
8888#pragma warn -rch /* unreachable code */
8889#pragma warn -ccc /* Condition is always true or false */
8890#pragma warn -aus /* Assigned value is never used */
8891#pragma warn -csu /* Comparing signed and unsigned */
8892#pragma warn -spa /* Suspicious pointer arithmetic */
8893#endif
8894
8895/*
8896** Include standard header files as necessary
8897*/
8898#ifdef HAVE_STDINT_H
8899#include <stdint.h>
8900#endif
8901#ifdef HAVE_INTTYPES_H
8902#include <inttypes.h>
8903#endif
8904
8905/*
8906** The following macros are used to cast pointers to integers and
8907** integers to pointers.  The way you do this varies from one compiler
8908** to the next, so we have developed the following set of #if statements
8909** to generate appropriate macros for a wide range of compilers.
8910**
8911** The correct "ANSI" way to do this is to use the intptr_t type.
8912** Unfortunately, that typedef is not available on all compilers, or
8913** if it is available, it requires an #include of specific headers
8914** that vary from one machine to the next.
8915**
8916** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
8917** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
8918** So we have to define the macros in different ways depending on the
8919** compiler.
8920*/
8921#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
8922# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
8923# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
8924#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
8925# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
8926# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
8927#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
8928# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
8929# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
8930#else                          /* Generates a warning - but it always works */
8931# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
8932# define SQLITE_PTR_TO_INT(X)  ((int)(X))
8933#endif
8934
8935/*
8936** A macro to hint to the compiler that a function should not be
8937** inlined.
8938*/
8939#if defined(__GNUC__)
8940#  define SQLITE_NOINLINE  __attribute__((noinline))
8941#elif defined(_MSC_VER) && _MSC_VER>=1310
8942#  define SQLITE_NOINLINE  __declspec(noinline)
8943#else
8944#  define SQLITE_NOINLINE
8945#endif
8946
8947/*
8948** Make sure that the compiler intrinsics we desire are enabled when
8949** compiling with an appropriate version of MSVC unless prevented by
8950** the SQLITE_DISABLE_INTRINSIC define.
8951*/
8952#if !defined(SQLITE_DISABLE_INTRINSIC)
8953#  if defined(_MSC_VER) && _MSC_VER>=1300
8954#    if !defined(_WIN32_WCE)
8955#      include <intrin.h>
8956#      pragma intrinsic(_byteswap_ushort)
8957#      pragma intrinsic(_byteswap_ulong)
8958#      pragma intrinsic(_ReadWriteBarrier)
8959#    else
8960#      include <cmnintrin.h>
8961#    endif
8962#  endif
8963#endif
8964
8965/*
8966** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
8967** 0 means mutexes are permanently disable and the library is never
8968** threadsafe.  1 means the library is serialized which is the highest
8969** level of threadsafety.  2 means the library is multithreaded - multiple
8970** threads can use SQLite as long as no two threads try to use the same
8971** database connection at the same time.
8972**
8973** Older versions of SQLite used an optional THREADSAFE macro.
8974** We support that for legacy.
8975*/
8976#if !defined(SQLITE_THREADSAFE)
8977# if defined(THREADSAFE)
8978#   define SQLITE_THREADSAFE THREADSAFE
8979# else
8980#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
8981# endif
8982#endif
8983
8984/*
8985** Powersafe overwrite is on by default.  But can be turned off using
8986** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
8987*/
8988#ifndef SQLITE_POWERSAFE_OVERWRITE
8989# define SQLITE_POWERSAFE_OVERWRITE 1
8990#endif
8991
8992/*
8993** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
8994** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
8995** which case memory allocation statistics are disabled by default.
8996*/
8997#if !defined(SQLITE_DEFAULT_MEMSTATUS)
8998# define SQLITE_DEFAULT_MEMSTATUS 1
8999#endif
9000
9001/*
9002** Exactly one of the following macros must be defined in order to
9003** specify which memory allocation subsystem to use.
9004**
9005**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
9006**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
9007**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
9008**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
9009**
9010** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
9011** assert() macro is enabled, each call into the Win32 native heap subsystem
9012** will cause HeapValidate to be called.  If heap validation should fail, an
9013** assertion will be triggered.
9014**
9015** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
9016** the default.
9017*/
9018#if defined(SQLITE_SYSTEM_MALLOC) \
9019  + defined(SQLITE_WIN32_MALLOC) \
9020  + defined(SQLITE_ZERO_MALLOC) \
9021  + defined(SQLITE_MEMDEBUG)>1
9022# error "Two or more of the following compile-time configuration options\
9023 are defined but at most one is allowed:\
9024 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
9025 SQLITE_ZERO_MALLOC"
9026#endif
9027#if defined(SQLITE_SYSTEM_MALLOC) \
9028  + defined(SQLITE_WIN32_MALLOC) \
9029  + defined(SQLITE_ZERO_MALLOC) \
9030  + defined(SQLITE_MEMDEBUG)==0
9031# define SQLITE_SYSTEM_MALLOC 1
9032#endif
9033
9034/*
9035** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
9036** sizes of memory allocations below this value where possible.
9037*/
9038#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
9039# define SQLITE_MALLOC_SOFT_LIMIT 1024
9040#endif
9041
9042/*
9043** We need to define _XOPEN_SOURCE as follows in order to enable
9044** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
9045** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
9046** it.
9047*/
9048#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
9049#  define _XOPEN_SOURCE 600
9050#endif
9051
9052/*
9053** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
9054** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
9055** make it true by defining or undefining NDEBUG.
9056**
9057** Setting NDEBUG makes the code smaller and faster by disabling the
9058** assert() statements in the code.  So we want the default action
9059** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
9060** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
9061** feature.
9062*/
9063#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
9064# define NDEBUG 1
9065#endif
9066#if defined(NDEBUG) && defined(SQLITE_DEBUG)
9067# undef NDEBUG
9068#endif
9069
9070/*
9071** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
9072*/
9073#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
9074# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
9075#endif
9076
9077/*
9078** The testcase() macro is used to aid in coverage testing.  When
9079** doing coverage testing, the condition inside the argument to
9080** testcase() must be evaluated both true and false in order to
9081** get full branch coverage.  The testcase() macro is inserted
9082** to help ensure adequate test coverage in places where simple
9083** condition/decision coverage is inadequate.  For example, testcase()
9084** can be used to make sure boundary values are tested.  For
9085** bitmask tests, testcase() can be used to make sure each bit
9086** is significant and used at least once.  On switch statements
9087** where multiple cases go to the same block of code, testcase()
9088** can insure that all cases are evaluated.
9089**
9090*/
9091#ifdef SQLITE_COVERAGE_TEST
9092SQLITE_PRIVATE   void sqlite3Coverage(int);
9093# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
9094#else
9095# define testcase(X)
9096#endif
9097
9098/*
9099** The TESTONLY macro is used to enclose variable declarations or
9100** other bits of code that are needed to support the arguments
9101** within testcase() and assert() macros.
9102*/
9103#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
9104# define TESTONLY(X)  X
9105#else
9106# define TESTONLY(X)
9107#endif
9108
9109/*
9110** Sometimes we need a small amount of code such as a variable initialization
9111** to setup for a later assert() statement.  We do not want this code to
9112** appear when assert() is disabled.  The following macro is therefore
9113** used to contain that setup code.  The "VVA" acronym stands for
9114** "Verification, Validation, and Accreditation".  In other words, the
9115** code within VVA_ONLY() will only run during verification processes.
9116*/
9117#ifndef NDEBUG
9118# define VVA_ONLY(X)  X
9119#else
9120# define VVA_ONLY(X)
9121#endif
9122
9123/*
9124** The ALWAYS and NEVER macros surround boolean expressions which
9125** are intended to always be true or false, respectively.  Such
9126** expressions could be omitted from the code completely.  But they
9127** are included in a few cases in order to enhance the resilience
9128** of SQLite to unexpected behavior - to make the code "self-healing"
9129** or "ductile" rather than being "brittle" and crashing at the first
9130** hint of unplanned behavior.
9131**
9132** In other words, ALWAYS and NEVER are added for defensive code.
9133**
9134** When doing coverage testing ALWAYS and NEVER are hard-coded to
9135** be true and false so that the unreachable code they specify will
9136** not be counted as untested code.
9137*/
9138#if defined(SQLITE_COVERAGE_TEST)
9139# define ALWAYS(X)      (1)
9140# define NEVER(X)       (0)
9141#elif !defined(NDEBUG)
9142# define ALWAYS(X)      ((X)?1:(assert(0),0))
9143# define NEVER(X)       ((X)?(assert(0),1):0)
9144#else
9145# define ALWAYS(X)      (X)
9146# define NEVER(X)       (X)
9147#endif
9148
9149/*
9150** Declarations used for tracing the operating system interfaces.
9151*/
9152#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
9153    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
9154  extern int sqlite3OSTrace;
9155# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
9156# define SQLITE_HAVE_OS_TRACE
9157#else
9158# define OSTRACE(X)
9159# undef  SQLITE_HAVE_OS_TRACE
9160#endif
9161
9162/*
9163** Is the sqlite3ErrName() function needed in the build?  Currently,
9164** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
9165** OSTRACE is enabled), and by several "test*.c" files (which are
9166** compiled using SQLITE_TEST).
9167*/
9168#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
9169    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
9170# define SQLITE_NEED_ERR_NAME
9171#else
9172# undef  SQLITE_NEED_ERR_NAME
9173#endif
9174
9175/*
9176** Return true (non-zero) if the input is an integer that is too large
9177** to fit in 32-bits.  This macro is used inside of various testcase()
9178** macros to verify that we have tested SQLite for large-file support.
9179*/
9180#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
9181
9182/*
9183** The macro unlikely() is a hint that surrounds a boolean
9184** expression that is usually false.  Macro likely() surrounds
9185** a boolean expression that is usually true.  These hints could,
9186** in theory, be used by the compiler to generate better code, but
9187** currently they are just comments for human readers.
9188*/
9189#define likely(X)    (X)
9190#define unlikely(X)  (X)
9191
9192/************** Include hash.h in the middle of sqliteInt.h ******************/
9193/************** Begin file hash.h ********************************************/
9194/*
9195** 2001 September 22
9196**
9197** The author disclaims copyright to this source code.  In place of
9198** a legal notice, here is a blessing:
9199**
9200**    May you do good and not evil.
9201**    May you find forgiveness for yourself and forgive others.
9202**    May you share freely, never taking more than you give.
9203**
9204*************************************************************************
9205** This is the header file for the generic hash-table implementation
9206** used in SQLite.
9207*/
9208#ifndef _SQLITE_HASH_H_
9209#define _SQLITE_HASH_H_
9210
9211/* Forward declarations of structures. */
9212typedef struct Hash Hash;
9213typedef struct HashElem HashElem;
9214
9215/* A complete hash table is an instance of the following structure.
9216** The internals of this structure are intended to be opaque -- client
9217** code should not attempt to access or modify the fields of this structure
9218** directly.  Change this structure only by using the routines below.
9219** However, some of the "procedures" and "functions" for modifying and
9220** accessing this structure are really macros, so we can't really make
9221** this structure opaque.
9222**
9223** All elements of the hash table are on a single doubly-linked list.
9224** Hash.first points to the head of this list.
9225**
9226** There are Hash.htsize buckets.  Each bucket points to a spot in
9227** the global doubly-linked list.  The contents of the bucket are the
9228** element pointed to plus the next _ht.count-1 elements in the list.
9229**
9230** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
9231** by a linear search of the global list.  For small tables, the
9232** Hash.ht table is never allocated because if there are few elements
9233** in the table, it is faster to do a linear search than to manage
9234** the hash table.
9235*/
9236struct Hash {
9237  unsigned int htsize;      /* Number of buckets in the hash table */
9238  unsigned int count;       /* Number of entries in this table */
9239  HashElem *first;          /* The first element of the array */
9240  struct _ht {              /* the hash table */
9241    int count;                 /* Number of entries with this hash */
9242    HashElem *chain;           /* Pointer to first entry with this hash */
9243  } *ht;
9244};
9245
9246/* Each element in the hash table is an instance of the following
9247** structure.  All elements are stored on a single doubly-linked list.
9248**
9249** Again, this structure is intended to be opaque, but it can't really
9250** be opaque because it is used by macros.
9251*/
9252struct HashElem {
9253  HashElem *next, *prev;       /* Next and previous elements in the table */
9254  void *data;                  /* Data associated with this element */
9255  const char *pKey;            /* Key associated with this element */
9256};
9257
9258/*
9259** Access routines.  To delete, insert a NULL pointer.
9260*/
9261SQLITE_PRIVATE void sqlite3HashInit(Hash*);
9262SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
9263SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
9264SQLITE_PRIVATE void sqlite3HashClear(Hash*);
9265
9266/*
9267** Macros for looping over all elements of a hash table.  The idiom is
9268** like this:
9269**
9270**   Hash h;
9271**   HashElem *p;
9272**   ...
9273**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
9274**     SomeStructure *pData = sqliteHashData(p);
9275**     // do something with pData
9276**   }
9277*/
9278#define sqliteHashFirst(H)  ((H)->first)
9279#define sqliteHashNext(E)   ((E)->next)
9280#define sqliteHashData(E)   ((E)->data)
9281/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
9282/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
9283
9284/*
9285** Number of entries in a hash table
9286*/
9287/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
9288
9289#endif /* _SQLITE_HASH_H_ */
9290
9291/************** End of hash.h ************************************************/
9292/************** Continuing where we left off in sqliteInt.h ******************/
9293/************** Include parse.h in the middle of sqliteInt.h *****************/
9294/************** Begin file parse.h *******************************************/
9295#define TK_SEMI                             1
9296#define TK_EXPLAIN                          2
9297#define TK_QUERY                            3
9298#define TK_PLAN                             4
9299#define TK_BEGIN                            5
9300#define TK_TRANSACTION                      6
9301#define TK_DEFERRED                         7
9302#define TK_IMMEDIATE                        8
9303#define TK_EXCLUSIVE                        9
9304#define TK_COMMIT                          10
9305#define TK_END                             11
9306#define TK_ROLLBACK                        12
9307#define TK_SAVEPOINT                       13
9308#define TK_RELEASE                         14
9309#define TK_TO                              15
9310#define TK_TABLE                           16
9311#define TK_CREATE                          17
9312#define TK_IF                              18
9313#define TK_NOT                             19
9314#define TK_EXISTS                          20
9315#define TK_TEMP                            21
9316#define TK_LP                              22
9317#define TK_RP                              23
9318#define TK_AS                              24
9319#define TK_WITHOUT                         25
9320#define TK_COMMA                           26
9321#define TK_ID                              27
9322#define TK_INDEXED                         28
9323#define TK_ABORT                           29
9324#define TK_ACTION                          30
9325#define TK_AFTER                           31
9326#define TK_ANALYZE                         32
9327#define TK_ASC                             33
9328#define TK_ATTACH                          34
9329#define TK_BEFORE                          35
9330#define TK_BY                              36
9331#define TK_CASCADE                         37
9332#define TK_CAST                            38
9333#define TK_COLUMNKW                        39
9334#define TK_CONFLICT                        40
9335#define TK_DATABASE                        41
9336#define TK_DESC                            42
9337#define TK_DETACH                          43
9338#define TK_EACH                            44
9339#define TK_FAIL                            45
9340#define TK_FOR                             46
9341#define TK_IGNORE                          47
9342#define TK_INITIALLY                       48
9343#define TK_INSTEAD                         49
9344#define TK_LIKE_KW                         50
9345#define TK_MATCH                           51
9346#define TK_NO                              52
9347#define TK_KEY                             53
9348#define TK_OF                              54
9349#define TK_OFFSET                          55
9350#define TK_PRAGMA                          56
9351#define TK_RAISE                           57
9352#define TK_RECURSIVE                       58
9353#define TK_REPLACE                         59
9354#define TK_RESTRICT                        60
9355#define TK_ROW                             61
9356#define TK_TRIGGER                         62
9357#define TK_VACUUM                          63
9358#define TK_VIEW                            64
9359#define TK_VIRTUAL                         65
9360#define TK_WITH                            66
9361#define TK_REINDEX                         67
9362#define TK_RENAME                          68
9363#define TK_CTIME_KW                        69
9364#define TK_ANY                             70
9365#define TK_OR                              71
9366#define TK_AND                             72
9367#define TK_IS                              73
9368#define TK_BETWEEN                         74
9369#define TK_IN                              75
9370#define TK_ISNULL                          76
9371#define TK_NOTNULL                         77
9372#define TK_NE                              78
9373#define TK_EQ                              79
9374#define TK_GT                              80
9375#define TK_LE                              81
9376#define TK_LT                              82
9377#define TK_GE                              83
9378#define TK_ESCAPE                          84
9379#define TK_BITAND                          85
9380#define TK_BITOR                           86
9381#define TK_LSHIFT                          87
9382#define TK_RSHIFT                          88
9383#define TK_PLUS                            89
9384#define TK_MINUS                           90
9385#define TK_STAR                            91
9386#define TK_SLASH                           92
9387#define TK_REM                             93
9388#define TK_CONCAT                          94
9389#define TK_COLLATE                         95
9390#define TK_BITNOT                          96
9391#define TK_STRING                          97
9392#define TK_JOIN_KW                         98
9393#define TK_CONSTRAINT                      99
9394#define TK_DEFAULT                        100
9395#define TK_NULL                           101
9396#define TK_PRIMARY                        102
9397#define TK_UNIQUE                         103
9398#define TK_CHECK                          104
9399#define TK_REFERENCES                     105
9400#define TK_AUTOINCR                       106
9401#define TK_ON                             107
9402#define TK_INSERT                         108
9403#define TK_DELETE                         109
9404#define TK_UPDATE                         110
9405#define TK_SET                            111
9406#define TK_DEFERRABLE                     112
9407#define TK_FOREIGN                        113
9408#define TK_DROP                           114
9409#define TK_UNION                          115
9410#define TK_ALL                            116
9411#define TK_EXCEPT                         117
9412#define TK_INTERSECT                      118
9413#define TK_SELECT                         119
9414#define TK_VALUES                         120
9415#define TK_DISTINCT                       121
9416#define TK_DOT                            122
9417#define TK_FROM                           123
9418#define TK_JOIN                           124
9419#define TK_USING                          125
9420#define TK_ORDER                          126
9421#define TK_GROUP                          127
9422#define TK_HAVING                         128
9423#define TK_LIMIT                          129
9424#define TK_WHERE                          130
9425#define TK_INTO                           131
9426#define TK_INTEGER                        132
9427#define TK_FLOAT                          133
9428#define TK_BLOB                           134
9429#define TK_VARIABLE                       135
9430#define TK_CASE                           136
9431#define TK_WHEN                           137
9432#define TK_THEN                           138
9433#define TK_ELSE                           139
9434#define TK_INDEX                          140
9435#define TK_ALTER                          141
9436#define TK_ADD                            142
9437#define TK_TO_TEXT                        143
9438#define TK_TO_BLOB                        144
9439#define TK_TO_NUMERIC                     145
9440#define TK_TO_INT                         146
9441#define TK_TO_REAL                        147
9442#define TK_ISNOT                          148
9443#define TK_END_OF_FILE                    149
9444#define TK_ILLEGAL                        150
9445#define TK_SPACE                          151
9446#define TK_UNCLOSED_STRING                152
9447#define TK_FUNCTION                       153
9448#define TK_COLUMN                         154
9449#define TK_AGG_FUNCTION                   155
9450#define TK_AGG_COLUMN                     156
9451#define TK_UMINUS                         157
9452#define TK_UPLUS                          158
9453#define TK_REGISTER                       159
9454
9455/************** End of parse.h ***********************************************/
9456/************** Continuing where we left off in sqliteInt.h ******************/
9457#include <stdio.h>
9458#include <stdlib.h>
9459#include <string.h>
9460#include <assert.h>
9461#include <stddef.h>
9462
9463/*
9464** If compiling for a processor that lacks floating point support,
9465** substitute integer for floating-point
9466*/
9467#ifdef SQLITE_OMIT_FLOATING_POINT
9468# define double sqlite_int64
9469# define float sqlite_int64
9470# define LONGDOUBLE_TYPE sqlite_int64
9471# ifndef SQLITE_BIG_DBL
9472#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
9473# endif
9474# define SQLITE_OMIT_DATETIME_FUNCS 1
9475# define SQLITE_OMIT_TRACE 1
9476# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
9477# undef SQLITE_HAVE_ISNAN
9478#endif
9479#ifndef SQLITE_BIG_DBL
9480# define SQLITE_BIG_DBL (1e99)
9481#endif
9482
9483/*
9484** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
9485** afterward. Having this macro allows us to cause the C compiler
9486** to omit code used by TEMP tables without messy #ifndef statements.
9487*/
9488#ifdef SQLITE_OMIT_TEMPDB
9489#define OMIT_TEMPDB 1
9490#else
9491#define OMIT_TEMPDB 0
9492#endif
9493
9494/*
9495** The "file format" number is an integer that is incremented whenever
9496** the VDBE-level file format changes.  The following macros define the
9497** the default file format for new databases and the maximum file format
9498** that the library can read.
9499*/
9500#define SQLITE_MAX_FILE_FORMAT 4
9501#ifndef SQLITE_DEFAULT_FILE_FORMAT
9502# define SQLITE_DEFAULT_FILE_FORMAT 4
9503#endif
9504
9505/*
9506** Determine whether triggers are recursive by default.  This can be
9507** changed at run-time using a pragma.
9508*/
9509#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
9510# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
9511#endif
9512
9513/*
9514** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
9515** on the command-line
9516*/
9517#ifndef SQLITE_TEMP_STORE
9518# define SQLITE_TEMP_STORE 1
9519# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
9520#endif
9521
9522/*
9523** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
9524** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
9525** to zero.
9526*/
9527#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
9528# undef SQLITE_MAX_WORKER_THREADS
9529# define SQLITE_MAX_WORKER_THREADS 0
9530#endif
9531#ifndef SQLITE_MAX_WORKER_THREADS
9532# define SQLITE_MAX_WORKER_THREADS 8
9533#endif
9534#ifndef SQLITE_DEFAULT_WORKER_THREADS
9535# define SQLITE_DEFAULT_WORKER_THREADS 0
9536#endif
9537#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
9538# undef SQLITE_MAX_WORKER_THREADS
9539# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
9540#endif
9541
9542/*
9543** The default initial allocation for the pagecache when using separate
9544** pagecaches for each database connection.  A positive number is the
9545** number of pages.  A negative number N translations means that a buffer
9546** of -1024*N bytes is allocated and used for as many pages as it will hold.
9547*/
9548#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
9549# define SQLITE_DEFAULT_PCACHE_INITSZ 100
9550#endif
9551
9552
9553/*
9554** GCC does not define the offsetof() macro so we'll have to do it
9555** ourselves.
9556*/
9557#ifndef offsetof
9558#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
9559#endif
9560
9561/*
9562** Macros to compute minimum and maximum of two numbers.
9563*/
9564#define MIN(A,B) ((A)<(B)?(A):(B))
9565#define MAX(A,B) ((A)>(B)?(A):(B))
9566
9567/*
9568** Swap two objects of type TYPE.
9569*/
9570#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
9571
9572/*
9573** Check to see if this machine uses EBCDIC.  (Yes, believe it or
9574** not, there are still machines out there that use EBCDIC.)
9575*/
9576#if 'A' == '\301'
9577# define SQLITE_EBCDIC 1
9578#else
9579# define SQLITE_ASCII 1
9580#endif
9581
9582/*
9583** Integers of known sizes.  These typedefs might change for architectures
9584** where the sizes very.  Preprocessor macros are available so that the
9585** types can be conveniently redefined at compile-type.  Like this:
9586**
9587**         cc '-DUINTPTR_TYPE=long long int' ...
9588*/
9589#ifndef UINT32_TYPE
9590# ifdef HAVE_UINT32_T
9591#  define UINT32_TYPE uint32_t
9592# else
9593#  define UINT32_TYPE unsigned int
9594# endif
9595#endif
9596#ifndef UINT16_TYPE
9597# ifdef HAVE_UINT16_T
9598#  define UINT16_TYPE uint16_t
9599# else
9600#  define UINT16_TYPE unsigned short int
9601# endif
9602#endif
9603#ifndef INT16_TYPE
9604# ifdef HAVE_INT16_T
9605#  define INT16_TYPE int16_t
9606# else
9607#  define INT16_TYPE short int
9608# endif
9609#endif
9610#ifndef UINT8_TYPE
9611# ifdef HAVE_UINT8_T
9612#  define UINT8_TYPE uint8_t
9613# else
9614#  define UINT8_TYPE unsigned char
9615# endif
9616#endif
9617#ifndef INT8_TYPE
9618# ifdef HAVE_INT8_T
9619#  define INT8_TYPE int8_t
9620# else
9621#  define INT8_TYPE signed char
9622# endif
9623#endif
9624#ifndef LONGDOUBLE_TYPE
9625# define LONGDOUBLE_TYPE long double
9626#endif
9627typedef sqlite_int64 i64;          /* 8-byte signed integer */
9628typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
9629typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
9630typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
9631typedef INT16_TYPE i16;            /* 2-byte signed integer */
9632typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
9633typedef INT8_TYPE i8;              /* 1-byte signed integer */
9634
9635/*
9636** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
9637** that can be stored in a u32 without loss of data.  The value
9638** is 0x00000000ffffffff.  But because of quirks of some compilers, we
9639** have to specify the value in the less intuitive manner shown:
9640*/
9641#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
9642
9643/*
9644** The datatype used to store estimates of the number of rows in a
9645** table or index.  This is an unsigned integer type.  For 99.9% of
9646** the world, a 32-bit integer is sufficient.  But a 64-bit integer
9647** can be used at compile-time if desired.
9648*/
9649#ifdef SQLITE_64BIT_STATS
9650 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
9651#else
9652 typedef u32 tRowcnt;    /* 32-bit is the default */
9653#endif
9654
9655/*
9656** Estimated quantities used for query planning are stored as 16-bit
9657** logarithms.  For quantity X, the value stored is 10*log2(X).  This
9658** gives a possible range of values of approximately 1.0e986 to 1e-986.
9659** But the allowed values are "grainy".  Not every value is representable.
9660** For example, quantities 16 and 17 are both represented by a LogEst
9661** of 40.  However, since LogEst quantities are suppose to be estimates,
9662** not exact values, this imprecision is not a problem.
9663**
9664** "LogEst" is short for "Logarithmic Estimate".
9665**
9666** Examples:
9667**      1 -> 0              20 -> 43          10000 -> 132
9668**      2 -> 10             25 -> 46          25000 -> 146
9669**      3 -> 16            100 -> 66        1000000 -> 199
9670**      4 -> 20           1000 -> 99        1048576 -> 200
9671**     10 -> 33           1024 -> 100    4294967296 -> 320
9672**
9673** The LogEst can be negative to indicate fractional values.
9674** Examples:
9675**
9676**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
9677*/
9678typedef INT16_TYPE LogEst;
9679
9680/*
9681** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
9682*/
9683#ifndef SQLITE_PTRSIZE
9684# if defined(__SIZEOF_POINTER__)
9685#   define SQLITE_PTRSIZE __SIZEOF_POINTER__
9686# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
9687       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
9688#   define SQLITE_PTRSIZE 4
9689# else
9690#   define SQLITE_PTRSIZE 8
9691# endif
9692#endif
9693
9694/*
9695** Macros to determine whether the machine is big or little endian,
9696** and whether or not that determination is run-time or compile-time.
9697**
9698** For best performance, an attempt is made to guess at the byte-order
9699** using C-preprocessor macros.  If that is unsuccessful, or if
9700** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
9701** at run-time.
9702*/
9703#ifdef SQLITE_AMALGAMATION
9704SQLITE_PRIVATE const int sqlite3one = 1;
9705#else
9706SQLITE_PRIVATE const int sqlite3one;
9707#endif
9708#if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
9709     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
9710     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
9711     defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
9712# define SQLITE_BYTEORDER    1234
9713# define SQLITE_BIGENDIAN    0
9714# define SQLITE_LITTLEENDIAN 1
9715# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
9716#endif
9717#if (defined(sparc)    || defined(__ppc__))  \
9718    && !defined(SQLITE_RUNTIME_BYTEORDER)
9719# define SQLITE_BYTEORDER    4321
9720# define SQLITE_BIGENDIAN    1
9721# define SQLITE_LITTLEENDIAN 0
9722# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
9723#endif
9724#if !defined(SQLITE_BYTEORDER)
9725# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
9726# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
9727# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
9728# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
9729#endif
9730
9731/*
9732** Constants for the largest and smallest possible 64-bit signed integers.
9733** These macros are designed to work correctly on both 32-bit and 64-bit
9734** compilers.
9735*/
9736#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
9737#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
9738
9739/*
9740** Round up a number to the next larger multiple of 8.  This is used
9741** to force 8-byte alignment on 64-bit architectures.
9742*/
9743#define ROUND8(x)     (((x)+7)&~7)
9744
9745/*
9746** Round down to the nearest multiple of 8
9747*/
9748#define ROUNDDOWN8(x) ((x)&~7)
9749
9750/*
9751** Assert that the pointer X is aligned to an 8-byte boundary.  This
9752** macro is used only within assert() to verify that the code gets
9753** all alignment restrictions correct.
9754**
9755** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
9756** underlying malloc() implementation might return us 4-byte aligned
9757** pointers.  In that case, only verify 4-byte alignment.
9758*/
9759#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
9760# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
9761#else
9762# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
9763#endif
9764
9765/*
9766** Disable MMAP on platforms where it is known to not work
9767*/
9768#if defined(__OpenBSD__) || defined(__QNXNTO__)
9769# undef SQLITE_MAX_MMAP_SIZE
9770# define SQLITE_MAX_MMAP_SIZE 0
9771#endif
9772
9773/*
9774** Default maximum size of memory used by memory-mapped I/O in the VFS
9775*/
9776#ifdef __APPLE__
9777# include <TargetConditionals.h>
9778# if TARGET_OS_IPHONE
9779#   undef SQLITE_MAX_MMAP_SIZE
9780#   define SQLITE_MAX_MMAP_SIZE 0
9781# endif
9782#endif
9783#ifndef SQLITE_MAX_MMAP_SIZE
9784# if defined(__linux__) \
9785  || defined(_WIN32) \
9786  || (defined(__APPLE__) && defined(__MACH__)) \
9787  || defined(__sun) \
9788  || defined(__FreeBSD__) \
9789  || defined(__DragonFly__)
9790#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
9791# else
9792#   define SQLITE_MAX_MMAP_SIZE 0
9793# endif
9794# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
9795#endif
9796
9797/*
9798** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
9799** default MMAP_SIZE is specified at compile-time, make sure that it does
9800** not exceed the maximum mmap size.
9801*/
9802#ifndef SQLITE_DEFAULT_MMAP_SIZE
9803# define SQLITE_DEFAULT_MMAP_SIZE 0
9804# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
9805#endif
9806#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
9807# undef SQLITE_DEFAULT_MMAP_SIZE
9808# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
9809#endif
9810
9811/*
9812** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
9813** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
9814** define SQLITE_ENABLE_STAT3_OR_STAT4
9815*/
9816#ifdef SQLITE_ENABLE_STAT4
9817# undef SQLITE_ENABLE_STAT3
9818# define SQLITE_ENABLE_STAT3_OR_STAT4 1
9819#elif SQLITE_ENABLE_STAT3
9820# define SQLITE_ENABLE_STAT3_OR_STAT4 1
9821#elif SQLITE_ENABLE_STAT3_OR_STAT4
9822# undef SQLITE_ENABLE_STAT3_OR_STAT4
9823#endif
9824
9825/*
9826** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
9827** the Select query generator tracing logic is turned on.
9828*/
9829#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
9830# define SELECTTRACE_ENABLED 1
9831#else
9832# define SELECTTRACE_ENABLED 0
9833#endif
9834
9835/*
9836** An instance of the following structure is used to store the busy-handler
9837** callback for a given sqlite handle.
9838**
9839** The sqlite.busyHandler member of the sqlite struct contains the busy
9840** callback for the database handle. Each pager opened via the sqlite
9841** handle is passed a pointer to sqlite.busyHandler. The busy-handler
9842** callback is currently invoked only from within pager.c.
9843*/
9844typedef struct BusyHandler BusyHandler;
9845struct BusyHandler {
9846  int (*xFunc)(void *,int);  /* The busy callback */
9847  void *pArg;                /* First arg to busy callback */
9848  int nBusy;                 /* Incremented with each busy call */
9849};
9850
9851/*
9852** Name of the master database table.  The master database table
9853** is a special table that holds the names and attributes of all
9854** user tables and indices.
9855*/
9856#define MASTER_NAME       "sqlite_master"
9857#define TEMP_MASTER_NAME  "sqlite_temp_master"
9858
9859/*
9860** The root-page of the master database table.
9861*/
9862#define MASTER_ROOT       1
9863
9864/*
9865** The name of the schema table.
9866*/
9867#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
9868
9869/*
9870** A convenience macro that returns the number of elements in
9871** an array.
9872*/
9873#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
9874
9875/*
9876** Determine if the argument is a power of two
9877*/
9878#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
9879
9880/*
9881** The following value as a destructor means to use sqlite3DbFree().
9882** The sqlite3DbFree() routine requires two parameters instead of the
9883** one parameter that destructors normally want.  So we have to introduce
9884** this magic value that the code knows to handle differently.  Any
9885** pointer will work here as long as it is distinct from SQLITE_STATIC
9886** and SQLITE_TRANSIENT.
9887*/
9888#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
9889
9890/*
9891** When SQLITE_OMIT_WSD is defined, it means that the target platform does
9892** not support Writable Static Data (WSD) such as global and static variables.
9893** All variables must either be on the stack or dynamically allocated from
9894** the heap.  When WSD is unsupported, the variable declarations scattered
9895** throughout the SQLite code must become constants instead.  The SQLITE_WSD
9896** macro is used for this purpose.  And instead of referencing the variable
9897** directly, we use its constant as a key to lookup the run-time allocated
9898** buffer that holds real variable.  The constant is also the initializer
9899** for the run-time allocated buffer.
9900**
9901** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
9902** macros become no-ops and have zero performance impact.
9903*/
9904#ifdef SQLITE_OMIT_WSD
9905  #define SQLITE_WSD const
9906  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
9907  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
9908SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
9909SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
9910#else
9911  #define SQLITE_WSD
9912  #define GLOBAL(t,v) v
9913  #define sqlite3GlobalConfig sqlite3Config
9914#endif
9915
9916/*
9917** The following macros are used to suppress compiler warnings and to
9918** make it clear to human readers when a function parameter is deliberately
9919** left unused within the body of a function. This usually happens when
9920** a function is called via a function pointer. For example the
9921** implementation of an SQL aggregate step callback may not use the
9922** parameter indicating the number of arguments passed to the aggregate,
9923** if it knows that this is enforced elsewhere.
9924**
9925** When a function parameter is not used at all within the body of a function,
9926** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
9927** However, these macros may also be used to suppress warnings related to
9928** parameters that may or may not be used depending on compilation options.
9929** For example those parameters only used in assert() statements. In these
9930** cases the parameters are named as per the usual conventions.
9931*/
9932#define UNUSED_PARAMETER(x) (void)(x)
9933#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
9934
9935/*
9936** Forward references to structures
9937*/
9938typedef struct AggInfo AggInfo;
9939typedef struct AuthContext AuthContext;
9940typedef struct AutoincInfo AutoincInfo;
9941typedef struct Bitvec Bitvec;
9942typedef struct CollSeq CollSeq;
9943typedef struct Column Column;
9944typedef struct Db Db;
9945typedef struct Schema Schema;
9946typedef struct Expr Expr;
9947typedef struct ExprList ExprList;
9948typedef struct ExprSpan ExprSpan;
9949typedef struct FKey FKey;
9950typedef struct FuncDestructor FuncDestructor;
9951typedef struct FuncDef FuncDef;
9952typedef struct FuncDefHash FuncDefHash;
9953typedef struct IdList IdList;
9954typedef struct Index Index;
9955typedef struct IndexSample IndexSample;
9956typedef struct KeyClass KeyClass;
9957typedef struct KeyInfo KeyInfo;
9958typedef struct Lookaside Lookaside;
9959typedef struct LookasideSlot LookasideSlot;
9960typedef struct Module Module;
9961typedef struct NameContext NameContext;
9962typedef struct Parse Parse;
9963typedef struct PrintfArguments PrintfArguments;
9964typedef struct RowSet RowSet;
9965typedef struct Savepoint Savepoint;
9966typedef struct Select Select;
9967typedef struct SQLiteThread SQLiteThread;
9968typedef struct SelectDest SelectDest;
9969typedef struct SrcList SrcList;
9970typedef struct StrAccum StrAccum;
9971typedef struct Table Table;
9972typedef struct TableLock TableLock;
9973typedef struct Token Token;
9974typedef struct TreeView TreeView;
9975typedef struct Trigger Trigger;
9976typedef struct TriggerPrg TriggerPrg;
9977typedef struct TriggerStep TriggerStep;
9978typedef struct UnpackedRecord UnpackedRecord;
9979typedef struct VTable VTable;
9980typedef struct VtabCtx VtabCtx;
9981typedef struct Walker Walker;
9982typedef struct WhereInfo WhereInfo;
9983typedef struct With With;
9984
9985/*
9986** Defer sourcing vdbe.h and btree.h until after the "u8" and
9987** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
9988** pointer types (i.e. FuncDef) defined above.
9989*/
9990/************** Include btree.h in the middle of sqliteInt.h *****************/
9991/************** Begin file btree.h *******************************************/
9992/*
9993** 2001 September 15
9994**
9995** The author disclaims copyright to this source code.  In place of
9996** a legal notice, here is a blessing:
9997**
9998**    May you do good and not evil.
9999**    May you find forgiveness for yourself and forgive others.
10000**    May you share freely, never taking more than you give.
10001**
10002*************************************************************************
10003** This header file defines the interface that the sqlite B-Tree file
10004** subsystem.  See comments in the source code for a detailed description
10005** of what each interface routine does.
10006*/
10007#ifndef _BTREE_H_
10008#define _BTREE_H_
10009
10010/* TODO: This definition is just included so other modules compile. It
10011** needs to be revisited.
10012*/
10013#define SQLITE_N_BTREE_META 16
10014
10015/*
10016** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
10017** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
10018*/
10019#ifndef SQLITE_DEFAULT_AUTOVACUUM
10020  #define SQLITE_DEFAULT_AUTOVACUUM 0
10021#endif
10022
10023#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
10024#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
10025#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
10026
10027/*
10028** Forward declarations of structure
10029*/
10030typedef struct Btree Btree;
10031typedef struct BtCursor BtCursor;
10032typedef struct BtShared BtShared;
10033
10034
10035SQLITE_PRIVATE int sqlite3BtreeOpen(
10036  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
10037  const char *zFilename,   /* Name of database file to open */
10038  sqlite3 *db,             /* Associated database connection */
10039  Btree **ppBtree,         /* Return open Btree* here */
10040  int flags,               /* Flags */
10041  int vfsFlags             /* Flags passed through to VFS open */
10042);
10043
10044/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
10045** following values.
10046**
10047** NOTE:  These values must match the corresponding PAGER_ values in
10048** pager.h.
10049*/
10050#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
10051#define BTREE_MEMORY        2  /* This is an in-memory DB */
10052#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
10053#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
10054
10055SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
10056SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
10057#if SQLITE_MAX_MMAP_SIZE>0
10058SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
10059#endif
10060SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
10061SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
10062SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
10063SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
10064SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
10065SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
10066SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
10067SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
10068SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
10069SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
10070SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
10071SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
10072SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
10073SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
10074SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
10075SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
10076SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
10077SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
10078SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
10079SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
10080SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
10081SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
10082SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
10083SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
10084SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
10085
10086SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
10087SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
10088SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
10089
10090SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
10091
10092/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
10093** of the flags shown below.
10094**
10095** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
10096** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
10097** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
10098** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
10099** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
10100** indices.)
10101*/
10102#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
10103#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
10104
10105SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
10106SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
10107SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
10108SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
10109
10110SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
10111SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
10112
10113SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
10114
10115/*
10116** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
10117** should be one of the following values. The integer values are assigned
10118** to constants so that the offset of the corresponding field in an
10119** SQLite database header may be found using the following formula:
10120**
10121**   offset = 36 + (idx * 4)
10122**
10123** For example, the free-page-count field is located at byte offset 36 of
10124** the database file header. The incr-vacuum-flag field is located at
10125** byte offset 64 (== 36+4*7).
10126**
10127** The BTREE_DATA_VERSION value is not really a value stored in the header.
10128** It is a read-only number computed by the pager.  But we merge it with
10129** the header value access routines since its access pattern is the same.
10130** Call it a "virtual meta value".
10131*/
10132#define BTREE_FREE_PAGE_COUNT     0
10133#define BTREE_SCHEMA_VERSION      1
10134#define BTREE_FILE_FORMAT         2
10135#define BTREE_DEFAULT_CACHE_SIZE  3
10136#define BTREE_LARGEST_ROOT_PAGE   4
10137#define BTREE_TEXT_ENCODING       5
10138#define BTREE_USER_VERSION        6
10139#define BTREE_INCR_VACUUM         7
10140#define BTREE_APPLICATION_ID      8
10141#define BTREE_DATA_VERSION        15  /* A virtual meta-value */
10142
10143/*
10144** Values that may be OR'd together to form the second argument of an
10145** sqlite3BtreeCursorHints() call.
10146**
10147** The BTREE_BULKLOAD flag is set on index cursors when the index is going
10148** to be filled with content that is already in sorted order.
10149**
10150** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
10151** OP_SeekLE opcodes for a range search, but where the range of entries
10152** selected will all have the same key.  In other words, the cursor will
10153** be used only for equality key searches.
10154**
10155*/
10156#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
10157#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
10158
10159SQLITE_PRIVATE int sqlite3BtreeCursor(
10160  Btree*,                              /* BTree containing table to open */
10161  int iTable,                          /* Index of root page */
10162  int wrFlag,                          /* 1 for writing.  0 for read-only */
10163  struct KeyInfo*,                     /* First argument to compare function */
10164  BtCursor *pCursor                    /* Space to write cursor structure */
10165);
10166SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
10167SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
10168
10169SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
10170SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
10171  BtCursor*,
10172  UnpackedRecord *pUnKey,
10173  i64 intKey,
10174  int bias,
10175  int *pRes
10176);
10177SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
10178SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
10179SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, int);
10180SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
10181                                  const void *pData, int nData,
10182                                  int nZero, int bias, int seekResult);
10183SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
10184SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
10185SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
10186SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
10187SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
10188SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
10189SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
10190SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
10191SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
10192SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
10193SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
10194
10195SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
10196SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
10197
10198SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
10199SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
10200SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
10201SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
10202SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
10203#ifdef SQLITE_DEBUG
10204SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
10205#endif
10206SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
10207SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
10208
10209#ifndef NDEBUG
10210SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
10211#endif
10212
10213#ifndef SQLITE_OMIT_BTREECOUNT
10214SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
10215#endif
10216
10217#ifdef SQLITE_TEST
10218SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
10219SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
10220#endif
10221
10222#ifndef SQLITE_OMIT_WAL
10223SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
10224#endif
10225
10226/*
10227** If we are not using shared cache, then there is no need to
10228** use mutexes to access the BtShared structures.  So make the
10229** Enter and Leave procedures no-ops.
10230*/
10231#ifndef SQLITE_OMIT_SHARED_CACHE
10232SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
10233SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
10234#else
10235# define sqlite3BtreeEnter(X)
10236# define sqlite3BtreeEnterAll(X)
10237#endif
10238
10239#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
10240SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
10241SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
10242SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
10243SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
10244SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
10245#ifndef NDEBUG
10246  /* These routines are used inside assert() statements only. */
10247SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
10248SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
10249SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
10250#endif
10251#else
10252
10253# define sqlite3BtreeSharable(X) 0
10254# define sqlite3BtreeLeave(X)
10255# define sqlite3BtreeEnterCursor(X)
10256# define sqlite3BtreeLeaveCursor(X)
10257# define sqlite3BtreeLeaveAll(X)
10258
10259# define sqlite3BtreeHoldsMutex(X) 1
10260# define sqlite3BtreeHoldsAllMutexes(X) 1
10261# define sqlite3SchemaMutexHeld(X,Y,Z) 1
10262#endif
10263
10264
10265#endif /* _BTREE_H_ */
10266
10267/************** End of btree.h ***********************************************/
10268/************** Continuing where we left off in sqliteInt.h ******************/
10269/************** Include vdbe.h in the middle of sqliteInt.h ******************/
10270/************** Begin file vdbe.h ********************************************/
10271/*
10272** 2001 September 15
10273**
10274** The author disclaims copyright to this source code.  In place of
10275** a legal notice, here is a blessing:
10276**
10277**    May you do good and not evil.
10278**    May you find forgiveness for yourself and forgive others.
10279**    May you share freely, never taking more than you give.
10280**
10281*************************************************************************
10282** Header file for the Virtual DataBase Engine (VDBE)
10283**
10284** This header defines the interface to the virtual database engine
10285** or VDBE.  The VDBE implements an abstract machine that runs a
10286** simple program to access and modify the underlying database.
10287*/
10288#ifndef _SQLITE_VDBE_H_
10289#define _SQLITE_VDBE_H_
10290/* #include <stdio.h> */
10291
10292/*
10293** A single VDBE is an opaque structure named "Vdbe".  Only routines
10294** in the source file sqliteVdbe.c are allowed to see the insides
10295** of this structure.
10296*/
10297typedef struct Vdbe Vdbe;
10298
10299/*
10300** The names of the following types declared in vdbeInt.h are required
10301** for the VdbeOp definition.
10302*/
10303typedef struct Mem Mem;
10304typedef struct SubProgram SubProgram;
10305
10306/*
10307** A single instruction of the virtual machine has an opcode
10308** and as many as three operands.  The instruction is recorded
10309** as an instance of the following structure:
10310*/
10311struct VdbeOp {
10312  u8 opcode;          /* What operation to perform */
10313  signed char p4type; /* One of the P4_xxx constants for p4 */
10314  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
10315  u8 p5;              /* Fifth parameter is an unsigned character */
10316  int p1;             /* First operand */
10317  int p2;             /* Second parameter (often the jump destination) */
10318  int p3;             /* The third parameter */
10319  union p4union {     /* fourth parameter */
10320    int i;                 /* Integer value if p4type==P4_INT32 */
10321    void *p;               /* Generic pointer */
10322    char *z;               /* Pointer to data for string (char array) types */
10323    i64 *pI64;             /* Used when p4type is P4_INT64 */
10324    double *pReal;         /* Used when p4type is P4_REAL */
10325    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
10326    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
10327    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
10328    Mem *pMem;             /* Used when p4type is P4_MEM */
10329    VTable *pVtab;         /* Used when p4type is P4_VTAB */
10330    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
10331    int *ai;               /* Used when p4type is P4_INTARRAY */
10332    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
10333    int (*xAdvance)(BtCursor *, int *);
10334  } p4;
10335#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
10336  char *zComment;          /* Comment to improve readability */
10337#endif
10338#ifdef VDBE_PROFILE
10339  u32 cnt;                 /* Number of times this instruction was executed */
10340  u64 cycles;              /* Total time spent executing this instruction */
10341#endif
10342#ifdef SQLITE_VDBE_COVERAGE
10343  int iSrcLine;            /* Source-code line that generated this opcode */
10344#endif
10345};
10346typedef struct VdbeOp VdbeOp;
10347
10348
10349/*
10350** A sub-routine used to implement a trigger program.
10351*/
10352struct SubProgram {
10353  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
10354  int nOp;                      /* Elements in aOp[] */
10355  int nMem;                     /* Number of memory cells required */
10356  int nCsr;                     /* Number of cursors required */
10357  int nOnce;                    /* Number of OP_Once instructions */
10358  void *token;                  /* id that may be used to recursive triggers */
10359  SubProgram *pNext;            /* Next sub-program already visited */
10360};
10361
10362/*
10363** A smaller version of VdbeOp used for the VdbeAddOpList() function because
10364** it takes up less space.
10365*/
10366struct VdbeOpList {
10367  u8 opcode;          /* What operation to perform */
10368  signed char p1;     /* First operand */
10369  signed char p2;     /* Second parameter (often the jump destination) */
10370  signed char p3;     /* Third parameter */
10371};
10372typedef struct VdbeOpList VdbeOpList;
10373
10374/*
10375** Allowed values of VdbeOp.p4type
10376*/
10377#define P4_NOTUSED    0   /* The P4 parameter is not used */
10378#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
10379#define P4_STATIC   (-2)  /* Pointer to a static string */
10380#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
10381#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
10382#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
10383#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
10384#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
10385#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
10386#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
10387#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
10388#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
10389#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
10390#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
10391#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
10392#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
10393#define P4_FUNCCTX  (-20) /* P4 is a pointer to an sqlite3_context object */
10394
10395/* Error message codes for OP_Halt */
10396#define P5_ConstraintNotNull 1
10397#define P5_ConstraintUnique  2
10398#define P5_ConstraintCheck   3
10399#define P5_ConstraintFK      4
10400
10401/*
10402** The Vdbe.aColName array contains 5n Mem structures, where n is the
10403** number of columns of data returned by the statement.
10404*/
10405#define COLNAME_NAME     0
10406#define COLNAME_DECLTYPE 1
10407#define COLNAME_DATABASE 2
10408#define COLNAME_TABLE    3
10409#define COLNAME_COLUMN   4
10410#ifdef SQLITE_ENABLE_COLUMN_METADATA
10411# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
10412#else
10413# ifdef SQLITE_OMIT_DECLTYPE
10414#   define COLNAME_N      1      /* Store only the name */
10415# else
10416#   define COLNAME_N      2      /* Store the name and decltype */
10417# endif
10418#endif
10419
10420/*
10421** The following macro converts a relative address in the p2 field
10422** of a VdbeOp structure into a negative number so that
10423** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
10424** the macro again restores the address.
10425*/
10426#define ADDR(X)  (-1-(X))
10427
10428/*
10429** The makefile scans the vdbe.c source file and creates the "opcodes.h"
10430** header file that defines a number for each opcode used by the VDBE.
10431*/
10432/************** Include opcodes.h in the middle of vdbe.h ********************/
10433/************** Begin file opcodes.h *****************************************/
10434/* Automatically generated.  Do not edit */
10435/* See the mkopcodeh.awk script for details */
10436#define OP_Savepoint       1
10437#define OP_AutoCommit      2
10438#define OP_Transaction     3
10439#define OP_SorterNext      4
10440#define OP_PrevIfOpen      5
10441#define OP_NextIfOpen      6
10442#define OP_Prev            7
10443#define OP_Next            8
10444#define OP_Checkpoint      9
10445#define OP_JournalMode    10
10446#define OP_Vacuum         11
10447#define OP_VFilter        12 /* synopsis: iplan=r[P3] zplan='P4'           */
10448#define OP_VUpdate        13 /* synopsis: data=r[P3@P2]                    */
10449#define OP_Goto           14
10450#define OP_Gosub          15
10451#define OP_Return         16
10452#define OP_InitCoroutine  17
10453#define OP_EndCoroutine   18
10454#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
10455#define OP_Yield          20
10456#define OP_HaltIfNull     21 /* synopsis: if r[P3]=null halt               */
10457#define OP_Halt           22
10458#define OP_Integer        23 /* synopsis: r[P2]=P1                         */
10459#define OP_Int64          24 /* synopsis: r[P2]=P4                         */
10460#define OP_String         25 /* synopsis: r[P2]='P4' (len=P1)              */
10461#define OP_Null           26 /* synopsis: r[P2..P3]=NULL                   */
10462#define OP_SoftNull       27 /* synopsis: r[P1]=NULL                       */
10463#define OP_Blob           28 /* synopsis: r[P2]=P4 (len=P1)                */
10464#define OP_Variable       29 /* synopsis: r[P2]=parameter(P1,P4)           */
10465#define OP_Move           30 /* synopsis: r[P2@P3]=r[P1@P3]                */
10466#define OP_Copy           31 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
10467#define OP_SCopy          32 /* synopsis: r[P2]=r[P1]                      */
10468#define OP_ResultRow      33 /* synopsis: output=r[P1@P2]                  */
10469#define OP_CollSeq        34
10470#define OP_Function0      35 /* synopsis: r[P3]=func(r[P2@P5])             */
10471#define OP_Function       36 /* synopsis: r[P3]=func(r[P2@P5])             */
10472#define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
10473#define OP_MustBeInt      38
10474#define OP_RealAffinity   39
10475#define OP_Cast           40 /* synopsis: affinity(r[P1])                  */
10476#define OP_Permutation    41
10477#define OP_Compare        42 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
10478#define OP_Jump           43
10479#define OP_Once           44
10480#define OP_If             45
10481#define OP_IfNot          46
10482#define OP_Column         47 /* synopsis: r[P3]=PX                         */
10483#define OP_Affinity       48 /* synopsis: affinity(r[P1@P2])               */
10484#define OP_MakeRecord     49 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
10485#define OP_Count          50 /* synopsis: r[P2]=count()                    */
10486#define OP_ReadCookie     51
10487#define OP_SetCookie      52
10488#define OP_ReopenIdx      53 /* synopsis: root=P2 iDb=P3                   */
10489#define OP_OpenRead       54 /* synopsis: root=P2 iDb=P3                   */
10490#define OP_OpenWrite      55 /* synopsis: root=P2 iDb=P3                   */
10491#define OP_OpenAutoindex  56 /* synopsis: nColumn=P2                       */
10492#define OP_OpenEphemeral  57 /* synopsis: nColumn=P2                       */
10493#define OP_SorterOpen     58
10494#define OP_SequenceTest   59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
10495#define OP_OpenPseudo     60 /* synopsis: P3 columns in r[P2]              */
10496#define OP_Close          61
10497#define OP_ColumnsUsed    62
10498#define OP_SeekLT         63 /* synopsis: key=r[P3@P4]                     */
10499#define OP_SeekLE         64 /* synopsis: key=r[P3@P4]                     */
10500#define OP_SeekGE         65 /* synopsis: key=r[P3@P4]                     */
10501#define OP_SeekGT         66 /* synopsis: key=r[P3@P4]                     */
10502#define OP_Seek           67 /* synopsis: intkey=r[P2]                     */
10503#define OP_NoConflict     68 /* synopsis: key=r[P3@P4]                     */
10504#define OP_NotFound       69 /* synopsis: key=r[P3@P4]                     */
10505#define OP_Found          70 /* synopsis: key=r[P3@P4]                     */
10506#define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
10507#define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
10508#define OP_NotExists      73 /* synopsis: intkey=r[P3]                     */
10509#define OP_Sequence       74 /* synopsis: r[P2]=cursor[P1].ctr++           */
10510#define OP_NewRowid       75 /* synopsis: r[P2]=rowid                      */
10511#define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
10512#define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
10513#define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
10514#define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
10515#define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
10516#define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
10517#define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
10518#define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
10519#define OP_Insert         84 /* synopsis: intkey=r[P3] data=r[P2]          */
10520#define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
10521#define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
10522#define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
10523#define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
10524#define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
10525#define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
10526#define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
10527#define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
10528#define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
10529#define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
10530#define OP_InsertInt      95 /* synopsis: intkey=P3 data=r[P2]             */
10531#define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
10532#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
10533#define OP_Delete         98
10534#define OP_ResetCount     99
10535#define OP_SorterCompare 100 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
10536#define OP_SorterData    101 /* synopsis: r[P2]=data                       */
10537#define OP_RowKey        102 /* synopsis: r[P2]=key                        */
10538#define OP_RowData       103 /* synopsis: r[P2]=data                       */
10539#define OP_Rowid         104 /* synopsis: r[P2]=rowid                      */
10540#define OP_NullRow       105
10541#define OP_Last          106
10542#define OP_SorterSort    107
10543#define OP_Sort          108
10544#define OP_Rewind        109
10545#define OP_SorterInsert  110
10546#define OP_IdxInsert     111 /* synopsis: key=r[P2]                        */
10547#define OP_IdxDelete     112 /* synopsis: key=r[P2@P3]                     */
10548#define OP_IdxRowid      113 /* synopsis: r[P2]=rowid                      */
10549#define OP_IdxLE         114 /* synopsis: key=r[P3@P4]                     */
10550#define OP_IdxGT         115 /* synopsis: key=r[P3@P4]                     */
10551#define OP_IdxLT         116 /* synopsis: key=r[P3@P4]                     */
10552#define OP_IdxGE         117 /* synopsis: key=r[P3@P4]                     */
10553#define OP_Destroy       118
10554#define OP_Clear         119
10555#define OP_ResetSorter   120
10556#define OP_CreateIndex   121 /* synopsis: r[P2]=root iDb=P1                */
10557#define OP_CreateTable   122 /* synopsis: r[P2]=root iDb=P1                */
10558#define OP_ParseSchema   123
10559#define OP_LoadAnalysis  124
10560#define OP_DropTable     125
10561#define OP_DropIndex     126
10562#define OP_DropTrigger   127
10563#define OP_IntegrityCk   128
10564#define OP_RowSetAdd     129 /* synopsis: rowset(P1)=r[P2]                 */
10565#define OP_RowSetRead    130 /* synopsis: r[P3]=rowset(P1)                 */
10566#define OP_RowSetTest    131 /* synopsis: if r[P3] in rowset(P1) goto P2   */
10567#define OP_Program       132
10568#define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
10569#define OP_Param         134
10570#define OP_FkCounter     135 /* synopsis: fkctr[P1]+=P2                    */
10571#define OP_FkIfZero      136 /* synopsis: if fkctr[P1]==0 goto P2          */
10572#define OP_MemMax        137 /* synopsis: r[P1]=max(r[P1],r[P2])           */
10573#define OP_IfPos         138 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
10574#define OP_SetIfNotPos   139 /* synopsis: if r[P1]<=0 then r[P2]=P3        */
10575#define OP_IfNotZero     140 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
10576#define OP_DecrJumpZero  141 /* synopsis: if (--r[P1])==0 goto P2          */
10577#define OP_JumpZeroIncr  142 /* synopsis: if (r[P1]++)==0 ) goto P2        */
10578#define OP_AggStep0      143 /* synopsis: accum=r[P3] step(r[P2@P5])       */
10579#define OP_AggStep       144 /* synopsis: accum=r[P3] step(r[P2@P5])       */
10580#define OP_AggFinal      145 /* synopsis: accum=r[P1] N=P2                 */
10581#define OP_IncrVacuum    146
10582#define OP_Expire        147
10583#define OP_TableLock     148 /* synopsis: iDb=P1 root=P2 write=P3          */
10584#define OP_VBegin        149
10585#define OP_VCreate       150
10586#define OP_VDestroy      151
10587#define OP_VOpen         152
10588#define OP_VColumn       153 /* synopsis: r[P3]=vcolumn(P2)                */
10589#define OP_VNext         154
10590#define OP_VRename       155
10591#define OP_Pagecount     156
10592#define OP_MaxPgcnt      157
10593#define OP_Init          158 /* synopsis: Start at P2                      */
10594#define OP_Noop          159
10595#define OP_Explain       160
10596
10597
10598/* Properties such as "out2" or "jump" that are specified in
10599** comments following the "case" for each opcode in the vdbe.c
10600** are encoded into bitvectors as follows:
10601*/
10602#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
10603#define OPFLG_IN1             0x0002  /* in1:   P1 is an input */
10604#define OPFLG_IN2             0x0004  /* in2:   P2 is an input */
10605#define OPFLG_IN3             0x0008  /* in3:   P3 is an input */
10606#define OPFLG_OUT2            0x0010  /* out2:  P2 is an output */
10607#define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
10608#define OPFLG_INITIALIZER {\
10609/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,\
10610/*   8 */ 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01,\
10611/*  16 */ 0x02, 0x01, 0x02, 0x12, 0x03, 0x08, 0x00, 0x10,\
10612/*  24 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
10613/*  32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
10614/*  40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
10615/*  48 */ 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00, 0x00,\
10616/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
10617/*  64 */ 0x09, 0x09, 0x09, 0x04, 0x09, 0x09, 0x09, 0x26,\
10618/*  72 */ 0x26, 0x09, 0x10, 0x10, 0x03, 0x03, 0x0b, 0x0b,\
10619/*  80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
10620/*  88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
10621/*  96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
10622/* 104 */ 0x10, 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04,\
10623/* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
10624/* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
10625/* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
10626/* 136 */ 0x01, 0x04, 0x03, 0x06, 0x03, 0x03, 0x03, 0x00,\
10627/* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
10628/* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
10629/* 160 */ 0x00,}
10630
10631/************** End of opcodes.h *********************************************/
10632/************** Continuing where we left off in vdbe.h ***********************/
10633
10634/*
10635** Prototypes for the VDBE interface.  See comments on the implementation
10636** for a description of what each of these routines does.
10637*/
10638SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
10639SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
10640SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
10641SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
10642SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
10643SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
10644SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
10645SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
10646SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
10647SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
10648SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
10649SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
10650SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
10651SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
10652SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
10653SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
10654SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
10655SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
10656SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
10657SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
10658SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
10659SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
10660SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
10661SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
10662SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
10663SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
10664SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
10665SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
10666SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
10667SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
10668SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
10669SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
10670SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
10671#ifdef SQLITE_DEBUG
10672SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
10673#endif
10674SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
10675SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
10676SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
10677SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
10678SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
10679SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
10680SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
10681SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
10682SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
10683SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
10684SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
10685SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
10686#ifndef SQLITE_OMIT_TRACE
10687SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
10688#endif
10689SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
10690
10691SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
10692SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
10693SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
10694SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
10695
10696typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
10697SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
10698
10699#ifndef SQLITE_OMIT_TRIGGER
10700SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
10701#endif
10702
10703/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
10704** each VDBE opcode.
10705**
10706** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
10707** comments in VDBE programs that show key decision points in the code
10708** generator.
10709*/
10710#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
10711SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
10712# define VdbeComment(X)  sqlite3VdbeComment X
10713SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
10714# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
10715# ifdef SQLITE_ENABLE_MODULE_COMMENTS
10716#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
10717# else
10718#   define VdbeModuleComment(X)
10719# endif
10720#else
10721# define VdbeComment(X)
10722# define VdbeNoopComment(X)
10723# define VdbeModuleComment(X)
10724#endif
10725
10726/*
10727** The VdbeCoverage macros are used to set a coverage testing point
10728** for VDBE branch instructions.  The coverage testing points are line
10729** numbers in the sqlite3.c source file.  VDBE branch coverage testing
10730** only works with an amalagmation build.  That's ok since a VDBE branch
10731** coverage build designed for testing the test suite only.  No application
10732** should ever ship with VDBE branch coverage measuring turned on.
10733**
10734**    VdbeCoverage(v)                  // Mark the previously coded instruction
10735**                                     // as a branch
10736**
10737**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
10738**
10739**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
10740**
10741**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
10742**
10743** Every VDBE branch operation must be tagged with one of the macros above.
10744** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
10745** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
10746** routine in vdbe.c, alerting the developer to the missed tag.
10747*/
10748#ifdef SQLITE_VDBE_COVERAGE
10749SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
10750# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
10751# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
10752# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
10753# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
10754# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
10755#else
10756# define VdbeCoverage(v)
10757# define VdbeCoverageIf(v,x)
10758# define VdbeCoverageAlwaysTaken(v)
10759# define VdbeCoverageNeverTaken(v)
10760# define VDBE_OFFSET_LINENO(x) 0
10761#endif
10762
10763#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
10764SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
10765#else
10766# define sqlite3VdbeScanStatus(a,b,c,d,e)
10767#endif
10768
10769#endif
10770
10771/************** End of vdbe.h ************************************************/
10772/************** Continuing where we left off in sqliteInt.h ******************/
10773/************** Include pager.h in the middle of sqliteInt.h *****************/
10774/************** Begin file pager.h *******************************************/
10775/*
10776** 2001 September 15
10777**
10778** The author disclaims copyright to this source code.  In place of
10779** a legal notice, here is a blessing:
10780**
10781**    May you do good and not evil.
10782**    May you find forgiveness for yourself and forgive others.
10783**    May you share freely, never taking more than you give.
10784**
10785*************************************************************************
10786** This header file defines the interface that the sqlite page cache
10787** subsystem.  The page cache subsystem reads and writes a file a page
10788** at a time and provides a journal for rollback.
10789*/
10790
10791#ifndef _PAGER_H_
10792#define _PAGER_H_
10793
10794/*
10795** Default maximum size for persistent journal files. A negative
10796** value means no limit. This value may be overridden using the
10797** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
10798*/
10799#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
10800  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
10801#endif
10802
10803/*
10804** The type used to represent a page number.  The first page in a file
10805** is called page 1.  0 is used to represent "not a page".
10806*/
10807typedef u32 Pgno;
10808
10809/*
10810** Each open file is managed by a separate instance of the "Pager" structure.
10811*/
10812typedef struct Pager Pager;
10813
10814/*
10815** Handle type for pages.
10816*/
10817typedef struct PgHdr DbPage;
10818
10819/*
10820** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
10821** reserved for working around a windows/posix incompatibility). It is
10822** used in the journal to signify that the remainder of the journal file
10823** is devoted to storing a master journal name - there are no more pages to
10824** roll back. See comments for function writeMasterJournal() in pager.c
10825** for details.
10826*/
10827#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
10828
10829/*
10830** Allowed values for the flags parameter to sqlite3PagerOpen().
10831**
10832** NOTE: These values must match the corresponding BTREE_ values in btree.h.
10833*/
10834#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
10835#define PAGER_MEMORY        0x0002    /* In-memory database */
10836
10837/*
10838** Valid values for the second argument to sqlite3PagerLockingMode().
10839*/
10840#define PAGER_LOCKINGMODE_QUERY      -1
10841#define PAGER_LOCKINGMODE_NORMAL      0
10842#define PAGER_LOCKINGMODE_EXCLUSIVE   1
10843
10844/*
10845** Numeric constants that encode the journalmode.
10846*/
10847#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
10848#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
10849#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
10850#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
10851#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
10852#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
10853#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
10854
10855/*
10856** Flags that make up the mask passed to sqlite3PagerAcquire().
10857*/
10858#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
10859#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
10860
10861/*
10862** Flags for sqlite3PagerSetFlags()
10863*/
10864#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
10865#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
10866#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
10867#define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
10868#define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
10869#define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
10870#define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
10871#define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
10872
10873/*
10874** The remainder of this file contains the declarations of the functions
10875** that make up the Pager sub-system API. See source code comments for
10876** a detailed description of each routine.
10877*/
10878
10879/* Open and close a Pager connection. */
10880SQLITE_PRIVATE int sqlite3PagerOpen(
10881  sqlite3_vfs*,
10882  Pager **ppPager,
10883  const char*,
10884  int,
10885  int,
10886  int,
10887  void(*)(DbPage*)
10888);
10889SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
10890SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
10891
10892/* Functions used to configure a Pager object. */
10893SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
10894SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
10895#ifdef SQLITE_HAS_CODEC
10896SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
10897#endif
10898SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
10899SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
10900SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
10901SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
10902SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
10903SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
10904SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
10905SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
10906SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
10907SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
10908SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
10909
10910/* Functions used to obtain and release page references. */
10911SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
10912#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
10913SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
10914SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
10915SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
10916SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
10917
10918/* Operations on page references. */
10919SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
10920SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
10921SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
10922SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
10923SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
10924SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
10925
10926/* Functions used to manage pager transactions and savepoints. */
10927SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
10928SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
10929SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
10930SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
10931SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
10932SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
10933SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
10934SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
10935SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
10936SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
10937
10938#ifndef SQLITE_OMIT_WAL
10939SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
10940SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
10941SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
10942SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
10943SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
10944#endif
10945
10946#ifdef SQLITE_ENABLE_ZIPVFS
10947SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
10948#endif
10949
10950/* Functions used to query pager state and configuration. */
10951SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
10952SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
10953#ifdef SQLITE_DEBUG
10954SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
10955#endif
10956SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
10957SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
10958SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
10959SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
10960SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
10961SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
10962SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
10963SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
10964SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
10965SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
10966SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
10967
10968/* Functions used to truncate the database file. */
10969SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
10970
10971SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
10972
10973#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
10974SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
10975#endif
10976
10977/* Functions to support testing and debugging. */
10978#if !defined(NDEBUG) || defined(SQLITE_TEST)
10979SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
10980SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
10981#endif
10982#ifdef SQLITE_TEST
10983SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
10984SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
10985  void disable_simulated_io_errors(void);
10986  void enable_simulated_io_errors(void);
10987#else
10988# define disable_simulated_io_errors()
10989# define enable_simulated_io_errors()
10990#endif
10991
10992#endif /* _PAGER_H_ */
10993
10994/************** End of pager.h ***********************************************/
10995/************** Continuing where we left off in sqliteInt.h ******************/
10996/************** Include pcache.h in the middle of sqliteInt.h ****************/
10997/************** Begin file pcache.h ******************************************/
10998/*
10999** 2008 August 05
11000**
11001** The author disclaims copyright to this source code.  In place of
11002** a legal notice, here is a blessing:
11003**
11004**    May you do good and not evil.
11005**    May you find forgiveness for yourself and forgive others.
11006**    May you share freely, never taking more than you give.
11007**
11008*************************************************************************
11009** This header file defines the interface that the sqlite page cache
11010** subsystem.
11011*/
11012
11013#ifndef _PCACHE_H_
11014
11015typedef struct PgHdr PgHdr;
11016typedef struct PCache PCache;
11017
11018/*
11019** Every page in the cache is controlled by an instance of the following
11020** structure.
11021*/
11022struct PgHdr {
11023  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
11024  void *pData;                   /* Page data */
11025  void *pExtra;                  /* Extra content */
11026  PgHdr *pDirty;                 /* Transient list of dirty pages */
11027  Pager *pPager;                 /* The pager this page is part of */
11028  Pgno pgno;                     /* Page number for this page */
11029#ifdef SQLITE_CHECK_PAGES
11030  u32 pageHash;                  /* Hash of page content */
11031#endif
11032  u16 flags;                     /* PGHDR flags defined below */
11033
11034  /**********************************************************************
11035  ** Elements above are public.  All that follows is private to pcache.c
11036  ** and should not be accessed by other modules.
11037  */
11038  i16 nRef;                      /* Number of users of this page */
11039  PCache *pCache;                /* Cache that owns this page */
11040
11041  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
11042  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
11043};
11044
11045/* Bit values for PgHdr.flags */
11046#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
11047#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
11048#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
11049#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
11050                                     ** writing this page to the database */
11051#define PGHDR_NEED_READ       0x010  /* Content is unread */
11052#define PGHDR_DONT_WRITE      0x020  /* Do not write content to disk */
11053#define PGHDR_MMAP            0x040  /* This is an mmap page object */
11054
11055/* Initialize and shutdown the page cache subsystem */
11056SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
11057SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
11058
11059/* Page cache buffer management:
11060** These routines implement SQLITE_CONFIG_PAGECACHE.
11061*/
11062SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
11063
11064/* Create a new pager cache.
11065** Under memory stress, invoke xStress to try to make pages clean.
11066** Only clean and unpinned pages can be reclaimed.
11067*/
11068SQLITE_PRIVATE int sqlite3PcacheOpen(
11069  int szPage,                    /* Size of every page */
11070  int szExtra,                   /* Extra space associated with each page */
11071  int bPurgeable,                /* True if pages are on backing store */
11072  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
11073  void *pStress,                 /* Argument to xStress */
11074  PCache *pToInit                /* Preallocated space for the PCache */
11075);
11076
11077/* Modify the page-size after the cache has been created. */
11078SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
11079
11080/* Return the size in bytes of a PCache object.  Used to preallocate
11081** storage space.
11082*/
11083SQLITE_PRIVATE int sqlite3PcacheSize(void);
11084
11085/* One release per successful fetch.  Page is pinned until released.
11086** Reference counted.
11087*/
11088SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
11089SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
11090SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
11091SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
11092
11093SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
11094SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
11095SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
11096SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
11097
11098/* Change a page number.  Used by incr-vacuum. */
11099SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
11100
11101/* Remove all pages with pgno>x.  Reset the cache if x==0 */
11102SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
11103
11104/* Get a list of all dirty pages in the cache, sorted by page number */
11105SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
11106
11107/* Reset and close the cache object */
11108SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
11109
11110/* Clear flags from pages of the page cache */
11111SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
11112
11113/* Discard the contents of the cache */
11114SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
11115
11116/* Return the total number of outstanding page references */
11117SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
11118
11119/* Increment the reference count of an existing page */
11120SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
11121
11122SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
11123
11124/* Return the total number of pages stored in the cache */
11125SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
11126
11127#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
11128/* Iterate through all dirty pages currently stored in the cache. This
11129** interface is only available if SQLITE_CHECK_PAGES is defined when the
11130** library is built.
11131*/
11132SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
11133#endif
11134
11135/* Set and get the suggested cache-size for the specified pager-cache.
11136**
11137** If no global maximum is configured, then the system attempts to limit
11138** the total number of pages cached by purgeable pager-caches to the sum
11139** of the suggested cache-sizes.
11140*/
11141SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
11142#ifdef SQLITE_TEST
11143SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
11144#endif
11145
11146/* Free up as much memory as possible from the page cache */
11147SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
11148
11149#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11150/* Try to return memory used by the pcache module to the main memory heap */
11151SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
11152#endif
11153
11154#ifdef SQLITE_TEST
11155SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
11156#endif
11157
11158SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
11159
11160/* Return the header size */
11161SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
11162SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
11163
11164#endif /* _PCACHE_H_ */
11165
11166/************** End of pcache.h **********************************************/
11167/************** Continuing where we left off in sqliteInt.h ******************/
11168
11169/************** Include os.h in the middle of sqliteInt.h ********************/
11170/************** Begin file os.h **********************************************/
11171/*
11172** 2001 September 16
11173**
11174** The author disclaims copyright to this source code.  In place of
11175** a legal notice, here is a blessing:
11176**
11177**    May you do good and not evil.
11178**    May you find forgiveness for yourself and forgive others.
11179**    May you share freely, never taking more than you give.
11180**
11181******************************************************************************
11182**
11183** This header file (together with is companion C source-code file
11184** "os.c") attempt to abstract the underlying operating system so that
11185** the SQLite library will work on both POSIX and windows systems.
11186**
11187** This header file is #include-ed by sqliteInt.h and thus ends up
11188** being included by every source file.
11189*/
11190#ifndef _SQLITE_OS_H_
11191#define _SQLITE_OS_H_
11192
11193/*
11194** Attempt to automatically detect the operating system and setup the
11195** necessary pre-processor macros for it.
11196*/
11197/************** Include os_setup.h in the middle of os.h *********************/
11198/************** Begin file os_setup.h ****************************************/
11199/*
11200** 2013 November 25
11201**
11202** The author disclaims copyright to this source code.  In place of
11203** a legal notice, here is a blessing:
11204**
11205**    May you do good and not evil.
11206**    May you find forgiveness for yourself and forgive others.
11207**    May you share freely, never taking more than you give.
11208**
11209******************************************************************************
11210**
11211** This file contains pre-processor directives related to operating system
11212** detection and/or setup.
11213*/
11214#ifndef _OS_SETUP_H_
11215#define _OS_SETUP_H_
11216
11217/*
11218** Figure out if we are dealing with Unix, Windows, or some other operating
11219** system.
11220**
11221** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
11222** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
11223** the three will be 1.  The other two will be 0.
11224*/
11225#if defined(SQLITE_OS_OTHER)
11226#  if SQLITE_OS_OTHER==1
11227#    undef SQLITE_OS_UNIX
11228#    define SQLITE_OS_UNIX 0
11229#    undef SQLITE_OS_WIN
11230#    define SQLITE_OS_WIN 0
11231#  else
11232#    undef SQLITE_OS_OTHER
11233#  endif
11234#endif
11235#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
11236#  define SQLITE_OS_OTHER 0
11237#  ifndef SQLITE_OS_WIN
11238#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
11239        defined(__MINGW32__) || defined(__BORLANDC__)
11240#      define SQLITE_OS_WIN 1
11241#      define SQLITE_OS_UNIX 0
11242#    else
11243#      define SQLITE_OS_WIN 0
11244#      define SQLITE_OS_UNIX 1
11245#    endif
11246#  else
11247#    define SQLITE_OS_UNIX 0
11248#  endif
11249#else
11250#  ifndef SQLITE_OS_WIN
11251#    define SQLITE_OS_WIN 0
11252#  endif
11253#endif
11254
11255#endif /* _OS_SETUP_H_ */
11256
11257/************** End of os_setup.h ********************************************/
11258/************** Continuing where we left off in os.h *************************/
11259
11260/* If the SET_FULLSYNC macro is not defined above, then make it
11261** a no-op
11262*/
11263#ifndef SET_FULLSYNC
11264# define SET_FULLSYNC(x,y)
11265#endif
11266
11267/*
11268** The default size of a disk sector
11269*/
11270#ifndef SQLITE_DEFAULT_SECTOR_SIZE
11271# define SQLITE_DEFAULT_SECTOR_SIZE 4096
11272#endif
11273
11274/*
11275** Temporary files are named starting with this prefix followed by 16 random
11276** alphanumeric characters, and no file extension. They are stored in the
11277** OS's standard temporary file directory, and are deleted prior to exit.
11278** If sqlite is being embedded in another program, you may wish to change the
11279** prefix to reflect your program's name, so that if your program exits
11280** prematurely, old temporary files can be easily identified. This can be done
11281** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
11282**
11283** 2006-10-31:  The default prefix used to be "sqlite_".  But then
11284** Mcafee started using SQLite in their anti-virus product and it
11285** started putting files with the "sqlite" name in the c:/temp folder.
11286** This annoyed many windows users.  Those users would then do a
11287** Google search for "sqlite", find the telephone numbers of the
11288** developers and call to wake them up at night and complain.
11289** For this reason, the default name prefix is changed to be "sqlite"
11290** spelled backwards.  So the temp files are still identified, but
11291** anybody smart enough to figure out the code is also likely smart
11292** enough to know that calling the developer will not help get rid
11293** of the file.
11294*/
11295#ifndef SQLITE_TEMP_FILE_PREFIX
11296# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
11297#endif
11298
11299/*
11300** The following values may be passed as the second argument to
11301** sqlite3OsLock(). The various locks exhibit the following semantics:
11302**
11303** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
11304** RESERVED:  A single process may hold a RESERVED lock on a file at
11305**            any time. Other processes may hold and obtain new SHARED locks.
11306** PENDING:   A single process may hold a PENDING lock on a file at
11307**            any one time. Existing SHARED locks may persist, but no new
11308**            SHARED locks may be obtained by other processes.
11309** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
11310**
11311** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
11312** process that requests an EXCLUSIVE lock may actually obtain a PENDING
11313** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
11314** sqlite3OsLock().
11315*/
11316#define NO_LOCK         0
11317#define SHARED_LOCK     1
11318#define RESERVED_LOCK   2
11319#define PENDING_LOCK    3
11320#define EXCLUSIVE_LOCK  4
11321
11322/*
11323** File Locking Notes:  (Mostly about windows but also some info for Unix)
11324**
11325** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
11326** those functions are not available.  So we use only LockFile() and
11327** UnlockFile().
11328**
11329** LockFile() prevents not just writing but also reading by other processes.
11330** A SHARED_LOCK is obtained by locking a single randomly-chosen
11331** byte out of a specific range of bytes. The lock byte is obtained at
11332** random so two separate readers can probably access the file at the
11333** same time, unless they are unlucky and choose the same lock byte.
11334** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
11335** There can only be one writer.  A RESERVED_LOCK is obtained by locking
11336** a single byte of the file that is designated as the reserved lock byte.
11337** A PENDING_LOCK is obtained by locking a designated byte different from
11338** the RESERVED_LOCK byte.
11339**
11340** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
11341** which means we can use reader/writer locks.  When reader/writer locks
11342** are used, the lock is placed on the same range of bytes that is used
11343** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
11344** will support two or more Win95 readers or two or more WinNT readers.
11345** But a single Win95 reader will lock out all WinNT readers and a single
11346** WinNT reader will lock out all other Win95 readers.
11347**
11348** The following #defines specify the range of bytes used for locking.
11349** SHARED_SIZE is the number of bytes available in the pool from which
11350** a random byte is selected for a shared lock.  The pool of bytes for
11351** shared locks begins at SHARED_FIRST.
11352**
11353** The same locking strategy and
11354** byte ranges are used for Unix.  This leaves open the possibility of having
11355** clients on win95, winNT, and unix all talking to the same shared file
11356** and all locking correctly.  To do so would require that samba (or whatever
11357** tool is being used for file sharing) implements locks correctly between
11358** windows and unix.  I'm guessing that isn't likely to happen, but by
11359** using the same locking range we are at least open to the possibility.
11360**
11361** Locking in windows is manditory.  For this reason, we cannot store
11362** actual data in the bytes used for locking.  The pager never allocates
11363** the pages involved in locking therefore.  SHARED_SIZE is selected so
11364** that all locks will fit on a single page even at the minimum page size.
11365** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
11366** is set high so that we don't have to allocate an unused page except
11367** for very large databases.  But one should test the page skipping logic
11368** by setting PENDING_BYTE low and running the entire regression suite.
11369**
11370** Changing the value of PENDING_BYTE results in a subtly incompatible
11371** file format.  Depending on how it is changed, you might not notice
11372** the incompatibility right away, even running a full regression test.
11373** The default location of PENDING_BYTE is the first byte past the
11374** 1GB boundary.
11375**
11376*/
11377#ifdef SQLITE_OMIT_WSD
11378# define PENDING_BYTE     (0x40000000)
11379#else
11380# define PENDING_BYTE      sqlite3PendingByte
11381#endif
11382#define RESERVED_BYTE     (PENDING_BYTE+1)
11383#define SHARED_FIRST      (PENDING_BYTE+2)
11384#define SHARED_SIZE       510
11385
11386/*
11387** Wrapper around OS specific sqlite3_os_init() function.
11388*/
11389SQLITE_PRIVATE int sqlite3OsInit(void);
11390
11391/*
11392** Functions for accessing sqlite3_file methods
11393*/
11394SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
11395SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
11396SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
11397SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
11398SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
11399SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
11400SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
11401SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
11402SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
11403SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
11404SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
11405#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
11406SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
11407SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
11408SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
11409SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
11410SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
11411SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
11412SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
11413SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
11414
11415
11416/*
11417** Functions for accessing sqlite3_vfs methods
11418*/
11419SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
11420SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
11421SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
11422SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
11423#ifndef SQLITE_OMIT_LOAD_EXTENSION
11424SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
11425SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
11426SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
11427SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
11428#endif /* SQLITE_OMIT_LOAD_EXTENSION */
11429SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
11430SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
11431SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
11432
11433/*
11434** Convenience functions for opening and closing files using
11435** sqlite3_malloc() to obtain space for the file-handle structure.
11436*/
11437SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
11438SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
11439
11440#endif /* _SQLITE_OS_H_ */
11441
11442/************** End of os.h **************************************************/
11443/************** Continuing where we left off in sqliteInt.h ******************/
11444/************** Include mutex.h in the middle of sqliteInt.h *****************/
11445/************** Begin file mutex.h *******************************************/
11446/*
11447** 2007 August 28
11448**
11449** The author disclaims copyright to this source code.  In place of
11450** a legal notice, here is a blessing:
11451**
11452**    May you do good and not evil.
11453**    May you find forgiveness for yourself and forgive others.
11454**    May you share freely, never taking more than you give.
11455**
11456*************************************************************************
11457**
11458** This file contains the common header for all mutex implementations.
11459** The sqliteInt.h header #includes this file so that it is available
11460** to all source files.  We break it out in an effort to keep the code
11461** better organized.
11462**
11463** NOTE:  source files should *not* #include this header file directly.
11464** Source files should #include the sqliteInt.h file and let that file
11465** include this one indirectly.
11466*/
11467
11468
11469/*
11470** Figure out what version of the code to use.  The choices are
11471**
11472**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
11473**                             mutexes implementation cannot be overridden
11474**                             at start-time.
11475**
11476**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
11477**                             mutual exclusion is provided.  But this
11478**                             implementation can be overridden at
11479**                             start-time.
11480**
11481**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
11482**
11483**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
11484*/
11485#if !SQLITE_THREADSAFE
11486# define SQLITE_MUTEX_OMIT
11487#endif
11488#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
11489#  if SQLITE_OS_UNIX
11490#    define SQLITE_MUTEX_PTHREADS
11491#  elif SQLITE_OS_WIN
11492#    define SQLITE_MUTEX_W32
11493#  else
11494#    define SQLITE_MUTEX_NOOP
11495#  endif
11496#endif
11497
11498#ifdef SQLITE_MUTEX_OMIT
11499/*
11500** If this is a no-op implementation, implement everything as macros.
11501*/
11502#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
11503#define sqlite3_mutex_free(X)
11504#define sqlite3_mutex_enter(X)
11505#define sqlite3_mutex_try(X)      SQLITE_OK
11506#define sqlite3_mutex_leave(X)
11507#define sqlite3_mutex_held(X)     ((void)(X),1)
11508#define sqlite3_mutex_notheld(X)  ((void)(X),1)
11509#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
11510#define sqlite3MutexInit()        SQLITE_OK
11511#define sqlite3MutexEnd()
11512#define MUTEX_LOGIC(X)
11513#else
11514#define MUTEX_LOGIC(X)            X
11515#endif /* defined(SQLITE_MUTEX_OMIT) */
11516
11517/************** End of mutex.h ***********************************************/
11518/************** Continuing where we left off in sqliteInt.h ******************/
11519
11520
11521/*
11522** Each database file to be accessed by the system is an instance
11523** of the following structure.  There are normally two of these structures
11524** in the sqlite.aDb[] array.  aDb[0] is the main database file and
11525** aDb[1] is the database file used to hold temporary tables.  Additional
11526** databases may be attached.
11527*/
11528struct Db {
11529  char *zName;         /* Name of this database */
11530  Btree *pBt;          /* The B*Tree structure for this database file */
11531  u8 safety_level;     /* How aggressive at syncing data to disk */
11532  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
11533};
11534
11535/*
11536** An instance of the following structure stores a database schema.
11537**
11538** Most Schema objects are associated with a Btree.  The exception is
11539** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
11540** In shared cache mode, a single Schema object can be shared by multiple
11541** Btrees that refer to the same underlying BtShared object.
11542**
11543** Schema objects are automatically deallocated when the last Btree that
11544** references them is destroyed.   The TEMP Schema is manually freed by
11545** sqlite3_close().
11546*
11547** A thread must be holding a mutex on the corresponding Btree in order
11548** to access Schema content.  This implies that the thread must also be
11549** holding a mutex on the sqlite3 connection pointer that owns the Btree.
11550** For a TEMP Schema, only the connection mutex is required.
11551*/
11552struct Schema {
11553  int schema_cookie;   /* Database schema version number for this file */
11554  int iGeneration;     /* Generation counter.  Incremented with each change */
11555  Hash tblHash;        /* All tables indexed by name */
11556  Hash idxHash;        /* All (named) indices indexed by name */
11557  Hash trigHash;       /* All triggers indexed by name */
11558  Hash fkeyHash;       /* All foreign keys by referenced table name */
11559  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
11560  u8 file_format;      /* Schema format version for this file */
11561  u8 enc;              /* Text encoding used by this database */
11562  u16 schemaFlags;     /* Flags associated with this schema */
11563  int cache_size;      /* Number of pages to use in the cache */
11564};
11565
11566/*
11567** These macros can be used to test, set, or clear bits in the
11568** Db.pSchema->flags field.
11569*/
11570#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
11571#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
11572#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
11573#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
11574
11575/*
11576** Allowed values for the DB.pSchema->flags field.
11577**
11578** The DB_SchemaLoaded flag is set after the database schema has been
11579** read into internal hash tables.
11580**
11581** DB_UnresetViews means that one or more views have column names that
11582** have been filled out.  If the schema changes, these column names might
11583** changes and so the view will need to be reset.
11584*/
11585#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
11586#define DB_UnresetViews    0x0002  /* Some views have defined column names */
11587#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
11588
11589/*
11590** The number of different kinds of things that can be limited
11591** using the sqlite3_limit() interface.
11592*/
11593#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
11594
11595/*
11596** Lookaside malloc is a set of fixed-size buffers that can be used
11597** to satisfy small transient memory allocation requests for objects
11598** associated with a particular database connection.  The use of
11599** lookaside malloc provides a significant performance enhancement
11600** (approx 10%) by avoiding numerous malloc/free requests while parsing
11601** SQL statements.
11602**
11603** The Lookaside structure holds configuration information about the
11604** lookaside malloc subsystem.  Each available memory allocation in
11605** the lookaside subsystem is stored on a linked list of LookasideSlot
11606** objects.
11607**
11608** Lookaside allocations are only allowed for objects that are associated
11609** with a particular database connection.  Hence, schema information cannot
11610** be stored in lookaside because in shared cache mode the schema information
11611** is shared by multiple database connections.  Therefore, while parsing
11612** schema information, the Lookaside.bEnabled flag is cleared so that
11613** lookaside allocations are not used to construct the schema objects.
11614*/
11615struct Lookaside {
11616  u16 sz;                 /* Size of each buffer in bytes */
11617  u8 bEnabled;            /* False to disable new lookaside allocations */
11618  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
11619  int nOut;               /* Number of buffers currently checked out */
11620  int mxOut;              /* Highwater mark for nOut */
11621  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
11622  LookasideSlot *pFree;   /* List of available buffers */
11623  void *pStart;           /* First byte of available memory space */
11624  void *pEnd;             /* First byte past end of available space */
11625};
11626struct LookasideSlot {
11627  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
11628};
11629
11630/*
11631** A hash table for function definitions.
11632**
11633** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
11634** Collisions are on the FuncDef.pHash chain.
11635*/
11636struct FuncDefHash {
11637  FuncDef *a[23];       /* Hash table for functions */
11638};
11639
11640#ifdef SQLITE_USER_AUTHENTICATION
11641/*
11642** Information held in the "sqlite3" database connection object and used
11643** to manage user authentication.
11644*/
11645typedef struct sqlite3_userauth sqlite3_userauth;
11646struct sqlite3_userauth {
11647  u8 authLevel;                 /* Current authentication level */
11648  int nAuthPW;                  /* Size of the zAuthPW in bytes */
11649  char *zAuthPW;                /* Password used to authenticate */
11650  char *zAuthUser;              /* User name used to authenticate */
11651};
11652
11653/* Allowed values for sqlite3_userauth.authLevel */
11654#define UAUTH_Unknown     0     /* Authentication not yet checked */
11655#define UAUTH_Fail        1     /* User authentication failed */
11656#define UAUTH_User        2     /* Authenticated as a normal user */
11657#define UAUTH_Admin       3     /* Authenticated as an administrator */
11658
11659/* Functions used only by user authorization logic */
11660SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
11661SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
11662SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
11663SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
11664
11665#endif /* SQLITE_USER_AUTHENTICATION */
11666
11667/*
11668** typedef for the authorization callback function.
11669*/
11670#ifdef SQLITE_USER_AUTHENTICATION
11671  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11672                               const char*, const char*);
11673#else
11674  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11675                               const char*);
11676#endif
11677
11678
11679/*
11680** Each database connection is an instance of the following structure.
11681*/
11682struct sqlite3 {
11683  sqlite3_vfs *pVfs;            /* OS Interface */
11684  struct Vdbe *pVdbe;           /* List of active virtual machines */
11685  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
11686  sqlite3_mutex *mutex;         /* Connection mutex */
11687  Db *aDb;                      /* All backends */
11688  int nDb;                      /* Number of backends currently in use */
11689  int flags;                    /* Miscellaneous flags. See below */
11690  i64 lastRowid;                /* ROWID of most recent insert (see above) */
11691  i64 szMmap;                   /* Default mmap_size setting */
11692  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
11693  int errCode;                  /* Most recent error code (SQLITE_*) */
11694  int errMask;                  /* & result codes with this before returning */
11695  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
11696  u8 enc;                       /* Text encoding */
11697  u8 autoCommit;                /* The auto-commit flag. */
11698  u8 temp_store;                /* 1: file 2: memory 0: default */
11699  u8 mallocFailed;              /* True if we have seen a malloc failure */
11700  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
11701  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
11702  u8 suppressErr;               /* Do not issue error messages if true */
11703  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
11704  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
11705  int nextPagesize;             /* Pagesize after VACUUM if >0 */
11706  u32 magic;                    /* Magic number for detect library misuse */
11707  int nChange;                  /* Value returned by sqlite3_changes() */
11708  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
11709  int aLimit[SQLITE_N_LIMIT];   /* Limits */
11710  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
11711  struct sqlite3InitInfo {      /* Information used during initialization */
11712    int newTnum;                /* Rootpage of table being initialized */
11713    u8 iDb;                     /* Which db file is being initialized */
11714    u8 busy;                    /* TRUE if currently initializing */
11715    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
11716    u8 imposterTable;           /* Building an imposter table */
11717  } init;
11718  int nVdbeActive;              /* Number of VDBEs currently running */
11719  int nVdbeRead;                /* Number of active VDBEs that read or write */
11720  int nVdbeWrite;               /* Number of active VDBEs that read and write */
11721  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
11722  int nVDestroy;                /* Number of active OP_VDestroy operations */
11723  int nExtension;               /* Number of loaded extensions */
11724  void **aExtension;            /* Array of shared library handles */
11725  void (*xTrace)(void*,const char*);        /* Trace function */
11726  void *pTraceArg;                          /* Argument to the trace function */
11727  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
11728  void *pProfileArg;                        /* Argument to profile function */
11729  void *pCommitArg;                 /* Argument to xCommitCallback() */
11730  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
11731  void *pRollbackArg;               /* Argument to xRollbackCallback() */
11732  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
11733  void *pUpdateArg;
11734  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
11735#ifndef SQLITE_OMIT_WAL
11736  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
11737  void *pWalArg;
11738#endif
11739  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
11740  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
11741  void *pCollNeededArg;
11742  sqlite3_value *pErr;          /* Most recent error message */
11743  union {
11744    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
11745    double notUsed1;            /* Spacer */
11746  } u1;
11747  Lookaside lookaside;          /* Lookaside malloc configuration */
11748#ifndef SQLITE_OMIT_AUTHORIZATION
11749  sqlite3_xauth xAuth;          /* Access authorization function */
11750  void *pAuthArg;               /* 1st argument to the access auth function */
11751#endif
11752#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
11753  int (*xProgress)(void *);     /* The progress callback */
11754  void *pProgressArg;           /* Argument to the progress callback */
11755  unsigned nProgressOps;        /* Number of opcodes for progress callback */
11756#endif
11757#ifndef SQLITE_OMIT_VIRTUALTABLE
11758  int nVTrans;                  /* Allocated size of aVTrans */
11759  Hash aModule;                 /* populated by sqlite3_create_module() */
11760  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
11761  VTable **aVTrans;             /* Virtual tables with open transactions */
11762  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
11763#endif
11764  FuncDefHash aFunc;            /* Hash table of connection functions */
11765  Hash aCollSeq;                /* All collating sequences */
11766  BusyHandler busyHandler;      /* Busy callback */
11767  Db aDbStatic[2];              /* Static space for the 2 default backends */
11768  Savepoint *pSavepoint;        /* List of active savepoints */
11769  int busyTimeout;              /* Busy handler timeout, in msec */
11770  int nSavepoint;               /* Number of non-transaction savepoints */
11771  int nStatement;               /* Number of nested statement-transactions  */
11772  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
11773  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
11774  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
11775#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11776  /* The following variables are all protected by the STATIC_MASTER
11777  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
11778  **
11779  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
11780  ** unlock so that it can proceed.
11781  **
11782  ** When X.pBlockingConnection==Y, that means that something that X tried
11783  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
11784  ** held by Y.
11785  */
11786  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
11787  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
11788  void *pUnlockArg;                     /* Argument to xUnlockNotify */
11789  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
11790  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
11791#endif
11792#ifdef SQLITE_USER_AUTHENTICATION
11793  sqlite3_userauth auth;        /* User authentication information */
11794#endif
11795};
11796
11797/*
11798** A macro to discover the encoding of a database.
11799*/
11800#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
11801#define ENC(db)        ((db)->enc)
11802
11803/*
11804** Possible values for the sqlite3.flags.
11805*/
11806#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
11807#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
11808#define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
11809#define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
11810#define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
11811#define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
11812#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
11813#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
11814                                          /*   DELETE, or UPDATE and return */
11815                                          /*   the count using a callback. */
11816#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
11817                                          /*   result set is empty */
11818#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
11819#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
11820#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
11821#define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
11822#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
11823#define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
11824#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
11825#define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
11826#define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
11827#define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
11828#define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
11829#define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
11830#define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
11831#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
11832#define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
11833#define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
11834#define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
11835#define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
11836#define SQLITE_Vacuum         0x08000000  /* Currently in a VACUUM */
11837#define SQLITE_CellSizeCk     0x10000000  /* Check btree cell sizes on load */
11838
11839
11840/*
11841** Bits of the sqlite3.dbOptFlags field that are used by the
11842** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
11843** selectively disable various optimizations.
11844*/
11845#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
11846#define SQLITE_ColumnCache    0x0002   /* Column cache */
11847#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
11848#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
11849/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
11850#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
11851#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
11852#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
11853#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
11854#define SQLITE_Transitive     0x0200   /* Transitive constraints */
11855#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
11856#define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
11857#define SQLITE_AllOpts        0xffff   /* All optimizations */
11858
11859/*
11860** Macros for testing whether or not optimizations are enabled or disabled.
11861*/
11862#ifndef SQLITE_OMIT_BUILTIN_TEST
11863#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
11864#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
11865#else
11866#define OptimizationDisabled(db, mask)  0
11867#define OptimizationEnabled(db, mask)   1
11868#endif
11869
11870/*
11871** Return true if it OK to factor constant expressions into the initialization
11872** code. The argument is a Parse object for the code generator.
11873*/
11874#define ConstFactorOk(P) ((P)->okConstFactor)
11875
11876/*
11877** Possible values for the sqlite.magic field.
11878** The numbers are obtained at random and have no special meaning, other
11879** than being distinct from one another.
11880*/
11881#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
11882#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
11883#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
11884#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
11885#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
11886#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
11887
11888/*
11889** Each SQL function is defined by an instance of the following
11890** structure.  A pointer to this structure is stored in the sqlite.aFunc
11891** hash table.  When multiple functions have the same name, the hash table
11892** points to a linked list of these structures.
11893*/
11894struct FuncDef {
11895  i16 nArg;            /* Number of arguments.  -1 means unlimited */
11896  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
11897  void *pUserData;     /* User data parameter */
11898  FuncDef *pNext;      /* Next function with same name */
11899  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
11900  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
11901  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
11902  char *zName;         /* SQL name of the function. */
11903  FuncDef *pHash;      /* Next with a different name but the same hash */
11904  FuncDestructor *pDestructor;   /* Reference counted destructor function */
11905};
11906
11907/*
11908** This structure encapsulates a user-function destructor callback (as
11909** configured using create_function_v2()) and a reference counter. When
11910** create_function_v2() is called to create a function with a destructor,
11911** a single object of this type is allocated. FuncDestructor.nRef is set to
11912** the number of FuncDef objects created (either 1 or 3, depending on whether
11913** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
11914** member of each of the new FuncDef objects is set to point to the allocated
11915** FuncDestructor.
11916**
11917** Thereafter, when one of the FuncDef objects is deleted, the reference
11918** count on this object is decremented. When it reaches 0, the destructor
11919** is invoked and the FuncDestructor structure freed.
11920*/
11921struct FuncDestructor {
11922  int nRef;
11923  void (*xDestroy)(void *);
11924  void *pUserData;
11925};
11926
11927/*
11928** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
11929** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
11930** are assert() statements in the code to verify this.
11931*/
11932#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
11933#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
11934#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
11935#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
11936#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
11937#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
11938#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
11939#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
11940#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
11941#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
11942#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
11943#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
11944#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
11945                                    ** single query - might change over time */
11946
11947/*
11948** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
11949** used to create the initializers for the FuncDef structures.
11950**
11951**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
11952**     Used to create a scalar function definition of a function zName
11953**     implemented by C function xFunc that accepts nArg arguments. The
11954**     value passed as iArg is cast to a (void*) and made available
11955**     as the user-data (sqlite3_user_data()) for the function. If
11956**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
11957**
11958**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
11959**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
11960**
11961**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
11962**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
11963**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
11964**     and functions like sqlite_version() that can change, but not during
11965**     a single query.
11966**
11967**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
11968**     Used to create an aggregate function definition implemented by
11969**     the C functions xStep and xFinal. The first four parameters
11970**     are interpreted in the same way as the first 4 parameters to
11971**     FUNCTION().
11972**
11973**   LIKEFUNC(zName, nArg, pArg, flags)
11974**     Used to create a scalar function definition of a function zName
11975**     that accepts nArg arguments and is implemented by a call to C
11976**     function likeFunc. Argument pArg is cast to a (void *) and made
11977**     available as the function user-data (sqlite3_user_data()). The
11978**     FuncDef.flags variable is set to the value passed as the flags
11979**     parameter.
11980*/
11981#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
11982  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11983   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11984#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
11985  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11986   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11987#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
11988  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11989   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11990#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
11991  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
11992   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11993#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
11994  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11995   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
11996#define LIKEFUNC(zName, nArg, arg, flags) \
11997  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
11998   (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
11999#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
12000  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
12001   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
12002#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
12003  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
12004   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
12005
12006/*
12007** All current savepoints are stored in a linked list starting at
12008** sqlite3.pSavepoint. The first element in the list is the most recently
12009** opened savepoint. Savepoints are added to the list by the vdbe
12010** OP_Savepoint instruction.
12011*/
12012struct Savepoint {
12013  char *zName;                        /* Savepoint name (nul-terminated) */
12014  i64 nDeferredCons;                  /* Number of deferred fk violations */
12015  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
12016  Savepoint *pNext;                   /* Parent savepoint (if any) */
12017};
12018
12019/*
12020** The following are used as the second parameter to sqlite3Savepoint(),
12021** and as the P1 argument to the OP_Savepoint instruction.
12022*/
12023#define SAVEPOINT_BEGIN      0
12024#define SAVEPOINT_RELEASE    1
12025#define SAVEPOINT_ROLLBACK   2
12026
12027
12028/*
12029** Each SQLite module (virtual table definition) is defined by an
12030** instance of the following structure, stored in the sqlite3.aModule
12031** hash table.
12032*/
12033struct Module {
12034  const sqlite3_module *pModule;       /* Callback pointers */
12035  const char *zName;                   /* Name passed to create_module() */
12036  void *pAux;                          /* pAux passed to create_module() */
12037  void (*xDestroy)(void *);            /* Module destructor function */
12038  Table *pEpoTab;                      /* Eponymous table for this module */
12039};
12040
12041/*
12042** information about each column of an SQL table is held in an instance
12043** of this structure.
12044*/
12045struct Column {
12046  char *zName;     /* Name of this column */
12047  Expr *pDflt;     /* Default value of this column */
12048  char *zDflt;     /* Original text of the default value */
12049  char *zType;     /* Data type for this column */
12050  char *zColl;     /* Collating sequence.  If NULL, use the default */
12051  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
12052  char affinity;   /* One of the SQLITE_AFF_... values */
12053  u8 szEst;        /* Estimated size of this column.  INT==1 */
12054  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
12055};
12056
12057/* Allowed values for Column.colFlags:
12058*/
12059#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
12060#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
12061
12062/*
12063** A "Collating Sequence" is defined by an instance of the following
12064** structure. Conceptually, a collating sequence consists of a name and
12065** a comparison routine that defines the order of that sequence.
12066**
12067** If CollSeq.xCmp is NULL, it means that the
12068** collating sequence is undefined.  Indices built on an undefined
12069** collating sequence may not be read or written.
12070*/
12071struct CollSeq {
12072  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
12073  u8 enc;               /* Text encoding handled by xCmp() */
12074  void *pUser;          /* First argument to xCmp() */
12075  int (*xCmp)(void*,int, const void*, int, const void*);
12076  void (*xDel)(void*);  /* Destructor for pUser */
12077};
12078
12079/*
12080** A sort order can be either ASC or DESC.
12081*/
12082#define SQLITE_SO_ASC       0  /* Sort in ascending order */
12083#define SQLITE_SO_DESC      1  /* Sort in ascending order */
12084#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
12085
12086/*
12087** Column affinity types.
12088**
12089** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
12090** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
12091** the speed a little by numbering the values consecutively.
12092**
12093** But rather than start with 0 or 1, we begin with 'A'.  That way,
12094** when multiple affinity types are concatenated into a string and
12095** used as the P4 operand, they will be more readable.
12096**
12097** Note also that the numeric types are grouped together so that testing
12098** for a numeric type is a single comparison.  And the BLOB type is first.
12099*/
12100#define SQLITE_AFF_BLOB     'A'
12101#define SQLITE_AFF_TEXT     'B'
12102#define SQLITE_AFF_NUMERIC  'C'
12103#define SQLITE_AFF_INTEGER  'D'
12104#define SQLITE_AFF_REAL     'E'
12105
12106#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
12107
12108/*
12109** The SQLITE_AFF_MASK values masks off the significant bits of an
12110** affinity value.
12111*/
12112#define SQLITE_AFF_MASK     0x47
12113
12114/*
12115** Additional bit values that can be ORed with an affinity without
12116** changing the affinity.
12117**
12118** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
12119** It causes an assert() to fire if either operand to a comparison
12120** operator is NULL.  It is added to certain comparison operators to
12121** prove that the operands are always NOT NULL.
12122*/
12123#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
12124#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
12125#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
12126#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
12127
12128/*
12129** An object of this type is created for each virtual table present in
12130** the database schema.
12131**
12132** If the database schema is shared, then there is one instance of this
12133** structure for each database connection (sqlite3*) that uses the shared
12134** schema. This is because each database connection requires its own unique
12135** instance of the sqlite3_vtab* handle used to access the virtual table
12136** implementation. sqlite3_vtab* handles can not be shared between
12137** database connections, even when the rest of the in-memory database
12138** schema is shared, as the implementation often stores the database
12139** connection handle passed to it via the xConnect() or xCreate() method
12140** during initialization internally. This database connection handle may
12141** then be used by the virtual table implementation to access real tables
12142** within the database. So that they appear as part of the callers
12143** transaction, these accesses need to be made via the same database
12144** connection as that used to execute SQL operations on the virtual table.
12145**
12146** All VTable objects that correspond to a single table in a shared
12147** database schema are initially stored in a linked-list pointed to by
12148** the Table.pVTable member variable of the corresponding Table object.
12149** When an sqlite3_prepare() operation is required to access the virtual
12150** table, it searches the list for the VTable that corresponds to the
12151** database connection doing the preparing so as to use the correct
12152** sqlite3_vtab* handle in the compiled query.
12153**
12154** When an in-memory Table object is deleted (for example when the
12155** schema is being reloaded for some reason), the VTable objects are not
12156** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
12157** immediately. Instead, they are moved from the Table.pVTable list to
12158** another linked list headed by the sqlite3.pDisconnect member of the
12159** corresponding sqlite3 structure. They are then deleted/xDisconnected
12160** next time a statement is prepared using said sqlite3*. This is done
12161** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
12162** Refer to comments above function sqlite3VtabUnlockList() for an
12163** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
12164** list without holding the corresponding sqlite3.mutex mutex.
12165**
12166** The memory for objects of this type is always allocated by
12167** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
12168** the first argument.
12169*/
12170struct VTable {
12171  sqlite3 *db;              /* Database connection associated with this table */
12172  Module *pMod;             /* Pointer to module implementation */
12173  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
12174  int nRef;                 /* Number of pointers to this structure */
12175  u8 bConstraint;           /* True if constraints are supported */
12176  int iSavepoint;           /* Depth of the SAVEPOINT stack */
12177  VTable *pNext;            /* Next in linked list (see above) */
12178};
12179
12180/*
12181** The schema for each SQL table and view is represented in memory
12182** by an instance of the following structure.
12183*/
12184struct Table {
12185  char *zName;         /* Name of the table or view */
12186  Column *aCol;        /* Information about each column */
12187  Index *pIndex;       /* List of SQL indexes on this table. */
12188  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
12189  FKey *pFKey;         /* Linked list of all foreign keys in this table */
12190  char *zColAff;       /* String defining the affinity of each column */
12191  ExprList *pCheck;    /* All CHECK constraints */
12192                       /*   ... also used as column name list in a VIEW */
12193  int tnum;            /* Root BTree page for this table */
12194  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
12195  i16 nCol;            /* Number of columns in this table */
12196  u16 nRef;            /* Number of pointers to this Table */
12197  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
12198  LogEst szTabRow;     /* Estimated size of each table row in bytes */
12199#ifdef SQLITE_ENABLE_COSTMULT
12200  LogEst costMult;     /* Cost multiplier for using this table */
12201#endif
12202  u8 tabFlags;         /* Mask of TF_* values */
12203  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
12204#ifndef SQLITE_OMIT_ALTERTABLE
12205  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
12206#endif
12207#ifndef SQLITE_OMIT_VIRTUALTABLE
12208  int nModuleArg;      /* Number of arguments to the module */
12209  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
12210  VTable *pVTable;     /* List of VTable objects. */
12211#endif
12212  Trigger *pTrigger;   /* List of triggers stored in pSchema */
12213  Schema *pSchema;     /* Schema that contains this table */
12214  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
12215};
12216
12217/*
12218** Allowed values for Table.tabFlags.
12219**
12220** TF_OOOHidden applies to virtual tables that have hidden columns that are
12221** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
12222** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
12223** the TF_OOOHidden attribute would apply in this case.  Such tables require
12224** special handling during INSERT processing.
12225*/
12226#define TF_Readonly        0x01    /* Read-only system table */
12227#define TF_Ephemeral       0x02    /* An ephemeral table */
12228#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
12229#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
12230#define TF_Virtual         0x10    /* Is a virtual table */
12231#define TF_WithoutRowid    0x20    /* No rowid.  PRIMARY KEY is the key */
12232#define TF_NoVisibleRowid  0x40    /* No user-visible "rowid" column */
12233#define TF_OOOHidden       0x80    /* Out-of-Order hidden columns */
12234
12235
12236/*
12237** Test to see whether or not a table is a virtual table.  This is
12238** done as a macro so that it will be optimized out when virtual
12239** table support is omitted from the build.
12240*/
12241#ifndef SQLITE_OMIT_VIRTUALTABLE
12242#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
12243#  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
12244#else
12245#  define IsVirtual(X)      0
12246#  define IsHiddenColumn(X) 0
12247#endif
12248
12249/* Does the table have a rowid */
12250#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
12251#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
12252
12253/*
12254** Each foreign key constraint is an instance of the following structure.
12255**
12256** A foreign key is associated with two tables.  The "from" table is
12257** the table that contains the REFERENCES clause that creates the foreign
12258** key.  The "to" table is the table that is named in the REFERENCES clause.
12259** Consider this example:
12260**
12261**     CREATE TABLE ex1(
12262**       a INTEGER PRIMARY KEY,
12263**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
12264**     );
12265**
12266** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
12267** Equivalent names:
12268**
12269**     from-table == child-table
12270**       to-table == parent-table
12271**
12272** Each REFERENCES clause generates an instance of the following structure
12273** which is attached to the from-table.  The to-table need not exist when
12274** the from-table is created.  The existence of the to-table is not checked.
12275**
12276** The list of all parents for child Table X is held at X.pFKey.
12277**
12278** A list of all children for a table named Z (which might not even exist)
12279** is held in Schema.fkeyHash with a hash key of Z.
12280*/
12281struct FKey {
12282  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
12283  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
12284  char *zTo;        /* Name of table that the key points to (aka: Parent) */
12285  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
12286  FKey *pPrevTo;    /* Previous with the same zTo */
12287  int nCol;         /* Number of columns in this key */
12288  /* EV: R-30323-21917 */
12289  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
12290  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
12291  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
12292  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
12293    int iFrom;            /* Index of column in pFrom */
12294    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
12295  } aCol[1];            /* One entry for each of nCol columns */
12296};
12297
12298/*
12299** SQLite supports many different ways to resolve a constraint
12300** error.  ROLLBACK processing means that a constraint violation
12301** causes the operation in process to fail and for the current transaction
12302** to be rolled back.  ABORT processing means the operation in process
12303** fails and any prior changes from that one operation are backed out,
12304** but the transaction is not rolled back.  FAIL processing means that
12305** the operation in progress stops and returns an error code.  But prior
12306** changes due to the same operation are not backed out and no rollback
12307** occurs.  IGNORE means that the particular row that caused the constraint
12308** error is not inserted or updated.  Processing continues and no error
12309** is returned.  REPLACE means that preexisting database rows that caused
12310** a UNIQUE constraint violation are removed so that the new insert or
12311** update can proceed.  Processing continues and no error is reported.
12312**
12313** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
12314** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
12315** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
12316** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
12317** referenced table row is propagated into the row that holds the
12318** foreign key.
12319**
12320** The following symbolic values are used to record which type
12321** of action to take.
12322*/
12323#define OE_None     0   /* There is no constraint to check */
12324#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
12325#define OE_Abort    2   /* Back out changes but do no rollback transaction */
12326#define OE_Fail     3   /* Stop the operation but leave all prior changes */
12327#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
12328#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
12329
12330#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
12331#define OE_SetNull  7   /* Set the foreign key value to NULL */
12332#define OE_SetDflt  8   /* Set the foreign key value to its default */
12333#define OE_Cascade  9   /* Cascade the changes */
12334
12335#define OE_Default  10  /* Do whatever the default action is */
12336
12337
12338/*
12339** An instance of the following structure is passed as the first
12340** argument to sqlite3VdbeKeyCompare and is used to control the
12341** comparison of the two index keys.
12342**
12343** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
12344** are nField slots for the columns of an index then one extra slot
12345** for the rowid at the end.
12346*/
12347struct KeyInfo {
12348  u32 nRef;           /* Number of references to this KeyInfo object */
12349  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
12350  u16 nField;         /* Number of key columns in the index */
12351  u16 nXField;        /* Number of columns beyond the key columns */
12352  sqlite3 *db;        /* The database connection */
12353  u8 *aSortOrder;     /* Sort order for each column. */
12354  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
12355};
12356
12357/*
12358** An instance of the following structure holds information about a
12359** single index record that has already been parsed out into individual
12360** values.
12361**
12362** A record is an object that contains one or more fields of data.
12363** Records are used to store the content of a table row and to store
12364** the key of an index.  A blob encoding of a record is created by
12365** the OP_MakeRecord opcode of the VDBE and is disassembled by the
12366** OP_Column opcode.
12367**
12368** This structure holds a record that has already been disassembled
12369** into its constituent fields.
12370**
12371** The r1 and r2 member variables are only used by the optimized comparison
12372** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
12373*/
12374struct UnpackedRecord {
12375  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
12376  u16 nField;         /* Number of entries in apMem[] */
12377  i8 default_rc;      /* Comparison result if keys are equal */
12378  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
12379  Mem *aMem;          /* Values */
12380  int r1;             /* Value to return if (lhs > rhs) */
12381  int r2;             /* Value to return if (rhs < lhs) */
12382};
12383
12384
12385/*
12386** Each SQL index is represented in memory by an
12387** instance of the following structure.
12388**
12389** The columns of the table that are to be indexed are described
12390** by the aiColumn[] field of this structure.  For example, suppose
12391** we have the following table and index:
12392**
12393**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
12394**     CREATE INDEX Ex2 ON Ex1(c3,c1);
12395**
12396** In the Table structure describing Ex1, nCol==3 because there are
12397** three columns in the table.  In the Index structure describing
12398** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
12399** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
12400** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
12401** The second column to be indexed (c1) has an index of 0 in
12402** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
12403**
12404** The Index.onError field determines whether or not the indexed columns
12405** must be unique and what to do if they are not.  When Index.onError=OE_None,
12406** it means this is not a unique index.  Otherwise it is a unique index
12407** and the value of Index.onError indicate the which conflict resolution
12408** algorithm to employ whenever an attempt is made to insert a non-unique
12409** element.
12410**
12411** While parsing a CREATE TABLE or CREATE INDEX statement in order to
12412** generate VDBE code (as opposed to parsing one read from an sqlite_master
12413** table as part of parsing an existing database schema), transient instances
12414** of this structure may be created. In this case the Index.tnum variable is
12415** used to store the address of a VDBE instruction, not a database page
12416** number (it cannot - the database page is not allocated until the VDBE
12417** program is executed). See convertToWithoutRowidTable() for details.
12418*/
12419struct Index {
12420  char *zName;             /* Name of this index */
12421  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
12422  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
12423  Table *pTable;           /* The SQL table being indexed */
12424  char *zColAff;           /* String defining the affinity of each column */
12425  Index *pNext;            /* The next index associated with the same table */
12426  Schema *pSchema;         /* Schema containing this index */
12427  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
12428  char **azColl;           /* Array of collation sequence names for index */
12429  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
12430  ExprList *aColExpr;      /* Column expressions */
12431  int tnum;                /* DB Page containing root of this index */
12432  LogEst szIdxRow;         /* Estimated average row size in bytes */
12433  u16 nKeyCol;             /* Number of columns forming the key */
12434  u16 nColumn;             /* Number of columns stored in the index */
12435  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
12436  unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
12437  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
12438  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
12439  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
12440  unsigned isCovering:1;   /* True if this is a covering index */
12441  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
12442#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
12443  int nSample;             /* Number of elements in aSample[] */
12444  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
12445  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
12446  IndexSample *aSample;    /* Samples of the left-most key */
12447  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
12448  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
12449#endif
12450};
12451
12452/*
12453** Allowed values for Index.idxType
12454*/
12455#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
12456#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
12457#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
12458
12459/* Return true if index X is a PRIMARY KEY index */
12460#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
12461
12462/* Return true if index X is a UNIQUE index */
12463#define IsUniqueIndex(X)      ((X)->onError!=OE_None)
12464
12465/* The Index.aiColumn[] values are normally positive integer.  But
12466** there are some negative values that have special meaning:
12467*/
12468#define XN_ROWID     (-1)     /* Indexed column is the rowid */
12469#define XN_EXPR      (-2)     /* Indexed column is an expression */
12470
12471/*
12472** Each sample stored in the sqlite_stat3 table is represented in memory
12473** using a structure of this type.  See documentation at the top of the
12474** analyze.c source file for additional information.
12475*/
12476struct IndexSample {
12477  void *p;          /* Pointer to sampled record */
12478  int n;            /* Size of record in bytes */
12479  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
12480  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
12481  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
12482};
12483
12484/*
12485** Each token coming out of the lexer is an instance of
12486** this structure.  Tokens are also used as part of an expression.
12487**
12488** Note if Token.z==0 then Token.dyn and Token.n are undefined and
12489** may contain random values.  Do not make any assumptions about Token.dyn
12490** and Token.n when Token.z==0.
12491*/
12492struct Token {
12493  const char *z;     /* Text of the token.  Not NULL-terminated! */
12494  unsigned int n;    /* Number of characters in this token */
12495};
12496
12497/*
12498** An instance of this structure contains information needed to generate
12499** code for a SELECT that contains aggregate functions.
12500**
12501** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
12502** pointer to this structure.  The Expr.iColumn field is the index in
12503** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
12504** code for that node.
12505**
12506** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
12507** original Select structure that describes the SELECT statement.  These
12508** fields do not need to be freed when deallocating the AggInfo structure.
12509*/
12510struct AggInfo {
12511  u8 directMode;          /* Direct rendering mode means take data directly
12512                          ** from source tables rather than from accumulators */
12513  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
12514                          ** than the source table */
12515  int sortingIdx;         /* Cursor number of the sorting index */
12516  int sortingIdxPTab;     /* Cursor number of pseudo-table */
12517  int nSortingColumn;     /* Number of columns in the sorting index */
12518  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
12519  ExprList *pGroupBy;     /* The group by clause */
12520  struct AggInfo_col {    /* For each column used in source tables */
12521    Table *pTab;             /* Source table */
12522    int iTable;              /* Cursor number of the source table */
12523    int iColumn;             /* Column number within the source table */
12524    int iSorterColumn;       /* Column number in the sorting index */
12525    int iMem;                /* Memory location that acts as accumulator */
12526    Expr *pExpr;             /* The original expression */
12527  } *aCol;
12528  int nColumn;            /* Number of used entries in aCol[] */
12529  int nAccumulator;       /* Number of columns that show through to the output.
12530                          ** Additional columns are used only as parameters to
12531                          ** aggregate functions */
12532  struct AggInfo_func {   /* For each aggregate function */
12533    Expr *pExpr;             /* Expression encoding the function */
12534    FuncDef *pFunc;          /* The aggregate function implementation */
12535    int iMem;                /* Memory location that acts as accumulator */
12536    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
12537  } *aFunc;
12538  int nFunc;              /* Number of entries in aFunc[] */
12539};
12540
12541/*
12542** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
12543** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
12544** than 32767 we have to make it 32-bit.  16-bit is preferred because
12545** it uses less memory in the Expr object, which is a big memory user
12546** in systems with lots of prepared statements.  And few applications
12547** need more than about 10 or 20 variables.  But some extreme users want
12548** to have prepared statements with over 32767 variables, and for them
12549** the option is available (at compile-time).
12550*/
12551#if SQLITE_MAX_VARIABLE_NUMBER<=32767
12552typedef i16 ynVar;
12553#else
12554typedef int ynVar;
12555#endif
12556
12557/*
12558** Each node of an expression in the parse tree is an instance
12559** of this structure.
12560**
12561** Expr.op is the opcode. The integer parser token codes are reused
12562** as opcodes here. For example, the parser defines TK_GE to be an integer
12563** code representing the ">=" operator. This same integer code is reused
12564** to represent the greater-than-or-equal-to operator in the expression
12565** tree.
12566**
12567** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
12568** or TK_STRING), then Expr.token contains the text of the SQL literal. If
12569** the expression is a variable (TK_VARIABLE), then Expr.token contains the
12570** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
12571** then Expr.token contains the name of the function.
12572**
12573** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
12574** binary operator. Either or both may be NULL.
12575**
12576** Expr.x.pList is a list of arguments if the expression is an SQL function,
12577** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
12578** Expr.x.pSelect is used if the expression is a sub-select or an expression of
12579** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
12580** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
12581** valid.
12582**
12583** An expression of the form ID or ID.ID refers to a column in a table.
12584** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
12585** the integer cursor number of a VDBE cursor pointing to that table and
12586** Expr.iColumn is the column number for the specific column.  If the
12587** expression is used as a result in an aggregate SELECT, then the
12588** value is also stored in the Expr.iAgg column in the aggregate so that
12589** it can be accessed after all aggregates are computed.
12590**
12591** If the expression is an unbound variable marker (a question mark
12592** character '?' in the original SQL) then the Expr.iTable holds the index
12593** number for that variable.
12594**
12595** If the expression is a subquery then Expr.iColumn holds an integer
12596** register number containing the result of the subquery.  If the
12597** subquery gives a constant result, then iTable is -1.  If the subquery
12598** gives a different answer at different times during statement processing
12599** then iTable is the address of a subroutine that computes the subquery.
12600**
12601** If the Expr is of type OP_Column, and the table it is selecting from
12602** is a disk table or the "old.*" pseudo-table, then pTab points to the
12603** corresponding table definition.
12604**
12605** ALLOCATION NOTES:
12606**
12607** Expr objects can use a lot of memory space in database schema.  To
12608** help reduce memory requirements, sometimes an Expr object will be
12609** truncated.  And to reduce the number of memory allocations, sometimes
12610** two or more Expr objects will be stored in a single memory allocation,
12611** together with Expr.zToken strings.
12612**
12613** If the EP_Reduced and EP_TokenOnly flags are set when
12614** an Expr object is truncated.  When EP_Reduced is set, then all
12615** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
12616** are contained within the same memory allocation.  Note, however, that
12617** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
12618** allocated, regardless of whether or not EP_Reduced is set.
12619*/
12620struct Expr {
12621  u8 op;                 /* Operation performed by this node */
12622  char affinity;         /* The affinity of the column or 0 if not a column */
12623  u32 flags;             /* Various flags.  EP_* See below */
12624  union {
12625    char *zToken;          /* Token value. Zero terminated and dequoted */
12626    int iValue;            /* Non-negative integer value if EP_IntValue */
12627  } u;
12628
12629  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
12630  ** space is allocated for the fields below this point. An attempt to
12631  ** access them will result in a segfault or malfunction.
12632  *********************************************************************/
12633
12634  Expr *pLeft;           /* Left subnode */
12635  Expr *pRight;          /* Right subnode */
12636  union {
12637    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
12638    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
12639  } x;
12640
12641  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
12642  ** space is allocated for the fields below this point. An attempt to
12643  ** access them will result in a segfault or malfunction.
12644  *********************************************************************/
12645
12646#if SQLITE_MAX_EXPR_DEPTH>0
12647  int nHeight;           /* Height of the tree headed by this node */
12648#endif
12649  int iTable;            /* TK_COLUMN: cursor number of table holding column
12650                         ** TK_REGISTER: register number
12651                         ** TK_TRIGGER: 1 -> new, 0 -> old
12652                         ** EP_Unlikely:  134217728 times likelihood */
12653  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
12654                         ** TK_VARIABLE: variable number (always >= 1). */
12655  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
12656  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
12657  u8 op2;                /* TK_REGISTER: original value of Expr.op
12658                         ** TK_COLUMN: the value of p5 for OP_Column
12659                         ** TK_AGG_FUNCTION: nesting depth */
12660  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
12661  Table *pTab;           /* Table for TK_COLUMN expressions. */
12662};
12663
12664/*
12665** The following are the meanings of bits in the Expr.flags field.
12666*/
12667#define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
12668#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
12669#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
12670#define EP_Error     0x000008 /* Expression contains one or more errors */
12671#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
12672#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
12673#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
12674#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
12675#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
12676#define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
12677#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
12678#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
12679#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
12680#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
12681#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
12682#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
12683#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
12684#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
12685#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
12686#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
12687#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
12688#define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
12689#define EP_Alias     0x400000 /* Is an alias for a result set column */
12690
12691/*
12692** Combinations of two or more EP_* flags
12693*/
12694#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
12695
12696/*
12697** These macros can be used to test, set, or clear bits in the
12698** Expr.flags field.
12699*/
12700#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
12701#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
12702#define ExprSetProperty(E,P)     (E)->flags|=(P)
12703#define ExprClearProperty(E,P)   (E)->flags&=~(P)
12704
12705/* The ExprSetVVAProperty() macro is used for Verification, Validation,
12706** and Accreditation only.  It works like ExprSetProperty() during VVA
12707** processes but is a no-op for delivery.
12708*/
12709#ifdef SQLITE_DEBUG
12710# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
12711#else
12712# define ExprSetVVAProperty(E,P)
12713#endif
12714
12715/*
12716** Macros to determine the number of bytes required by a normal Expr
12717** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
12718** and an Expr struct with the EP_TokenOnly flag set.
12719*/
12720#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
12721#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
12722#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
12723
12724/*
12725** Flags passed to the sqlite3ExprDup() function. See the header comment
12726** above sqlite3ExprDup() for details.
12727*/
12728#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
12729
12730/*
12731** A list of expressions.  Each expression may optionally have a
12732** name.  An expr/name combination can be used in several ways, such
12733** as the list of "expr AS ID" fields following a "SELECT" or in the
12734** list of "ID = expr" items in an UPDATE.  A list of expressions can
12735** also be used as the argument to a function, in which case the a.zName
12736** field is not used.
12737**
12738** By default the Expr.zSpan field holds a human-readable description of
12739** the expression that is used in the generation of error messages and
12740** column labels.  In this case, Expr.zSpan is typically the text of a
12741** column expression as it exists in a SELECT statement.  However, if
12742** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
12743** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
12744** form is used for name resolution with nested FROM clauses.
12745*/
12746struct ExprList {
12747  int nExpr;             /* Number of expressions on the list */
12748  struct ExprList_item { /* For each expression in the list */
12749    Expr *pExpr;            /* The list of expressions */
12750    char *zName;            /* Token associated with this expression */
12751    char *zSpan;            /* Original text of the expression */
12752    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
12753    unsigned done :1;       /* A flag to indicate when processing is finished */
12754    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
12755    unsigned reusable :1;   /* Constant expression is reusable */
12756    union {
12757      struct {
12758        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
12759        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
12760      } x;
12761      int iConstExprReg;      /* Register in which Expr value is cached */
12762    } u;
12763  } *a;                  /* Alloc a power of two greater or equal to nExpr */
12764};
12765
12766/*
12767** An instance of this structure is used by the parser to record both
12768** the parse tree for an expression and the span of input text for an
12769** expression.
12770*/
12771struct ExprSpan {
12772  Expr *pExpr;          /* The expression parse tree */
12773  const char *zStart;   /* First character of input text */
12774  const char *zEnd;     /* One character past the end of input text */
12775};
12776
12777/*
12778** An instance of this structure can hold a simple list of identifiers,
12779** such as the list "a,b,c" in the following statements:
12780**
12781**      INSERT INTO t(a,b,c) VALUES ...;
12782**      CREATE INDEX idx ON t(a,b,c);
12783**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
12784**
12785** The IdList.a.idx field is used when the IdList represents the list of
12786** column names after a table name in an INSERT statement.  In the statement
12787**
12788**     INSERT INTO t(a,b,c) ...
12789**
12790** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
12791*/
12792struct IdList {
12793  struct IdList_item {
12794    char *zName;      /* Name of the identifier */
12795    int idx;          /* Index in some Table.aCol[] of a column named zName */
12796  } *a;
12797  int nId;         /* Number of identifiers on the list */
12798};
12799
12800/*
12801** The bitmask datatype defined below is used for various optimizations.
12802**
12803** Changing this from a 64-bit to a 32-bit type limits the number of
12804** tables in a join to 32 instead of 64.  But it also reduces the size
12805** of the library by 738 bytes on ix86.
12806*/
12807typedef u64 Bitmask;
12808
12809/*
12810** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
12811*/
12812#define BMS  ((int)(sizeof(Bitmask)*8))
12813
12814/*
12815** A bit in a Bitmask
12816*/
12817#define MASKBIT(n)   (((Bitmask)1)<<(n))
12818#define MASKBIT32(n) (((unsigned int)1)<<(n))
12819
12820/*
12821** The following structure describes the FROM clause of a SELECT statement.
12822** Each table or subquery in the FROM clause is a separate element of
12823** the SrcList.a[] array.
12824**
12825** With the addition of multiple database support, the following structure
12826** can also be used to describe a particular table such as the table that
12827** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
12828** such a table must be a simple name: ID.  But in SQLite, the table can
12829** now be identified by a database name, a dot, then the table name: ID.ID.
12830**
12831** The jointype starts out showing the join type between the current table
12832** and the next table on the list.  The parser builds the list this way.
12833** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
12834** jointype expresses the join between the table and the previous table.
12835**
12836** In the colUsed field, the high-order bit (bit 63) is set if the table
12837** contains more than 63 columns and the 64-th or later column is used.
12838*/
12839struct SrcList {
12840  int nSrc;        /* Number of tables or subqueries in the FROM clause */
12841  u32 nAlloc;      /* Number of entries allocated in a[] below */
12842  struct SrcList_item {
12843    Schema *pSchema;  /* Schema to which this item is fixed */
12844    char *zDatabase;  /* Name of database holding this table */
12845    char *zName;      /* Name of the table */
12846    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
12847    Table *pTab;      /* An SQL table corresponding to zName */
12848    Select *pSelect;  /* A SELECT statement used in place of a table name */
12849    int addrFillSub;  /* Address of subroutine to manifest a subquery */
12850    int regReturn;    /* Register holding return address of addrFillSub */
12851    int regResult;    /* Registers holding results of a co-routine */
12852    struct {
12853      u8 jointype;      /* Type of join between this able and the previous */
12854      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
12855      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
12856      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
12857      unsigned isCorrelated :1;  /* True if sub-query is correlated */
12858      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
12859      unsigned isRecursive :1;   /* True for recursive reference in WITH */
12860    } fg;
12861#ifndef SQLITE_OMIT_EXPLAIN
12862    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
12863#endif
12864    int iCursor;      /* The VDBE cursor number used to access this table */
12865    Expr *pOn;        /* The ON clause of a join */
12866    IdList *pUsing;   /* The USING clause of a join */
12867    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
12868    union {
12869      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
12870      ExprList *pFuncArg;  /* Arguments to table-valued-function */
12871    } u1;
12872    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
12873  } a[1];             /* One entry for each identifier on the list */
12874};
12875
12876/*
12877** Permitted values of the SrcList.a.jointype field
12878*/
12879#define JT_INNER     0x0001    /* Any kind of inner or cross join */
12880#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
12881#define JT_NATURAL   0x0004    /* True for a "natural" join */
12882#define JT_LEFT      0x0008    /* Left outer join */
12883#define JT_RIGHT     0x0010    /* Right outer join */
12884#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
12885#define JT_ERROR     0x0040    /* unknown or unsupported join type */
12886
12887
12888/*
12889** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
12890** and the WhereInfo.wctrlFlags member.
12891*/
12892#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
12893#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
12894#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
12895#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
12896#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
12897#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
12898#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
12899#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
12900#define WHERE_NO_AUTOINDEX     0x0080 /* Disallow automatic indexes */
12901#define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
12902#define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
12903#define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
12904#define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
12905#define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
12906#define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
12907
12908/* Allowed return values from sqlite3WhereIsDistinct()
12909*/
12910#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
12911#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
12912#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
12913#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
12914
12915/*
12916** A NameContext defines a context in which to resolve table and column
12917** names.  The context consists of a list of tables (the pSrcList) field and
12918** a list of named expression (pEList).  The named expression list may
12919** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
12920** to the table being operated on by INSERT, UPDATE, or DELETE.  The
12921** pEList corresponds to the result set of a SELECT and is NULL for
12922** other statements.
12923**
12924** NameContexts can be nested.  When resolving names, the inner-most
12925** context is searched first.  If no match is found, the next outer
12926** context is checked.  If there is still no match, the next context
12927** is checked.  This process continues until either a match is found
12928** or all contexts are check.  When a match is found, the nRef member of
12929** the context containing the match is incremented.
12930**
12931** Each subquery gets a new NameContext.  The pNext field points to the
12932** NameContext in the parent query.  Thus the process of scanning the
12933** NameContext list corresponds to searching through successively outer
12934** subqueries looking for a match.
12935*/
12936struct NameContext {
12937  Parse *pParse;       /* The parser */
12938  SrcList *pSrcList;   /* One or more tables used to resolve names */
12939  ExprList *pEList;    /* Optional list of result-set columns */
12940  AggInfo *pAggInfo;   /* Information about aggregates at this level */
12941  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
12942  int nRef;            /* Number of names resolved by this context */
12943  int nErr;            /* Number of errors encountered while resolving names */
12944  u16 ncFlags;         /* Zero or more NC_* flags defined below */
12945};
12946
12947/*
12948** Allowed values for the NameContext, ncFlags field.
12949**
12950** Note:  NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
12951** SQLITE_FUNC_MINMAX.
12952**
12953*/
12954#define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
12955#define NC_HasAgg    0x0002  /* One or more aggregate functions seen */
12956#define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
12957#define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
12958#define NC_PartIdx   0x0010  /* True if resolving a partial index WHERE */
12959#define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
12960#define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
12961
12962/*
12963** An instance of the following structure contains all information
12964** needed to generate code for a single SELECT statement.
12965**
12966** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
12967** If there is a LIMIT clause, the parser sets nLimit to the value of the
12968** limit and nOffset to the value of the offset (or 0 if there is not
12969** offset).  But later on, nLimit and nOffset become the memory locations
12970** in the VDBE that record the limit and offset counters.
12971**
12972** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
12973** These addresses must be stored so that we can go back and fill in
12974** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
12975** the number of columns in P2 can be computed at the same time
12976** as the OP_OpenEphm instruction is coded because not
12977** enough information about the compound query is known at that point.
12978** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
12979** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
12980** sequences for the ORDER BY clause.
12981*/
12982struct Select {
12983  ExprList *pEList;      /* The fields of the result */
12984  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
12985  u16 selFlags;          /* Various SF_* values */
12986  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
12987#if SELECTTRACE_ENABLED
12988  char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
12989#endif
12990  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
12991  u64 nSelectRow;        /* Estimated number of result rows */
12992  SrcList *pSrc;         /* The FROM clause */
12993  Expr *pWhere;          /* The WHERE clause */
12994  ExprList *pGroupBy;    /* The GROUP BY clause */
12995  Expr *pHaving;         /* The HAVING clause */
12996  ExprList *pOrderBy;    /* The ORDER BY clause */
12997  Select *pPrior;        /* Prior select in a compound select statement */
12998  Select *pNext;         /* Next select to the left in a compound */
12999  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
13000  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
13001  With *pWith;           /* WITH clause attached to this select. Or NULL. */
13002};
13003
13004/*
13005** Allowed values for Select.selFlags.  The "SF" prefix stands for
13006** "Select Flag".
13007*/
13008#define SF_Distinct        0x0001  /* Output should be DISTINCT */
13009#define SF_All             0x0002  /* Includes the ALL keyword */
13010#define SF_Resolved        0x0004  /* Identifiers have been resolved */
13011#define SF_Aggregate       0x0008  /* Contains aggregate functions */
13012#define SF_UsesEphemeral   0x0010  /* Uses the OpenEphemeral opcode */
13013#define SF_Expanded        0x0020  /* sqlite3SelectExpand() called on this */
13014#define SF_HasTypeInfo     0x0040  /* FROM subqueries have Table metadata */
13015#define SF_Compound        0x0080  /* Part of a compound query */
13016#define SF_Values          0x0100  /* Synthesized from VALUES clause */
13017#define SF_MultiValue      0x0200  /* Single VALUES term with multiple rows */
13018#define SF_NestedFrom      0x0400  /* Part of a parenthesized FROM clause */
13019#define SF_MaybeConvert    0x0800  /* Need convertCompoundSelectToSubquery() */
13020#define SF_MinMaxAgg       0x1000  /* Aggregate containing min() or max() */
13021#define SF_Recursive       0x2000  /* The recursive part of a recursive CTE */
13022#define SF_Converted       0x4000  /* By convertCompoundSelectToSubquery() */
13023
13024
13025/*
13026** The results of a SELECT can be distributed in several ways, as defined
13027** by one of the following macros.  The "SRT" prefix means "SELECT Result
13028** Type".
13029**
13030**     SRT_Union       Store results as a key in a temporary index
13031**                     identified by pDest->iSDParm.
13032**
13033**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
13034**
13035**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
13036**                     set is not empty.
13037**
13038**     SRT_Discard     Throw the results away.  This is used by SELECT
13039**                     statements within triggers whose only purpose is
13040**                     the side-effects of functions.
13041**
13042** All of the above are free to ignore their ORDER BY clause. Those that
13043** follow must honor the ORDER BY clause.
13044**
13045**     SRT_Output      Generate a row of output (using the OP_ResultRow
13046**                     opcode) for each row in the result set.
13047**
13048**     SRT_Mem         Only valid if the result is a single column.
13049**                     Store the first column of the first result row
13050**                     in register pDest->iSDParm then abandon the rest
13051**                     of the query.  This destination implies "LIMIT 1".
13052**
13053**     SRT_Set         The result must be a single column.  Store each
13054**                     row of result as the key in table pDest->iSDParm.
13055**                     Apply the affinity pDest->affSdst before storing
13056**                     results.  Used to implement "IN (SELECT ...)".
13057**
13058**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
13059**                     the result there. The cursor is left open after
13060**                     returning.  This is like SRT_Table except that
13061**                     this destination uses OP_OpenEphemeral to create
13062**                     the table first.
13063**
13064**     SRT_Coroutine   Generate a co-routine that returns a new row of
13065**                     results each time it is invoked.  The entry point
13066**                     of the co-routine is stored in register pDest->iSDParm
13067**                     and the result row is stored in pDest->nDest registers
13068**                     starting with pDest->iSdst.
13069**
13070**     SRT_Table       Store results in temporary table pDest->iSDParm.
13071**     SRT_Fifo        This is like SRT_EphemTab except that the table
13072**                     is assumed to already be open.  SRT_Fifo has
13073**                     the additional property of being able to ignore
13074**                     the ORDER BY clause.
13075**
13076**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
13077**                     But also use temporary table pDest->iSDParm+1 as
13078**                     a record of all prior results and ignore any duplicate
13079**                     rows.  Name means:  "Distinct Fifo".
13080**
13081**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
13082**                     an index).  Append a sequence number so that all entries
13083**                     are distinct.
13084**
13085**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
13086**                     the same record has never been stored before.  The
13087**                     index at pDest->iSDParm+1 hold all prior stores.
13088*/
13089#define SRT_Union        1  /* Store result as keys in an index */
13090#define SRT_Except       2  /* Remove result from a UNION index */
13091#define SRT_Exists       3  /* Store 1 if the result is not empty */
13092#define SRT_Discard      4  /* Do not save the results anywhere */
13093#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
13094#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
13095#define SRT_Queue        7  /* Store result in an queue */
13096#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
13097
13098/* The ORDER BY clause is ignored for all of the above */
13099#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
13100
13101#define SRT_Output       9  /* Output each row of result */
13102#define SRT_Mem         10  /* Store result in a memory cell */
13103#define SRT_Set         11  /* Store results as keys in an index */
13104#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
13105#define SRT_Coroutine   13  /* Generate a single row of result */
13106#define SRT_Table       14  /* Store result as data with an automatic rowid */
13107
13108/*
13109** An instance of this object describes where to put of the results of
13110** a SELECT statement.
13111*/
13112struct SelectDest {
13113  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
13114  char affSdst;        /* Affinity used when eDest==SRT_Set */
13115  int iSDParm;         /* A parameter used by the eDest disposal method */
13116  int iSdst;           /* Base register where results are written */
13117  int nSdst;           /* Number of registers allocated */
13118  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
13119};
13120
13121/*
13122** During code generation of statements that do inserts into AUTOINCREMENT
13123** tables, the following information is attached to the Table.u.autoInc.p
13124** pointer of each autoincrement table to record some side information that
13125** the code generator needs.  We have to keep per-table autoincrement
13126** information in case inserts are down within triggers.  Triggers do not
13127** normally coordinate their activities, but we do need to coordinate the
13128** loading and saving of autoincrement information.
13129*/
13130struct AutoincInfo {
13131  AutoincInfo *pNext;   /* Next info block in a list of them all */
13132  Table *pTab;          /* Table this info block refers to */
13133  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
13134  int regCtr;           /* Memory register holding the rowid counter */
13135};
13136
13137/*
13138** Size of the column cache
13139*/
13140#ifndef SQLITE_N_COLCACHE
13141# define SQLITE_N_COLCACHE 10
13142#endif
13143
13144/*
13145** At least one instance of the following structure is created for each
13146** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
13147** statement. All such objects are stored in the linked list headed at
13148** Parse.pTriggerPrg and deleted once statement compilation has been
13149** completed.
13150**
13151** A Vdbe sub-program that implements the body and WHEN clause of trigger
13152** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
13153** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
13154** The Parse.pTriggerPrg list never contains two entries with the same
13155** values for both pTrigger and orconf.
13156**
13157** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
13158** accessed (or set to 0 for triggers fired as a result of INSERT
13159** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
13160** a mask of new.* columns used by the program.
13161*/
13162struct TriggerPrg {
13163  Trigger *pTrigger;      /* Trigger this program was coded from */
13164  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
13165  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
13166  int orconf;             /* Default ON CONFLICT policy */
13167  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
13168};
13169
13170/*
13171** The yDbMask datatype for the bitmask of all attached databases.
13172*/
13173#if SQLITE_MAX_ATTACHED>30
13174  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
13175# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
13176# define DbMaskZero(M)      memset((M),0,sizeof(M))
13177# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
13178# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
13179# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
13180#else
13181  typedef unsigned int yDbMask;
13182# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
13183# define DbMaskZero(M)      (M)=0
13184# define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
13185# define DbMaskAllZero(M)   (M)==0
13186# define DbMaskNonZero(M)   (M)!=0
13187#endif
13188
13189/*
13190** An SQL parser context.  A copy of this structure is passed through
13191** the parser and down into all the parser action routine in order to
13192** carry around information that is global to the entire parse.
13193**
13194** The structure is divided into two parts.  When the parser and code
13195** generate call themselves recursively, the first part of the structure
13196** is constant but the second part is reset at the beginning and end of
13197** each recursion.
13198**
13199** The nTableLock and aTableLock variables are only used if the shared-cache
13200** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
13201** used to store the set of table-locks required by the statement being
13202** compiled. Function sqlite3TableLock() is used to add entries to the
13203** list.
13204*/
13205struct Parse {
13206  sqlite3 *db;         /* The main database structure */
13207  char *zErrMsg;       /* An error message */
13208  Vdbe *pVdbe;         /* An engine for executing database bytecode */
13209  int rc;              /* Return code from execution */
13210  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
13211  u8 checkSchema;      /* Causes schema cookie check after an error */
13212  u8 nested;           /* Number of nested calls to the parser/code generator */
13213  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
13214  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
13215  u8 mayAbort;         /* True if statement may throw an ABORT exception */
13216  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
13217  u8 okConstFactor;    /* OK to factor out constants */
13218  int aTempReg[8];     /* Holding area for temporary registers */
13219  int nRangeReg;       /* Size of the temporary register block */
13220  int iRangeReg;       /* First register in temporary register block */
13221  int nErr;            /* Number of errors seen */
13222  int nTab;            /* Number of previously allocated VDBE cursors */
13223  int nMem;            /* Number of memory cells used so far */
13224  int nSet;            /* Number of sets used so far */
13225  int nOnce;           /* Number of OP_Once instructions so far */
13226  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
13227  int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
13228  int ckBase;          /* Base register of data during check constraints */
13229  int iSelfTab;        /* Table of an index whose exprs are being coded */
13230  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
13231  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
13232  int nLabel;          /* Number of labels used */
13233  int *aLabel;         /* Space to hold the labels */
13234  struct yColCache {
13235    int iTable;           /* Table cursor number */
13236    i16 iColumn;          /* Table column number */
13237    u8 tempReg;           /* iReg is a temp register that needs to be freed */
13238    int iLevel;           /* Nesting level */
13239    int iReg;             /* Reg with value of this column. 0 means none. */
13240    int lru;              /* Least recently used entry has the smallest value */
13241  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
13242  ExprList *pConstExpr;/* Constant expressions */
13243  Token constraintName;/* Name of the constraint currently being parsed */
13244  yDbMask writeMask;   /* Start a write transaction on these databases */
13245  yDbMask cookieMask;  /* Bitmask of schema verified databases */
13246  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
13247  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
13248  int regRoot;         /* Register holding root page number for new objects */
13249  int nMaxArg;         /* Max args passed to user function by sub-program */
13250#if SELECTTRACE_ENABLED
13251  int nSelect;         /* Number of SELECT statements seen */
13252  int nSelectIndent;   /* How far to indent SELECTTRACE() output */
13253#endif
13254#ifndef SQLITE_OMIT_SHARED_CACHE
13255  int nTableLock;        /* Number of locks in aTableLock */
13256  TableLock *aTableLock; /* Required table locks for shared-cache mode */
13257#endif
13258  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
13259
13260  /* Information used while coding trigger programs. */
13261  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
13262  Table *pTriggerTab;  /* Table triggers are being coded for */
13263  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
13264  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
13265  u32 oldmask;         /* Mask of old.* columns referenced */
13266  u32 newmask;         /* Mask of new.* columns referenced */
13267  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
13268  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
13269  u8 disableTriggers;  /* True to disable triggers */
13270
13271  /************************************************************************
13272  ** Above is constant between recursions.  Below is reset before and after
13273  ** each recursion.  The boundary between these two regions is determined
13274  ** using offsetof(Parse,nVar) so the nVar field must be the first field
13275  ** in the recursive region.
13276  ************************************************************************/
13277
13278  int nVar;                 /* Number of '?' variables seen in the SQL so far */
13279  int nzVar;                /* Number of available slots in azVar[] */
13280  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
13281  u8 bFreeWith;             /* True if pWith should be freed with parser */
13282  u8 explain;               /* True if the EXPLAIN flag is found on the query */
13283#ifndef SQLITE_OMIT_VIRTUALTABLE
13284  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
13285  int nVtabLock;            /* Number of virtual tables to lock */
13286#endif
13287  int nAlias;               /* Number of aliased result set columns */
13288  int nHeight;              /* Expression tree height of current sub-select */
13289#ifndef SQLITE_OMIT_EXPLAIN
13290  int iSelectId;            /* ID of current select for EXPLAIN output */
13291  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
13292#endif
13293  char **azVar;             /* Pointers to names of parameters */
13294  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
13295  const char *zTail;        /* All SQL text past the last semicolon parsed */
13296  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
13297  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
13298  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
13299  Token sNameToken;         /* Token with unqualified schema object name */
13300  Token sLastToken;         /* The last token parsed */
13301#ifndef SQLITE_OMIT_VIRTUALTABLE
13302  Token sArg;               /* Complete text of a module argument */
13303  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
13304#endif
13305  Table *pZombieTab;        /* List of Table objects to delete after code gen */
13306  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
13307  With *pWith;              /* Current WITH clause, or NULL */
13308};
13309
13310/*
13311** Return true if currently inside an sqlite3_declare_vtab() call.
13312*/
13313#ifdef SQLITE_OMIT_VIRTUALTABLE
13314  #define IN_DECLARE_VTAB 0
13315#else
13316  #define IN_DECLARE_VTAB (pParse->declareVtab)
13317#endif
13318
13319/*
13320** An instance of the following structure can be declared on a stack and used
13321** to save the Parse.zAuthContext value so that it can be restored later.
13322*/
13323struct AuthContext {
13324  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
13325  Parse *pParse;              /* The Parse structure */
13326};
13327
13328/*
13329** Bitfield flags for P5 value in various opcodes.
13330*/
13331#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
13332#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
13333#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
13334#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
13335#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
13336#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
13337#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
13338#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
13339#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
13340#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
13341#define OPFLAG_P2ISREG       0x04    /* P2 to OP_Open** is a register number */
13342#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
13343
13344/*
13345 * Each trigger present in the database schema is stored as an instance of
13346 * struct Trigger.
13347 *
13348 * Pointers to instances of struct Trigger are stored in two ways.
13349 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
13350 *    database). This allows Trigger structures to be retrieved by name.
13351 * 2. All triggers associated with a single table form a linked list, using the
13352 *    pNext member of struct Trigger. A pointer to the first element of the
13353 *    linked list is stored as the "pTrigger" member of the associated
13354 *    struct Table.
13355 *
13356 * The "step_list" member points to the first element of a linked list
13357 * containing the SQL statements specified as the trigger program.
13358 */
13359struct Trigger {
13360  char *zName;            /* The name of the trigger                        */
13361  char *table;            /* The table or view to which the trigger applies */
13362  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
13363  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
13364  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
13365  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
13366                             the <column-list> is stored here */
13367  Schema *pSchema;        /* Schema containing the trigger */
13368  Schema *pTabSchema;     /* Schema containing the table */
13369  TriggerStep *step_list; /* Link list of trigger program steps             */
13370  Trigger *pNext;         /* Next trigger associated with the table */
13371};
13372
13373/*
13374** A trigger is either a BEFORE or an AFTER trigger.  The following constants
13375** determine which.
13376**
13377** If there are multiple triggers, you might of some BEFORE and some AFTER.
13378** In that cases, the constants below can be ORed together.
13379*/
13380#define TRIGGER_BEFORE  1
13381#define TRIGGER_AFTER   2
13382
13383/*
13384 * An instance of struct TriggerStep is used to store a single SQL statement
13385 * that is a part of a trigger-program.
13386 *
13387 * Instances of struct TriggerStep are stored in a singly linked list (linked
13388 * using the "pNext" member) referenced by the "step_list" member of the
13389 * associated struct Trigger instance. The first element of the linked list is
13390 * the first step of the trigger-program.
13391 *
13392 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
13393 * "SELECT" statement. The meanings of the other members is determined by the
13394 * value of "op" as follows:
13395 *
13396 * (op == TK_INSERT)
13397 * orconf    -> stores the ON CONFLICT algorithm
13398 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
13399 *              this stores a pointer to the SELECT statement. Otherwise NULL.
13400 * zTarget   -> Dequoted name of the table to insert into.
13401 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
13402 *              this stores values to be inserted. Otherwise NULL.
13403 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
13404 *              statement, then this stores the column-names to be
13405 *              inserted into.
13406 *
13407 * (op == TK_DELETE)
13408 * zTarget   -> Dequoted name of the table to delete from.
13409 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
13410 *              Otherwise NULL.
13411 *
13412 * (op == TK_UPDATE)
13413 * zTarget   -> Dequoted name of the table to update.
13414 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
13415 *              Otherwise NULL.
13416 * pExprList -> A list of the columns to update and the expressions to update
13417 *              them to. See sqlite3Update() documentation of "pChanges"
13418 *              argument.
13419 *
13420 */
13421struct TriggerStep {
13422  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
13423  u8 orconf;           /* OE_Rollback etc. */
13424  Trigger *pTrig;      /* The trigger that this step is a part of */
13425  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
13426  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
13427  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
13428  ExprList *pExprList; /* SET clause for UPDATE. */
13429  IdList *pIdList;     /* Column names for INSERT */
13430  TriggerStep *pNext;  /* Next in the link-list */
13431  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
13432};
13433
13434/*
13435** The following structure contains information used by the sqliteFix...
13436** routines as they walk the parse tree to make database references
13437** explicit.
13438*/
13439typedef struct DbFixer DbFixer;
13440struct DbFixer {
13441  Parse *pParse;      /* The parsing context.  Error messages written here */
13442  Schema *pSchema;    /* Fix items to this schema */
13443  int bVarOnly;       /* Check for variable references only */
13444  const char *zDb;    /* Make sure all objects are contained in this database */
13445  const char *zType;  /* Type of the container - used for error messages */
13446  const Token *pName; /* Name of the container - used for error messages */
13447};
13448
13449/*
13450** An objected used to accumulate the text of a string where we
13451** do not necessarily know how big the string will be in the end.
13452*/
13453struct StrAccum {
13454  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
13455  char *zBase;         /* A base allocation.  Not from malloc. */
13456  char *zText;         /* The string collected so far */
13457  int  nChar;          /* Length of the string so far */
13458  int  nAlloc;         /* Amount of space allocated in zText */
13459  int  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
13460  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
13461};
13462#define STRACCUM_NOMEM   1
13463#define STRACCUM_TOOBIG  2
13464
13465/*
13466** A pointer to this structure is used to communicate information
13467** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
13468*/
13469typedef struct {
13470  sqlite3 *db;        /* The database being initialized */
13471  char **pzErrMsg;    /* Error message stored here */
13472  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
13473  int rc;             /* Result code stored here */
13474} InitData;
13475
13476/*
13477** Structure containing global configuration data for the SQLite library.
13478**
13479** This structure also contains some state information.
13480*/
13481struct Sqlite3Config {
13482  int bMemstat;                     /* True to enable memory status */
13483  int bCoreMutex;                   /* True to enable core mutexing */
13484  int bFullMutex;                   /* True to enable full mutexing */
13485  int bOpenUri;                     /* True to interpret filenames as URIs */
13486  int bUseCis;                      /* Use covering indices for full-scans */
13487  int mxStrlen;                     /* Maximum string length */
13488  int neverCorrupt;                 /* Database is always well-formed */
13489  int szLookaside;                  /* Default lookaside buffer size */
13490  int nLookaside;                   /* Default lookaside buffer count */
13491  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
13492  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
13493  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
13494  void *pHeap;                      /* Heap storage space */
13495  int nHeap;                        /* Size of pHeap[] */
13496  int mnReq, mxReq;                 /* Min and max heap requests sizes */
13497  sqlite3_int64 szMmap;             /* mmap() space per open file */
13498  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
13499  void *pScratch;                   /* Scratch memory */
13500  int szScratch;                    /* Size of each scratch buffer */
13501  int nScratch;                     /* Number of scratch buffers */
13502  void *pPage;                      /* Page cache memory */
13503  int szPage;                       /* Size of each page in pPage[] */
13504  int nPage;                        /* Number of pages in pPage[] */
13505  int mxParserStack;                /* maximum depth of the parser stack */
13506  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
13507  u32 szPma;                        /* Maximum Sorter PMA size */
13508  /* The above might be initialized to non-zero.  The following need to always
13509  ** initially be zero, however. */
13510  int isInit;                       /* True after initialization has finished */
13511  int inProgress;                   /* True while initialization in progress */
13512  int isMutexInit;                  /* True after mutexes are initialized */
13513  int isMallocInit;                 /* True after malloc is initialized */
13514  int isPCacheInit;                 /* True after malloc is initialized */
13515  int nRefInitMutex;                /* Number of users of pInitMutex */
13516  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
13517  void (*xLog)(void*,int,const char*); /* Function for logging */
13518  void *pLogArg;                       /* First argument to xLog() */
13519#ifdef SQLITE_ENABLE_SQLLOG
13520  void(*xSqllog)(void*,sqlite3*,const char*, int);
13521  void *pSqllogArg;
13522#endif
13523#ifdef SQLITE_VDBE_COVERAGE
13524  /* The following callback (if not NULL) is invoked on every VDBE branch
13525  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
13526  */
13527  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
13528  void *pVdbeBranchArg;                                     /* 1st argument */
13529#endif
13530#ifndef SQLITE_OMIT_BUILTIN_TEST
13531  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
13532#endif
13533  int bLocaltimeFault;              /* True to fail localtime() calls */
13534};
13535
13536/*
13537** This macro is used inside of assert() statements to indicate that
13538** the assert is only valid on a well-formed database.  Instead of:
13539**
13540**     assert( X );
13541**
13542** One writes:
13543**
13544**     assert( X || CORRUPT_DB );
13545**
13546** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
13547** that the database is definitely corrupt, only that it might be corrupt.
13548** For most test cases, CORRUPT_DB is set to false using a special
13549** sqlite3_test_control().  This enables assert() statements to prove
13550** things that are always true for well-formed databases.
13551*/
13552#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
13553
13554/*
13555** Context pointer passed down through the tree-walk.
13556*/
13557struct Walker {
13558  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
13559  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
13560  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
13561  Parse *pParse;                            /* Parser context.  */
13562  int walkerDepth;                          /* Number of subqueries */
13563  u8 eCode;                                 /* A small processing code */
13564  union {                                   /* Extra data for callback */
13565    NameContext *pNC;                          /* Naming context */
13566    int n;                                     /* A counter */
13567    int iCur;                                  /* A cursor number */
13568    SrcList *pSrcList;                         /* FROM clause */
13569    struct SrcCount *pSrcCount;                /* Counting column references */
13570  } u;
13571};
13572
13573/* Forward declarations */
13574SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
13575SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
13576SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
13577SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
13578SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
13579
13580/*
13581** Return code from the parse-tree walking primitives and their
13582** callbacks.
13583*/
13584#define WRC_Continue    0   /* Continue down into children */
13585#define WRC_Prune       1   /* Omit children but continue walking siblings */
13586#define WRC_Abort       2   /* Abandon the tree walk */
13587
13588/*
13589** An instance of this structure represents a set of one or more CTEs
13590** (common table expressions) created by a single WITH clause.
13591*/
13592struct With {
13593  int nCte;                       /* Number of CTEs in the WITH clause */
13594  With *pOuter;                   /* Containing WITH clause, or NULL */
13595  struct Cte {                    /* For each CTE in the WITH clause.... */
13596    char *zName;                    /* Name of this CTE */
13597    ExprList *pCols;                /* List of explicit column names, or NULL */
13598    Select *pSelect;                /* The definition of this CTE */
13599    const char *zCteErr;            /* Error message for circular references */
13600  } a[1];
13601};
13602
13603#ifdef SQLITE_DEBUG
13604/*
13605** An instance of the TreeView object is used for printing the content of
13606** data structures on sqlite3DebugPrintf() using a tree-like view.
13607*/
13608struct TreeView {
13609  int iLevel;             /* Which level of the tree we are on */
13610  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
13611};
13612#endif /* SQLITE_DEBUG */
13613
13614/*
13615** Assuming zIn points to the first byte of a UTF-8 character,
13616** advance zIn to point to the first byte of the next UTF-8 character.
13617*/
13618#define SQLITE_SKIP_UTF8(zIn) {                        \
13619  if( (*(zIn++))>=0xc0 ){                              \
13620    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
13621  }                                                    \
13622}
13623
13624/*
13625** The SQLITE_*_BKPT macros are substitutes for the error codes with
13626** the same name but without the _BKPT suffix.  These macros invoke
13627** routines that report the line-number on which the error originated
13628** using sqlite3_log().  The routines also provide a convenient place
13629** to set a debugger breakpoint.
13630*/
13631SQLITE_PRIVATE int sqlite3CorruptError(int);
13632SQLITE_PRIVATE int sqlite3MisuseError(int);
13633SQLITE_PRIVATE int sqlite3CantopenError(int);
13634#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
13635#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
13636#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
13637
13638
13639/*
13640** FTS4 is really an extension for FTS3.  It is enabled using the
13641** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
13642** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
13643*/
13644#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
13645# define SQLITE_ENABLE_FTS3 1
13646#endif
13647
13648/*
13649** The ctype.h header is needed for non-ASCII systems.  It is also
13650** needed by FTS3 when FTS3 is included in the amalgamation.
13651*/
13652#if !defined(SQLITE_ASCII) || \
13653    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
13654# include <ctype.h>
13655#endif
13656
13657/*
13658** The following macros mimic the standard library functions toupper(),
13659** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
13660** sqlite versions only work for ASCII characters, regardless of locale.
13661*/
13662#ifdef SQLITE_ASCII
13663# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
13664# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
13665# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
13666# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
13667# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
13668# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
13669# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
13670#else
13671# define sqlite3Toupper(x)   toupper((unsigned char)(x))
13672# define sqlite3Isspace(x)   isspace((unsigned char)(x))
13673# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
13674# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
13675# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
13676# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
13677# define sqlite3Tolower(x)   tolower((unsigned char)(x))
13678#endif
13679#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13680SQLITE_PRIVATE int sqlite3IsIdChar(u8);
13681#endif
13682
13683/*
13684** Internal function prototypes
13685*/
13686#define sqlite3StrICmp sqlite3_stricmp
13687SQLITE_PRIVATE int sqlite3Strlen30(const char*);
13688#define sqlite3StrNICmp sqlite3_strnicmp
13689
13690SQLITE_PRIVATE int sqlite3MallocInit(void);
13691SQLITE_PRIVATE void sqlite3MallocEnd(void);
13692SQLITE_PRIVATE void *sqlite3Malloc(u64);
13693SQLITE_PRIVATE void *sqlite3MallocZero(u64);
13694SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
13695SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
13696SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
13697SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
13698SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
13699SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
13700SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
13701SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
13702SQLITE_PRIVATE int sqlite3MallocSize(void*);
13703SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
13704SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
13705SQLITE_PRIVATE void sqlite3ScratchFree(void*);
13706SQLITE_PRIVATE void *sqlite3PageMalloc(int);
13707SQLITE_PRIVATE void sqlite3PageFree(void*);
13708SQLITE_PRIVATE void sqlite3MemSetDefault(void);
13709#ifndef SQLITE_OMIT_BUILTIN_TEST
13710SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
13711#endif
13712SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
13713
13714/*
13715** On systems with ample stack space and that support alloca(), make
13716** use of alloca() to obtain space for large automatic objects.  By default,
13717** obtain space from malloc().
13718**
13719** The alloca() routine never returns NULL.  This will cause code paths
13720** that deal with sqlite3StackAlloc() failures to be unreachable.
13721*/
13722#ifdef SQLITE_USE_ALLOCA
13723# define sqlite3StackAllocRaw(D,N)   alloca(N)
13724# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
13725# define sqlite3StackFree(D,P)
13726#else
13727# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
13728# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
13729# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
13730#endif
13731
13732#ifdef SQLITE_ENABLE_MEMSYS3
13733SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
13734#endif
13735#ifdef SQLITE_ENABLE_MEMSYS5
13736SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
13737#endif
13738
13739
13740#ifndef SQLITE_MUTEX_OMIT
13741SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
13742SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
13743SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
13744SQLITE_PRIVATE   int sqlite3MutexInit(void);
13745SQLITE_PRIVATE   int sqlite3MutexEnd(void);
13746#endif
13747#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
13748SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
13749#else
13750# define sqlite3MemoryBarrier()
13751#endif
13752
13753SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
13754SQLITE_PRIVATE void sqlite3StatusUp(int, int);
13755SQLITE_PRIVATE void sqlite3StatusDown(int, int);
13756SQLITE_PRIVATE void sqlite3StatusSet(int, int);
13757
13758/* Access to mutexes used by sqlite3_status() */
13759SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
13760SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
13761
13762#ifndef SQLITE_OMIT_FLOATING_POINT
13763SQLITE_PRIVATE   int sqlite3IsNaN(double);
13764#else
13765# define sqlite3IsNaN(X)  0
13766#endif
13767
13768/*
13769** An instance of the following structure holds information about SQL
13770** functions arguments that are the parameters to the printf() function.
13771*/
13772struct PrintfArguments {
13773  int nArg;                /* Total number of arguments */
13774  int nUsed;               /* Number of arguments used so far */
13775  sqlite3_value **apArg;   /* The argument values */
13776};
13777
13778#define SQLITE_PRINTF_INTERNAL 0x01
13779#define SQLITE_PRINTF_SQLFUNC  0x02
13780SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
13781SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
13782SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
13783SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
13784#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
13785SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
13786#endif
13787#if defined(SQLITE_TEST)
13788SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
13789#endif
13790
13791#if defined(SQLITE_DEBUG)
13792SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
13793SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
13794SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
13795#endif
13796
13797
13798SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
13799SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
13800SQLITE_PRIVATE int sqlite3Dequote(char*);
13801SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
13802SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
13803SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
13804SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
13805SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
13806SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
13807SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
13808SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
13809SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
13810SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
13811SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
13812SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
13813SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
13814SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
13815SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
13816SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
13817SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
13818SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
13819SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
13820SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
13821SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
13822SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
13823SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
13824SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
13825SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
13826SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
13827SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
13828SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
13829SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
13830SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
13831SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
13832SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
13833SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
13834SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
13835SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
13836SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
13837SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
13838SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
13839SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
13840SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
13841SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
13842SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
13843SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
13844SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
13845SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
13846SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
13847                    sqlite3_vfs**,char**,char **);
13848SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
13849SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
13850
13851#ifdef SQLITE_OMIT_BUILTIN_TEST
13852# define sqlite3FaultSim(X) SQLITE_OK
13853#else
13854SQLITE_PRIVATE   int sqlite3FaultSim(int);
13855#endif
13856
13857SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
13858SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
13859SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
13860SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
13861SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
13862SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
13863SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
13864#ifndef SQLITE_OMIT_BUILTIN_TEST
13865SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
13866#endif
13867
13868SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
13869SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
13870SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
13871SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
13872SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
13873
13874SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
13875
13876#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
13877SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
13878#else
13879# define sqlite3ViewGetColumnNames(A,B) 0
13880#endif
13881
13882#if SQLITE_MAX_ATTACHED>30
13883SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
13884#endif
13885SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
13886SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
13887SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
13888#ifndef SQLITE_OMIT_AUTOINCREMENT
13889SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
13890SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
13891#else
13892# define sqlite3AutoincrementBegin(X)
13893# define sqlite3AutoincrementEnd(X)
13894#endif
13895SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
13896SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
13897SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
13898SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
13899SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
13900SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
13901SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
13902                                      Token*, Select*, Expr*, IdList*);
13903SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
13904SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
13905SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
13906SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
13907SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
13908SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
13909SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
13910SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
13911SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
13912                          Expr*, int, int);
13913SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
13914SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
13915SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
13916                         Expr*,ExprList*,u16,Expr*,Expr*);
13917SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
13918SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
13919SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
13920SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
13921#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
13922SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
13923#endif
13924SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
13925SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
13926SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
13927SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
13928SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
13929SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
13930SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
13931SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
13932SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
13933SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
13934SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
13935#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
13936#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
13937#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
13938SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
13939SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
13940SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
13941SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
13942SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
13943SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
13944SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
13945SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
13946SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
13947SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
13948SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
13949SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
13950SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
13951SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
13952SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
13953SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
13954SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
13955#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
13956#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
13957#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
13958SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
13959SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
13960SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
13961SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
13962SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
13963SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
13964SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
13965SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
13966SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
13967SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
13968SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
13969SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
13970SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
13971SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
13972SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
13973SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
13974SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
13975SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
13976SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
13977#ifndef SQLITE_OMIT_BUILTIN_TEST
13978SQLITE_PRIVATE void sqlite3PrngSaveState(void);
13979SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
13980#endif
13981SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
13982SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
13983SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
13984SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
13985SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
13986SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
13987SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
13988SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
13989SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
13990SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
13991SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
13992SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
13993SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
13994SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
13995SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
13996SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
13997SQLITE_PRIVATE int sqlite3IsRowid(const char*);
13998SQLITE_PRIVATE void sqlite3GenerateRowDelete(
13999    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
14000SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
14001SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
14002SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
14003SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
14004                                     u8,u8,int,int*);
14005SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
14006SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
14007SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
14008SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
14009SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
14010SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
14011SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
14012SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
14013SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
14014SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
14015SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
14016SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
14017SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
14018#if SELECTTRACE_ENABLED
14019SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
14020#else
14021# define sqlite3SelectSetName(A,B)
14022#endif
14023SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
14024SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
14025SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
14026SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
14027SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
14028SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
14029SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
14030SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
14031
14032#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
14033SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
14034#endif
14035
14036#ifndef SQLITE_OMIT_TRIGGER
14037SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
14038                           Expr*,int, int);
14039SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
14040SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
14041SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
14042SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
14043SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
14044SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
14045                            int, int, int);
14046SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
14047  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
14048SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
14049SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
14050SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
14051                                        Select*,u8);
14052SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
14053SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
14054SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
14055SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
14056SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
14057# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
14058# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
14059#else
14060# define sqlite3TriggersExist(B,C,D,E,F) 0
14061# define sqlite3DeleteTrigger(A,B)
14062# define sqlite3DropTriggerPtr(A,B)
14063# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
14064# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
14065# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
14066# define sqlite3TriggerList(X, Y) 0
14067# define sqlite3ParseToplevel(p) p
14068# define sqlite3IsToplevel(p) 1
14069# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
14070#endif
14071
14072SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
14073SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
14074SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
14075#ifndef SQLITE_OMIT_AUTHORIZATION
14076SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
14077SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
14078SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
14079SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
14080SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
14081#else
14082# define sqlite3AuthRead(a,b,c,d)
14083# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
14084# define sqlite3AuthContextPush(a,b,c)
14085# define sqlite3AuthContextPop(a)  ((void)(a))
14086#endif
14087SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
14088SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
14089SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
14090SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
14091SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
14092SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
14093SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
14094SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
14095SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
14096SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
14097SQLITE_PRIVATE int sqlite3Atoi(const char*);
14098SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
14099SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
14100SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
14101SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
14102SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
14103#ifndef SQLITE_OMIT_VIRTUALTABLE
14104SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
14105#endif
14106SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
14107
14108/*
14109** Routines to read and write variable-length integers.  These used to
14110** be defined locally, but now we use the varint routines in the util.c
14111** file.
14112*/
14113SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
14114SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
14115SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
14116SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
14117
14118/*
14119** The common case is for a varint to be a single byte.  They following
14120** macros handle the common case without a procedure call, but then call
14121** the procedure for larger varints.
14122*/
14123#define getVarint32(A,B)  \
14124  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
14125#define putVarint32(A,B)  \
14126  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
14127  sqlite3PutVarint((A),(B)))
14128#define getVarint    sqlite3GetVarint
14129#define putVarint    sqlite3PutVarint
14130
14131
14132SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
14133SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
14134SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
14135SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
14136SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
14137SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
14138SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
14139SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
14140SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
14141SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
14142SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
14143SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
14144
14145#if defined(SQLITE_NEED_ERR_NAME)
14146SQLITE_PRIVATE const char *sqlite3ErrName(int);
14147#endif
14148
14149SQLITE_PRIVATE const char *sqlite3ErrStr(int);
14150SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
14151SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
14152SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
14153SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
14154SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
14155SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
14156SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
14157SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
14158SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
14159SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
14160SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
14161SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
14162SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
14163SQLITE_PRIVATE int sqlite3AbsInt32(int);
14164#ifdef SQLITE_ENABLE_8_3_NAMES
14165SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
14166#else
14167# define sqlite3FileSuffix3(X,Y)
14168#endif
14169SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
14170
14171SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
14172SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
14173SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
14174                        void(*)(void*));
14175SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
14176SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
14177SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
14178SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
14179SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
14180SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
14181#ifndef SQLITE_AMALGAMATION
14182SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
14183SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
14184SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
14185SQLITE_PRIVATE const Token sqlite3IntTokens[];
14186SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
14187SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
14188#ifndef SQLITE_OMIT_WSD
14189SQLITE_PRIVATE int sqlite3PendingByte;
14190#endif
14191#endif
14192SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
14193SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
14194SQLITE_PRIVATE void sqlite3AlterFunctions(void);
14195SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
14196SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
14197SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
14198SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
14199SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
14200SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
14201SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
14202SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
14203SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
14204SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
14205SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
14206SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
14207SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
14208SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
14209SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
14210SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
14211SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
14212SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
14213SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
14214SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
14215SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
14216SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
14217SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
14218SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
14219SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
14220SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
14221SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
14222SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
14223SQLITE_PRIVATE void sqlite3SchemaClear(void *);
14224SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
14225SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
14226SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
14227SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
14228SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
14229SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
14230#ifdef SQLITE_DEBUG
14231SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
14232#endif
14233SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
14234  void (*)(sqlite3_context*,int,sqlite3_value **),
14235  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
14236  FuncDestructor *pDestructor
14237);
14238SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
14239SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
14240
14241SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
14242SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
14243SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
14244SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
14245SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
14246SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
14247SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
14248SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
14249
14250SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
14251SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
14252
14253#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14254SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
14255SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
14256SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
14257SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
14258SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
14259#endif
14260
14261/*
14262** The interface to the LEMON-generated parser
14263*/
14264SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
14265SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
14266SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
14267#ifdef YYTRACKMAXSTACKDEPTH
14268SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
14269#endif
14270
14271SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
14272#ifndef SQLITE_OMIT_LOAD_EXTENSION
14273SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
14274#else
14275# define sqlite3CloseExtensions(X)
14276#endif
14277
14278#ifndef SQLITE_OMIT_SHARED_CACHE
14279SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
14280#else
14281  #define sqlite3TableLock(v,w,x,y,z)
14282#endif
14283
14284#ifdef SQLITE_TEST
14285SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
14286#endif
14287
14288#ifdef SQLITE_OMIT_VIRTUALTABLE
14289#  define sqlite3VtabClear(Y)
14290#  define sqlite3VtabSync(X,Y) SQLITE_OK
14291#  define sqlite3VtabRollback(X)
14292#  define sqlite3VtabCommit(X)
14293#  define sqlite3VtabInSync(db) 0
14294#  define sqlite3VtabLock(X)
14295#  define sqlite3VtabUnlock(X)
14296#  define sqlite3VtabUnlockList(X)
14297#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
14298#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
14299#else
14300SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
14301SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
14302SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
14303SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
14304SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
14305SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
14306SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
14307SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
14308SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
14309SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
14310SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
14311#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
14312#endif
14313SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
14314SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
14315SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
14316SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
14317SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
14318SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
14319SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
14320SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
14321SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
14322SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
14323SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
14324SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
14325SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
14326SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
14327SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
14328SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
14329SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
14330SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
14331SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
14332SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
14333SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
14334SQLITE_PRIVATE const char *sqlite3JournalModename(int);
14335#ifndef SQLITE_OMIT_WAL
14336SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
14337SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
14338#endif
14339#ifndef SQLITE_OMIT_CTE
14340SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
14341SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
14342SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
14343#else
14344#define sqlite3WithPush(x,y,z)
14345#define sqlite3WithDelete(x,y)
14346#endif
14347
14348/* Declarations for functions in fkey.c. All of these are replaced by
14349** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
14350** key functionality is available. If OMIT_TRIGGER is defined but
14351** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
14352** this case foreign keys are parsed, but no other functionality is
14353** provided (enforcement of FK constraints requires the triggers sub-system).
14354*/
14355#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
14356SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
14357SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
14358SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
14359SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
14360SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
14361SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
14362#else
14363  #define sqlite3FkActions(a,b,c,d,e,f)
14364  #define sqlite3FkCheck(a,b,c,d,e,f)
14365  #define sqlite3FkDropTable(a,b,c)
14366  #define sqlite3FkOldmask(a,b)         0
14367  #define sqlite3FkRequired(a,b,c,d)    0
14368#endif
14369#ifndef SQLITE_OMIT_FOREIGN_KEY
14370SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
14371SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
14372#else
14373  #define sqlite3FkDelete(a,b)
14374  #define sqlite3FkLocateIndex(a,b,c,d,e)
14375#endif
14376
14377
14378/*
14379** Available fault injectors.  Should be numbered beginning with 0.
14380*/
14381#define SQLITE_FAULTINJECTOR_MALLOC     0
14382#define SQLITE_FAULTINJECTOR_COUNT      1
14383
14384/*
14385** The interface to the code in fault.c used for identifying "benign"
14386** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
14387** is not defined.
14388*/
14389#ifndef SQLITE_OMIT_BUILTIN_TEST
14390SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
14391SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
14392#else
14393  #define sqlite3BeginBenignMalloc()
14394  #define sqlite3EndBenignMalloc()
14395#endif
14396
14397/*
14398** Allowed return values from sqlite3FindInIndex()
14399*/
14400#define IN_INDEX_ROWID        1   /* Search the rowid of the table */
14401#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
14402#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
14403#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
14404#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
14405/*
14406** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
14407*/
14408#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
14409#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
14410#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
14411SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
14412
14413#ifdef SQLITE_ENABLE_ATOMIC_WRITE
14414SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
14415SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
14416SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
14417SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
14418#else
14419  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
14420  #define sqlite3JournalExists(p) 1
14421#endif
14422
14423SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
14424SQLITE_PRIVATE int sqlite3MemJournalSize(void);
14425SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
14426
14427SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
14428#if SQLITE_MAX_EXPR_DEPTH>0
14429SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
14430SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
14431#else
14432  #define sqlite3SelectExprHeight(x) 0
14433  #define sqlite3ExprCheckHeight(x,y)
14434#endif
14435
14436SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
14437SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
14438
14439#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
14440SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
14441SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
14442SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
14443#else
14444  #define sqlite3ConnectionBlocked(x,y)
14445  #define sqlite3ConnectionUnlocked(x)
14446  #define sqlite3ConnectionClosed(x)
14447#endif
14448
14449#ifdef SQLITE_DEBUG
14450SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
14451#endif
14452
14453/*
14454** If the SQLITE_ENABLE IOTRACE exists then the global variable
14455** sqlite3IoTrace is a pointer to a printf-like routine used to
14456** print I/O tracing messages.
14457*/
14458#ifdef SQLITE_ENABLE_IOTRACE
14459# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
14460SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
14461SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
14462#else
14463# define IOTRACE(A)
14464# define sqlite3VdbeIOTraceSql(X)
14465#endif
14466
14467/*
14468** These routines are available for the mem2.c debugging memory allocator
14469** only.  They are used to verify that different "types" of memory
14470** allocations are properly tracked by the system.
14471**
14472** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
14473** the MEMTYPE_* macros defined below.  The type must be a bitmask with
14474** a single bit set.
14475**
14476** sqlite3MemdebugHasType() returns true if any of the bits in its second
14477** argument match the type set by the previous sqlite3MemdebugSetType().
14478** sqlite3MemdebugHasType() is intended for use inside assert() statements.
14479**
14480** sqlite3MemdebugNoType() returns true if none of the bits in its second
14481** argument match the type set by the previous sqlite3MemdebugSetType().
14482**
14483** Perhaps the most important point is the difference between MEMTYPE_HEAP
14484** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
14485** it might have been allocated by lookaside, except the allocation was
14486** too large or lookaside was already full.  It is important to verify
14487** that allocations that might have been satisfied by lookaside are not
14488** passed back to non-lookaside free() routines.  Asserts such as the
14489** example above are placed on the non-lookaside free() routines to verify
14490** this constraint.
14491**
14492** All of this is no-op for a production build.  It only comes into
14493** play when the SQLITE_MEMDEBUG compile-time option is used.
14494*/
14495#ifdef SQLITE_MEMDEBUG
14496SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
14497SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
14498SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
14499#else
14500# define sqlite3MemdebugSetType(X,Y)  /* no-op */
14501# define sqlite3MemdebugHasType(X,Y)  1
14502# define sqlite3MemdebugNoType(X,Y)   1
14503#endif
14504#define MEMTYPE_HEAP       0x01  /* General heap allocations */
14505#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
14506#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
14507#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
14508
14509/*
14510** Threading interface
14511*/
14512#if SQLITE_MAX_WORKER_THREADS>0
14513SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
14514SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
14515#endif
14516
14517#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
14518SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
14519#endif
14520
14521#endif /* _SQLITEINT_H_ */
14522
14523/************** End of sqliteInt.h *******************************************/
14524/************** Begin file global.c ******************************************/
14525/*
14526** 2008 June 13
14527**
14528** The author disclaims copyright to this source code.  In place of
14529** a legal notice, here is a blessing:
14530**
14531**    May you do good and not evil.
14532**    May you find forgiveness for yourself and forgive others.
14533**    May you share freely, never taking more than you give.
14534**
14535*************************************************************************
14536**
14537** This file contains definitions of global variables and constants.
14538*/
14539/* #include "sqliteInt.h" */
14540
14541/* An array to map all upper-case characters into their corresponding
14542** lower-case character.
14543**
14544** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
14545** handle case conversions for the UTF character set since the tables
14546** involved are nearly as big or bigger than SQLite itself.
14547*/
14548SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
14549#ifdef SQLITE_ASCII
14550      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
14551     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
14552     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
14553     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
14554    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
14555    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
14556    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
14557    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
14558    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
14559    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
14560    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
14561    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
14562    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
14563    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
14564    252,253,254,255
14565#endif
14566#ifdef SQLITE_EBCDIC
14567      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
14568     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
14569     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
14570     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
14571     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
14572     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
14573     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
14574    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
14575    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
14576    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
14577    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
14578    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
14579    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
14580    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
14581    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
14582    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
14583#endif
14584};
14585
14586/*
14587** The following 256 byte lookup table is used to support SQLites built-in
14588** equivalents to the following standard library functions:
14589**
14590**   isspace()                        0x01
14591**   isalpha()                        0x02
14592**   isdigit()                        0x04
14593**   isalnum()                        0x06
14594**   isxdigit()                       0x08
14595**   toupper()                        0x20
14596**   SQLite identifier character      0x40
14597**
14598** Bit 0x20 is set if the mapped character requires translation to upper
14599** case. i.e. if the character is a lower-case ASCII character.
14600** If x is a lower-case ASCII character, then its upper-case equivalent
14601** is (x - 0x20). Therefore toupper() can be implemented as:
14602**
14603**   (x & ~(map[x]&0x20))
14604**
14605** Standard function tolower() is implemented using the sqlite3UpperToLower[]
14606** array. tolower() is used more often than toupper() by SQLite.
14607**
14608** Bit 0x40 is set if the character non-alphanumeric and can be used in an
14609** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
14610** non-ASCII UTF character. Hence the test for whether or not a character is
14611** part of an identifier is 0x46.
14612**
14613** SQLite's versions are identical to the standard versions assuming a
14614** locale of "C". They are implemented as macros in sqliteInt.h.
14615*/
14616#ifdef SQLITE_ASCII
14617SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
14618  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
14619  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
14620  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
14621  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
14622  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
14623  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
14624  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
14625  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
14626
14627  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
14628  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
14629  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
14630  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
14631  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
14632  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
14633  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
14634  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
14635
14636  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
14637  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
14638  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
14639  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
14640  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
14641  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
14642  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
14643  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
14644
14645  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
14646  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
14647  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
14648  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
14649  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
14650  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
14651  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
14652  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
14653};
14654#endif
14655
14656/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
14657** compatibility for legacy applications, the URI filename capability is
14658** disabled by default.
14659**
14660** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
14661** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
14662**
14663** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
14664** disabled. The default value may be changed by compiling with the
14665** SQLITE_USE_URI symbol defined.
14666*/
14667#ifndef SQLITE_USE_URI
14668# define  SQLITE_USE_URI 0
14669#endif
14670
14671/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
14672** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
14673** that compile-time option is omitted.
14674*/
14675#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
14676# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
14677#endif
14678
14679/* The minimum PMA size is set to this value multiplied by the database
14680** page size in bytes.
14681*/
14682#ifndef SQLITE_SORTER_PMASZ
14683# define SQLITE_SORTER_PMASZ 250
14684#endif
14685
14686/*
14687** The following singleton contains the global configuration for
14688** the SQLite library.
14689*/
14690SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
14691   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
14692   1,                         /* bCoreMutex */
14693   SQLITE_THREADSAFE==1,      /* bFullMutex */
14694   SQLITE_USE_URI,            /* bOpenUri */
14695   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
14696   0x7ffffffe,                /* mxStrlen */
14697   0,                         /* neverCorrupt */
14698   128,                       /* szLookaside */
14699   500,                       /* nLookaside */
14700   {0,0,0,0,0,0,0,0},         /* m */
14701   {0,0,0,0,0,0,0,0,0},       /* mutex */
14702   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
14703   (void*)0,                  /* pHeap */
14704   0,                         /* nHeap */
14705   0, 0,                      /* mnHeap, mxHeap */
14706   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
14707   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
14708   (void*)0,                  /* pScratch */
14709   0,                         /* szScratch */
14710   0,                         /* nScratch */
14711   (void*)0,                  /* pPage */
14712   0,                         /* szPage */
14713   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
14714   0,                         /* mxParserStack */
14715   0,                         /* sharedCacheEnabled */
14716   SQLITE_SORTER_PMASZ,       /* szPma */
14717   /* All the rest should always be initialized to zero */
14718   0,                         /* isInit */
14719   0,                         /* inProgress */
14720   0,                         /* isMutexInit */
14721   0,                         /* isMallocInit */
14722   0,                         /* isPCacheInit */
14723   0,                         /* nRefInitMutex */
14724   0,                         /* pInitMutex */
14725   0,                         /* xLog */
14726   0,                         /* pLogArg */
14727#ifdef SQLITE_ENABLE_SQLLOG
14728   0,                         /* xSqllog */
14729   0,                         /* pSqllogArg */
14730#endif
14731#ifdef SQLITE_VDBE_COVERAGE
14732   0,                         /* xVdbeBranch */
14733   0,                         /* pVbeBranchArg */
14734#endif
14735#ifndef SQLITE_OMIT_BUILTIN_TEST
14736   0,                         /* xTestCallback */
14737#endif
14738   0                          /* bLocaltimeFault */
14739};
14740
14741/*
14742** Hash table for global functions - functions common to all
14743** database connections.  After initialization, this table is
14744** read-only.
14745*/
14746SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
14747
14748/*
14749** Constant tokens for values 0 and 1.
14750*/
14751SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
14752   { "0", 1 },
14753   { "1", 1 }
14754};
14755
14756
14757/*
14758** The value of the "pending" byte must be 0x40000000 (1 byte past the
14759** 1-gibabyte boundary) in a compatible database.  SQLite never uses
14760** the database page that contains the pending byte.  It never attempts
14761** to read or write that page.  The pending byte page is set assign
14762** for use by the VFS layers as space for managing file locks.
14763**
14764** During testing, it is often desirable to move the pending byte to
14765** a different position in the file.  This allows code that has to
14766** deal with the pending byte to run on files that are much smaller
14767** than 1 GiB.  The sqlite3_test_control() interface can be used to
14768** move the pending byte.
14769**
14770** IMPORTANT:  Changing the pending byte to any value other than
14771** 0x40000000 results in an incompatible database file format!
14772** Changing the pending byte during operation will result in undefined
14773** and incorrect behavior.
14774*/
14775#ifndef SQLITE_OMIT_WSD
14776SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
14777#endif
14778
14779/* #include "opcodes.h" */
14780/*
14781** Properties of opcodes.  The OPFLG_INITIALIZER macro is
14782** created by mkopcodeh.awk during compilation.  Data is obtained
14783** from the comments following the "case OP_xxxx:" statements in
14784** the vdbe.c file.
14785*/
14786SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
14787
14788/************** End of global.c **********************************************/
14789/************** Begin file ctime.c *******************************************/
14790/*
14791** 2010 February 23
14792**
14793** The author disclaims copyright to this source code.  In place of
14794** a legal notice, here is a blessing:
14795**
14796**    May you do good and not evil.
14797**    May you find forgiveness for yourself and forgive others.
14798**    May you share freely, never taking more than you give.
14799**
14800*************************************************************************
14801**
14802** This file implements routines used to report what compile-time options
14803** SQLite was built with.
14804*/
14805
14806#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
14807
14808/* #include "sqliteInt.h" */
14809
14810/*
14811** An array of names of all compile-time options.  This array should
14812** be sorted A-Z.
14813**
14814** This array looks large, but in a typical installation actually uses
14815** only a handful of compile-time options, so most times this array is usually
14816** rather short and uses little memory space.
14817*/
14818static const char * const azCompileOpt[] = {
14819
14820/* These macros are provided to "stringify" the value of the define
14821** for those options in which the value is meaningful. */
14822#define CTIMEOPT_VAL_(opt) #opt
14823#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14824
14825#if SQLITE_32BIT_ROWID
14826  "32BIT_ROWID",
14827#endif
14828#if SQLITE_4_BYTE_ALIGNED_MALLOC
14829  "4_BYTE_ALIGNED_MALLOC",
14830#endif
14831#if SQLITE_CASE_SENSITIVE_LIKE
14832  "CASE_SENSITIVE_LIKE",
14833#endif
14834#if SQLITE_CHECK_PAGES
14835  "CHECK_PAGES",
14836#endif
14837#if SQLITE_COVERAGE_TEST
14838  "COVERAGE_TEST",
14839#endif
14840#if SQLITE_DEBUG
14841  "DEBUG",
14842#endif
14843#if SQLITE_DEFAULT_LOCKING_MODE
14844  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
14845#endif
14846#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
14847  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
14848#endif
14849#if SQLITE_DISABLE_DIRSYNC
14850  "DISABLE_DIRSYNC",
14851#endif
14852#if SQLITE_DISABLE_LFS
14853  "DISABLE_LFS",
14854#endif
14855#if SQLITE_ENABLE_API_ARMOR
14856  "ENABLE_API_ARMOR",
14857#endif
14858#if SQLITE_ENABLE_ATOMIC_WRITE
14859  "ENABLE_ATOMIC_WRITE",
14860#endif
14861#if SQLITE_ENABLE_CEROD
14862  "ENABLE_CEROD",
14863#endif
14864#if SQLITE_ENABLE_COLUMN_METADATA
14865  "ENABLE_COLUMN_METADATA",
14866#endif
14867#if SQLITE_ENABLE_DBSTAT_VTAB
14868  "ENABLE_DBSTAT_VTAB",
14869#endif
14870#if SQLITE_ENABLE_EXPENSIVE_ASSERT
14871  "ENABLE_EXPENSIVE_ASSERT",
14872#endif
14873#if SQLITE_ENABLE_FTS1
14874  "ENABLE_FTS1",
14875#endif
14876#if SQLITE_ENABLE_FTS2
14877  "ENABLE_FTS2",
14878#endif
14879#if SQLITE_ENABLE_FTS3
14880  "ENABLE_FTS3",
14881#endif
14882#if SQLITE_ENABLE_FTS3_PARENTHESIS
14883  "ENABLE_FTS3_PARENTHESIS",
14884#endif
14885#if SQLITE_ENABLE_FTS4
14886  "ENABLE_FTS4",
14887#endif
14888#if SQLITE_ENABLE_FTS5
14889  "ENABLE_FTS5",
14890#endif
14891#if SQLITE_ENABLE_ICU
14892  "ENABLE_ICU",
14893#endif
14894#if SQLITE_ENABLE_IOTRACE
14895  "ENABLE_IOTRACE",
14896#endif
14897#if SQLITE_ENABLE_JSON1
14898  "ENABLE_JSON1",
14899#endif
14900#if SQLITE_ENABLE_LOAD_EXTENSION
14901  "ENABLE_LOAD_EXTENSION",
14902#endif
14903#if SQLITE_ENABLE_LOCKING_STYLE
14904  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
14905#endif
14906#if SQLITE_ENABLE_MEMORY_MANAGEMENT
14907  "ENABLE_MEMORY_MANAGEMENT",
14908#endif
14909#if SQLITE_ENABLE_MEMSYS3
14910  "ENABLE_MEMSYS3",
14911#endif
14912#if SQLITE_ENABLE_MEMSYS5
14913  "ENABLE_MEMSYS5",
14914#endif
14915#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
14916  "ENABLE_OVERSIZE_CELL_CHECK",
14917#endif
14918#if SQLITE_ENABLE_RTREE
14919  "ENABLE_RTREE",
14920#endif
14921#if defined(SQLITE_ENABLE_STAT4)
14922  "ENABLE_STAT4",
14923#elif defined(SQLITE_ENABLE_STAT3)
14924  "ENABLE_STAT3",
14925#endif
14926#if SQLITE_ENABLE_UNLOCK_NOTIFY
14927  "ENABLE_UNLOCK_NOTIFY",
14928#endif
14929#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
14930  "ENABLE_UPDATE_DELETE_LIMIT",
14931#endif
14932#if SQLITE_HAS_CODEC
14933  "HAS_CODEC",
14934#endif
14935#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
14936  "HAVE_ISNAN",
14937#endif
14938#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14939  "HOMEGROWN_RECURSIVE_MUTEX",
14940#endif
14941#if SQLITE_IGNORE_AFP_LOCK_ERRORS
14942  "IGNORE_AFP_LOCK_ERRORS",
14943#endif
14944#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
14945  "IGNORE_FLOCK_LOCK_ERRORS",
14946#endif
14947#ifdef SQLITE_INT64_TYPE
14948  "INT64_TYPE",
14949#endif
14950#if SQLITE_LOCK_TRACE
14951  "LOCK_TRACE",
14952#endif
14953#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
14954  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
14955#endif
14956#ifdef SQLITE_MAX_SCHEMA_RETRY
14957  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
14958#endif
14959#if SQLITE_MEMDEBUG
14960  "MEMDEBUG",
14961#endif
14962#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
14963  "MIXED_ENDIAN_64BIT_FLOAT",
14964#endif
14965#if SQLITE_NO_SYNC
14966  "NO_SYNC",
14967#endif
14968#if SQLITE_OMIT_ALTERTABLE
14969  "OMIT_ALTERTABLE",
14970#endif
14971#if SQLITE_OMIT_ANALYZE
14972  "OMIT_ANALYZE",
14973#endif
14974#if SQLITE_OMIT_ATTACH
14975  "OMIT_ATTACH",
14976#endif
14977#if SQLITE_OMIT_AUTHORIZATION
14978  "OMIT_AUTHORIZATION",
14979#endif
14980#if SQLITE_OMIT_AUTOINCREMENT
14981  "OMIT_AUTOINCREMENT",
14982#endif
14983#if SQLITE_OMIT_AUTOINIT
14984  "OMIT_AUTOINIT",
14985#endif
14986#if SQLITE_OMIT_AUTOMATIC_INDEX
14987  "OMIT_AUTOMATIC_INDEX",
14988#endif
14989#if SQLITE_OMIT_AUTORESET
14990  "OMIT_AUTORESET",
14991#endif
14992#if SQLITE_OMIT_AUTOVACUUM
14993  "OMIT_AUTOVACUUM",
14994#endif
14995#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
14996  "OMIT_BETWEEN_OPTIMIZATION",
14997#endif
14998#if SQLITE_OMIT_BLOB_LITERAL
14999  "OMIT_BLOB_LITERAL",
15000#endif
15001#if SQLITE_OMIT_BTREECOUNT
15002  "OMIT_BTREECOUNT",
15003#endif
15004#if SQLITE_OMIT_BUILTIN_TEST
15005  "OMIT_BUILTIN_TEST",
15006#endif
15007#if SQLITE_OMIT_CAST
15008  "OMIT_CAST",
15009#endif
15010#if SQLITE_OMIT_CHECK
15011  "OMIT_CHECK",
15012#endif
15013#if SQLITE_OMIT_COMPLETE
15014  "OMIT_COMPLETE",
15015#endif
15016#if SQLITE_OMIT_COMPOUND_SELECT
15017  "OMIT_COMPOUND_SELECT",
15018#endif
15019#if SQLITE_OMIT_CTE
15020  "OMIT_CTE",
15021#endif
15022#if SQLITE_OMIT_DATETIME_FUNCS
15023  "OMIT_DATETIME_FUNCS",
15024#endif
15025#if SQLITE_OMIT_DECLTYPE
15026  "OMIT_DECLTYPE",
15027#endif
15028#if SQLITE_OMIT_DEPRECATED
15029  "OMIT_DEPRECATED",
15030#endif
15031#if SQLITE_OMIT_DISKIO
15032  "OMIT_DISKIO",
15033#endif
15034#if SQLITE_OMIT_EXPLAIN
15035  "OMIT_EXPLAIN",
15036#endif
15037#if SQLITE_OMIT_FLAG_PRAGMAS
15038  "OMIT_FLAG_PRAGMAS",
15039#endif
15040#if SQLITE_OMIT_FLOATING_POINT
15041  "OMIT_FLOATING_POINT",
15042#endif
15043#if SQLITE_OMIT_FOREIGN_KEY
15044  "OMIT_FOREIGN_KEY",
15045#endif
15046#if SQLITE_OMIT_GET_TABLE
15047  "OMIT_GET_TABLE",
15048#endif
15049#if SQLITE_OMIT_INCRBLOB
15050  "OMIT_INCRBLOB",
15051#endif
15052#if SQLITE_OMIT_INTEGRITY_CHECK
15053  "OMIT_INTEGRITY_CHECK",
15054#endif
15055#if SQLITE_OMIT_LIKE_OPTIMIZATION
15056  "OMIT_LIKE_OPTIMIZATION",
15057#endif
15058#if SQLITE_OMIT_LOAD_EXTENSION
15059  "OMIT_LOAD_EXTENSION",
15060#endif
15061#if SQLITE_OMIT_LOCALTIME
15062  "OMIT_LOCALTIME",
15063#endif
15064#if SQLITE_OMIT_LOOKASIDE
15065  "OMIT_LOOKASIDE",
15066#endif
15067#if SQLITE_OMIT_MEMORYDB
15068  "OMIT_MEMORYDB",
15069#endif
15070#if SQLITE_OMIT_OR_OPTIMIZATION
15071  "OMIT_OR_OPTIMIZATION",
15072#endif
15073#if SQLITE_OMIT_PAGER_PRAGMAS
15074  "OMIT_PAGER_PRAGMAS",
15075#endif
15076#if SQLITE_OMIT_PRAGMA
15077  "OMIT_PRAGMA",
15078#endif
15079#if SQLITE_OMIT_PROGRESS_CALLBACK
15080  "OMIT_PROGRESS_CALLBACK",
15081#endif
15082#if SQLITE_OMIT_QUICKBALANCE
15083  "OMIT_QUICKBALANCE",
15084#endif
15085#if SQLITE_OMIT_REINDEX
15086  "OMIT_REINDEX",
15087#endif
15088#if SQLITE_OMIT_SCHEMA_PRAGMAS
15089  "OMIT_SCHEMA_PRAGMAS",
15090#endif
15091#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
15092  "OMIT_SCHEMA_VERSION_PRAGMAS",
15093#endif
15094#if SQLITE_OMIT_SHARED_CACHE
15095  "OMIT_SHARED_CACHE",
15096#endif
15097#if SQLITE_OMIT_SUBQUERY
15098  "OMIT_SUBQUERY",
15099#endif
15100#if SQLITE_OMIT_TCL_VARIABLE
15101  "OMIT_TCL_VARIABLE",
15102#endif
15103#if SQLITE_OMIT_TEMPDB
15104  "OMIT_TEMPDB",
15105#endif
15106#if SQLITE_OMIT_TRACE
15107  "OMIT_TRACE",
15108#endif
15109#if SQLITE_OMIT_TRIGGER
15110  "OMIT_TRIGGER",
15111#endif
15112#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
15113  "OMIT_TRUNCATE_OPTIMIZATION",
15114#endif
15115#if SQLITE_OMIT_UTF16
15116  "OMIT_UTF16",
15117#endif
15118#if SQLITE_OMIT_VACUUM
15119  "OMIT_VACUUM",
15120#endif
15121#if SQLITE_OMIT_VIEW
15122  "OMIT_VIEW",
15123#endif
15124#if SQLITE_OMIT_VIRTUALTABLE
15125  "OMIT_VIRTUALTABLE",
15126#endif
15127#if SQLITE_OMIT_WAL
15128  "OMIT_WAL",
15129#endif
15130#if SQLITE_OMIT_WSD
15131  "OMIT_WSD",
15132#endif
15133#if SQLITE_OMIT_XFER_OPT
15134  "OMIT_XFER_OPT",
15135#endif
15136#if SQLITE_PERFORMANCE_TRACE
15137  "PERFORMANCE_TRACE",
15138#endif
15139#if SQLITE_PROXY_DEBUG
15140  "PROXY_DEBUG",
15141#endif
15142#if SQLITE_RTREE_INT_ONLY
15143  "RTREE_INT_ONLY",
15144#endif
15145#if SQLITE_SECURE_DELETE
15146  "SECURE_DELETE",
15147#endif
15148#if SQLITE_SMALL_STACK
15149  "SMALL_STACK",
15150#endif
15151#if SQLITE_SOUNDEX
15152  "SOUNDEX",
15153#endif
15154#if SQLITE_SYSTEM_MALLOC
15155  "SYSTEM_MALLOC",
15156#endif
15157#if SQLITE_TCL
15158  "TCL",
15159#endif
15160#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
15161  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
15162#endif
15163#if SQLITE_TEST
15164  "TEST",
15165#endif
15166#if defined(SQLITE_THREADSAFE)
15167  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
15168#endif
15169#if SQLITE_USE_ALLOCA
15170  "USE_ALLOCA",
15171#endif
15172#if SQLITE_USER_AUTHENTICATION
15173  "USER_AUTHENTICATION",
15174#endif
15175#if SQLITE_WIN32_MALLOC
15176  "WIN32_MALLOC",
15177#endif
15178#if SQLITE_ZERO_MALLOC
15179  "ZERO_MALLOC"
15180#endif
15181};
15182
15183/*
15184** Given the name of a compile-time option, return true if that option
15185** was used and false if not.
15186**
15187** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
15188** is not required for a match.
15189*/
15190SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
15191  int i, n;
15192
15193#if SQLITE_ENABLE_API_ARMOR
15194  if( zOptName==0 ){
15195    (void)SQLITE_MISUSE_BKPT;
15196    return 0;
15197  }
15198#endif
15199  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
15200  n = sqlite3Strlen30(zOptName);
15201
15202  /* Since ArraySize(azCompileOpt) is normally in single digits, a
15203  ** linear search is adequate.  No need for a binary search. */
15204  for(i=0; i<ArraySize(azCompileOpt); i++){
15205    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
15206     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
15207    ){
15208      return 1;
15209    }
15210  }
15211  return 0;
15212}
15213
15214/*
15215** Return the N-th compile-time option string.  If N is out of range,
15216** return a NULL pointer.
15217*/
15218SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
15219  if( N>=0 && N<ArraySize(azCompileOpt) ){
15220    return azCompileOpt[N];
15221  }
15222  return 0;
15223}
15224
15225#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
15226
15227/************** End of ctime.c ***********************************************/
15228/************** Begin file status.c ******************************************/
15229/*
15230** 2008 June 18
15231**
15232** The author disclaims copyright to this source code.  In place of
15233** a legal notice, here is a blessing:
15234**
15235**    May you do good and not evil.
15236**    May you find forgiveness for yourself and forgive others.
15237**    May you share freely, never taking more than you give.
15238**
15239*************************************************************************
15240**
15241** This module implements the sqlite3_status() interface and related
15242** functionality.
15243*/
15244/* #include "sqliteInt.h" */
15245/************** Include vdbeInt.h in the middle of status.c ******************/
15246/************** Begin file vdbeInt.h *****************************************/
15247/*
15248** 2003 September 6
15249**
15250** The author disclaims copyright to this source code.  In place of
15251** a legal notice, here is a blessing:
15252**
15253**    May you do good and not evil.
15254**    May you find forgiveness for yourself and forgive others.
15255**    May you share freely, never taking more than you give.
15256**
15257*************************************************************************
15258** This is the header file for information that is private to the
15259** VDBE.  This information used to all be at the top of the single
15260** source code file "vdbe.c".  When that file became too big (over
15261** 6000 lines long) it was split up into several smaller files and
15262** this header information was factored out.
15263*/
15264#ifndef _VDBEINT_H_
15265#define _VDBEINT_H_
15266
15267/*
15268** The maximum number of times that a statement will try to reparse
15269** itself before giving up and returning SQLITE_SCHEMA.
15270*/
15271#ifndef SQLITE_MAX_SCHEMA_RETRY
15272# define SQLITE_MAX_SCHEMA_RETRY 50
15273#endif
15274
15275/*
15276** SQL is translated into a sequence of instructions to be
15277** executed by a virtual machine.  Each instruction is an instance
15278** of the following structure.
15279*/
15280typedef struct VdbeOp Op;
15281
15282/*
15283** Boolean values
15284*/
15285typedef unsigned Bool;
15286
15287/* Opaque type used by code in vdbesort.c */
15288typedef struct VdbeSorter VdbeSorter;
15289
15290/* Opaque type used by the explainer */
15291typedef struct Explain Explain;
15292
15293/* Elements of the linked list at Vdbe.pAuxData */
15294typedef struct AuxData AuxData;
15295
15296/*
15297** A cursor is a pointer into a single BTree within a database file.
15298** The cursor can seek to a BTree entry with a particular key, or
15299** loop over all entries of the Btree.  You can also insert new BTree
15300** entries or retrieve the key or data from the entry that the cursor
15301** is currently pointing to.
15302**
15303** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
15304** A pseudo-table is a single-row table implemented by registers.
15305**
15306** Every cursor that the virtual machine has open is represented by an
15307** instance of the following structure.
15308*/
15309struct VdbeCursor {
15310  BtCursor *pCursor;    /* The cursor structure of the backend */
15311  Btree *pBt;           /* Separate file holding temporary table */
15312  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
15313  int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
15314  int pseudoTableReg;   /* Register holding pseudotable content. */
15315  i16 nField;           /* Number of fields in the header */
15316  u16 nHdrParsed;       /* Number of header fields parsed so far */
15317#ifdef SQLITE_DEBUG
15318  u8 seekOp;            /* Most recent seek operation on this cursor */
15319#endif
15320  i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
15321  u8 nullRow;           /* True if pointing to a row with no data */
15322  u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
15323  Bool isEphemeral:1;   /* True for an ephemeral table */
15324  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
15325  Bool isTable:1;       /* True if a table requiring integer keys */
15326  Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
15327  Pgno pgnoRoot;        /* Root page of the open btree cursor */
15328  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
15329  i64 seqCount;         /* Sequence counter */
15330  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
15331  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
15332#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
15333  u64 maskUsed;         /* Mask of columns used by this cursor */
15334#endif
15335
15336  /* Cached information about the header for the data record that the
15337  ** cursor is currently pointing to.  Only valid if cacheStatus matches
15338  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
15339  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
15340  ** the cache is out of date.
15341  **
15342  ** aRow might point to (ephemeral) data for the current row, or it might
15343  ** be NULL.
15344  */
15345  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
15346  u32 payloadSize;      /* Total number of bytes in the record */
15347  u32 szRow;            /* Byte available in aRow */
15348  u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
15349  const u8 *aRow;       /* Data for the current row, if all on one page */
15350  u32 *aOffset;         /* Pointer to aType[nField] */
15351  u32 aType[1];         /* Type values for all entries in the record */
15352  /* 2*nField extra array elements allocated for aType[], beyond the one
15353  ** static element declared in the structure.  nField total array slots for
15354  ** aType[] and nField+1 array slots for aOffset[] */
15355};
15356typedef struct VdbeCursor VdbeCursor;
15357
15358/*
15359** When a sub-program is executed (OP_Program), a structure of this type
15360** is allocated to store the current value of the program counter, as
15361** well as the current memory cell array and various other frame specific
15362** values stored in the Vdbe struct. When the sub-program is finished,
15363** these values are copied back to the Vdbe from the VdbeFrame structure,
15364** restoring the state of the VM to as it was before the sub-program
15365** began executing.
15366**
15367** The memory for a VdbeFrame object is allocated and managed by a memory
15368** cell in the parent (calling) frame. When the memory cell is deleted or
15369** overwritten, the VdbeFrame object is not freed immediately. Instead, it
15370** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
15371** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
15372** this instead of deleting the VdbeFrame immediately is to avoid recursive
15373** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
15374** child frame are released.
15375**
15376** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
15377** set to NULL if the currently executing frame is the main program.
15378*/
15379typedef struct VdbeFrame VdbeFrame;
15380struct VdbeFrame {
15381  Vdbe *v;                /* VM this frame belongs to */
15382  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
15383  Op *aOp;                /* Program instructions for parent frame */
15384  i64 *anExec;            /* Event counters from parent frame */
15385  Mem *aMem;              /* Array of memory cells for parent frame */
15386  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
15387  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
15388  void *token;            /* Copy of SubProgram.token */
15389  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
15390  int nCursor;            /* Number of entries in apCsr */
15391  int pc;                 /* Program Counter in parent (calling) frame */
15392  int nOp;                /* Size of aOp array */
15393  int nMem;               /* Number of entries in aMem */
15394  int nOnceFlag;          /* Number of entries in aOnceFlag */
15395  int nChildMem;          /* Number of memory cells for child frame */
15396  int nChildCsr;          /* Number of cursors for child frame */
15397  int nChange;            /* Statement changes (Vdbe.nChange)     */
15398  int nDbChange;          /* Value of db->nChange */
15399};
15400
15401#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
15402
15403/*
15404** A value for VdbeCursor.cacheValid that means the cache is always invalid.
15405*/
15406#define CACHE_STALE 0
15407
15408/*
15409** Internally, the vdbe manipulates nearly all SQL values as Mem
15410** structures. Each Mem struct may cache multiple representations (string,
15411** integer etc.) of the same value.
15412*/
15413struct Mem {
15414  union MemValue {
15415    double r;           /* Real value used when MEM_Real is set in flags */
15416    i64 i;              /* Integer value used when MEM_Int is set in flags */
15417    int nZero;          /* Used when bit MEM_Zero is set in flags */
15418    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
15419    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
15420    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
15421  } u;
15422  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
15423  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
15424  u8  eSubtype;       /* Subtype for this value */
15425  int n;              /* Number of characters in string value, excluding '\0' */
15426  char *z;            /* String or BLOB value */
15427  /* ShallowCopy only needs to copy the information above */
15428  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
15429  int szMalloc;       /* Size of the zMalloc allocation */
15430  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
15431  sqlite3 *db;        /* The associated database connection */
15432  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
15433#ifdef SQLITE_DEBUG
15434  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
15435  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
15436#endif
15437};
15438
15439/*
15440** Size of struct Mem not including the Mem.zMalloc member or anything that
15441** follows.
15442*/
15443#define MEMCELLSIZE offsetof(Mem,zMalloc)
15444
15445/* One or more of the following flags are set to indicate the validOK
15446** representations of the value stored in the Mem struct.
15447**
15448** If the MEM_Null flag is set, then the value is an SQL NULL value.
15449** No other flags may be set in this case.
15450**
15451** If the MEM_Str flag is set then Mem.z points at a string representation.
15452** Usually this is encoded in the same unicode encoding as the main
15453** database (see below for exceptions). If the MEM_Term flag is also
15454** set, then the string is nul terminated. The MEM_Int and MEM_Real
15455** flags may coexist with the MEM_Str flag.
15456*/
15457#define MEM_Null      0x0001   /* Value is NULL */
15458#define MEM_Str       0x0002   /* Value is a string */
15459#define MEM_Int       0x0004   /* Value is an integer */
15460#define MEM_Real      0x0008   /* Value is a real number */
15461#define MEM_Blob      0x0010   /* Value is a BLOB */
15462#define MEM_AffMask   0x001f   /* Mask of affinity bits */
15463#define MEM_RowSet    0x0020   /* Value is a RowSet object */
15464#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
15465#define MEM_Undefined 0x0080   /* Value is undefined */
15466#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
15467#define MEM_TypeMask  0x01ff   /* Mask of type bits */
15468
15469
15470/* Whenever Mem contains a valid string or blob representation, one of
15471** the following flags must be set to determine the memory management
15472** policy for Mem.z.  The MEM_Term flag tells us whether or not the
15473** string is \000 or \u0000 terminated
15474*/
15475#define MEM_Term      0x0200   /* String rep is nul terminated */
15476#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
15477#define MEM_Static    0x0800   /* Mem.z points to a static string */
15478#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
15479#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
15480#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
15481#ifdef SQLITE_OMIT_INCRBLOB
15482  #undef MEM_Zero
15483  #define MEM_Zero 0x0000
15484#endif
15485
15486/*
15487** Clear any existing type flags from a Mem and replace them with f
15488*/
15489#define MemSetTypeFlag(p, f) \
15490   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
15491
15492/*
15493** Return true if a memory cell is not marked as invalid.  This macro
15494** is for use inside assert() statements only.
15495*/
15496#ifdef SQLITE_DEBUG
15497#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
15498#endif
15499
15500/*
15501** Each auxiliary data pointer stored by a user defined function
15502** implementation calling sqlite3_set_auxdata() is stored in an instance
15503** of this structure. All such structures associated with a single VM
15504** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
15505** when the VM is halted (if not before).
15506*/
15507struct AuxData {
15508  int iOp;                        /* Instruction number of OP_Function opcode */
15509  int iArg;                       /* Index of function argument. */
15510  void *pAux;                     /* Aux data pointer */
15511  void (*xDelete)(void *);        /* Destructor for the aux data */
15512  AuxData *pNext;                 /* Next element in list */
15513};
15514
15515/*
15516** The "context" argument for an installable function.  A pointer to an
15517** instance of this structure is the first argument to the routines used
15518** implement the SQL functions.
15519**
15520** There is a typedef for this structure in sqlite.h.  So all routines,
15521** even the public interface to SQLite, can use a pointer to this structure.
15522** But this file is the only place where the internal details of this
15523** structure are known.
15524**
15525** This structure is defined inside of vdbeInt.h because it uses substructures
15526** (Mem) which are only defined there.
15527*/
15528struct sqlite3_context {
15529  Mem *pOut;              /* The return value is stored here */
15530  FuncDef *pFunc;         /* Pointer to function information */
15531  Mem *pMem;              /* Memory cell used to store aggregate context */
15532  Vdbe *pVdbe;            /* The VM that owns this context */
15533  int iOp;                /* Instruction number of OP_Function */
15534  int isError;            /* Error code returned by the function. */
15535  u8 skipFlag;            /* Skip accumulator loading if true */
15536  u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
15537  u8 argc;                /* Number of arguments */
15538  sqlite3_value *argv[1]; /* Argument set */
15539};
15540
15541/*
15542** An Explain object accumulates indented output which is helpful
15543** in describing recursive data structures.
15544*/
15545struct Explain {
15546  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
15547  StrAccum str;      /* The string being accumulated */
15548  int nIndent;       /* Number of elements in aIndent */
15549  u16 aIndent[100];  /* Levels of indentation */
15550  char zBase[100];   /* Initial space */
15551};
15552
15553/* A bitfield type for use inside of structures.  Always follow with :N where
15554** N is the number of bits.
15555*/
15556typedef unsigned bft;  /* Bit Field Type */
15557
15558typedef struct ScanStatus ScanStatus;
15559struct ScanStatus {
15560  int addrExplain;                /* OP_Explain for loop */
15561  int addrLoop;                   /* Address of "loops" counter */
15562  int addrVisit;                  /* Address of "rows visited" counter */
15563  int iSelectID;                  /* The "Select-ID" for this loop */
15564  LogEst nEst;                    /* Estimated output rows per loop */
15565  char *zName;                    /* Name of table or index */
15566};
15567
15568/*
15569** An instance of the virtual machine.  This structure contains the complete
15570** state of the virtual machine.
15571**
15572** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
15573** is really a pointer to an instance of this structure.
15574*/
15575struct Vdbe {
15576  sqlite3 *db;            /* The database connection that owns this statement */
15577  Op *aOp;                /* Space to hold the virtual machine's program */
15578  Mem *aMem;              /* The memory locations */
15579  Mem **apArg;            /* Arguments to currently executing user function */
15580  Mem *aColName;          /* Column names to return */
15581  Mem *pResultSet;        /* Pointer to an array of results */
15582  Parse *pParse;          /* Parsing context used to create this Vdbe */
15583  int nMem;               /* Number of memory locations currently allocated */
15584  int nOp;                /* Number of instructions in the program */
15585  int nCursor;            /* Number of slots in apCsr[] */
15586  u32 magic;              /* Magic number for sanity checking */
15587  char *zErrMsg;          /* Error message written here */
15588  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
15589  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
15590  Mem *aVar;              /* Values for the OP_Variable opcode. */
15591  char **azVar;           /* Name of variables */
15592  ynVar nVar;             /* Number of entries in aVar[] */
15593  ynVar nzVar;            /* Number of entries in azVar[] */
15594  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
15595  int pc;                 /* The program counter */
15596  int rc;                 /* Value to return */
15597#ifdef SQLITE_DEBUG
15598  int rcApp;              /* errcode set by sqlite3_result_error_code() */
15599#endif
15600  u16 nResColumn;         /* Number of columns in one row of the result set */
15601  u8 errorAction;         /* Recovery action to do in case of an error */
15602  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
15603  bft explain:2;          /* True if EXPLAIN present on SQL command */
15604  bft changeCntOn:1;      /* True to update the change-counter */
15605  bft expired:1;          /* True if the VM needs to be recompiled */
15606  bft runOnlyOnce:1;      /* Automatically expire on reset */
15607  bft usesStmtJournal:1;  /* True if uses a statement journal */
15608  bft readOnly:1;         /* True for statements that do not write */
15609  bft bIsReader:1;        /* True for statements that read */
15610  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
15611  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
15612  int nChange;            /* Number of db changes made since last reset */
15613  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
15614  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
15615  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
15616  u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
15617#ifndef SQLITE_OMIT_TRACE
15618  i64 startTime;          /* Time when query started - used for profiling */
15619#endif
15620  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
15621  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
15622  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
15623  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
15624  char *zSql;             /* Text of the SQL statement that generated this */
15625  void *pFree;            /* Free this when deleting the vdbe */
15626  VdbeFrame *pFrame;      /* Parent frame */
15627  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
15628  int nFrame;             /* Number of frames in pFrame list */
15629  u32 expmask;            /* Binding to these vars invalidates VM */
15630  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
15631  int nOnceFlag;          /* Size of array aOnceFlag[] */
15632  u8 *aOnceFlag;          /* Flags for OP_Once */
15633  AuxData *pAuxData;      /* Linked list of auxdata allocations */
15634#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
15635  i64 *anExec;            /* Number of times each op has been executed */
15636  int nScan;              /* Entries in aScan[] */
15637  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
15638#endif
15639};
15640
15641/*
15642** The following are allowed values for Vdbe.magic
15643*/
15644#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
15645#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
15646#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
15647#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
15648
15649/*
15650** Function prototypes
15651*/
15652SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
15653SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
15654void sqliteVdbePopStack(Vdbe*,int);
15655SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
15656SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
15657#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
15658SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
15659#endif
15660SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
15661SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
15662SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
15663SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
15664SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
15665
15666int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
15667SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
15668SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
15669SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
15670SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
15671SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
15672SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
15673SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
15674SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
15675SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
15676SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
15677SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
15678SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
15679SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
15680#ifdef SQLITE_OMIT_FLOATING_POINT
15681# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
15682#else
15683SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
15684#endif
15685SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
15686SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
15687SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
15688SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
15689SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
15690SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
15691SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
15692SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
15693SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
15694SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
15695SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
15696SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
15697SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
15698SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
15699SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
15700#define VdbeMemDynamic(X)  \
15701  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
15702SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
15703SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
15704SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
15705SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
15706SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
15707SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
15708SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
15709SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
15710
15711SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
15712SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
15713SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
15714SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
15715SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
15716SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
15717SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
15718SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
15719
15720#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
15721SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
15722SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
15723#else
15724# define sqlite3VdbeEnter(X)
15725# define sqlite3VdbeLeave(X)
15726#endif
15727
15728#ifdef SQLITE_DEBUG
15729SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
15730SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
15731#endif
15732
15733#ifndef SQLITE_OMIT_FOREIGN_KEY
15734SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
15735#else
15736# define sqlite3VdbeCheckFk(p,i) 0
15737#endif
15738
15739SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
15740#ifdef SQLITE_DEBUG
15741SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
15742SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15743#endif
15744SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
15745
15746#ifndef SQLITE_OMIT_INCRBLOB
15747SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
15748  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
15749#else
15750  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
15751  #define ExpandBlob(P) SQLITE_OK
15752#endif
15753
15754#endif /* !defined(_VDBEINT_H_) */
15755
15756/************** End of vdbeInt.h *********************************************/
15757/************** Continuing where we left off in status.c *********************/
15758
15759/*
15760** Variables in which to record status information.
15761*/
15762typedef struct sqlite3StatType sqlite3StatType;
15763static SQLITE_WSD struct sqlite3StatType {
15764#if SQLITE_PTRSIZE>4
15765  sqlite3_int64 nowValue[10];         /* Current value */
15766  sqlite3_int64 mxValue[10];          /* Maximum value */
15767#else
15768  u32 nowValue[10];                   /* Current value */
15769  u32 mxValue[10];                    /* Maximum value */
15770#endif
15771} sqlite3Stat = { {0,}, {0,} };
15772
15773/*
15774** Elements of sqlite3Stat[] are protected by either the memory allocator
15775** mutex, or by the pcache1 mutex.  The following array determines which.
15776*/
15777static const char statMutex[] = {
15778  0,  /* SQLITE_STATUS_MEMORY_USED */
15779  1,  /* SQLITE_STATUS_PAGECACHE_USED */
15780  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
15781  0,  /* SQLITE_STATUS_SCRATCH_USED */
15782  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
15783  0,  /* SQLITE_STATUS_MALLOC_SIZE */
15784  0,  /* SQLITE_STATUS_PARSER_STACK */
15785  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
15786  0,  /* SQLITE_STATUS_SCRATCH_SIZE */
15787  0,  /* SQLITE_STATUS_MALLOC_COUNT */
15788};
15789
15790
15791/* The "wsdStat" macro will resolve to the status information
15792** state vector.  If writable static data is unsupported on the target,
15793** we have to locate the state vector at run-time.  In the more common
15794** case where writable static data is supported, wsdStat can refer directly
15795** to the "sqlite3Stat" state vector declared above.
15796*/
15797#ifdef SQLITE_OMIT_WSD
15798# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
15799# define wsdStat x[0]
15800#else
15801# define wsdStatInit
15802# define wsdStat sqlite3Stat
15803#endif
15804
15805/*
15806** Return the current value of a status parameter.  The caller must
15807** be holding the appropriate mutex.
15808*/
15809SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
15810  wsdStatInit;
15811  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15812  assert( op>=0 && op<ArraySize(statMutex) );
15813  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15814                                           : sqlite3MallocMutex()) );
15815  return wsdStat.nowValue[op];
15816}
15817
15818/*
15819** Add N to the value of a status record.  The caller must hold the
15820** appropriate mutex.  (Locking is checked by assert()).
15821**
15822** The StatusUp() routine can accept positive or negative values for N.
15823** The value of N is added to the current status value and the high-water
15824** mark is adjusted if necessary.
15825**
15826** The StatusDown() routine lowers the current value by N.  The highwater
15827** mark is unchanged.  N must be non-negative for StatusDown().
15828*/
15829SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
15830  wsdStatInit;
15831  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15832  assert( op>=0 && op<ArraySize(statMutex) );
15833  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15834                                           : sqlite3MallocMutex()) );
15835  wsdStat.nowValue[op] += N;
15836  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15837    wsdStat.mxValue[op] = wsdStat.nowValue[op];
15838  }
15839}
15840SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
15841  wsdStatInit;
15842  assert( N>=0 );
15843  assert( op>=0 && op<ArraySize(statMutex) );
15844  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15845                                           : sqlite3MallocMutex()) );
15846  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15847  wsdStat.nowValue[op] -= N;
15848}
15849
15850/*
15851** Set the value of a status to X.  The highwater mark is adjusted if
15852** necessary.  The caller must hold the appropriate mutex.
15853*/
15854SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
15855  wsdStatInit;
15856  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15857  assert( op>=0 && op<ArraySize(statMutex) );
15858  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15859                                           : sqlite3MallocMutex()) );
15860  wsdStat.nowValue[op] = X;
15861  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15862    wsdStat.mxValue[op] = wsdStat.nowValue[op];
15863  }
15864}
15865
15866/*
15867** Query status information.
15868*/
15869SQLITE_API int SQLITE_STDCALL sqlite3_status64(
15870  int op,
15871  sqlite3_int64 *pCurrent,
15872  sqlite3_int64 *pHighwater,
15873  int resetFlag
15874){
15875  sqlite3_mutex *pMutex;
15876  wsdStatInit;
15877  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15878    return SQLITE_MISUSE_BKPT;
15879  }
15880#ifdef SQLITE_ENABLE_API_ARMOR
15881  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15882#endif
15883  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
15884  sqlite3_mutex_enter(pMutex);
15885  *pCurrent = wsdStat.nowValue[op];
15886  *pHighwater = wsdStat.mxValue[op];
15887  if( resetFlag ){
15888    wsdStat.mxValue[op] = wsdStat.nowValue[op];
15889  }
15890  sqlite3_mutex_leave(pMutex);
15891  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
15892  return SQLITE_OK;
15893}
15894SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15895  sqlite3_int64 iCur, iHwtr;
15896  int rc;
15897#ifdef SQLITE_ENABLE_API_ARMOR
15898  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15899#endif
15900  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
15901  if( rc==0 ){
15902    *pCurrent = (int)iCur;
15903    *pHighwater = (int)iHwtr;
15904  }
15905  return rc;
15906}
15907
15908/*
15909** Query status information for a single database connection
15910*/
15911SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
15912  sqlite3 *db,          /* The database connection whose status is desired */
15913  int op,               /* Status verb */
15914  int *pCurrent,        /* Write current value here */
15915  int *pHighwater,      /* Write high-water mark here */
15916  int resetFlag         /* Reset high-water mark if true */
15917){
15918  int rc = SQLITE_OK;   /* Return code */
15919#ifdef SQLITE_ENABLE_API_ARMOR
15920  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
15921    return SQLITE_MISUSE_BKPT;
15922  }
15923#endif
15924  sqlite3_mutex_enter(db->mutex);
15925  switch( op ){
15926    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
15927      *pCurrent = db->lookaside.nOut;
15928      *pHighwater = db->lookaside.mxOut;
15929      if( resetFlag ){
15930        db->lookaside.mxOut = db->lookaside.nOut;
15931      }
15932      break;
15933    }
15934
15935    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
15936    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
15937    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
15938      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
15939      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
15940      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
15941      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
15942      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
15943      *pCurrent = 0;
15944      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
15945      if( resetFlag ){
15946        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
15947      }
15948      break;
15949    }
15950
15951    /*
15952    ** Return an approximation for the amount of memory currently used
15953    ** by all pagers associated with the given database connection.  The
15954    ** highwater mark is meaningless and is returned as zero.
15955    */
15956    case SQLITE_DBSTATUS_CACHE_USED: {
15957      int totalUsed = 0;
15958      int i;
15959      sqlite3BtreeEnterAll(db);
15960      for(i=0; i<db->nDb; i++){
15961        Btree *pBt = db->aDb[i].pBt;
15962        if( pBt ){
15963          Pager *pPager = sqlite3BtreePager(pBt);
15964          totalUsed += sqlite3PagerMemUsed(pPager);
15965        }
15966      }
15967      sqlite3BtreeLeaveAll(db);
15968      *pCurrent = totalUsed;
15969      *pHighwater = 0;
15970      break;
15971    }
15972
15973    /*
15974    ** *pCurrent gets an accurate estimate of the amount of memory used
15975    ** to store the schema for all databases (main, temp, and any ATTACHed
15976    ** databases.  *pHighwater is set to zero.
15977    */
15978    case SQLITE_DBSTATUS_SCHEMA_USED: {
15979      int i;                      /* Used to iterate through schemas */
15980      int nByte = 0;              /* Used to accumulate return value */
15981
15982      sqlite3BtreeEnterAll(db);
15983      db->pnBytesFreed = &nByte;
15984      for(i=0; i<db->nDb; i++){
15985        Schema *pSchema = db->aDb[i].pSchema;
15986        if( ALWAYS(pSchema!=0) ){
15987          HashElem *p;
15988
15989          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
15990              pSchema->tblHash.count
15991            + pSchema->trigHash.count
15992            + pSchema->idxHash.count
15993            + pSchema->fkeyHash.count
15994          );
15995          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
15996          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
15997          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
15998          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
15999
16000          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
16001            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
16002          }
16003          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
16004            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
16005          }
16006        }
16007      }
16008      db->pnBytesFreed = 0;
16009      sqlite3BtreeLeaveAll(db);
16010
16011      *pHighwater = 0;
16012      *pCurrent = nByte;
16013      break;
16014    }
16015
16016    /*
16017    ** *pCurrent gets an accurate estimate of the amount of memory used
16018    ** to store all prepared statements.
16019    ** *pHighwater is set to zero.
16020    */
16021    case SQLITE_DBSTATUS_STMT_USED: {
16022      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
16023      int nByte = 0;              /* Used to accumulate return value */
16024
16025      db->pnBytesFreed = &nByte;
16026      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
16027        sqlite3VdbeClearObject(db, pVdbe);
16028        sqlite3DbFree(db, pVdbe);
16029      }
16030      db->pnBytesFreed = 0;
16031
16032      *pHighwater = 0;  /* IMP: R-64479-57858 */
16033      *pCurrent = nByte;
16034
16035      break;
16036    }
16037
16038    /*
16039    ** Set *pCurrent to the total cache hits or misses encountered by all
16040    ** pagers the database handle is connected to. *pHighwater is always set
16041    ** to zero.
16042    */
16043    case SQLITE_DBSTATUS_CACHE_HIT:
16044    case SQLITE_DBSTATUS_CACHE_MISS:
16045    case SQLITE_DBSTATUS_CACHE_WRITE:{
16046      int i;
16047      int nRet = 0;
16048      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
16049      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
16050
16051      for(i=0; i<db->nDb; i++){
16052        if( db->aDb[i].pBt ){
16053          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
16054          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
16055        }
16056      }
16057      *pHighwater = 0; /* IMP: R-42420-56072 */
16058                       /* IMP: R-54100-20147 */
16059                       /* IMP: R-29431-39229 */
16060      *pCurrent = nRet;
16061      break;
16062    }
16063
16064    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
16065    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
16066    ** have been satisfied.  The *pHighwater is always set to zero.
16067    */
16068    case SQLITE_DBSTATUS_DEFERRED_FKS: {
16069      *pHighwater = 0;  /* IMP: R-11967-56545 */
16070      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
16071      break;
16072    }
16073
16074    default: {
16075      rc = SQLITE_ERROR;
16076    }
16077  }
16078  sqlite3_mutex_leave(db->mutex);
16079  return rc;
16080}
16081
16082/************** End of status.c **********************************************/
16083/************** Begin file date.c ********************************************/
16084/*
16085** 2003 October 31
16086**
16087** The author disclaims copyright to this source code.  In place of
16088** a legal notice, here is a blessing:
16089**
16090**    May you do good and not evil.
16091**    May you find forgiveness for yourself and forgive others.
16092**    May you share freely, never taking more than you give.
16093**
16094*************************************************************************
16095** This file contains the C functions that implement date and time
16096** functions for SQLite.
16097**
16098** There is only one exported symbol in this file - the function
16099** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
16100** All other code has file scope.
16101**
16102** SQLite processes all times and dates as julian day numbers.  The
16103** dates and times are stored as the number of days since noon
16104** in Greenwich on November 24, 4714 B.C. according to the Gregorian
16105** calendar system.
16106**
16107** 1970-01-01 00:00:00 is JD 2440587.5
16108** 2000-01-01 00:00:00 is JD 2451544.5
16109**
16110** This implementation requires years to be expressed as a 4-digit number
16111** which means that only dates between 0000-01-01 and 9999-12-31 can
16112** be represented, even though julian day numbers allow a much wider
16113** range of dates.
16114**
16115** The Gregorian calendar system is used for all dates and times,
16116** even those that predate the Gregorian calendar.  Historians usually
16117** use the julian calendar for dates prior to 1582-10-15 and for some
16118** dates afterwards, depending on locale.  Beware of this difference.
16119**
16120** The conversion algorithms are implemented based on descriptions
16121** in the following text:
16122**
16123**      Jean Meeus
16124**      Astronomical Algorithms, 2nd Edition, 1998
16125**      ISBM 0-943396-61-1
16126**      Willmann-Bell, Inc
16127**      Richmond, Virginia (USA)
16128*/
16129/* #include "sqliteInt.h" */
16130/* #include <stdlib.h> */
16131/* #include <assert.h> */
16132#include <time.h>
16133
16134#ifndef SQLITE_OMIT_DATETIME_FUNCS
16135
16136
16137/*
16138** A structure for holding a single date and time.
16139*/
16140typedef struct DateTime DateTime;
16141struct DateTime {
16142  sqlite3_int64 iJD; /* The julian day number times 86400000 */
16143  int Y, M, D;       /* Year, month, and day */
16144  int h, m;          /* Hour and minutes */
16145  int tz;            /* Timezone offset in minutes */
16146  double s;          /* Seconds */
16147  char validYMD;     /* True (1) if Y,M,D are valid */
16148  char validHMS;     /* True (1) if h,m,s are valid */
16149  char validJD;      /* True (1) if iJD is valid */
16150  char validTZ;      /* True (1) if tz is valid */
16151};
16152
16153
16154/*
16155** Convert zDate into one or more integers.  Additional arguments
16156** come in groups of 5 as follows:
16157**
16158**       N       number of digits in the integer
16159**       min     minimum allowed value of the integer
16160**       max     maximum allowed value of the integer
16161**       nextC   first character after the integer
16162**       pVal    where to write the integers value.
16163**
16164** Conversions continue until one with nextC==0 is encountered.
16165** The function returns the number of successful conversions.
16166*/
16167static int getDigits(const char *zDate, ...){
16168  va_list ap;
16169  int val;
16170  int N;
16171  int min;
16172  int max;
16173  int nextC;
16174  int *pVal;
16175  int cnt = 0;
16176  va_start(ap, zDate);
16177  do{
16178    N = va_arg(ap, int);
16179    min = va_arg(ap, int);
16180    max = va_arg(ap, int);
16181    nextC = va_arg(ap, int);
16182    pVal = va_arg(ap, int*);
16183    val = 0;
16184    while( N-- ){
16185      if( !sqlite3Isdigit(*zDate) ){
16186        goto end_getDigits;
16187      }
16188      val = val*10 + *zDate - '0';
16189      zDate++;
16190    }
16191    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
16192      goto end_getDigits;
16193    }
16194    *pVal = val;
16195    zDate++;
16196    cnt++;
16197  }while( nextC );
16198end_getDigits:
16199  va_end(ap);
16200  return cnt;
16201}
16202
16203/*
16204** Parse a timezone extension on the end of a date-time.
16205** The extension is of the form:
16206**
16207**        (+/-)HH:MM
16208**
16209** Or the "zulu" notation:
16210**
16211**        Z
16212**
16213** If the parse is successful, write the number of minutes
16214** of change in p->tz and return 0.  If a parser error occurs,
16215** return non-zero.
16216**
16217** A missing specifier is not considered an error.
16218*/
16219static int parseTimezone(const char *zDate, DateTime *p){
16220  int sgn = 0;
16221  int nHr, nMn;
16222  int c;
16223  while( sqlite3Isspace(*zDate) ){ zDate++; }
16224  p->tz = 0;
16225  c = *zDate;
16226  if( c=='-' ){
16227    sgn = -1;
16228  }else if( c=='+' ){
16229    sgn = +1;
16230  }else if( c=='Z' || c=='z' ){
16231    zDate++;
16232    goto zulu_time;
16233  }else{
16234    return c!=0;
16235  }
16236  zDate++;
16237  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
16238    return 1;
16239  }
16240  zDate += 5;
16241  p->tz = sgn*(nMn + nHr*60);
16242zulu_time:
16243  while( sqlite3Isspace(*zDate) ){ zDate++; }
16244  return *zDate!=0;
16245}
16246
16247/*
16248** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
16249** The HH, MM, and SS must each be exactly 2 digits.  The
16250** fractional seconds FFFF can be one or more digits.
16251**
16252** Return 1 if there is a parsing error and 0 on success.
16253*/
16254static int parseHhMmSs(const char *zDate, DateTime *p){
16255  int h, m, s;
16256  double ms = 0.0;
16257  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
16258    return 1;
16259  }
16260  zDate += 5;
16261  if( *zDate==':' ){
16262    zDate++;
16263    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
16264      return 1;
16265    }
16266    zDate += 2;
16267    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
16268      double rScale = 1.0;
16269      zDate++;
16270      while( sqlite3Isdigit(*zDate) ){
16271        ms = ms*10.0 + *zDate - '0';
16272        rScale *= 10.0;
16273        zDate++;
16274      }
16275      ms /= rScale;
16276    }
16277  }else{
16278    s = 0;
16279  }
16280  p->validJD = 0;
16281  p->validHMS = 1;
16282  p->h = h;
16283  p->m = m;
16284  p->s = s + ms;
16285  if( parseTimezone(zDate, p) ) return 1;
16286  p->validTZ = (p->tz!=0)?1:0;
16287  return 0;
16288}
16289
16290/*
16291** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
16292** that the YYYY-MM-DD is according to the Gregorian calendar.
16293**
16294** Reference:  Meeus page 61
16295*/
16296static void computeJD(DateTime *p){
16297  int Y, M, D, A, B, X1, X2;
16298
16299  if( p->validJD ) return;
16300  if( p->validYMD ){
16301    Y = p->Y;
16302    M = p->M;
16303    D = p->D;
16304  }else{
16305    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
16306    M = 1;
16307    D = 1;
16308  }
16309  if( M<=2 ){
16310    Y--;
16311    M += 12;
16312  }
16313  A = Y/100;
16314  B = 2 - A + (A/4);
16315  X1 = 36525*(Y+4716)/100;
16316  X2 = 306001*(M+1)/10000;
16317  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
16318  p->validJD = 1;
16319  if( p->validHMS ){
16320    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
16321    if( p->validTZ ){
16322      p->iJD -= p->tz*60000;
16323      p->validYMD = 0;
16324      p->validHMS = 0;
16325      p->validTZ = 0;
16326    }
16327  }
16328}
16329
16330/*
16331** Parse dates of the form
16332**
16333**     YYYY-MM-DD HH:MM:SS.FFF
16334**     YYYY-MM-DD HH:MM:SS
16335**     YYYY-MM-DD HH:MM
16336**     YYYY-MM-DD
16337**
16338** Write the result into the DateTime structure and return 0
16339** on success and 1 if the input string is not a well-formed
16340** date.
16341*/
16342static int parseYyyyMmDd(const char *zDate, DateTime *p){
16343  int Y, M, D, neg;
16344
16345  if( zDate[0]=='-' ){
16346    zDate++;
16347    neg = 1;
16348  }else{
16349    neg = 0;
16350  }
16351  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
16352    return 1;
16353  }
16354  zDate += 10;
16355  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
16356  if( parseHhMmSs(zDate, p)==0 ){
16357    /* We got the time */
16358  }else if( *zDate==0 ){
16359    p->validHMS = 0;
16360  }else{
16361    return 1;
16362  }
16363  p->validJD = 0;
16364  p->validYMD = 1;
16365  p->Y = neg ? -Y : Y;
16366  p->M = M;
16367  p->D = D;
16368  if( p->validTZ ){
16369    computeJD(p);
16370  }
16371  return 0;
16372}
16373
16374/*
16375** Set the time to the current time reported by the VFS.
16376**
16377** Return the number of errors.
16378*/
16379static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
16380  p->iJD = sqlite3StmtCurrentTime(context);
16381  if( p->iJD>0 ){
16382    p->validJD = 1;
16383    return 0;
16384  }else{
16385    return 1;
16386  }
16387}
16388
16389/*
16390** Attempt to parse the given string into a julian day number.  Return
16391** the number of errors.
16392**
16393** The following are acceptable forms for the input string:
16394**
16395**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
16396**      DDDD.DD
16397**      now
16398**
16399** In the first form, the +/-HH:MM is always optional.  The fractional
16400** seconds extension (the ".FFF") is optional.  The seconds portion
16401** (":SS.FFF") is option.  The year and date can be omitted as long
16402** as there is a time string.  The time string can be omitted as long
16403** as there is a year and date.
16404*/
16405static int parseDateOrTime(
16406  sqlite3_context *context,
16407  const char *zDate,
16408  DateTime *p
16409){
16410  double r;
16411  if( parseYyyyMmDd(zDate,p)==0 ){
16412    return 0;
16413  }else if( parseHhMmSs(zDate, p)==0 ){
16414    return 0;
16415  }else if( sqlite3StrICmp(zDate,"now")==0){
16416    return setDateTimeToCurrent(context, p);
16417  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
16418    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
16419    p->validJD = 1;
16420    return 0;
16421  }
16422  return 1;
16423}
16424
16425/*
16426** Compute the Year, Month, and Day from the julian day number.
16427*/
16428static void computeYMD(DateTime *p){
16429  int Z, A, B, C, D, E, X1;
16430  if( p->validYMD ) return;
16431  if( !p->validJD ){
16432    p->Y = 2000;
16433    p->M = 1;
16434    p->D = 1;
16435  }else{
16436    Z = (int)((p->iJD + 43200000)/86400000);
16437    A = (int)((Z - 1867216.25)/36524.25);
16438    A = Z + 1 + A - (A/4);
16439    B = A + 1524;
16440    C = (int)((B - 122.1)/365.25);
16441    D = (36525*(C&32767))/100;
16442    E = (int)((B-D)/30.6001);
16443    X1 = (int)(30.6001*E);
16444    p->D = B - D - X1;
16445    p->M = E<14 ? E-1 : E-13;
16446    p->Y = p->M>2 ? C - 4716 : C - 4715;
16447  }
16448  p->validYMD = 1;
16449}
16450
16451/*
16452** Compute the Hour, Minute, and Seconds from the julian day number.
16453*/
16454static void computeHMS(DateTime *p){
16455  int s;
16456  if( p->validHMS ) return;
16457  computeJD(p);
16458  s = (int)((p->iJD + 43200000) % 86400000);
16459  p->s = s/1000.0;
16460  s = (int)p->s;
16461  p->s -= s;
16462  p->h = s/3600;
16463  s -= p->h*3600;
16464  p->m = s/60;
16465  p->s += s - p->m*60;
16466  p->validHMS = 1;
16467}
16468
16469/*
16470** Compute both YMD and HMS
16471*/
16472static void computeYMD_HMS(DateTime *p){
16473  computeYMD(p);
16474  computeHMS(p);
16475}
16476
16477/*
16478** Clear the YMD and HMS and the TZ
16479*/
16480static void clearYMD_HMS_TZ(DateTime *p){
16481  p->validYMD = 0;
16482  p->validHMS = 0;
16483  p->validTZ = 0;
16484}
16485
16486/*
16487** On recent Windows platforms, the localtime_s() function is available
16488** as part of the "Secure CRT". It is essentially equivalent to
16489** localtime_r() available under most POSIX platforms, except that the
16490** order of the parameters is reversed.
16491**
16492** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
16493**
16494** If the user has not indicated to use localtime_r() or localtime_s()
16495** already, check for an MSVC build environment that provides
16496** localtime_s().
16497*/
16498#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
16499    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
16500#undef  HAVE_LOCALTIME_S
16501#define HAVE_LOCALTIME_S 1
16502#endif
16503
16504#ifndef SQLITE_OMIT_LOCALTIME
16505/*
16506** The following routine implements the rough equivalent of localtime_r()
16507** using whatever operating-system specific localtime facility that
16508** is available.  This routine returns 0 on success and
16509** non-zero on any kind of error.
16510**
16511** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
16512** routine will always fail.
16513**
16514** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
16515** library function localtime_r() is used to assist in the calculation of
16516** local time.
16517*/
16518static int osLocaltime(time_t *t, struct tm *pTm){
16519  int rc;
16520#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
16521  struct tm *pX;
16522#if SQLITE_THREADSAFE>0
16523  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16524#endif
16525  sqlite3_mutex_enter(mutex);
16526  pX = localtime(t);
16527#ifndef SQLITE_OMIT_BUILTIN_TEST
16528  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
16529#endif
16530  if( pX ) *pTm = *pX;
16531  sqlite3_mutex_leave(mutex);
16532  rc = pX==0;
16533#else
16534#ifndef SQLITE_OMIT_BUILTIN_TEST
16535  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
16536#endif
16537#if HAVE_LOCALTIME_R
16538  rc = localtime_r(t, pTm)==0;
16539#else
16540  rc = localtime_s(pTm, t);
16541#endif /* HAVE_LOCALTIME_R */
16542#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
16543  return rc;
16544}
16545#endif /* SQLITE_OMIT_LOCALTIME */
16546
16547
16548#ifndef SQLITE_OMIT_LOCALTIME
16549/*
16550** Compute the difference (in milliseconds) between localtime and UTC
16551** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
16552** return this value and set *pRc to SQLITE_OK.
16553**
16554** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
16555** is undefined in this case.
16556*/
16557static sqlite3_int64 localtimeOffset(
16558  DateTime *p,                    /* Date at which to calculate offset */
16559  sqlite3_context *pCtx,          /* Write error here if one occurs */
16560  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
16561){
16562  DateTime x, y;
16563  time_t t;
16564  struct tm sLocal;
16565
16566  /* Initialize the contents of sLocal to avoid a compiler warning. */
16567  memset(&sLocal, 0, sizeof(sLocal));
16568
16569  x = *p;
16570  computeYMD_HMS(&x);
16571  if( x.Y<1971 || x.Y>=2038 ){
16572    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
16573    ** works for years between 1970 and 2037. For dates outside this range,
16574    ** SQLite attempts to map the year into an equivalent year within this
16575    ** range, do the calculation, then map the year back.
16576    */
16577    x.Y = 2000;
16578    x.M = 1;
16579    x.D = 1;
16580    x.h = 0;
16581    x.m = 0;
16582    x.s = 0.0;
16583  } else {
16584    int s = (int)(x.s + 0.5);
16585    x.s = s;
16586  }
16587  x.tz = 0;
16588  x.validJD = 0;
16589  computeJD(&x);
16590  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
16591  if( osLocaltime(&t, &sLocal) ){
16592    sqlite3_result_error(pCtx, "local time unavailable", -1);
16593    *pRc = SQLITE_ERROR;
16594    return 0;
16595  }
16596  y.Y = sLocal.tm_year + 1900;
16597  y.M = sLocal.tm_mon + 1;
16598  y.D = sLocal.tm_mday;
16599  y.h = sLocal.tm_hour;
16600  y.m = sLocal.tm_min;
16601  y.s = sLocal.tm_sec;
16602  y.validYMD = 1;
16603  y.validHMS = 1;
16604  y.validJD = 0;
16605  y.validTZ = 0;
16606  computeJD(&y);
16607  *pRc = SQLITE_OK;
16608  return y.iJD - x.iJD;
16609}
16610#endif /* SQLITE_OMIT_LOCALTIME */
16611
16612/*
16613** Process a modifier to a date-time stamp.  The modifiers are
16614** as follows:
16615**
16616**     NNN days
16617**     NNN hours
16618**     NNN minutes
16619**     NNN.NNNN seconds
16620**     NNN months
16621**     NNN years
16622**     start of month
16623**     start of year
16624**     start of week
16625**     start of day
16626**     weekday N
16627**     unixepoch
16628**     localtime
16629**     utc
16630**
16631** Return 0 on success and 1 if there is any kind of error. If the error
16632** is in a system call (i.e. localtime()), then an error message is written
16633** to context pCtx. If the error is an unrecognized modifier, no error is
16634** written to pCtx.
16635*/
16636static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
16637  int rc = 1;
16638  int n;
16639  double r;
16640  char *z, zBuf[30];
16641  z = zBuf;
16642  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
16643    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
16644  }
16645  z[n] = 0;
16646  switch( z[0] ){
16647#ifndef SQLITE_OMIT_LOCALTIME
16648    case 'l': {
16649      /*    localtime
16650      **
16651      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
16652      ** show local time.
16653      */
16654      if( strcmp(z, "localtime")==0 ){
16655        computeJD(p);
16656        p->iJD += localtimeOffset(p, pCtx, &rc);
16657        clearYMD_HMS_TZ(p);
16658      }
16659      break;
16660    }
16661#endif
16662    case 'u': {
16663      /*
16664      **    unixepoch
16665      **
16666      ** Treat the current value of p->iJD as the number of
16667      ** seconds since 1970.  Convert to a real julian day number.
16668      */
16669      if( strcmp(z, "unixepoch")==0 && p->validJD ){
16670        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
16671        clearYMD_HMS_TZ(p);
16672        rc = 0;
16673      }
16674#ifndef SQLITE_OMIT_LOCALTIME
16675      else if( strcmp(z, "utc")==0 ){
16676        sqlite3_int64 c1;
16677        computeJD(p);
16678        c1 = localtimeOffset(p, pCtx, &rc);
16679        if( rc==SQLITE_OK ){
16680          p->iJD -= c1;
16681          clearYMD_HMS_TZ(p);
16682          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
16683        }
16684      }
16685#endif
16686      break;
16687    }
16688    case 'w': {
16689      /*
16690      **    weekday N
16691      **
16692      ** Move the date to the same time on the next occurrence of
16693      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
16694      ** date is already on the appropriate weekday, this is a no-op.
16695      */
16696      if( strncmp(z, "weekday ", 8)==0
16697               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
16698               && (n=(int)r)==r && n>=0 && r<7 ){
16699        sqlite3_int64 Z;
16700        computeYMD_HMS(p);
16701        p->validTZ = 0;
16702        p->validJD = 0;
16703        computeJD(p);
16704        Z = ((p->iJD + 129600000)/86400000) % 7;
16705        if( Z>n ) Z -= 7;
16706        p->iJD += (n - Z)*86400000;
16707        clearYMD_HMS_TZ(p);
16708        rc = 0;
16709      }
16710      break;
16711    }
16712    case 's': {
16713      /*
16714      **    start of TTTTT
16715      **
16716      ** Move the date backwards to the beginning of the current day,
16717      ** or month or year.
16718      */
16719      if( strncmp(z, "start of ", 9)!=0 ) break;
16720      z += 9;
16721      computeYMD(p);
16722      p->validHMS = 1;
16723      p->h = p->m = 0;
16724      p->s = 0.0;
16725      p->validTZ = 0;
16726      p->validJD = 0;
16727      if( strcmp(z,"month")==0 ){
16728        p->D = 1;
16729        rc = 0;
16730      }else if( strcmp(z,"year")==0 ){
16731        computeYMD(p);
16732        p->M = 1;
16733        p->D = 1;
16734        rc = 0;
16735      }else if( strcmp(z,"day")==0 ){
16736        rc = 0;
16737      }
16738      break;
16739    }
16740    case '+':
16741    case '-':
16742    case '0':
16743    case '1':
16744    case '2':
16745    case '3':
16746    case '4':
16747    case '5':
16748    case '6':
16749    case '7':
16750    case '8':
16751    case '9': {
16752      double rRounder;
16753      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
16754      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
16755        rc = 1;
16756        break;
16757      }
16758      if( z[n]==':' ){
16759        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
16760        ** specified number of hours, minutes, seconds, and fractional seconds
16761        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
16762        ** omitted.
16763        */
16764        const char *z2 = z;
16765        DateTime tx;
16766        sqlite3_int64 day;
16767        if( !sqlite3Isdigit(*z2) ) z2++;
16768        memset(&tx, 0, sizeof(tx));
16769        if( parseHhMmSs(z2, &tx) ) break;
16770        computeJD(&tx);
16771        tx.iJD -= 43200000;
16772        day = tx.iJD/86400000;
16773        tx.iJD -= day*86400000;
16774        if( z[0]=='-' ) tx.iJD = -tx.iJD;
16775        computeJD(p);
16776        clearYMD_HMS_TZ(p);
16777        p->iJD += tx.iJD;
16778        rc = 0;
16779        break;
16780      }
16781      z += n;
16782      while( sqlite3Isspace(*z) ) z++;
16783      n = sqlite3Strlen30(z);
16784      if( n>10 || n<3 ) break;
16785      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
16786      computeJD(p);
16787      rc = 0;
16788      rRounder = r<0 ? -0.5 : +0.5;
16789      if( n==3 && strcmp(z,"day")==0 ){
16790        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
16791      }else if( n==4 && strcmp(z,"hour")==0 ){
16792        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
16793      }else if( n==6 && strcmp(z,"minute")==0 ){
16794        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
16795      }else if( n==6 && strcmp(z,"second")==0 ){
16796        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
16797      }else if( n==5 && strcmp(z,"month")==0 ){
16798        int x, y;
16799        computeYMD_HMS(p);
16800        p->M += (int)r;
16801        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
16802        p->Y += x;
16803        p->M -= x*12;
16804        p->validJD = 0;
16805        computeJD(p);
16806        y = (int)r;
16807        if( y!=r ){
16808          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
16809        }
16810      }else if( n==4 && strcmp(z,"year")==0 ){
16811        int y = (int)r;
16812        computeYMD_HMS(p);
16813        p->Y += y;
16814        p->validJD = 0;
16815        computeJD(p);
16816        if( y!=r ){
16817          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
16818        }
16819      }else{
16820        rc = 1;
16821      }
16822      clearYMD_HMS_TZ(p);
16823      break;
16824    }
16825    default: {
16826      break;
16827    }
16828  }
16829  return rc;
16830}
16831
16832/*
16833** Process time function arguments.  argv[0] is a date-time stamp.
16834** argv[1] and following are modifiers.  Parse them all and write
16835** the resulting time into the DateTime structure p.  Return 0
16836** on success and 1 if there are any errors.
16837**
16838** If there are zero parameters (if even argv[0] is undefined)
16839** then assume a default value of "now" for argv[0].
16840*/
16841static int isDate(
16842  sqlite3_context *context,
16843  int argc,
16844  sqlite3_value **argv,
16845  DateTime *p
16846){
16847  int i;
16848  const unsigned char *z;
16849  int eType;
16850  memset(p, 0, sizeof(*p));
16851  if( argc==0 ){
16852    return setDateTimeToCurrent(context, p);
16853  }
16854  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
16855                   || eType==SQLITE_INTEGER ){
16856    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
16857    p->validJD = 1;
16858  }else{
16859    z = sqlite3_value_text(argv[0]);
16860    if( !z || parseDateOrTime(context, (char*)z, p) ){
16861      return 1;
16862    }
16863  }
16864  for(i=1; i<argc; i++){
16865    z = sqlite3_value_text(argv[i]);
16866    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16867  }
16868  return 0;
16869}
16870
16871
16872/*
16873** The following routines implement the various date and time functions
16874** of SQLite.
16875*/
16876
16877/*
16878**    julianday( TIMESTRING, MOD, MOD, ...)
16879**
16880** Return the julian day number of the date specified in the arguments
16881*/
16882static void juliandayFunc(
16883  sqlite3_context *context,
16884  int argc,
16885  sqlite3_value **argv
16886){
16887  DateTime x;
16888  if( isDate(context, argc, argv, &x)==0 ){
16889    computeJD(&x);
16890    sqlite3_result_double(context, x.iJD/86400000.0);
16891  }
16892}
16893
16894/*
16895**    datetime( TIMESTRING, MOD, MOD, ...)
16896**
16897** Return YYYY-MM-DD HH:MM:SS
16898*/
16899static void datetimeFunc(
16900  sqlite3_context *context,
16901  int argc,
16902  sqlite3_value **argv
16903){
16904  DateTime x;
16905  if( isDate(context, argc, argv, &x)==0 ){
16906    char zBuf[100];
16907    computeYMD_HMS(&x);
16908    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16909                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16910    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16911  }
16912}
16913
16914/*
16915**    time( TIMESTRING, MOD, MOD, ...)
16916**
16917** Return HH:MM:SS
16918*/
16919static void timeFunc(
16920  sqlite3_context *context,
16921  int argc,
16922  sqlite3_value **argv
16923){
16924  DateTime x;
16925  if( isDate(context, argc, argv, &x)==0 ){
16926    char zBuf[100];
16927    computeHMS(&x);
16928    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16929    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16930  }
16931}
16932
16933/*
16934**    date( TIMESTRING, MOD, MOD, ...)
16935**
16936** Return YYYY-MM-DD
16937*/
16938static void dateFunc(
16939  sqlite3_context *context,
16940  int argc,
16941  sqlite3_value **argv
16942){
16943  DateTime x;
16944  if( isDate(context, argc, argv, &x)==0 ){
16945    char zBuf[100];
16946    computeYMD(&x);
16947    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16948    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16949  }
16950}
16951
16952/*
16953**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16954**
16955** Return a string described by FORMAT.  Conversions as follows:
16956**
16957**   %d  day of month
16958**   %f  ** fractional seconds  SS.SSS
16959**   %H  hour 00-24
16960**   %j  day of year 000-366
16961**   %J  ** julian day number
16962**   %m  month 01-12
16963**   %M  minute 00-59
16964**   %s  seconds since 1970-01-01
16965**   %S  seconds 00-59
16966**   %w  day of week 0-6  sunday==0
16967**   %W  week of year 00-53
16968**   %Y  year 0000-9999
16969**   %%  %
16970*/
16971static void strftimeFunc(
16972  sqlite3_context *context,
16973  int argc,
16974  sqlite3_value **argv
16975){
16976  DateTime x;
16977  u64 n;
16978  size_t i,j;
16979  char *z;
16980  sqlite3 *db;
16981  const char *zFmt;
16982  char zBuf[100];
16983  if( argc==0 ) return;
16984  zFmt = (const char*)sqlite3_value_text(argv[0]);
16985  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16986  db = sqlite3_context_db_handle(context);
16987  for(i=0, n=1; zFmt[i]; i++, n++){
16988    if( zFmt[i]=='%' ){
16989      switch( zFmt[i+1] ){
16990        case 'd':
16991        case 'H':
16992        case 'm':
16993        case 'M':
16994        case 'S':
16995        case 'W':
16996          n++;
16997          /* fall thru */
16998        case 'w':
16999        case '%':
17000          break;
17001        case 'f':
17002          n += 8;
17003          break;
17004        case 'j':
17005          n += 3;
17006          break;
17007        case 'Y':
17008          n += 8;
17009          break;
17010        case 's':
17011        case 'J':
17012          n += 50;
17013          break;
17014        default:
17015          return;  /* ERROR.  return a NULL */
17016      }
17017      i++;
17018    }
17019  }
17020  testcase( n==sizeof(zBuf)-1 );
17021  testcase( n==sizeof(zBuf) );
17022  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
17023  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
17024  if( n<sizeof(zBuf) ){
17025    z = zBuf;
17026  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
17027    sqlite3_result_error_toobig(context);
17028    return;
17029  }else{
17030    z = sqlite3DbMallocRaw(db, (int)n);
17031    if( z==0 ){
17032      sqlite3_result_error_nomem(context);
17033      return;
17034    }
17035  }
17036  computeJD(&x);
17037  computeYMD_HMS(&x);
17038  for(i=j=0; zFmt[i]; i++){
17039    if( zFmt[i]!='%' ){
17040      z[j++] = zFmt[i];
17041    }else{
17042      i++;
17043      switch( zFmt[i] ){
17044        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
17045        case 'f': {
17046          double s = x.s;
17047          if( s>59.999 ) s = 59.999;
17048          sqlite3_snprintf(7, &z[j],"%06.3f", s);
17049          j += sqlite3Strlen30(&z[j]);
17050          break;
17051        }
17052        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
17053        case 'W': /* Fall thru */
17054        case 'j': {
17055          int nDay;             /* Number of days since 1st day of year */
17056          DateTime y = x;
17057          y.validJD = 0;
17058          y.M = 1;
17059          y.D = 1;
17060          computeJD(&y);
17061          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
17062          if( zFmt[i]=='W' ){
17063            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
17064            wd = (int)(((x.iJD+43200000)/86400000)%7);
17065            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
17066            j += 2;
17067          }else{
17068            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
17069            j += 3;
17070          }
17071          break;
17072        }
17073        case 'J': {
17074          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
17075          j+=sqlite3Strlen30(&z[j]);
17076          break;
17077        }
17078        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
17079        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
17080        case 's': {
17081          sqlite3_snprintf(30,&z[j],"%lld",
17082                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
17083          j += sqlite3Strlen30(&z[j]);
17084          break;
17085        }
17086        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
17087        case 'w': {
17088          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
17089          break;
17090        }
17091        case 'Y': {
17092          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
17093          break;
17094        }
17095        default:   z[j++] = '%'; break;
17096      }
17097    }
17098  }
17099  z[j] = 0;
17100  sqlite3_result_text(context, z, -1,
17101                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
17102}
17103
17104/*
17105** current_time()
17106**
17107** This function returns the same value as time('now').
17108*/
17109static void ctimeFunc(
17110  sqlite3_context *context,
17111  int NotUsed,
17112  sqlite3_value **NotUsed2
17113){
17114  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17115  timeFunc(context, 0, 0);
17116}
17117
17118/*
17119** current_date()
17120**
17121** This function returns the same value as date('now').
17122*/
17123static void cdateFunc(
17124  sqlite3_context *context,
17125  int NotUsed,
17126  sqlite3_value **NotUsed2
17127){
17128  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17129  dateFunc(context, 0, 0);
17130}
17131
17132/*
17133** current_timestamp()
17134**
17135** This function returns the same value as datetime('now').
17136*/
17137static void ctimestampFunc(
17138  sqlite3_context *context,
17139  int NotUsed,
17140  sqlite3_value **NotUsed2
17141){
17142  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17143  datetimeFunc(context, 0, 0);
17144}
17145#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
17146
17147#ifdef SQLITE_OMIT_DATETIME_FUNCS
17148/*
17149** If the library is compiled to omit the full-scale date and time
17150** handling (to get a smaller binary), the following minimal version
17151** of the functions current_time(), current_date() and current_timestamp()
17152** are included instead. This is to support column declarations that
17153** include "DEFAULT CURRENT_TIME" etc.
17154**
17155** This function uses the C-library functions time(), gmtime()
17156** and strftime(). The format string to pass to strftime() is supplied
17157** as the user-data for the function.
17158*/
17159static void currentTimeFunc(
17160  sqlite3_context *context,
17161  int argc,
17162  sqlite3_value **argv
17163){
17164  time_t t;
17165  char *zFormat = (char *)sqlite3_user_data(context);
17166  sqlite3 *db;
17167  sqlite3_int64 iT;
17168  struct tm *pTm;
17169  struct tm sNow;
17170  char zBuf[20];
17171
17172  UNUSED_PARAMETER(argc);
17173  UNUSED_PARAMETER(argv);
17174
17175  iT = sqlite3StmtCurrentTime(context);
17176  if( iT<=0 ) return;
17177  t = iT/1000 - 10000*(sqlite3_int64)21086676;
17178#if HAVE_GMTIME_R
17179  pTm = gmtime_r(&t, &sNow);
17180#else
17181  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17182  pTm = gmtime(&t);
17183  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
17184  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17185#endif
17186  if( pTm ){
17187    strftime(zBuf, 20, zFormat, &sNow);
17188    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17189  }
17190}
17191#endif
17192
17193/*
17194** This function registered all of the above C functions as SQL
17195** functions.  This should be the only routine in this file with
17196** external linkage.
17197*/
17198SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
17199  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
17200#ifndef SQLITE_OMIT_DATETIME_FUNCS
17201    DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
17202    DFUNCTION(date,             -1, 0, 0, dateFunc      ),
17203    DFUNCTION(time,             -1, 0, 0, timeFunc      ),
17204    DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
17205    DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
17206    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
17207    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
17208    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
17209#else
17210    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
17211    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
17212    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
17213#endif
17214  };
17215  int i;
17216  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
17217  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
17218
17219  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
17220    sqlite3FuncDefInsert(pHash, &aFunc[i]);
17221  }
17222}
17223
17224/************** End of date.c ************************************************/
17225/************** Begin file os.c **********************************************/
17226/*
17227** 2005 November 29
17228**
17229** The author disclaims copyright to this source code.  In place of
17230** a legal notice, here is a blessing:
17231**
17232**    May you do good and not evil.
17233**    May you find forgiveness for yourself and forgive others.
17234**    May you share freely, never taking more than you give.
17235**
17236******************************************************************************
17237**
17238** This file contains OS interface code that is common to all
17239** architectures.
17240*/
17241#define _SQLITE_OS_C_ 1
17242/* #include "sqliteInt.h" */
17243#undef _SQLITE_OS_C_
17244
17245/*
17246** The default SQLite sqlite3_vfs implementations do not allocate
17247** memory (actually, os_unix.c allocates a small amount of memory
17248** from within OsOpen()), but some third-party implementations may.
17249** So we test the effects of a malloc() failing and the sqlite3OsXXX()
17250** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
17251**
17252** The following functions are instrumented for malloc() failure
17253** testing:
17254**
17255**     sqlite3OsRead()
17256**     sqlite3OsWrite()
17257**     sqlite3OsSync()
17258**     sqlite3OsFileSize()
17259**     sqlite3OsLock()
17260**     sqlite3OsCheckReservedLock()
17261**     sqlite3OsFileControl()
17262**     sqlite3OsShmMap()
17263**     sqlite3OsOpen()
17264**     sqlite3OsDelete()
17265**     sqlite3OsAccess()
17266**     sqlite3OsFullPathname()
17267**
17268*/
17269#if defined(SQLITE_TEST)
17270SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
17271  #define DO_OS_MALLOC_TEST(x)                                       \
17272  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
17273    void *pTstAlloc = sqlite3Malloc(10);                             \
17274    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
17275    sqlite3_free(pTstAlloc);                                         \
17276  }
17277#else
17278  #define DO_OS_MALLOC_TEST(x)
17279#endif
17280
17281/*
17282** The following routines are convenience wrappers around methods
17283** of the sqlite3_file object.  This is mostly just syntactic sugar. All
17284** of this would be completely automatic if SQLite were coded using
17285** C++ instead of plain old C.
17286*/
17287SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
17288  int rc = SQLITE_OK;
17289  if( pId->pMethods ){
17290    rc = pId->pMethods->xClose(pId);
17291    pId->pMethods = 0;
17292  }
17293  return rc;
17294}
17295SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
17296  DO_OS_MALLOC_TEST(id);
17297  return id->pMethods->xRead(id, pBuf, amt, offset);
17298}
17299SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
17300  DO_OS_MALLOC_TEST(id);
17301  return id->pMethods->xWrite(id, pBuf, amt, offset);
17302}
17303SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
17304  return id->pMethods->xTruncate(id, size);
17305}
17306SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
17307  DO_OS_MALLOC_TEST(id);
17308  return id->pMethods->xSync(id, flags);
17309}
17310SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
17311  DO_OS_MALLOC_TEST(id);
17312  return id->pMethods->xFileSize(id, pSize);
17313}
17314SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
17315  DO_OS_MALLOC_TEST(id);
17316  return id->pMethods->xLock(id, lockType);
17317}
17318SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
17319  return id->pMethods->xUnlock(id, lockType);
17320}
17321SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
17322  DO_OS_MALLOC_TEST(id);
17323  return id->pMethods->xCheckReservedLock(id, pResOut);
17324}
17325
17326/*
17327** Use sqlite3OsFileControl() when we are doing something that might fail
17328** and we need to know about the failures.  Use sqlite3OsFileControlHint()
17329** when simply tossing information over the wall to the VFS and we do not
17330** really care if the VFS receives and understands the information since it
17331** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
17332** routine has no return value since the return value would be meaningless.
17333*/
17334SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
17335#ifdef SQLITE_TEST
17336  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
17337    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
17338    ** is using a regular VFS, it is called after the corresponding
17339    ** transaction has been committed. Injecting a fault at this point
17340    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
17341    ** but the transaction is committed anyway.
17342    **
17343    ** The core must call OsFileControl() though, not OsFileControlHint(),
17344    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
17345    ** means the commit really has failed and an error should be returned
17346    ** to the user.  */
17347    DO_OS_MALLOC_TEST(id);
17348  }
17349#endif
17350  return id->pMethods->xFileControl(id, op, pArg);
17351}
17352SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
17353  (void)id->pMethods->xFileControl(id, op, pArg);
17354}
17355
17356SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
17357  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
17358  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
17359}
17360SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
17361  return id->pMethods->xDeviceCharacteristics(id);
17362}
17363SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
17364  return id->pMethods->xShmLock(id, offset, n, flags);
17365}
17366SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
17367  id->pMethods->xShmBarrier(id);
17368}
17369SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
17370  return id->pMethods->xShmUnmap(id, deleteFlag);
17371}
17372SQLITE_PRIVATE int sqlite3OsShmMap(
17373  sqlite3_file *id,               /* Database file handle */
17374  int iPage,
17375  int pgsz,
17376  int bExtend,                    /* True to extend file if necessary */
17377  void volatile **pp              /* OUT: Pointer to mapping */
17378){
17379  DO_OS_MALLOC_TEST(id);
17380  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
17381}
17382
17383#if SQLITE_MAX_MMAP_SIZE>0
17384/* The real implementation of xFetch and xUnfetch */
17385SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
17386  DO_OS_MALLOC_TEST(id);
17387  return id->pMethods->xFetch(id, iOff, iAmt, pp);
17388}
17389SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
17390  return id->pMethods->xUnfetch(id, iOff, p);
17391}
17392#else
17393/* No-op stubs to use when memory-mapped I/O is disabled */
17394SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
17395  *pp = 0;
17396  return SQLITE_OK;
17397}
17398SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
17399  return SQLITE_OK;
17400}
17401#endif
17402
17403/*
17404** The next group of routines are convenience wrappers around the
17405** VFS methods.
17406*/
17407SQLITE_PRIVATE int sqlite3OsOpen(
17408  sqlite3_vfs *pVfs,
17409  const char *zPath,
17410  sqlite3_file *pFile,
17411  int flags,
17412  int *pFlagsOut
17413){
17414  int rc;
17415  DO_OS_MALLOC_TEST(0);
17416  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
17417  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
17418  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
17419  ** reaching the VFS. */
17420  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
17421  assert( rc==SQLITE_OK || pFile->pMethods==0 );
17422  return rc;
17423}
17424SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
17425  DO_OS_MALLOC_TEST(0);
17426  assert( dirSync==0 || dirSync==1 );
17427  return pVfs->xDelete(pVfs, zPath, dirSync);
17428}
17429SQLITE_PRIVATE int sqlite3OsAccess(
17430  sqlite3_vfs *pVfs,
17431  const char *zPath,
17432  int flags,
17433  int *pResOut
17434){
17435  DO_OS_MALLOC_TEST(0);
17436  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
17437}
17438SQLITE_PRIVATE int sqlite3OsFullPathname(
17439  sqlite3_vfs *pVfs,
17440  const char *zPath,
17441  int nPathOut,
17442  char *zPathOut
17443){
17444  DO_OS_MALLOC_TEST(0);
17445  zPathOut[0] = 0;
17446  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
17447}
17448#ifndef SQLITE_OMIT_LOAD_EXTENSION
17449SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
17450  return pVfs->xDlOpen(pVfs, zPath);
17451}
17452SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
17453  pVfs->xDlError(pVfs, nByte, zBufOut);
17454}
17455SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
17456  return pVfs->xDlSym(pVfs, pHdle, zSym);
17457}
17458SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
17459  pVfs->xDlClose(pVfs, pHandle);
17460}
17461#endif /* SQLITE_OMIT_LOAD_EXTENSION */
17462SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
17463  return pVfs->xRandomness(pVfs, nByte, zBufOut);
17464}
17465SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
17466  return pVfs->xSleep(pVfs, nMicro);
17467}
17468SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
17469  int rc;
17470  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
17471  ** method to get the current date and time if that method is available
17472  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
17473  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
17474  ** unavailable.
17475  */
17476  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
17477    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
17478  }else{
17479    double r;
17480    rc = pVfs->xCurrentTime(pVfs, &r);
17481    *pTimeOut = (sqlite3_int64)(r*86400000.0);
17482  }
17483  return rc;
17484}
17485
17486SQLITE_PRIVATE int sqlite3OsOpenMalloc(
17487  sqlite3_vfs *pVfs,
17488  const char *zFile,
17489  sqlite3_file **ppFile,
17490  int flags,
17491  int *pOutFlags
17492){
17493  int rc = SQLITE_NOMEM;
17494  sqlite3_file *pFile;
17495  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
17496  if( pFile ){
17497    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
17498    if( rc!=SQLITE_OK ){
17499      sqlite3_free(pFile);
17500    }else{
17501      *ppFile = pFile;
17502    }
17503  }
17504  return rc;
17505}
17506SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
17507  int rc = SQLITE_OK;
17508  assert( pFile );
17509  rc = sqlite3OsClose(pFile);
17510  sqlite3_free(pFile);
17511  return rc;
17512}
17513
17514/*
17515** This function is a wrapper around the OS specific implementation of
17516** sqlite3_os_init(). The purpose of the wrapper is to provide the
17517** ability to simulate a malloc failure, so that the handling of an
17518** error in sqlite3_os_init() by the upper layers can be tested.
17519*/
17520SQLITE_PRIVATE int sqlite3OsInit(void){
17521  void *p = sqlite3_malloc(10);
17522  if( p==0 ) return SQLITE_NOMEM;
17523  sqlite3_free(p);
17524  return sqlite3_os_init();
17525}
17526
17527/*
17528** The list of all registered VFS implementations.
17529*/
17530static sqlite3_vfs * SQLITE_WSD vfsList = 0;
17531#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
17532
17533/*
17534** Locate a VFS by name.  If no name is given, simply return the
17535** first VFS on the list.
17536*/
17537SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
17538  sqlite3_vfs *pVfs = 0;
17539#if SQLITE_THREADSAFE
17540  sqlite3_mutex *mutex;
17541#endif
17542#ifndef SQLITE_OMIT_AUTOINIT
17543  int rc = sqlite3_initialize();
17544  if( rc ) return 0;
17545#endif
17546#if SQLITE_THREADSAFE
17547  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
17548#endif
17549  sqlite3_mutex_enter(mutex);
17550  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
17551    if( zVfs==0 ) break;
17552    if( strcmp(zVfs, pVfs->zName)==0 ) break;
17553  }
17554  sqlite3_mutex_leave(mutex);
17555  return pVfs;
17556}
17557
17558/*
17559** Unlink a VFS from the linked list
17560*/
17561static void vfsUnlink(sqlite3_vfs *pVfs){
17562  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
17563  if( pVfs==0 ){
17564    /* No-op */
17565  }else if( vfsList==pVfs ){
17566    vfsList = pVfs->pNext;
17567  }else if( vfsList ){
17568    sqlite3_vfs *p = vfsList;
17569    while( p->pNext && p->pNext!=pVfs ){
17570      p = p->pNext;
17571    }
17572    if( p->pNext==pVfs ){
17573      p->pNext = pVfs->pNext;
17574    }
17575  }
17576}
17577
17578/*
17579** Register a VFS with the system.  It is harmless to register the same
17580** VFS multiple times.  The new VFS becomes the default if makeDflt is
17581** true.
17582*/
17583SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
17584  MUTEX_LOGIC(sqlite3_mutex *mutex;)
17585#ifndef SQLITE_OMIT_AUTOINIT
17586  int rc = sqlite3_initialize();
17587  if( rc ) return rc;
17588#endif
17589#ifdef SQLITE_ENABLE_API_ARMOR
17590  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
17591#endif
17592
17593  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
17594  sqlite3_mutex_enter(mutex);
17595  vfsUnlink(pVfs);
17596  if( makeDflt || vfsList==0 ){
17597    pVfs->pNext = vfsList;
17598    vfsList = pVfs;
17599  }else{
17600    pVfs->pNext = vfsList->pNext;
17601    vfsList->pNext = pVfs;
17602  }
17603  assert(vfsList);
17604  sqlite3_mutex_leave(mutex);
17605  return SQLITE_OK;
17606}
17607
17608/*
17609** Unregister a VFS so that it is no longer accessible.
17610*/
17611SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
17612#if SQLITE_THREADSAFE
17613  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
17614#endif
17615  sqlite3_mutex_enter(mutex);
17616  vfsUnlink(pVfs);
17617  sqlite3_mutex_leave(mutex);
17618  return SQLITE_OK;
17619}
17620
17621/************** End of os.c **************************************************/
17622/************** Begin file fault.c *******************************************/
17623/*
17624** 2008 Jan 22
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**
17635** This file contains code to support the concept of "benign"
17636** malloc failures (when the xMalloc() or xRealloc() method of the
17637** sqlite3_mem_methods structure fails to allocate a block of memory
17638** and returns 0).
17639**
17640** Most malloc failures are non-benign. After they occur, SQLite
17641** abandons the current operation and returns an error code (usually
17642** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
17643** fatal. For example, if a malloc fails while resizing a hash table, this
17644** is completely recoverable simply by not carrying out the resize. The
17645** hash table will continue to function normally.  So a malloc failure
17646** during a hash table resize is a benign fault.
17647*/
17648
17649/* #include "sqliteInt.h" */
17650
17651#ifndef SQLITE_OMIT_BUILTIN_TEST
17652
17653/*
17654** Global variables.
17655*/
17656typedef struct BenignMallocHooks BenignMallocHooks;
17657static SQLITE_WSD struct BenignMallocHooks {
17658  void (*xBenignBegin)(void);
17659  void (*xBenignEnd)(void);
17660} sqlite3Hooks = { 0, 0 };
17661
17662/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
17663** structure.  If writable static data is unsupported on the target,
17664** we have to locate the state vector at run-time.  In the more common
17665** case where writable static data is supported, wsdHooks can refer directly
17666** to the "sqlite3Hooks" state vector declared above.
17667*/
17668#ifdef SQLITE_OMIT_WSD
17669# define wsdHooksInit \
17670  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
17671# define wsdHooks x[0]
17672#else
17673# define wsdHooksInit
17674# define wsdHooks sqlite3Hooks
17675#endif
17676
17677
17678/*
17679** Register hooks to call when sqlite3BeginBenignMalloc() and
17680** sqlite3EndBenignMalloc() are called, respectively.
17681*/
17682SQLITE_PRIVATE void sqlite3BenignMallocHooks(
17683  void (*xBenignBegin)(void),
17684  void (*xBenignEnd)(void)
17685){
17686  wsdHooksInit;
17687  wsdHooks.xBenignBegin = xBenignBegin;
17688  wsdHooks.xBenignEnd = xBenignEnd;
17689}
17690
17691/*
17692** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
17693** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
17694** indicates that subsequent malloc failures are non-benign.
17695*/
17696SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
17697  wsdHooksInit;
17698  if( wsdHooks.xBenignBegin ){
17699    wsdHooks.xBenignBegin();
17700  }
17701}
17702SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
17703  wsdHooksInit;
17704  if( wsdHooks.xBenignEnd ){
17705    wsdHooks.xBenignEnd();
17706  }
17707}
17708
17709#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
17710
17711/************** End of fault.c ***********************************************/
17712/************** Begin file mem0.c ********************************************/
17713/*
17714** 2008 October 28
17715**
17716** The author disclaims copyright to this source code.  In place of
17717** a legal notice, here is a blessing:
17718**
17719**    May you do good and not evil.
17720**    May you find forgiveness for yourself and forgive others.
17721**    May you share freely, never taking more than you give.
17722**
17723*************************************************************************
17724**
17725** This file contains a no-op memory allocation drivers for use when
17726** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
17727** here always fail.  SQLite will not operate with these drivers.  These
17728** are merely placeholders.  Real drivers must be substituted using
17729** sqlite3_config() before SQLite will operate.
17730*/
17731/* #include "sqliteInt.h" */
17732
17733/*
17734** This version of the memory allocator is the default.  It is
17735** used when no other memory allocator is specified using compile-time
17736** macros.
17737*/
17738#ifdef SQLITE_ZERO_MALLOC
17739
17740/*
17741** No-op versions of all memory allocation routines
17742*/
17743static void *sqlite3MemMalloc(int nByte){ return 0; }
17744static void sqlite3MemFree(void *pPrior){ return; }
17745static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
17746static int sqlite3MemSize(void *pPrior){ return 0; }
17747static int sqlite3MemRoundup(int n){ return n; }
17748static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
17749static void sqlite3MemShutdown(void *NotUsed){ return; }
17750
17751/*
17752** This routine is the only routine in this file with external linkage.
17753**
17754** Populate the low-level memory allocation function pointers in
17755** sqlite3GlobalConfig.m with pointers to the routines in this file.
17756*/
17757SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17758  static const sqlite3_mem_methods defaultMethods = {
17759     sqlite3MemMalloc,
17760     sqlite3MemFree,
17761     sqlite3MemRealloc,
17762     sqlite3MemSize,
17763     sqlite3MemRoundup,
17764     sqlite3MemInit,
17765     sqlite3MemShutdown,
17766     0
17767  };
17768  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17769}
17770
17771#endif /* SQLITE_ZERO_MALLOC */
17772
17773/************** End of mem0.c ************************************************/
17774/************** Begin file mem1.c ********************************************/
17775/*
17776** 2007 August 14
17777**
17778** The author disclaims copyright to this source code.  In place of
17779** a legal notice, here is a blessing:
17780**
17781**    May you do good and not evil.
17782**    May you find forgiveness for yourself and forgive others.
17783**    May you share freely, never taking more than you give.
17784**
17785*************************************************************************
17786**
17787** This file contains low-level memory allocation drivers for when
17788** SQLite will use the standard C-library malloc/realloc/free interface
17789** to obtain the memory it needs.
17790**
17791** This file contains implementations of the low-level memory allocation
17792** routines specified in the sqlite3_mem_methods object.  The content of
17793** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
17794** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
17795** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
17796** default configuration is to use memory allocation routines in this
17797** file.
17798**
17799** C-preprocessor macro summary:
17800**
17801**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
17802**                                the malloc_usable_size() interface exists
17803**                                on the target platform.  Or, this symbol
17804**                                can be set manually, if desired.
17805**                                If an equivalent interface exists by
17806**                                a different name, using a separate -D
17807**                                option to rename it.
17808**
17809**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
17810**                                memory allocator.  Set this symbol to enable
17811**                                building on older macs.
17812**
17813**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
17814**                                _msize() on windows systems.  This might
17815**                                be necessary when compiling for Delphi,
17816**                                for example.
17817*/
17818/* #include "sqliteInt.h" */
17819
17820/*
17821** This version of the memory allocator is the default.  It is
17822** used when no other memory allocator is specified using compile-time
17823** macros.
17824*/
17825#ifdef SQLITE_SYSTEM_MALLOC
17826#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17827
17828/*
17829** Use the zone allocator available on apple products unless the
17830** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
17831*/
17832#include <sys/sysctl.h>
17833#include <malloc/malloc.h>
17834#include <libkern/OSAtomic.h>
17835static malloc_zone_t* _sqliteZone_;
17836#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
17837#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
17838#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
17839#define SQLITE_MALLOCSIZE(x) \
17840        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
17841
17842#else /* if not __APPLE__ */
17843
17844/*
17845** Use standard C library malloc and free on non-Apple systems.
17846** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
17847*/
17848#define SQLITE_MALLOC(x)             malloc(x)
17849#define SQLITE_FREE(x)               free(x)
17850#define SQLITE_REALLOC(x,y)          realloc((x),(y))
17851
17852/*
17853** The malloc.h header file is needed for malloc_usable_size() function
17854** on some systems (e.g. Linux).
17855*/
17856#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
17857#  define SQLITE_USE_MALLOC_H 1
17858#  define SQLITE_USE_MALLOC_USABLE_SIZE 1
17859/*
17860** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
17861** use of _msize() is automatic, but can be disabled by compiling with
17862** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
17863** the malloc.h header file.
17864*/
17865#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
17866#  define SQLITE_USE_MALLOC_H
17867#  define SQLITE_USE_MSIZE
17868#endif
17869
17870/*
17871** Include the malloc.h header file, if necessary.  Also set define macro
17872** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
17873** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
17874** The memory size function can always be overridden manually by defining
17875** the macro SQLITE_MALLOCSIZE to the desired function name.
17876*/
17877#if defined(SQLITE_USE_MALLOC_H)
17878#  include <malloc.h>
17879#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
17880#    if !defined(SQLITE_MALLOCSIZE)
17881#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
17882#    endif
17883#  elif defined(SQLITE_USE_MSIZE)
17884#    if !defined(SQLITE_MALLOCSIZE)
17885#      define SQLITE_MALLOCSIZE      _msize
17886#    endif
17887#  endif
17888#endif /* defined(SQLITE_USE_MALLOC_H) */
17889
17890#endif /* __APPLE__ or not __APPLE__ */
17891
17892/*
17893** Like malloc(), but remember the size of the allocation
17894** so that we can find it later using sqlite3MemSize().
17895**
17896** For this low-level routine, we are guaranteed that nByte>0 because
17897** cases of nByte<=0 will be intercepted and dealt with by higher level
17898** routines.
17899*/
17900static void *sqlite3MemMalloc(int nByte){
17901#ifdef SQLITE_MALLOCSIZE
17902  void *p = SQLITE_MALLOC( nByte );
17903  if( p==0 ){
17904    testcase( sqlite3GlobalConfig.xLog!=0 );
17905    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17906  }
17907  return p;
17908#else
17909  sqlite3_int64 *p;
17910  assert( nByte>0 );
17911  nByte = ROUND8(nByte);
17912  p = SQLITE_MALLOC( nByte+8 );
17913  if( p ){
17914    p[0] = nByte;
17915    p++;
17916  }else{
17917    testcase( sqlite3GlobalConfig.xLog!=0 );
17918    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17919  }
17920  return (void *)p;
17921#endif
17922}
17923
17924/*
17925** Like free() but works for allocations obtained from sqlite3MemMalloc()
17926** or sqlite3MemRealloc().
17927**
17928** For this low-level routine, we already know that pPrior!=0 since
17929** cases where pPrior==0 will have been intecepted and dealt with
17930** by higher-level routines.
17931*/
17932static void sqlite3MemFree(void *pPrior){
17933#ifdef SQLITE_MALLOCSIZE
17934  SQLITE_FREE(pPrior);
17935#else
17936  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17937  assert( pPrior!=0 );
17938  p--;
17939  SQLITE_FREE(p);
17940#endif
17941}
17942
17943/*
17944** Report the allocated size of a prior return from xMalloc()
17945** or xRealloc().
17946*/
17947static int sqlite3MemSize(void *pPrior){
17948#ifdef SQLITE_MALLOCSIZE
17949  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
17950#else
17951  sqlite3_int64 *p;
17952  if( pPrior==0 ) return 0;
17953  p = (sqlite3_int64*)pPrior;
17954  p--;
17955  return (int)p[0];
17956#endif
17957}
17958
17959/*
17960** Like realloc().  Resize an allocation previously obtained from
17961** sqlite3MemMalloc().
17962**
17963** For this low-level interface, we know that pPrior!=0.  Cases where
17964** pPrior==0 while have been intercepted by higher-level routine and
17965** redirected to xMalloc.  Similarly, we know that nByte>0 because
17966** cases where nByte<=0 will have been intercepted by higher-level
17967** routines and redirected to xFree.
17968*/
17969static void *sqlite3MemRealloc(void *pPrior, int nByte){
17970#ifdef SQLITE_MALLOCSIZE
17971  void *p = SQLITE_REALLOC(pPrior, nByte);
17972  if( p==0 ){
17973    testcase( sqlite3GlobalConfig.xLog!=0 );
17974    sqlite3_log(SQLITE_NOMEM,
17975      "failed memory resize %u to %u bytes",
17976      SQLITE_MALLOCSIZE(pPrior), nByte);
17977  }
17978  return p;
17979#else
17980  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17981  assert( pPrior!=0 && nByte>0 );
17982  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17983  p--;
17984  p = SQLITE_REALLOC(p, nByte+8 );
17985  if( p ){
17986    p[0] = nByte;
17987    p++;
17988  }else{
17989    testcase( sqlite3GlobalConfig.xLog!=0 );
17990    sqlite3_log(SQLITE_NOMEM,
17991      "failed memory resize %u to %u bytes",
17992      sqlite3MemSize(pPrior), nByte);
17993  }
17994  return (void*)p;
17995#endif
17996}
17997
17998/*
17999** Round up a request size to the next valid allocation size.
18000*/
18001static int sqlite3MemRoundup(int n){
18002  return ROUND8(n);
18003}
18004
18005/*
18006** Initialize this module.
18007*/
18008static int sqlite3MemInit(void *NotUsed){
18009#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
18010  int cpuCount;
18011  size_t len;
18012  if( _sqliteZone_ ){
18013    return SQLITE_OK;
18014  }
18015  len = sizeof(cpuCount);
18016  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
18017  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
18018  if( cpuCount>1 ){
18019    /* defer MT decisions to system malloc */
18020    _sqliteZone_ = malloc_default_zone();
18021  }else{
18022    /* only 1 core, use our own zone to contention over global locks,
18023    ** e.g. we have our own dedicated locks */
18024    bool success;
18025    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
18026    malloc_set_zone_name(newzone, "Sqlite_Heap");
18027    do{
18028      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
18029                                 (void * volatile *)&_sqliteZone_);
18030    }while(!_sqliteZone_);
18031    if( !success ){
18032      /* somebody registered a zone first */
18033      malloc_destroy_zone(newzone);
18034    }
18035  }
18036#endif
18037  UNUSED_PARAMETER(NotUsed);
18038  return SQLITE_OK;
18039}
18040
18041/*
18042** Deinitialize this module.
18043*/
18044static void sqlite3MemShutdown(void *NotUsed){
18045  UNUSED_PARAMETER(NotUsed);
18046  return;
18047}
18048
18049/*
18050** This routine is the only routine in this file with external linkage.
18051**
18052** Populate the low-level memory allocation function pointers in
18053** sqlite3GlobalConfig.m with pointers to the routines in this file.
18054*/
18055SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18056  static const sqlite3_mem_methods defaultMethods = {
18057     sqlite3MemMalloc,
18058     sqlite3MemFree,
18059     sqlite3MemRealloc,
18060     sqlite3MemSize,
18061     sqlite3MemRoundup,
18062     sqlite3MemInit,
18063     sqlite3MemShutdown,
18064     0
18065  };
18066  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18067}
18068
18069#endif /* SQLITE_SYSTEM_MALLOC */
18070
18071/************** End of mem1.c ************************************************/
18072/************** Begin file mem2.c ********************************************/
18073/*
18074** 2007 August 15
18075**
18076** The author disclaims copyright to this source code.  In place of
18077** a legal notice, here is a blessing:
18078**
18079**    May you do good and not evil.
18080**    May you find forgiveness for yourself and forgive others.
18081**    May you share freely, never taking more than you give.
18082**
18083*************************************************************************
18084**
18085** This file contains low-level memory allocation drivers for when
18086** SQLite will use the standard C-library malloc/realloc/free interface
18087** to obtain the memory it needs while adding lots of additional debugging
18088** information to each allocation in order to help detect and fix memory
18089** leaks and memory usage errors.
18090**
18091** This file contains implementations of the low-level memory allocation
18092** routines specified in the sqlite3_mem_methods object.
18093*/
18094/* #include "sqliteInt.h" */
18095
18096/*
18097** This version of the memory allocator is used only if the
18098** SQLITE_MEMDEBUG macro is defined
18099*/
18100#ifdef SQLITE_MEMDEBUG
18101
18102/*
18103** The backtrace functionality is only available with GLIBC
18104*/
18105#ifdef __GLIBC__
18106  extern int backtrace(void**,int);
18107  extern void backtrace_symbols_fd(void*const*,int,int);
18108#else
18109# define backtrace(A,B) 1
18110# define backtrace_symbols_fd(A,B,C)
18111#endif
18112/* #include <stdio.h> */
18113
18114/*
18115** Each memory allocation looks like this:
18116**
18117**  ------------------------------------------------------------------------
18118**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
18119**  ------------------------------------------------------------------------
18120**
18121** The application code sees only a pointer to the allocation.  We have
18122** to back up from the allocation pointer to find the MemBlockHdr.  The
18123** MemBlockHdr tells us the size of the allocation and the number of
18124** backtrace pointers.  There is also a guard word at the end of the
18125** MemBlockHdr.
18126*/
18127struct MemBlockHdr {
18128  i64 iSize;                          /* Size of this allocation */
18129  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
18130  char nBacktrace;                    /* Number of backtraces on this alloc */
18131  char nBacktraceSlots;               /* Available backtrace slots */
18132  u8 nTitle;                          /* Bytes of title; includes '\0' */
18133  u8 eType;                           /* Allocation type code */
18134  int iForeGuard;                     /* Guard word for sanity */
18135};
18136
18137/*
18138** Guard words
18139*/
18140#define FOREGUARD 0x80F5E153
18141#define REARGUARD 0xE4676B53
18142
18143/*
18144** Number of malloc size increments to track.
18145*/
18146#define NCSIZE  1000
18147
18148/*
18149** All of the static variables used by this module are collected
18150** into a single structure named "mem".  This is to keep the
18151** static variables organized and to reduce namespace pollution
18152** when this module is combined with other in the amalgamation.
18153*/
18154static struct {
18155
18156  /*
18157  ** Mutex to control access to the memory allocation subsystem.
18158  */
18159  sqlite3_mutex *mutex;
18160
18161  /*
18162  ** Head and tail of a linked list of all outstanding allocations
18163  */
18164  struct MemBlockHdr *pFirst;
18165  struct MemBlockHdr *pLast;
18166
18167  /*
18168  ** The number of levels of backtrace to save in new allocations.
18169  */
18170  int nBacktrace;
18171  void (*xBacktrace)(int, int, void **);
18172
18173  /*
18174  ** Title text to insert in front of each block
18175  */
18176  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
18177  char zTitle[100];  /* The title text */
18178
18179  /*
18180  ** sqlite3MallocDisallow() increments the following counter.
18181  ** sqlite3MallocAllow() decrements it.
18182  */
18183  int disallow; /* Do not allow memory allocation */
18184
18185  /*
18186  ** Gather statistics on the sizes of memory allocations.
18187  ** nAlloc[i] is the number of allocation attempts of i*8
18188  ** bytes.  i==NCSIZE is the number of allocation attempts for
18189  ** sizes more than NCSIZE*8 bytes.
18190  */
18191  int nAlloc[NCSIZE];      /* Total number of allocations */
18192  int nCurrent[NCSIZE];    /* Current number of allocations */
18193  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
18194
18195} mem;
18196
18197
18198/*
18199** Adjust memory usage statistics
18200*/
18201static void adjustStats(int iSize, int increment){
18202  int i = ROUND8(iSize)/8;
18203  if( i>NCSIZE-1 ){
18204    i = NCSIZE - 1;
18205  }
18206  if( increment>0 ){
18207    mem.nAlloc[i]++;
18208    mem.nCurrent[i]++;
18209    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
18210      mem.mxCurrent[i] = mem.nCurrent[i];
18211    }
18212  }else{
18213    mem.nCurrent[i]--;
18214    assert( mem.nCurrent[i]>=0 );
18215  }
18216}
18217
18218/*
18219** Given an allocation, find the MemBlockHdr for that allocation.
18220**
18221** This routine checks the guards at either end of the allocation and
18222** if they are incorrect it asserts.
18223*/
18224static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
18225  struct MemBlockHdr *p;
18226  int *pInt;
18227  u8 *pU8;
18228  int nReserve;
18229
18230  p = (struct MemBlockHdr*)pAllocation;
18231  p--;
18232  assert( p->iForeGuard==(int)FOREGUARD );
18233  nReserve = ROUND8(p->iSize);
18234  pInt = (int*)pAllocation;
18235  pU8 = (u8*)pAllocation;
18236  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
18237  /* This checks any of the "extra" bytes allocated due
18238  ** to rounding up to an 8 byte boundary to ensure
18239  ** they haven't been overwritten.
18240  */
18241  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
18242  return p;
18243}
18244
18245/*
18246** Return the number of bytes currently allocated at address p.
18247*/
18248static int sqlite3MemSize(void *p){
18249  struct MemBlockHdr *pHdr;
18250  if( !p ){
18251    return 0;
18252  }
18253  pHdr = sqlite3MemsysGetHeader(p);
18254  return (int)pHdr->iSize;
18255}
18256
18257/*
18258** Initialize the memory allocation subsystem.
18259*/
18260static int sqlite3MemInit(void *NotUsed){
18261  UNUSED_PARAMETER(NotUsed);
18262  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
18263  if( !sqlite3GlobalConfig.bMemstat ){
18264    /* If memory status is enabled, then the malloc.c wrapper will already
18265    ** hold the STATIC_MEM mutex when the routines here are invoked. */
18266    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18267  }
18268  return SQLITE_OK;
18269}
18270
18271/*
18272** Deinitialize the memory allocation subsystem.
18273*/
18274static void sqlite3MemShutdown(void *NotUsed){
18275  UNUSED_PARAMETER(NotUsed);
18276  mem.mutex = 0;
18277}
18278
18279/*
18280** Round up a request size to the next valid allocation size.
18281*/
18282static int sqlite3MemRoundup(int n){
18283  return ROUND8(n);
18284}
18285
18286/*
18287** Fill a buffer with pseudo-random bytes.  This is used to preset
18288** the content of a new memory allocation to unpredictable values and
18289** to clear the content of a freed allocation to unpredictable values.
18290*/
18291static void randomFill(char *pBuf, int nByte){
18292  unsigned int x, y, r;
18293  x = SQLITE_PTR_TO_INT(pBuf);
18294  y = nByte | 1;
18295  while( nByte >= 4 ){
18296    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
18297    y = y*1103515245 + 12345;
18298    r = x ^ y;
18299    *(int*)pBuf = r;
18300    pBuf += 4;
18301    nByte -= 4;
18302  }
18303  while( nByte-- > 0 ){
18304    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
18305    y = y*1103515245 + 12345;
18306    r = x ^ y;
18307    *(pBuf++) = r & 0xff;
18308  }
18309}
18310
18311/*
18312** Allocate nByte bytes of memory.
18313*/
18314static void *sqlite3MemMalloc(int nByte){
18315  struct MemBlockHdr *pHdr;
18316  void **pBt;
18317  char *z;
18318  int *pInt;
18319  void *p = 0;
18320  int totalSize;
18321  int nReserve;
18322  sqlite3_mutex_enter(mem.mutex);
18323  assert( mem.disallow==0 );
18324  nReserve = ROUND8(nByte);
18325  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
18326               mem.nBacktrace*sizeof(void*) + mem.nTitle;
18327  p = malloc(totalSize);
18328  if( p ){
18329    z = p;
18330    pBt = (void**)&z[mem.nTitle];
18331    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
18332    pHdr->pNext = 0;
18333    pHdr->pPrev = mem.pLast;
18334    if( mem.pLast ){
18335      mem.pLast->pNext = pHdr;
18336    }else{
18337      mem.pFirst = pHdr;
18338    }
18339    mem.pLast = pHdr;
18340    pHdr->iForeGuard = FOREGUARD;
18341    pHdr->eType = MEMTYPE_HEAP;
18342    pHdr->nBacktraceSlots = mem.nBacktrace;
18343    pHdr->nTitle = mem.nTitle;
18344    if( mem.nBacktrace ){
18345      void *aAddr[40];
18346      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
18347      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
18348      assert(pBt[0]);
18349      if( mem.xBacktrace ){
18350        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
18351      }
18352    }else{
18353      pHdr->nBacktrace = 0;
18354    }
18355    if( mem.nTitle ){
18356      memcpy(z, mem.zTitle, mem.nTitle);
18357    }
18358    pHdr->iSize = nByte;
18359    adjustStats(nByte, +1);
18360    pInt = (int*)&pHdr[1];
18361    pInt[nReserve/sizeof(int)] = REARGUARD;
18362    randomFill((char*)pInt, nByte);
18363    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
18364    p = (void*)pInt;
18365  }
18366  sqlite3_mutex_leave(mem.mutex);
18367  return p;
18368}
18369
18370/*
18371** Free memory.
18372*/
18373static void sqlite3MemFree(void *pPrior){
18374  struct MemBlockHdr *pHdr;
18375  void **pBt;
18376  char *z;
18377  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
18378       || mem.mutex!=0 );
18379  pHdr = sqlite3MemsysGetHeader(pPrior);
18380  pBt = (void**)pHdr;
18381  pBt -= pHdr->nBacktraceSlots;
18382  sqlite3_mutex_enter(mem.mutex);
18383  if( pHdr->pPrev ){
18384    assert( pHdr->pPrev->pNext==pHdr );
18385    pHdr->pPrev->pNext = pHdr->pNext;
18386  }else{
18387    assert( mem.pFirst==pHdr );
18388    mem.pFirst = pHdr->pNext;
18389  }
18390  if( pHdr->pNext ){
18391    assert( pHdr->pNext->pPrev==pHdr );
18392    pHdr->pNext->pPrev = pHdr->pPrev;
18393  }else{
18394    assert( mem.pLast==pHdr );
18395    mem.pLast = pHdr->pPrev;
18396  }
18397  z = (char*)pBt;
18398  z -= pHdr->nTitle;
18399  adjustStats((int)pHdr->iSize, -1);
18400  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
18401                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
18402  free(z);
18403  sqlite3_mutex_leave(mem.mutex);
18404}
18405
18406/*
18407** Change the size of an existing memory allocation.
18408**
18409** For this debugging implementation, we *always* make a copy of the
18410** allocation into a new place in memory.  In this way, if the
18411** higher level code is using pointer to the old allocation, it is
18412** much more likely to break and we are much more liking to find
18413** the error.
18414*/
18415static void *sqlite3MemRealloc(void *pPrior, int nByte){
18416  struct MemBlockHdr *pOldHdr;
18417  void *pNew;
18418  assert( mem.disallow==0 );
18419  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
18420  pOldHdr = sqlite3MemsysGetHeader(pPrior);
18421  pNew = sqlite3MemMalloc(nByte);
18422  if( pNew ){
18423    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
18424    if( nByte>pOldHdr->iSize ){
18425      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
18426    }
18427    sqlite3MemFree(pPrior);
18428  }
18429  return pNew;
18430}
18431
18432/*
18433** Populate the low-level memory allocation function pointers in
18434** sqlite3GlobalConfig.m with pointers to the routines in this file.
18435*/
18436SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18437  static const sqlite3_mem_methods defaultMethods = {
18438     sqlite3MemMalloc,
18439     sqlite3MemFree,
18440     sqlite3MemRealloc,
18441     sqlite3MemSize,
18442     sqlite3MemRoundup,
18443     sqlite3MemInit,
18444     sqlite3MemShutdown,
18445     0
18446  };
18447  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18448}
18449
18450/*
18451** Set the "type" of an allocation.
18452*/
18453SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
18454  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18455    struct MemBlockHdr *pHdr;
18456    pHdr = sqlite3MemsysGetHeader(p);
18457    assert( pHdr->iForeGuard==FOREGUARD );
18458    pHdr->eType = eType;
18459  }
18460}
18461
18462/*
18463** Return TRUE if the mask of type in eType matches the type of the
18464** allocation p.  Also return true if p==NULL.
18465**
18466** This routine is designed for use within an assert() statement, to
18467** verify the type of an allocation.  For example:
18468**
18469**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18470*/
18471SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
18472  int rc = 1;
18473  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18474    struct MemBlockHdr *pHdr;
18475    pHdr = sqlite3MemsysGetHeader(p);
18476    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
18477    if( (pHdr->eType&eType)==0 ){
18478      rc = 0;
18479    }
18480  }
18481  return rc;
18482}
18483
18484/*
18485** Return TRUE if the mask of type in eType matches no bits of the type of the
18486** allocation p.  Also return true if p==NULL.
18487**
18488** This routine is designed for use within an assert() statement, to
18489** verify the type of an allocation.  For example:
18490**
18491**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18492*/
18493SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
18494  int rc = 1;
18495  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18496    struct MemBlockHdr *pHdr;
18497    pHdr = sqlite3MemsysGetHeader(p);
18498    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
18499    if( (pHdr->eType&eType)!=0 ){
18500      rc = 0;
18501    }
18502  }
18503  return rc;
18504}
18505
18506/*
18507** Set the number of backtrace levels kept for each allocation.
18508** A value of zero turns off backtracing.  The number is always rounded
18509** up to a multiple of 2.
18510*/
18511SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
18512  if( depth<0 ){ depth = 0; }
18513  if( depth>20 ){ depth = 20; }
18514  depth = (depth+1)&0xfe;
18515  mem.nBacktrace = depth;
18516}
18517
18518SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
18519  mem.xBacktrace = xBacktrace;
18520}
18521
18522/*
18523** Set the title string for subsequent allocations.
18524*/
18525SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
18526  unsigned int n = sqlite3Strlen30(zTitle) + 1;
18527  sqlite3_mutex_enter(mem.mutex);
18528  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
18529  memcpy(mem.zTitle, zTitle, n);
18530  mem.zTitle[n] = 0;
18531  mem.nTitle = ROUND8(n);
18532  sqlite3_mutex_leave(mem.mutex);
18533}
18534
18535SQLITE_PRIVATE void sqlite3MemdebugSync(){
18536  struct MemBlockHdr *pHdr;
18537  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18538    void **pBt = (void**)pHdr;
18539    pBt -= pHdr->nBacktraceSlots;
18540    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
18541  }
18542}
18543
18544/*
18545** Open the file indicated and write a log of all unfreed memory
18546** allocations into that log.
18547*/
18548SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
18549  FILE *out;
18550  struct MemBlockHdr *pHdr;
18551  void **pBt;
18552  int i;
18553  out = fopen(zFilename, "w");
18554  if( out==0 ){
18555    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18556                    zFilename);
18557    return;
18558  }
18559  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18560    char *z = (char*)pHdr;
18561    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
18562    fprintf(out, "**** %lld bytes at %p from %s ****\n",
18563            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
18564    if( pHdr->nBacktrace ){
18565      fflush(out);
18566      pBt = (void**)pHdr;
18567      pBt -= pHdr->nBacktraceSlots;
18568      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
18569      fprintf(out, "\n");
18570    }
18571  }
18572  fprintf(out, "COUNTS:\n");
18573  for(i=0; i<NCSIZE-1; i++){
18574    if( mem.nAlloc[i] ){
18575      fprintf(out, "   %5d: %10d %10d %10d\n",
18576            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
18577    }
18578  }
18579  if( mem.nAlloc[NCSIZE-1] ){
18580    fprintf(out, "   %5d: %10d %10d %10d\n",
18581             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
18582             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
18583  }
18584  fclose(out);
18585}
18586
18587/*
18588** Return the number of times sqlite3MemMalloc() has been called.
18589*/
18590SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
18591  int i;
18592  int nTotal = 0;
18593  for(i=0; i<NCSIZE; i++){
18594    nTotal += mem.nAlloc[i];
18595  }
18596  return nTotal;
18597}
18598
18599
18600#endif /* SQLITE_MEMDEBUG */
18601
18602/************** End of mem2.c ************************************************/
18603/************** Begin file mem3.c ********************************************/
18604/*
18605** 2007 October 14
18606**
18607** The author disclaims copyright to this source code.  In place of
18608** a legal notice, here is a blessing:
18609**
18610**    May you do good and not evil.
18611**    May you find forgiveness for yourself and forgive others.
18612**    May you share freely, never taking more than you give.
18613**
18614*************************************************************************
18615** This file contains the C functions that implement a memory
18616** allocation subsystem for use by SQLite.
18617**
18618** This version of the memory allocation subsystem omits all
18619** use of malloc(). The SQLite user supplies a block of memory
18620** before calling sqlite3_initialize() from which allocations
18621** are made and returned by the xMalloc() and xRealloc()
18622** implementations. Once sqlite3_initialize() has been called,
18623** the amount of memory available to SQLite is fixed and cannot
18624** be changed.
18625**
18626** This version of the memory allocation subsystem is included
18627** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
18628*/
18629/* #include "sqliteInt.h" */
18630
18631/*
18632** This version of the memory allocator is only built into the library
18633** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
18634** mean that the library will use a memory-pool by default, just that
18635** it is available. The mempool allocator is activated by calling
18636** sqlite3_config().
18637*/
18638#ifdef SQLITE_ENABLE_MEMSYS3
18639
18640/*
18641** Maximum size (in Mem3Blocks) of a "small" chunk.
18642*/
18643#define MX_SMALL 10
18644
18645
18646/*
18647** Number of freelist hash slots
18648*/
18649#define N_HASH  61
18650
18651/*
18652** A memory allocation (also called a "chunk") consists of two or
18653** more blocks where each block is 8 bytes.  The first 8 bytes are
18654** a header that is not returned to the user.
18655**
18656** A chunk is two or more blocks that is either checked out or
18657** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
18658** size of the allocation in blocks if the allocation is free.
18659** The u.hdr.size4x&1 bit is true if the chunk is checked out and
18660** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
18661** is true if the previous chunk is checked out and false if the
18662** previous chunk is free.  The u.hdr.prevSize field is the size of
18663** the previous chunk in blocks if the previous chunk is on the
18664** freelist. If the previous chunk is checked out, then
18665** u.hdr.prevSize can be part of the data for that chunk and should
18666** not be read or written.
18667**
18668** We often identify a chunk by its index in mem3.aPool[].  When
18669** this is done, the chunk index refers to the second block of
18670** the chunk.  In this way, the first chunk has an index of 1.
18671** A chunk index of 0 means "no such chunk" and is the equivalent
18672** of a NULL pointer.
18673**
18674** The second block of free chunks is of the form u.list.  The
18675** two fields form a double-linked list of chunks of related sizes.
18676** Pointers to the head of the list are stored in mem3.aiSmall[]
18677** for smaller chunks and mem3.aiHash[] for larger chunks.
18678**
18679** The second block of a chunk is user data if the chunk is checked
18680** out.  If a chunk is checked out, the user data may extend into
18681** the u.hdr.prevSize value of the following chunk.
18682*/
18683typedef struct Mem3Block Mem3Block;
18684struct Mem3Block {
18685  union {
18686    struct {
18687      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
18688      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
18689    } hdr;
18690    struct {
18691      u32 next;       /* Index in mem3.aPool[] of next free chunk */
18692      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
18693    } list;
18694  } u;
18695};
18696
18697/*
18698** All of the static variables used by this module are collected
18699** into a single structure named "mem3".  This is to keep the
18700** static variables organized and to reduce namespace pollution
18701** when this module is combined with other in the amalgamation.
18702*/
18703static SQLITE_WSD struct Mem3Global {
18704  /*
18705  ** Memory available for allocation. nPool is the size of the array
18706  ** (in Mem3Blocks) pointed to by aPool less 2.
18707  */
18708  u32 nPool;
18709  Mem3Block *aPool;
18710
18711  /*
18712  ** True if we are evaluating an out-of-memory callback.
18713  */
18714  int alarmBusy;
18715
18716  /*
18717  ** Mutex to control access to the memory allocation subsystem.
18718  */
18719  sqlite3_mutex *mutex;
18720
18721  /*
18722  ** The minimum amount of free space that we have seen.
18723  */
18724  u32 mnMaster;
18725
18726  /*
18727  ** iMaster is the index of the master chunk.  Most new allocations
18728  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
18729  ** of the current master.  iMaster is 0 if there is not master chunk.
18730  ** The master chunk is not in either the aiHash[] or aiSmall[].
18731  */
18732  u32 iMaster;
18733  u32 szMaster;
18734
18735  /*
18736  ** Array of lists of free blocks according to the block size
18737  ** for smaller chunks, or a hash on the block size for larger
18738  ** chunks.
18739  */
18740  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
18741  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
18742} mem3 = { 97535575 };
18743
18744#define mem3 GLOBAL(struct Mem3Global, mem3)
18745
18746/*
18747** Unlink the chunk at mem3.aPool[i] from list it is currently
18748** on.  *pRoot is the list that i is a member of.
18749*/
18750static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
18751  u32 next = mem3.aPool[i].u.list.next;
18752  u32 prev = mem3.aPool[i].u.list.prev;
18753  assert( sqlite3_mutex_held(mem3.mutex) );
18754  if( prev==0 ){
18755    *pRoot = next;
18756  }else{
18757    mem3.aPool[prev].u.list.next = next;
18758  }
18759  if( next ){
18760    mem3.aPool[next].u.list.prev = prev;
18761  }
18762  mem3.aPool[i].u.list.next = 0;
18763  mem3.aPool[i].u.list.prev = 0;
18764}
18765
18766/*
18767** Unlink the chunk at index i from
18768** whatever list is currently a member of.
18769*/
18770static void memsys3Unlink(u32 i){
18771  u32 size, hash;
18772  assert( sqlite3_mutex_held(mem3.mutex) );
18773  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18774  assert( i>=1 );
18775  size = mem3.aPool[i-1].u.hdr.size4x/4;
18776  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18777  assert( size>=2 );
18778  if( size <= MX_SMALL ){
18779    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
18780  }else{
18781    hash = size % N_HASH;
18782    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18783  }
18784}
18785
18786/*
18787** Link the chunk at mem3.aPool[i] so that is on the list rooted
18788** at *pRoot.
18789*/
18790static void memsys3LinkIntoList(u32 i, u32 *pRoot){
18791  assert( sqlite3_mutex_held(mem3.mutex) );
18792  mem3.aPool[i].u.list.next = *pRoot;
18793  mem3.aPool[i].u.list.prev = 0;
18794  if( *pRoot ){
18795    mem3.aPool[*pRoot].u.list.prev = i;
18796  }
18797  *pRoot = i;
18798}
18799
18800/*
18801** Link the chunk at index i into either the appropriate
18802** small chunk list, or into the large chunk hash table.
18803*/
18804static void memsys3Link(u32 i){
18805  u32 size, hash;
18806  assert( sqlite3_mutex_held(mem3.mutex) );
18807  assert( i>=1 );
18808  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18809  size = mem3.aPool[i-1].u.hdr.size4x/4;
18810  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18811  assert( size>=2 );
18812  if( size <= MX_SMALL ){
18813    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
18814  }else{
18815    hash = size % N_HASH;
18816    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
18817  }
18818}
18819
18820/*
18821** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18822** will already be held (obtained by code in malloc.c) if
18823** sqlite3GlobalConfig.bMemStat is true.
18824*/
18825static void memsys3Enter(void){
18826  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
18827    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18828  }
18829  sqlite3_mutex_enter(mem3.mutex);
18830}
18831static void memsys3Leave(void){
18832  sqlite3_mutex_leave(mem3.mutex);
18833}
18834
18835/*
18836** Called when we are unable to satisfy an allocation of nBytes.
18837*/
18838static void memsys3OutOfMemory(int nByte){
18839  if( !mem3.alarmBusy ){
18840    mem3.alarmBusy = 1;
18841    assert( sqlite3_mutex_held(mem3.mutex) );
18842    sqlite3_mutex_leave(mem3.mutex);
18843    sqlite3_release_memory(nByte);
18844    sqlite3_mutex_enter(mem3.mutex);
18845    mem3.alarmBusy = 0;
18846  }
18847}
18848
18849
18850/*
18851** Chunk i is a free chunk that has been unlinked.  Adjust its
18852** size parameters for check-out and return a pointer to the
18853** user portion of the chunk.
18854*/
18855static void *memsys3Checkout(u32 i, u32 nBlock){
18856  u32 x;
18857  assert( sqlite3_mutex_held(mem3.mutex) );
18858  assert( i>=1 );
18859  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
18860  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
18861  x = mem3.aPool[i-1].u.hdr.size4x;
18862  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
18863  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
18864  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
18865  return &mem3.aPool[i];
18866}
18867
18868/*
18869** Carve a piece off of the end of the mem3.iMaster free chunk.
18870** Return a pointer to the new allocation.  Or, if the master chunk
18871** is not large enough, return 0.
18872*/
18873static void *memsys3FromMaster(u32 nBlock){
18874  assert( sqlite3_mutex_held(mem3.mutex) );
18875  assert( mem3.szMaster>=nBlock );
18876  if( nBlock>=mem3.szMaster-1 ){
18877    /* Use the entire master */
18878    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
18879    mem3.iMaster = 0;
18880    mem3.szMaster = 0;
18881    mem3.mnMaster = 0;
18882    return p;
18883  }else{
18884    /* Split the master block.  Return the tail. */
18885    u32 newi, x;
18886    newi = mem3.iMaster + mem3.szMaster - nBlock;
18887    assert( newi > mem3.iMaster+1 );
18888    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
18889    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
18890    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
18891    mem3.szMaster -= nBlock;
18892    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
18893    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18894    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18895    if( mem3.szMaster < mem3.mnMaster ){
18896      mem3.mnMaster = mem3.szMaster;
18897    }
18898    return (void*)&mem3.aPool[newi];
18899  }
18900}
18901
18902/*
18903** *pRoot is the head of a list of free chunks of the same size
18904** or same size hash.  In other words, *pRoot is an entry in either
18905** mem3.aiSmall[] or mem3.aiHash[].
18906**
18907** This routine examines all entries on the given list and tries
18908** to coalesce each entries with adjacent free chunks.
18909**
18910** If it sees a chunk that is larger than mem3.iMaster, it replaces
18911** the current mem3.iMaster with the new larger chunk.  In order for
18912** this mem3.iMaster replacement to work, the master chunk must be
18913** linked into the hash tables.  That is not the normal state of
18914** affairs, of course.  The calling routine must link the master
18915** chunk before invoking this routine, then must unlink the (possibly
18916** changed) master chunk once this routine has finished.
18917*/
18918static void memsys3Merge(u32 *pRoot){
18919  u32 iNext, prev, size, i, x;
18920
18921  assert( sqlite3_mutex_held(mem3.mutex) );
18922  for(i=*pRoot; i>0; i=iNext){
18923    iNext = mem3.aPool[i].u.list.next;
18924    size = mem3.aPool[i-1].u.hdr.size4x;
18925    assert( (size&1)==0 );
18926    if( (size&2)==0 ){
18927      memsys3UnlinkFromList(i, pRoot);
18928      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
18929      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
18930      if( prev==iNext ){
18931        iNext = mem3.aPool[prev].u.list.next;
18932      }
18933      memsys3Unlink(prev);
18934      size = i + size/4 - prev;
18935      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
18936      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
18937      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
18938      memsys3Link(prev);
18939      i = prev;
18940    }else{
18941      size /= 4;
18942    }
18943    if( size>mem3.szMaster ){
18944      mem3.iMaster = i;
18945      mem3.szMaster = size;
18946    }
18947  }
18948}
18949
18950/*
18951** Return a block of memory of at least nBytes in size.
18952** Return NULL if unable.
18953**
18954** This function assumes that the necessary mutexes, if any, are
18955** already held by the caller. Hence "Unsafe".
18956*/
18957static void *memsys3MallocUnsafe(int nByte){
18958  u32 i;
18959  u32 nBlock;
18960  u32 toFree;
18961
18962  assert( sqlite3_mutex_held(mem3.mutex) );
18963  assert( sizeof(Mem3Block)==8 );
18964  if( nByte<=12 ){
18965    nBlock = 2;
18966  }else{
18967    nBlock = (nByte + 11)/8;
18968  }
18969  assert( nBlock>=2 );
18970
18971  /* STEP 1:
18972  ** Look for an entry of the correct size in either the small
18973  ** chunk table or in the large chunk hash table.  This is
18974  ** successful most of the time (about 9 times out of 10).
18975  */
18976  if( nBlock <= MX_SMALL ){
18977    i = mem3.aiSmall[nBlock-2];
18978    if( i>0 ){
18979      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
18980      return memsys3Checkout(i, nBlock);
18981    }
18982  }else{
18983    int hash = nBlock % N_HASH;
18984    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
18985      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
18986        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18987        return memsys3Checkout(i, nBlock);
18988      }
18989    }
18990  }
18991
18992  /* STEP 2:
18993  ** Try to satisfy the allocation by carving a piece off of the end
18994  ** of the master chunk.  This step usually works if step 1 fails.
18995  */
18996  if( mem3.szMaster>=nBlock ){
18997    return memsys3FromMaster(nBlock);
18998  }
18999
19000
19001  /* STEP 3:
19002  ** Loop through the entire memory pool.  Coalesce adjacent free
19003  ** chunks.  Recompute the master chunk as the largest free chunk.
19004  ** Then try again to satisfy the allocation by carving a piece off
19005  ** of the end of the master chunk.  This step happens very
19006  ** rarely (we hope!)
19007  */
19008  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
19009    memsys3OutOfMemory(toFree);
19010    if( mem3.iMaster ){
19011      memsys3Link(mem3.iMaster);
19012      mem3.iMaster = 0;
19013      mem3.szMaster = 0;
19014    }
19015    for(i=0; i<N_HASH; i++){
19016      memsys3Merge(&mem3.aiHash[i]);
19017    }
19018    for(i=0; i<MX_SMALL-1; i++){
19019      memsys3Merge(&mem3.aiSmall[i]);
19020    }
19021    if( mem3.szMaster ){
19022      memsys3Unlink(mem3.iMaster);
19023      if( mem3.szMaster>=nBlock ){
19024        return memsys3FromMaster(nBlock);
19025      }
19026    }
19027  }
19028
19029  /* If none of the above worked, then we fail. */
19030  return 0;
19031}
19032
19033/*
19034** Free an outstanding memory allocation.
19035**
19036** This function assumes that the necessary mutexes, if any, are
19037** already held by the caller. Hence "Unsafe".
19038*/
19039static void memsys3FreeUnsafe(void *pOld){
19040  Mem3Block *p = (Mem3Block*)pOld;
19041  int i;
19042  u32 size, x;
19043  assert( sqlite3_mutex_held(mem3.mutex) );
19044  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
19045  i = p - mem3.aPool;
19046  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
19047  size = mem3.aPool[i-1].u.hdr.size4x/4;
19048  assert( i+size<=mem3.nPool+1 );
19049  mem3.aPool[i-1].u.hdr.size4x &= ~1;
19050  mem3.aPool[i+size-1].u.hdr.prevSize = size;
19051  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
19052  memsys3Link(i);
19053
19054  /* Try to expand the master using the newly freed chunk */
19055  if( mem3.iMaster ){
19056    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
19057      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
19058      mem3.iMaster -= size;
19059      mem3.szMaster += size;
19060      memsys3Unlink(mem3.iMaster);
19061      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19062      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19063      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19064    }
19065    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19066    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
19067      memsys3Unlink(mem3.iMaster+mem3.szMaster);
19068      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
19069      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19070      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19071    }
19072  }
19073}
19074
19075/*
19076** Return the size of an outstanding allocation, in bytes.  The
19077** size returned omits the 8-byte header overhead.  This only
19078** works for chunks that are currently checked out.
19079*/
19080static int memsys3Size(void *p){
19081  Mem3Block *pBlock;
19082  if( p==0 ) return 0;
19083  pBlock = (Mem3Block*)p;
19084  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
19085  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
19086}
19087
19088/*
19089** Round up a request size to the next valid allocation size.
19090*/
19091static int memsys3Roundup(int n){
19092  if( n<=12 ){
19093    return 12;
19094  }else{
19095    return ((n+11)&~7) - 4;
19096  }
19097}
19098
19099/*
19100** Allocate nBytes of memory.
19101*/
19102static void *memsys3Malloc(int nBytes){
19103  sqlite3_int64 *p;
19104  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
19105  memsys3Enter();
19106  p = memsys3MallocUnsafe(nBytes);
19107  memsys3Leave();
19108  return (void*)p;
19109}
19110
19111/*
19112** Free memory.
19113*/
19114static void memsys3Free(void *pPrior){
19115  assert( pPrior );
19116  memsys3Enter();
19117  memsys3FreeUnsafe(pPrior);
19118  memsys3Leave();
19119}
19120
19121/*
19122** Change the size of an existing memory allocation
19123*/
19124static void *memsys3Realloc(void *pPrior, int nBytes){
19125  int nOld;
19126  void *p;
19127  if( pPrior==0 ){
19128    return sqlite3_malloc(nBytes);
19129  }
19130  if( nBytes<=0 ){
19131    sqlite3_free(pPrior);
19132    return 0;
19133  }
19134  nOld = memsys3Size(pPrior);
19135  if( nBytes<=nOld && nBytes>=nOld-128 ){
19136    return pPrior;
19137  }
19138  memsys3Enter();
19139  p = memsys3MallocUnsafe(nBytes);
19140  if( p ){
19141    if( nOld<nBytes ){
19142      memcpy(p, pPrior, nOld);
19143    }else{
19144      memcpy(p, pPrior, nBytes);
19145    }
19146    memsys3FreeUnsafe(pPrior);
19147  }
19148  memsys3Leave();
19149  return p;
19150}
19151
19152/*
19153** Initialize this module.
19154*/
19155static int memsys3Init(void *NotUsed){
19156  UNUSED_PARAMETER(NotUsed);
19157  if( !sqlite3GlobalConfig.pHeap ){
19158    return SQLITE_ERROR;
19159  }
19160
19161  /* Store a pointer to the memory block in global structure mem3. */
19162  assert( sizeof(Mem3Block)==8 );
19163  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
19164  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
19165
19166  /* Initialize the master block. */
19167  mem3.szMaster = mem3.nPool;
19168  mem3.mnMaster = mem3.szMaster;
19169  mem3.iMaster = 1;
19170  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
19171  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
19172  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
19173
19174  return SQLITE_OK;
19175}
19176
19177/*
19178** Deinitialize this module.
19179*/
19180static void memsys3Shutdown(void *NotUsed){
19181  UNUSED_PARAMETER(NotUsed);
19182  mem3.mutex = 0;
19183  return;
19184}
19185
19186
19187
19188/*
19189** Open the file indicated and write a log of all unfreed memory
19190** allocations into that log.
19191*/
19192SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
19193#ifdef SQLITE_DEBUG
19194  FILE *out;
19195  u32 i, j;
19196  u32 size;
19197  if( zFilename==0 || zFilename[0]==0 ){
19198    out = stdout;
19199  }else{
19200    out = fopen(zFilename, "w");
19201    if( out==0 ){
19202      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19203                      zFilename);
19204      return;
19205    }
19206  }
19207  memsys3Enter();
19208  fprintf(out, "CHUNKS:\n");
19209  for(i=1; i<=mem3.nPool; i+=size/4){
19210    size = mem3.aPool[i-1].u.hdr.size4x;
19211    if( size/4<=1 ){
19212      fprintf(out, "%p size error\n", &mem3.aPool[i]);
19213      assert( 0 );
19214      break;
19215    }
19216    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
19217      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
19218      assert( 0 );
19219      break;
19220    }
19221    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
19222      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
19223      assert( 0 );
19224      break;
19225    }
19226    if( size&1 ){
19227      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
19228    }else{
19229      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
19230                  i==mem3.iMaster ? " **master**" : "");
19231    }
19232  }
19233  for(i=0; i<MX_SMALL-1; i++){
19234    if( mem3.aiSmall[i]==0 ) continue;
19235    fprintf(out, "small(%2d):", i);
19236    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
19237      fprintf(out, " %p(%d)", &mem3.aPool[j],
19238              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19239    }
19240    fprintf(out, "\n");
19241  }
19242  for(i=0; i<N_HASH; i++){
19243    if( mem3.aiHash[i]==0 ) continue;
19244    fprintf(out, "hash(%2d):", i);
19245    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
19246      fprintf(out, " %p(%d)", &mem3.aPool[j],
19247              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19248    }
19249    fprintf(out, "\n");
19250  }
19251  fprintf(out, "master=%d\n", mem3.iMaster);
19252  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
19253  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
19254  sqlite3_mutex_leave(mem3.mutex);
19255  if( out==stdout ){
19256    fflush(stdout);
19257  }else{
19258    fclose(out);
19259  }
19260#else
19261  UNUSED_PARAMETER(zFilename);
19262#endif
19263}
19264
19265/*
19266** This routine is the only routine in this file with external
19267** linkage.
19268**
19269** Populate the low-level memory allocation function pointers in
19270** sqlite3GlobalConfig.m with pointers to the routines in this file. The
19271** arguments specify the block of memory to manage.
19272**
19273** This routine is only called by sqlite3_config(), and therefore
19274** is not required to be threadsafe (it is not).
19275*/
19276SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
19277  static const sqlite3_mem_methods mempoolMethods = {
19278     memsys3Malloc,
19279     memsys3Free,
19280     memsys3Realloc,
19281     memsys3Size,
19282     memsys3Roundup,
19283     memsys3Init,
19284     memsys3Shutdown,
19285     0
19286  };
19287  return &mempoolMethods;
19288}
19289
19290#endif /* SQLITE_ENABLE_MEMSYS3 */
19291
19292/************** End of mem3.c ************************************************/
19293/************** Begin file mem5.c ********************************************/
19294/*
19295** 2007 October 14
19296**
19297** The author disclaims copyright to this source code.  In place of
19298** a legal notice, here is a blessing:
19299**
19300**    May you do good and not evil.
19301**    May you find forgiveness for yourself and forgive others.
19302**    May you share freely, never taking more than you give.
19303**
19304*************************************************************************
19305** This file contains the C functions that implement a memory
19306** allocation subsystem for use by SQLite.
19307**
19308** This version of the memory allocation subsystem omits all
19309** use of malloc(). The application gives SQLite a block of memory
19310** before calling sqlite3_initialize() from which allocations
19311** are made and returned by the xMalloc() and xRealloc()
19312** implementations. Once sqlite3_initialize() has been called,
19313** the amount of memory available to SQLite is fixed and cannot
19314** be changed.
19315**
19316** This version of the memory allocation subsystem is included
19317** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
19318**
19319** This memory allocator uses the following algorithm:
19320**
19321**   1.  All memory allocations sizes are rounded up to a power of 2.
19322**
19323**   2.  If two adjacent free blocks are the halves of a larger block,
19324**       then the two blocks are coalesced into the single larger block.
19325**
19326**   3.  New memory is allocated from the first available free block.
19327**
19328** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
19329** Concerning Dynamic Storage Allocation". Journal of the Association for
19330** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
19331**
19332** Let n be the size of the largest allocation divided by the minimum
19333** allocation size (after rounding all sizes up to a power of 2.)  Let M
19334** be the maximum amount of memory ever outstanding at one time.  Let
19335** N be the total amount of memory available for allocation.  Robson
19336** proved that this memory allocator will never breakdown due to
19337** fragmentation as long as the following constraint holds:
19338**
19339**      N >=  M*(1 + log2(n)/2) - n + 1
19340**
19341** The sqlite3_status() logic tracks the maximum values of n and M so
19342** that an application can, at any time, verify this constraint.
19343*/
19344/* #include "sqliteInt.h" */
19345
19346/*
19347** This version of the memory allocator is used only when
19348** SQLITE_ENABLE_MEMSYS5 is defined.
19349*/
19350#ifdef SQLITE_ENABLE_MEMSYS5
19351
19352/*
19353** A minimum allocation is an instance of the following structure.
19354** Larger allocations are an array of these structures where the
19355** size of the array is a power of 2.
19356**
19357** The size of this object must be a power of two.  That fact is
19358** verified in memsys5Init().
19359*/
19360typedef struct Mem5Link Mem5Link;
19361struct Mem5Link {
19362  int next;       /* Index of next free chunk */
19363  int prev;       /* Index of previous free chunk */
19364};
19365
19366/*
19367** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
19368** mem5.szAtom is always at least 8 and 32-bit integers are used,
19369** it is not actually possible to reach this limit.
19370*/
19371#define LOGMAX 30
19372
19373/*
19374** Masks used for mem5.aCtrl[] elements.
19375*/
19376#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
19377#define CTRL_FREE     0x20    /* True if not checked out */
19378
19379/*
19380** All of the static variables used by this module are collected
19381** into a single structure named "mem5".  This is to keep the
19382** static variables organized and to reduce namespace pollution
19383** when this module is combined with other in the amalgamation.
19384*/
19385static SQLITE_WSD struct Mem5Global {
19386  /*
19387  ** Memory available for allocation
19388  */
19389  int szAtom;      /* Smallest possible allocation in bytes */
19390  int nBlock;      /* Number of szAtom sized blocks in zPool */
19391  u8 *zPool;       /* Memory available to be allocated */
19392
19393  /*
19394  ** Mutex to control access to the memory allocation subsystem.
19395  */
19396  sqlite3_mutex *mutex;
19397
19398  /*
19399  ** Performance statistics
19400  */
19401  u64 nAlloc;         /* Total number of calls to malloc */
19402  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
19403  u64 totalExcess;    /* Total internal fragmentation */
19404  u32 currentOut;     /* Current checkout, including internal fragmentation */
19405  u32 currentCount;   /* Current number of distinct checkouts */
19406  u32 maxOut;         /* Maximum instantaneous currentOut */
19407  u32 maxCount;       /* Maximum instantaneous currentCount */
19408  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
19409
19410  /*
19411  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
19412  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
19413  ** and so forth.
19414  */
19415  int aiFreelist[LOGMAX+1];
19416
19417  /*
19418  ** Space for tracking which blocks are checked out and the size
19419  ** of each block.  One byte per block.
19420  */
19421  u8 *aCtrl;
19422
19423} mem5;
19424
19425/*
19426** Access the static variable through a macro for SQLITE_OMIT_WSD.
19427*/
19428#define mem5 GLOBAL(struct Mem5Global, mem5)
19429
19430/*
19431** Assuming mem5.zPool is divided up into an array of Mem5Link
19432** structures, return a pointer to the idx-th such link.
19433*/
19434#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
19435
19436/*
19437** Unlink the chunk at mem5.aPool[i] from list it is currently
19438** on.  It should be found on mem5.aiFreelist[iLogsize].
19439*/
19440static void memsys5Unlink(int i, int iLogsize){
19441  int next, prev;
19442  assert( i>=0 && i<mem5.nBlock );
19443  assert( iLogsize>=0 && iLogsize<=LOGMAX );
19444  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19445
19446  next = MEM5LINK(i)->next;
19447  prev = MEM5LINK(i)->prev;
19448  if( prev<0 ){
19449    mem5.aiFreelist[iLogsize] = next;
19450  }else{
19451    MEM5LINK(prev)->next = next;
19452  }
19453  if( next>=0 ){
19454    MEM5LINK(next)->prev = prev;
19455  }
19456}
19457
19458/*
19459** Link the chunk at mem5.aPool[i] so that is on the iLogsize
19460** free list.
19461*/
19462static void memsys5Link(int i, int iLogsize){
19463  int x;
19464  assert( sqlite3_mutex_held(mem5.mutex) );
19465  assert( i>=0 && i<mem5.nBlock );
19466  assert( iLogsize>=0 && iLogsize<=LOGMAX );
19467  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19468
19469  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
19470  MEM5LINK(i)->prev = -1;
19471  if( x>=0 ){
19472    assert( x<mem5.nBlock );
19473    MEM5LINK(x)->prev = i;
19474  }
19475  mem5.aiFreelist[iLogsize] = i;
19476}
19477
19478/*
19479** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
19480** will already be held (obtained by code in malloc.c) if
19481** sqlite3GlobalConfig.bMemStat is true.
19482*/
19483static void memsys5Enter(void){
19484  sqlite3_mutex_enter(mem5.mutex);
19485}
19486static void memsys5Leave(void){
19487  sqlite3_mutex_leave(mem5.mutex);
19488}
19489
19490/*
19491** Return the size of an outstanding allocation, in bytes.  The
19492** size returned omits the 8-byte header overhead.  This only
19493** works for chunks that are currently checked out.
19494*/
19495static int memsys5Size(void *p){
19496  int iSize = 0;
19497  if( p ){
19498    int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
19499    assert( i>=0 && i<mem5.nBlock );
19500    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
19501  }
19502  return iSize;
19503}
19504
19505/*
19506** Return a block of memory of at least nBytes in size.
19507** Return NULL if unable.  Return NULL if nBytes==0.
19508**
19509** The caller guarantees that nByte is positive.
19510**
19511** The caller has obtained a mutex prior to invoking this
19512** routine so there is never any chance that two or more
19513** threads can be in this routine at the same time.
19514*/
19515static void *memsys5MallocUnsafe(int nByte){
19516  int i;           /* Index of a mem5.aPool[] slot */
19517  int iBin;        /* Index into mem5.aiFreelist[] */
19518  int iFullSz;     /* Size of allocation rounded up to power of 2 */
19519  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
19520
19521  /* nByte must be a positive */
19522  assert( nByte>0 );
19523
19524  /* Keep track of the maximum allocation request.  Even unfulfilled
19525  ** requests are counted */
19526  if( (u32)nByte>mem5.maxRequest ){
19527    mem5.maxRequest = nByte;
19528  }
19529
19530  /* Abort if the requested allocation size is larger than the largest
19531  ** power of two that we can represent using 32-bit signed integers.
19532  */
19533  if( nByte > 0x40000000 ){
19534    return 0;
19535  }
19536
19537  /* Round nByte up to the next valid power of two */
19538  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
19539
19540  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
19541  ** block.  If not, then split a block of the next larger power of
19542  ** two in order to create a new free block of size iLogsize.
19543  */
19544  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
19545  if( iBin>LOGMAX ){
19546    testcase( sqlite3GlobalConfig.xLog!=0 );
19547    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
19548    return 0;
19549  }
19550  i = mem5.aiFreelist[iBin];
19551  memsys5Unlink(i, iBin);
19552  while( iBin>iLogsize ){
19553    int newSize;
19554
19555    iBin--;
19556    newSize = 1 << iBin;
19557    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
19558    memsys5Link(i+newSize, iBin);
19559  }
19560  mem5.aCtrl[i] = iLogsize;
19561
19562  /* Update allocator performance statistics. */
19563  mem5.nAlloc++;
19564  mem5.totalAlloc += iFullSz;
19565  mem5.totalExcess += iFullSz - nByte;
19566  mem5.currentCount++;
19567  mem5.currentOut += iFullSz;
19568  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
19569  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
19570
19571#ifdef SQLITE_DEBUG
19572  /* Make sure the allocated memory does not assume that it is set to zero
19573  ** or retains a value from a previous allocation */
19574  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
19575#endif
19576
19577  /* Return a pointer to the allocated memory. */
19578  return (void*)&mem5.zPool[i*mem5.szAtom];
19579}
19580
19581/*
19582** Free an outstanding memory allocation.
19583*/
19584static void memsys5FreeUnsafe(void *pOld){
19585  u32 size, iLogsize;
19586  int iBlock;
19587
19588  /* Set iBlock to the index of the block pointed to by pOld in
19589  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
19590  */
19591  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
19592
19593  /* Check that the pointer pOld points to a valid, non-free block. */
19594  assert( iBlock>=0 && iBlock<mem5.nBlock );
19595  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
19596  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
19597
19598  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
19599  size = 1<<iLogsize;
19600  assert( iBlock+size-1<(u32)mem5.nBlock );
19601
19602  mem5.aCtrl[iBlock] |= CTRL_FREE;
19603  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
19604  assert( mem5.currentCount>0 );
19605  assert( mem5.currentOut>=(size*mem5.szAtom) );
19606  mem5.currentCount--;
19607  mem5.currentOut -= size*mem5.szAtom;
19608  assert( mem5.currentOut>0 || mem5.currentCount==0 );
19609  assert( mem5.currentCount>0 || mem5.currentOut==0 );
19610
19611  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
19612  while( ALWAYS(iLogsize<LOGMAX) ){
19613    int iBuddy;
19614    if( (iBlock>>iLogsize) & 1 ){
19615      iBuddy = iBlock - size;
19616    }else{
19617      iBuddy = iBlock + size;
19618    }
19619    assert( iBuddy>=0 );
19620    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
19621    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
19622    memsys5Unlink(iBuddy, iLogsize);
19623    iLogsize++;
19624    if( iBuddy<iBlock ){
19625      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
19626      mem5.aCtrl[iBlock] = 0;
19627      iBlock = iBuddy;
19628    }else{
19629      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
19630      mem5.aCtrl[iBuddy] = 0;
19631    }
19632    size *= 2;
19633  }
19634
19635#ifdef SQLITE_DEBUG
19636  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
19637  ** not used after being freed */
19638  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
19639#endif
19640
19641  memsys5Link(iBlock, iLogsize);
19642}
19643
19644/*
19645** Allocate nBytes of memory.
19646*/
19647static void *memsys5Malloc(int nBytes){
19648  sqlite3_int64 *p = 0;
19649  if( nBytes>0 ){
19650    memsys5Enter();
19651    p = memsys5MallocUnsafe(nBytes);
19652    memsys5Leave();
19653  }
19654  return (void*)p;
19655}
19656
19657/*
19658** Free memory.
19659**
19660** The outer layer memory allocator prevents this routine from
19661** being called with pPrior==0.
19662*/
19663static void memsys5Free(void *pPrior){
19664  assert( pPrior!=0 );
19665  memsys5Enter();
19666  memsys5FreeUnsafe(pPrior);
19667  memsys5Leave();
19668}
19669
19670/*
19671** Change the size of an existing memory allocation.
19672**
19673** The outer layer memory allocator prevents this routine from
19674** being called with pPrior==0.
19675**
19676** nBytes is always a value obtained from a prior call to
19677** memsys5Round().  Hence nBytes is always a non-negative power
19678** of two.  If nBytes==0 that means that an oversize allocation
19679** (an allocation larger than 0x40000000) was requested and this
19680** routine should return 0 without freeing pPrior.
19681*/
19682static void *memsys5Realloc(void *pPrior, int nBytes){
19683  int nOld;
19684  void *p;
19685  assert( pPrior!=0 );
19686  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
19687  assert( nBytes>=0 );
19688  if( nBytes==0 ){
19689    return 0;
19690  }
19691  nOld = memsys5Size(pPrior);
19692  if( nBytes<=nOld ){
19693    return pPrior;
19694  }
19695  memsys5Enter();
19696  p = memsys5MallocUnsafe(nBytes);
19697  if( p ){
19698    memcpy(p, pPrior, nOld);
19699    memsys5FreeUnsafe(pPrior);
19700  }
19701  memsys5Leave();
19702  return p;
19703}
19704
19705/*
19706** Round up a request size to the next valid allocation size.  If
19707** the allocation is too large to be handled by this allocation system,
19708** return 0.
19709**
19710** All allocations must be a power of two and must be expressed by a
19711** 32-bit signed integer.  Hence the largest allocation is 0x40000000
19712** or 1073741824 bytes.
19713*/
19714static int memsys5Roundup(int n){
19715  int iFullSz;
19716  if( n > 0x40000000 ) return 0;
19717  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
19718  return iFullSz;
19719}
19720
19721/*
19722** Return the ceiling of the logarithm base 2 of iValue.
19723**
19724** Examples:   memsys5Log(1) -> 0
19725**             memsys5Log(2) -> 1
19726**             memsys5Log(4) -> 2
19727**             memsys5Log(5) -> 3
19728**             memsys5Log(8) -> 3
19729**             memsys5Log(9) -> 4
19730*/
19731static int memsys5Log(int iValue){
19732  int iLog;
19733  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
19734  return iLog;
19735}
19736
19737/*
19738** Initialize the memory allocator.
19739**
19740** This routine is not threadsafe.  The caller must be holding a mutex
19741** to prevent multiple threads from entering at the same time.
19742*/
19743static int memsys5Init(void *NotUsed){
19744  int ii;            /* Loop counter */
19745  int nByte;         /* Number of bytes of memory available to this allocator */
19746  u8 *zByte;         /* Memory usable by this allocator */
19747  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
19748  int iOffset;       /* An offset into mem5.aCtrl[] */
19749
19750  UNUSED_PARAMETER(NotUsed);
19751
19752  /* For the purposes of this routine, disable the mutex */
19753  mem5.mutex = 0;
19754
19755  /* The size of a Mem5Link object must be a power of two.  Verify that
19756  ** this is case.
19757  */
19758  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
19759
19760  nByte = sqlite3GlobalConfig.nHeap;
19761  zByte = (u8*)sqlite3GlobalConfig.pHeap;
19762  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
19763
19764  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
19765  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
19766  mem5.szAtom = (1<<nMinLog);
19767  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
19768    mem5.szAtom = mem5.szAtom << 1;
19769  }
19770
19771  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
19772  mem5.zPool = zByte;
19773  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
19774
19775  for(ii=0; ii<=LOGMAX; ii++){
19776    mem5.aiFreelist[ii] = -1;
19777  }
19778
19779  iOffset = 0;
19780  for(ii=LOGMAX; ii>=0; ii--){
19781    int nAlloc = (1<<ii);
19782    if( (iOffset+nAlloc)<=mem5.nBlock ){
19783      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
19784      memsys5Link(iOffset, ii);
19785      iOffset += nAlloc;
19786    }
19787    assert((iOffset+nAlloc)>mem5.nBlock);
19788  }
19789
19790  /* If a mutex is required for normal operation, allocate one */
19791  if( sqlite3GlobalConfig.bMemstat==0 ){
19792    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19793  }
19794
19795  return SQLITE_OK;
19796}
19797
19798/*
19799** Deinitialize this module.
19800*/
19801static void memsys5Shutdown(void *NotUsed){
19802  UNUSED_PARAMETER(NotUsed);
19803  mem5.mutex = 0;
19804  return;
19805}
19806
19807#ifdef SQLITE_TEST
19808/*
19809** Open the file indicated and write a log of all unfreed memory
19810** allocations into that log.
19811*/
19812SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
19813  FILE *out;
19814  int i, j, n;
19815  int nMinLog;
19816
19817  if( zFilename==0 || zFilename[0]==0 ){
19818    out = stdout;
19819  }else{
19820    out = fopen(zFilename, "w");
19821    if( out==0 ){
19822      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19823                      zFilename);
19824      return;
19825    }
19826  }
19827  memsys5Enter();
19828  nMinLog = memsys5Log(mem5.szAtom);
19829  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
19830    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
19831    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
19832  }
19833  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
19834  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
19835  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
19836  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
19837  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
19838  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
19839  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
19840  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
19841  memsys5Leave();
19842  if( out==stdout ){
19843    fflush(stdout);
19844  }else{
19845    fclose(out);
19846  }
19847}
19848#endif
19849
19850/*
19851** This routine is the only routine in this file with external
19852** linkage. It returns a pointer to a static sqlite3_mem_methods
19853** struct populated with the memsys5 methods.
19854*/
19855SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
19856  static const sqlite3_mem_methods memsys5Methods = {
19857     memsys5Malloc,
19858     memsys5Free,
19859     memsys5Realloc,
19860     memsys5Size,
19861     memsys5Roundup,
19862     memsys5Init,
19863     memsys5Shutdown,
19864     0
19865  };
19866  return &memsys5Methods;
19867}
19868
19869#endif /* SQLITE_ENABLE_MEMSYS5 */
19870
19871/************** End of mem5.c ************************************************/
19872/************** Begin file mutex.c *******************************************/
19873/*
19874** 2007 August 14
19875**
19876** The author disclaims copyright to this source code.  In place of
19877** a legal notice, here is a blessing:
19878**
19879**    May you do good and not evil.
19880**    May you find forgiveness for yourself and forgive others.
19881**    May you share freely, never taking more than you give.
19882**
19883*************************************************************************
19884** This file contains the C functions that implement mutexes.
19885**
19886** This file contains code that is common across all mutex implementations.
19887*/
19888/* #include "sqliteInt.h" */
19889
19890#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
19891/*
19892** For debugging purposes, record when the mutex subsystem is initialized
19893** and uninitialized so that we can assert() if there is an attempt to
19894** allocate a mutex while the system is uninitialized.
19895*/
19896static SQLITE_WSD int mutexIsInit = 0;
19897#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
19898
19899
19900#ifndef SQLITE_MUTEX_OMIT
19901/*
19902** Initialize the mutex system.
19903*/
19904SQLITE_PRIVATE int sqlite3MutexInit(void){
19905  int rc = SQLITE_OK;
19906  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
19907    /* If the xMutexAlloc method has not been set, then the user did not
19908    ** install a mutex implementation via sqlite3_config() prior to
19909    ** sqlite3_initialize() being called. This block copies pointers to
19910    ** the default implementation into the sqlite3GlobalConfig structure.
19911    */
19912    sqlite3_mutex_methods const *pFrom;
19913    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
19914
19915    if( sqlite3GlobalConfig.bCoreMutex ){
19916      pFrom = sqlite3DefaultMutex();
19917    }else{
19918      pFrom = sqlite3NoopMutex();
19919    }
19920    pTo->xMutexInit = pFrom->xMutexInit;
19921    pTo->xMutexEnd = pFrom->xMutexEnd;
19922    pTo->xMutexFree = pFrom->xMutexFree;
19923    pTo->xMutexEnter = pFrom->xMutexEnter;
19924    pTo->xMutexTry = pFrom->xMutexTry;
19925    pTo->xMutexLeave = pFrom->xMutexLeave;
19926    pTo->xMutexHeld = pFrom->xMutexHeld;
19927    pTo->xMutexNotheld = pFrom->xMutexNotheld;
19928    sqlite3MemoryBarrier();
19929    pTo->xMutexAlloc = pFrom->xMutexAlloc;
19930  }
19931  assert( sqlite3GlobalConfig.mutex.xMutexInit );
19932  rc = sqlite3GlobalConfig.mutex.xMutexInit();
19933
19934#ifdef SQLITE_DEBUG
19935  GLOBAL(int, mutexIsInit) = 1;
19936#endif
19937
19938  return rc;
19939}
19940
19941/*
19942** Shutdown the mutex system. This call frees resources allocated by
19943** sqlite3MutexInit().
19944*/
19945SQLITE_PRIVATE int sqlite3MutexEnd(void){
19946  int rc = SQLITE_OK;
19947  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
19948    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
19949  }
19950
19951#ifdef SQLITE_DEBUG
19952  GLOBAL(int, mutexIsInit) = 0;
19953#endif
19954
19955  return rc;
19956}
19957
19958/*
19959** Retrieve a pointer to a static mutex or allocate a new dynamic one.
19960*/
19961SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
19962#ifndef SQLITE_OMIT_AUTOINIT
19963  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
19964  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
19965#endif
19966  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
19967  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19968}
19969
19970SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
19971  if( !sqlite3GlobalConfig.bCoreMutex ){
19972    return 0;
19973  }
19974  assert( GLOBAL(int, mutexIsInit) );
19975  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
19976  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19977}
19978
19979/*
19980** Free a dynamic mutex.
19981*/
19982SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
19983  if( p ){
19984    assert( sqlite3GlobalConfig.mutex.xMutexFree );
19985    sqlite3GlobalConfig.mutex.xMutexFree(p);
19986  }
19987}
19988
19989/*
19990** Obtain the mutex p. If some other thread already has the mutex, block
19991** until it can be obtained.
19992*/
19993SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
19994  if( p ){
19995    assert( sqlite3GlobalConfig.mutex.xMutexEnter );
19996    sqlite3GlobalConfig.mutex.xMutexEnter(p);
19997  }
19998}
19999
20000/*
20001** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
20002** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
20003*/
20004SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
20005  int rc = SQLITE_OK;
20006  if( p ){
20007    assert( sqlite3GlobalConfig.mutex.xMutexTry );
20008    return sqlite3GlobalConfig.mutex.xMutexTry(p);
20009  }
20010  return rc;
20011}
20012
20013/*
20014** The sqlite3_mutex_leave() routine exits a mutex that was previously
20015** entered by the same thread.  The behavior is undefined if the mutex
20016** is not currently entered. If a NULL pointer is passed as an argument
20017** this function is a no-op.
20018*/
20019SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
20020  if( p ){
20021    assert( sqlite3GlobalConfig.mutex.xMutexLeave );
20022    sqlite3GlobalConfig.mutex.xMutexLeave(p);
20023  }
20024}
20025
20026#ifndef NDEBUG
20027/*
20028** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20029** intended for use inside assert() statements.
20030*/
20031SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
20032  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
20033  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
20034}
20035SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
20036  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
20037  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
20038}
20039#endif
20040
20041#endif /* !defined(SQLITE_MUTEX_OMIT) */
20042
20043/************** End of mutex.c ***********************************************/
20044/************** Begin file mutex_noop.c **************************************/
20045/*
20046** 2008 October 07
20047**
20048** The author disclaims copyright to this source code.  In place of
20049** a legal notice, here is a blessing:
20050**
20051**    May you do good and not evil.
20052**    May you find forgiveness for yourself and forgive others.
20053**    May you share freely, never taking more than you give.
20054**
20055*************************************************************************
20056** This file contains the C functions that implement mutexes.
20057**
20058** This implementation in this file does not provide any mutual
20059** exclusion and is thus suitable for use only in applications
20060** that use SQLite in a single thread.  The routines defined
20061** here are place-holders.  Applications can substitute working
20062** mutex routines at start-time using the
20063**
20064**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
20065**
20066** interface.
20067**
20068** If compiled with SQLITE_DEBUG, then additional logic is inserted
20069** that does error checking on mutexes to make sure they are being
20070** called correctly.
20071*/
20072/* #include "sqliteInt.h" */
20073
20074#ifndef SQLITE_MUTEX_OMIT
20075
20076#ifndef SQLITE_DEBUG
20077/*
20078** Stub routines for all mutex methods.
20079**
20080** This routines provide no mutual exclusion or error checking.
20081*/
20082static int noopMutexInit(void){ return SQLITE_OK; }
20083static int noopMutexEnd(void){ return SQLITE_OK; }
20084static sqlite3_mutex *noopMutexAlloc(int id){
20085  UNUSED_PARAMETER(id);
20086  return (sqlite3_mutex*)8;
20087}
20088static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20089static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20090static int noopMutexTry(sqlite3_mutex *p){
20091  UNUSED_PARAMETER(p);
20092  return SQLITE_OK;
20093}
20094static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20095
20096SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20097  static const sqlite3_mutex_methods sMutex = {
20098    noopMutexInit,
20099    noopMutexEnd,
20100    noopMutexAlloc,
20101    noopMutexFree,
20102    noopMutexEnter,
20103    noopMutexTry,
20104    noopMutexLeave,
20105
20106    0,
20107    0,
20108  };
20109
20110  return &sMutex;
20111}
20112#endif /* !SQLITE_DEBUG */
20113
20114#ifdef SQLITE_DEBUG
20115/*
20116** In this implementation, error checking is provided for testing
20117** and debugging purposes.  The mutexes still do not provide any
20118** mutual exclusion.
20119*/
20120
20121/*
20122** The mutex object
20123*/
20124typedef struct sqlite3_debug_mutex {
20125  int id;     /* The mutex type */
20126  int cnt;    /* Number of entries without a matching leave */
20127} sqlite3_debug_mutex;
20128
20129/*
20130** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20131** intended for use inside assert() statements.
20132*/
20133static int debugMutexHeld(sqlite3_mutex *pX){
20134  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20135  return p==0 || p->cnt>0;
20136}
20137static int debugMutexNotheld(sqlite3_mutex *pX){
20138  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20139  return p==0 || p->cnt==0;
20140}
20141
20142/*
20143** Initialize and deinitialize the mutex subsystem.
20144*/
20145static int debugMutexInit(void){ return SQLITE_OK; }
20146static int debugMutexEnd(void){ return SQLITE_OK; }
20147
20148/*
20149** The sqlite3_mutex_alloc() routine allocates a new
20150** mutex and returns a pointer to it.  If it returns NULL
20151** that means that a mutex could not be allocated.
20152*/
20153static sqlite3_mutex *debugMutexAlloc(int id){
20154  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
20155  sqlite3_debug_mutex *pNew = 0;
20156  switch( id ){
20157    case SQLITE_MUTEX_FAST:
20158    case SQLITE_MUTEX_RECURSIVE: {
20159      pNew = sqlite3Malloc(sizeof(*pNew));
20160      if( pNew ){
20161        pNew->id = id;
20162        pNew->cnt = 0;
20163      }
20164      break;
20165    }
20166    default: {
20167#ifdef SQLITE_ENABLE_API_ARMOR
20168      if( id-2<0 || id-2>=ArraySize(aStatic) ){
20169        (void)SQLITE_MISUSE_BKPT;
20170        return 0;
20171      }
20172#endif
20173      pNew = &aStatic[id-2];
20174      pNew->id = id;
20175      break;
20176    }
20177  }
20178  return (sqlite3_mutex*)pNew;
20179}
20180
20181/*
20182** This routine deallocates a previously allocated mutex.
20183*/
20184static void debugMutexFree(sqlite3_mutex *pX){
20185  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20186  assert( p->cnt==0 );
20187  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
20188    sqlite3_free(p);
20189  }else{
20190#ifdef SQLITE_ENABLE_API_ARMOR
20191    (void)SQLITE_MISUSE_BKPT;
20192#endif
20193  }
20194}
20195
20196/*
20197** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20198** to enter a mutex.  If another thread is already within the mutex,
20199** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20200** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20201** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20202** be entered multiple times by the same thread.  In such cases the,
20203** mutex must be exited an equal number of times before another thread
20204** can enter.  If the same thread tries to enter any other kind of mutex
20205** more than once, the behavior is undefined.
20206*/
20207static void debugMutexEnter(sqlite3_mutex *pX){
20208  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20209  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20210  p->cnt++;
20211}
20212static int debugMutexTry(sqlite3_mutex *pX){
20213  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20214  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20215  p->cnt++;
20216  return SQLITE_OK;
20217}
20218
20219/*
20220** The sqlite3_mutex_leave() routine exits a mutex that was
20221** previously entered by the same thread.  The behavior
20222** is undefined if the mutex is not currently entered or
20223** is not currently allocated.  SQLite will never do either.
20224*/
20225static void debugMutexLeave(sqlite3_mutex *pX){
20226  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20227  assert( debugMutexHeld(pX) );
20228  p->cnt--;
20229  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20230}
20231
20232SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20233  static const sqlite3_mutex_methods sMutex = {
20234    debugMutexInit,
20235    debugMutexEnd,
20236    debugMutexAlloc,
20237    debugMutexFree,
20238    debugMutexEnter,
20239    debugMutexTry,
20240    debugMutexLeave,
20241
20242    debugMutexHeld,
20243    debugMutexNotheld
20244  };
20245
20246  return &sMutex;
20247}
20248#endif /* SQLITE_DEBUG */
20249
20250/*
20251** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
20252** is used regardless of the run-time threadsafety setting.
20253*/
20254#ifdef SQLITE_MUTEX_NOOP
20255SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20256  return sqlite3NoopMutex();
20257}
20258#endif /* defined(SQLITE_MUTEX_NOOP) */
20259#endif /* !defined(SQLITE_MUTEX_OMIT) */
20260
20261/************** End of mutex_noop.c ******************************************/
20262/************** Begin file mutex_unix.c **************************************/
20263/*
20264** 2007 August 28
20265**
20266** The author disclaims copyright to this source code.  In place of
20267** a legal notice, here is a blessing:
20268**
20269**    May you do good and not evil.
20270**    May you find forgiveness for yourself and forgive others.
20271**    May you share freely, never taking more than you give.
20272**
20273*************************************************************************
20274** This file contains the C functions that implement mutexes for pthreads
20275*/
20276/* #include "sqliteInt.h" */
20277
20278/*
20279** The code in this file is only used if we are compiling threadsafe
20280** under unix with pthreads.
20281**
20282** Note that this implementation requires a version of pthreads that
20283** supports recursive mutexes.
20284*/
20285#ifdef SQLITE_MUTEX_PTHREADS
20286
20287#include <pthread.h>
20288
20289/*
20290** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
20291** are necessary under two condidtions:  (1) Debug builds and (2) using
20292** home-grown mutexes.  Encapsulate these conditions into a single #define.
20293*/
20294#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
20295# define SQLITE_MUTEX_NREF 1
20296#else
20297# define SQLITE_MUTEX_NREF 0
20298#endif
20299
20300/*
20301** Each recursive mutex is an instance of the following structure.
20302*/
20303struct sqlite3_mutex {
20304  pthread_mutex_t mutex;     /* Mutex controlling the lock */
20305#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
20306  int id;                    /* Mutex type */
20307#endif
20308#if SQLITE_MUTEX_NREF
20309  volatile int nRef;         /* Number of entrances */
20310  volatile pthread_t owner;  /* Thread that is within this mutex */
20311  int trace;                 /* True to trace changes */
20312#endif
20313};
20314#if SQLITE_MUTEX_NREF
20315#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
20316#else
20317#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
20318#endif
20319
20320/*
20321** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20322** intended for use only inside assert() statements.  On some platforms,
20323** there might be race conditions that can cause these routines to
20324** deliver incorrect results.  In particular, if pthread_equal() is
20325** not an atomic operation, then these routines might delivery
20326** incorrect results.  On most platforms, pthread_equal() is a
20327** comparison of two integers and is therefore atomic.  But we are
20328** told that HPUX is not such a platform.  If so, then these routines
20329** will not always work correctly on HPUX.
20330**
20331** On those platforms where pthread_equal() is not atomic, SQLite
20332** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
20333** make sure no assert() statements are evaluated and hence these
20334** routines are never called.
20335*/
20336#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
20337static int pthreadMutexHeld(sqlite3_mutex *p){
20338  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
20339}
20340static int pthreadMutexNotheld(sqlite3_mutex *p){
20341  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
20342}
20343#endif
20344
20345/*
20346** Try to provide a memory barrier operation, needed for initialization
20347** and also for the implementation of xShmBarrier in the VFS in cases
20348** where SQLite is compiled without mutexes.
20349*/
20350SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
20351#if defined(SQLITE_MEMORY_BARRIER)
20352  SQLITE_MEMORY_BARRIER;
20353#elif defined(__GNUC__) && GCC_VERSION>=4001000
20354  __sync_synchronize();
20355#endif
20356}
20357
20358/*
20359** Initialize and deinitialize the mutex subsystem.
20360*/
20361static int pthreadMutexInit(void){ return SQLITE_OK; }
20362static int pthreadMutexEnd(void){ return SQLITE_OK; }
20363
20364/*
20365** The sqlite3_mutex_alloc() routine allocates a new
20366** mutex and returns a pointer to it.  If it returns NULL
20367** that means that a mutex could not be allocated.  SQLite
20368** will unwind its stack and return an error.  The argument
20369** to sqlite3_mutex_alloc() is one of these integer constants:
20370**
20371** <ul>
20372** <li>  SQLITE_MUTEX_FAST
20373** <li>  SQLITE_MUTEX_RECURSIVE
20374** <li>  SQLITE_MUTEX_STATIC_MASTER
20375** <li>  SQLITE_MUTEX_STATIC_MEM
20376** <li>  SQLITE_MUTEX_STATIC_OPEN
20377** <li>  SQLITE_MUTEX_STATIC_PRNG
20378** <li>  SQLITE_MUTEX_STATIC_LRU
20379** <li>  SQLITE_MUTEX_STATIC_PMEM
20380** <li>  SQLITE_MUTEX_STATIC_APP1
20381** <li>  SQLITE_MUTEX_STATIC_APP2
20382** <li>  SQLITE_MUTEX_STATIC_APP3
20383** <li>  SQLITE_MUTEX_STATIC_VFS1
20384** <li>  SQLITE_MUTEX_STATIC_VFS2
20385** <li>  SQLITE_MUTEX_STATIC_VFS3
20386** </ul>
20387**
20388** The first two constants cause sqlite3_mutex_alloc() to create
20389** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
20390** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
20391** The mutex implementation does not need to make a distinction
20392** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
20393** not want to.  But SQLite will only request a recursive mutex in
20394** cases where it really needs one.  If a faster non-recursive mutex
20395** implementation is available on the host platform, the mutex subsystem
20396** might return such a mutex in response to SQLITE_MUTEX_FAST.
20397**
20398** The other allowed parameters to sqlite3_mutex_alloc() each return
20399** a pointer to a static preexisting mutex.  Six static mutexes are
20400** used by the current version of SQLite.  Future versions of SQLite
20401** may add additional static mutexes.  Static mutexes are for internal
20402** use by SQLite only.  Applications that use SQLite mutexes should
20403** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
20404** SQLITE_MUTEX_RECURSIVE.
20405**
20406** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
20407** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
20408** returns a different mutex on every call.  But for the static
20409** mutex types, the same mutex is returned on every call that has
20410** the same type number.
20411*/
20412static sqlite3_mutex *pthreadMutexAlloc(int iType){
20413  static sqlite3_mutex staticMutexes[] = {
20414    SQLITE3_MUTEX_INITIALIZER,
20415    SQLITE3_MUTEX_INITIALIZER,
20416    SQLITE3_MUTEX_INITIALIZER,
20417    SQLITE3_MUTEX_INITIALIZER,
20418    SQLITE3_MUTEX_INITIALIZER,
20419    SQLITE3_MUTEX_INITIALIZER,
20420    SQLITE3_MUTEX_INITIALIZER,
20421    SQLITE3_MUTEX_INITIALIZER,
20422    SQLITE3_MUTEX_INITIALIZER,
20423    SQLITE3_MUTEX_INITIALIZER,
20424    SQLITE3_MUTEX_INITIALIZER,
20425    SQLITE3_MUTEX_INITIALIZER
20426  };
20427  sqlite3_mutex *p;
20428  switch( iType ){
20429    case SQLITE_MUTEX_RECURSIVE: {
20430      p = sqlite3MallocZero( sizeof(*p) );
20431      if( p ){
20432#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20433        /* If recursive mutexes are not available, we will have to
20434        ** build our own.  See below. */
20435        pthread_mutex_init(&p->mutex, 0);
20436#else
20437        /* Use a recursive mutex if it is available */
20438        pthread_mutexattr_t recursiveAttr;
20439        pthread_mutexattr_init(&recursiveAttr);
20440        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
20441        pthread_mutex_init(&p->mutex, &recursiveAttr);
20442        pthread_mutexattr_destroy(&recursiveAttr);
20443#endif
20444      }
20445      break;
20446    }
20447    case SQLITE_MUTEX_FAST: {
20448      p = sqlite3MallocZero( sizeof(*p) );
20449      if( p ){
20450        pthread_mutex_init(&p->mutex, 0);
20451      }
20452      break;
20453    }
20454    default: {
20455#ifdef SQLITE_ENABLE_API_ARMOR
20456      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
20457        (void)SQLITE_MISUSE_BKPT;
20458        return 0;
20459      }
20460#endif
20461      p = &staticMutexes[iType-2];
20462      break;
20463    }
20464  }
20465#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
20466  if( p ) p->id = iType;
20467#endif
20468  return p;
20469}
20470
20471
20472/*
20473** This routine deallocates a previously
20474** allocated mutex.  SQLite is careful to deallocate every
20475** mutex that it allocates.
20476*/
20477static void pthreadMutexFree(sqlite3_mutex *p){
20478  assert( p->nRef==0 );
20479#if SQLITE_ENABLE_API_ARMOR
20480  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
20481#endif
20482  {
20483    pthread_mutex_destroy(&p->mutex);
20484    sqlite3_free(p);
20485  }
20486#ifdef SQLITE_ENABLE_API_ARMOR
20487  else{
20488    (void)SQLITE_MISUSE_BKPT;
20489  }
20490#endif
20491}
20492
20493/*
20494** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20495** to enter a mutex.  If another thread is already within the mutex,
20496** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20497** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20498** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20499** be entered multiple times by the same thread.  In such cases the,
20500** mutex must be exited an equal number of times before another thread
20501** can enter.  If the same thread tries to enter any other kind of mutex
20502** more than once, the behavior is undefined.
20503*/
20504static void pthreadMutexEnter(sqlite3_mutex *p){
20505  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
20506
20507#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20508  /* If recursive mutexes are not available, then we have to grow
20509  ** our own.  This implementation assumes that pthread_equal()
20510  ** is atomic - that it cannot be deceived into thinking self
20511  ** and p->owner are equal if p->owner changes between two values
20512  ** that are not equal to self while the comparison is taking place.
20513  ** This implementation also assumes a coherent cache - that
20514  ** separate processes cannot read different values from the same
20515  ** address at the same time.  If either of these two conditions
20516  ** are not met, then the mutexes will fail and problems will result.
20517  */
20518  {
20519    pthread_t self = pthread_self();
20520    if( p->nRef>0 && pthread_equal(p->owner, self) ){
20521      p->nRef++;
20522    }else{
20523      pthread_mutex_lock(&p->mutex);
20524      assert( p->nRef==0 );
20525      p->owner = self;
20526      p->nRef = 1;
20527    }
20528  }
20529#else
20530  /* Use the built-in recursive mutexes if they are available.
20531  */
20532  pthread_mutex_lock(&p->mutex);
20533#if SQLITE_MUTEX_NREF
20534  assert( p->nRef>0 || p->owner==0 );
20535  p->owner = pthread_self();
20536  p->nRef++;
20537#endif
20538#endif
20539
20540#ifdef SQLITE_DEBUG
20541  if( p->trace ){
20542    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20543  }
20544#endif
20545}
20546static int pthreadMutexTry(sqlite3_mutex *p){
20547  int rc;
20548  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
20549
20550#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20551  /* If recursive mutexes are not available, then we have to grow
20552  ** our own.  This implementation assumes that pthread_equal()
20553  ** is atomic - that it cannot be deceived into thinking self
20554  ** and p->owner are equal if p->owner changes between two values
20555  ** that are not equal to self while the comparison is taking place.
20556  ** This implementation also assumes a coherent cache - that
20557  ** separate processes cannot read different values from the same
20558  ** address at the same time.  If either of these two conditions
20559  ** are not met, then the mutexes will fail and problems will result.
20560  */
20561  {
20562    pthread_t self = pthread_self();
20563    if( p->nRef>0 && pthread_equal(p->owner, self) ){
20564      p->nRef++;
20565      rc = SQLITE_OK;
20566    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
20567      assert( p->nRef==0 );
20568      p->owner = self;
20569      p->nRef = 1;
20570      rc = SQLITE_OK;
20571    }else{
20572      rc = SQLITE_BUSY;
20573    }
20574  }
20575#else
20576  /* Use the built-in recursive mutexes if they are available.
20577  */
20578  if( pthread_mutex_trylock(&p->mutex)==0 ){
20579#if SQLITE_MUTEX_NREF
20580    p->owner = pthread_self();
20581    p->nRef++;
20582#endif
20583    rc = SQLITE_OK;
20584  }else{
20585    rc = SQLITE_BUSY;
20586  }
20587#endif
20588
20589#ifdef SQLITE_DEBUG
20590  if( rc==SQLITE_OK && p->trace ){
20591    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20592  }
20593#endif
20594  return rc;
20595}
20596
20597/*
20598** The sqlite3_mutex_leave() routine exits a mutex that was
20599** previously entered by the same thread.  The behavior
20600** is undefined if the mutex is not currently entered or
20601** is not currently allocated.  SQLite will never do either.
20602*/
20603static void pthreadMutexLeave(sqlite3_mutex *p){
20604  assert( pthreadMutexHeld(p) );
20605#if SQLITE_MUTEX_NREF
20606  p->nRef--;
20607  if( p->nRef==0 ) p->owner = 0;
20608#endif
20609  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
20610
20611#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20612  if( p->nRef==0 ){
20613    pthread_mutex_unlock(&p->mutex);
20614  }
20615#else
20616  pthread_mutex_unlock(&p->mutex);
20617#endif
20618
20619#ifdef SQLITE_DEBUG
20620  if( p->trace ){
20621    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20622  }
20623#endif
20624}
20625
20626SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20627  static const sqlite3_mutex_methods sMutex = {
20628    pthreadMutexInit,
20629    pthreadMutexEnd,
20630    pthreadMutexAlloc,
20631    pthreadMutexFree,
20632    pthreadMutexEnter,
20633    pthreadMutexTry,
20634    pthreadMutexLeave,
20635#ifdef SQLITE_DEBUG
20636    pthreadMutexHeld,
20637    pthreadMutexNotheld
20638#else
20639    0,
20640    0
20641#endif
20642  };
20643
20644  return &sMutex;
20645}
20646
20647#endif /* SQLITE_MUTEX_PTHREADS */
20648
20649/************** End of mutex_unix.c ******************************************/
20650/************** Begin file mutex_w32.c ***************************************/
20651/*
20652** 2007 August 14
20653**
20654** The author disclaims copyright to this source code.  In place of
20655** a legal notice, here is a blessing:
20656**
20657**    May you do good and not evil.
20658**    May you find forgiveness for yourself and forgive others.
20659**    May you share freely, never taking more than you give.
20660**
20661*************************************************************************
20662** This file contains the C functions that implement mutexes for Win32.
20663*/
20664/* #include "sqliteInt.h" */
20665
20666#if SQLITE_OS_WIN
20667/*
20668** Include code that is common to all os_*.c files
20669*/
20670/************** Include os_common.h in the middle of mutex_w32.c *************/
20671/************** Begin file os_common.h ***************************************/
20672/*
20673** 2004 May 22
20674**
20675** The author disclaims copyright to this source code.  In place of
20676** a legal notice, here is a blessing:
20677**
20678**    May you do good and not evil.
20679**    May you find forgiveness for yourself and forgive others.
20680**    May you share freely, never taking more than you give.
20681**
20682******************************************************************************
20683**
20684** This file contains macros and a little bit of code that is common to
20685** all of the platform-specific files (os_*.c) and is #included into those
20686** files.
20687**
20688** This file should be #included by the os_*.c files only.  It is not a
20689** general purpose header file.
20690*/
20691#ifndef _OS_COMMON_H_
20692#define _OS_COMMON_H_
20693
20694/*
20695** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20696** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20697** switch.  The following code should catch this problem at compile-time.
20698*/
20699#ifdef MEMORY_DEBUG
20700# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20701#endif
20702
20703/*
20704** Macros for performance tracing.  Normally turned off.  Only works
20705** on i486 hardware.
20706*/
20707#ifdef SQLITE_PERFORMANCE_TRACE
20708
20709/*
20710** hwtime.h contains inline assembler code for implementing
20711** high-performance timing routines.
20712*/
20713/************** Include hwtime.h in the middle of os_common.h ****************/
20714/************** Begin file hwtime.h ******************************************/
20715/*
20716** 2008 May 27
20717**
20718** The author disclaims copyright to this source code.  In place of
20719** a legal notice, here is a blessing:
20720**
20721**    May you do good and not evil.
20722**    May you find forgiveness for yourself and forgive others.
20723**    May you share freely, never taking more than you give.
20724**
20725******************************************************************************
20726**
20727** This file contains inline asm code for retrieving "high-performance"
20728** counters for x86 class CPUs.
20729*/
20730#ifndef _HWTIME_H_
20731#define _HWTIME_H_
20732
20733/*
20734** The following routine only works on pentium-class (or newer) processors.
20735** It uses the RDTSC opcode to read the cycle count value out of the
20736** processor and returns that value.  This can be used for high-res
20737** profiling.
20738*/
20739#if (defined(__GNUC__) || defined(_MSC_VER)) && \
20740      (defined(i386) || defined(__i386__) || defined(_M_IX86))
20741
20742  #if defined(__GNUC__)
20743
20744  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20745     unsigned int lo, hi;
20746     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20747     return (sqlite_uint64)hi << 32 | lo;
20748  }
20749
20750  #elif defined(_MSC_VER)
20751
20752  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20753     __asm {
20754        rdtsc
20755        ret       ; return value at EDX:EAX
20756     }
20757  }
20758
20759  #endif
20760
20761#elif (defined(__GNUC__) && defined(__x86_64__))
20762
20763  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20764      unsigned long val;
20765      __asm__ __volatile__ ("rdtsc" : "=A" (val));
20766      return val;
20767  }
20768
20769#elif (defined(__GNUC__) && defined(__ppc__))
20770
20771  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20772      unsigned long long retval;
20773      unsigned long junk;
20774      __asm__ __volatile__ ("\n\
20775          1:      mftbu   %1\n\
20776                  mftb    %L0\n\
20777                  mftbu   %0\n\
20778                  cmpw    %0,%1\n\
20779                  bne     1b"
20780                  : "=r" (retval), "=r" (junk));
20781      return retval;
20782  }
20783
20784#else
20785
20786  #error Need implementation of sqlite3Hwtime() for your platform.
20787
20788  /*
20789  ** To compile without implementing sqlite3Hwtime() for your platform,
20790  ** you can remove the above #error and use the following
20791  ** stub function.  You will lose timing support for many
20792  ** of the debugging and testing utilities, but it should at
20793  ** least compile and run.
20794  */
20795SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20796
20797#endif
20798
20799#endif /* !defined(_HWTIME_H_) */
20800
20801/************** End of hwtime.h **********************************************/
20802/************** Continuing where we left off in os_common.h ******************/
20803
20804static sqlite_uint64 g_start;
20805static sqlite_uint64 g_elapsed;
20806#define TIMER_START       g_start=sqlite3Hwtime()
20807#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20808#define TIMER_ELAPSED     g_elapsed
20809#else
20810#define TIMER_START
20811#define TIMER_END
20812#define TIMER_ELAPSED     ((sqlite_uint64)0)
20813#endif
20814
20815/*
20816** If we compile with the SQLITE_TEST macro set, then the following block
20817** of code will give us the ability to simulate a disk I/O error.  This
20818** is used for testing the I/O recovery logic.
20819*/
20820#ifdef SQLITE_TEST
20821SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20822SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20823SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20824SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20825SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20826SQLITE_API int sqlite3_diskfull_pending = 0;
20827SQLITE_API int sqlite3_diskfull = 0;
20828#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20829#define SimulateIOError(CODE)  \
20830  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20831       || sqlite3_io_error_pending-- == 1 )  \
20832              { local_ioerr(); CODE; }
20833static void local_ioerr(){
20834  IOTRACE(("IOERR\n"));
20835  sqlite3_io_error_hit++;
20836  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20837}
20838#define SimulateDiskfullError(CODE) \
20839   if( sqlite3_diskfull_pending ){ \
20840     if( sqlite3_diskfull_pending == 1 ){ \
20841       local_ioerr(); \
20842       sqlite3_diskfull = 1; \
20843       sqlite3_io_error_hit = 1; \
20844       CODE; \
20845     }else{ \
20846       sqlite3_diskfull_pending--; \
20847     } \
20848   }
20849#else
20850#define SimulateIOErrorBenign(X)
20851#define SimulateIOError(A)
20852#define SimulateDiskfullError(A)
20853#endif
20854
20855/*
20856** When testing, keep a count of the number of open files.
20857*/
20858#ifdef SQLITE_TEST
20859SQLITE_API int sqlite3_open_file_count = 0;
20860#define OpenCounter(X)  sqlite3_open_file_count+=(X)
20861#else
20862#define OpenCounter(X)
20863#endif
20864
20865#endif /* !defined(_OS_COMMON_H_) */
20866
20867/************** End of os_common.h *******************************************/
20868/************** Continuing where we left off in mutex_w32.c ******************/
20869
20870/*
20871** Include the header file for the Windows VFS.
20872*/
20873/************** Include os_win.h in the middle of mutex_w32.c ****************/
20874/************** Begin file os_win.h ******************************************/
20875/*
20876** 2013 November 25
20877**
20878** The author disclaims copyright to this source code.  In place of
20879** a legal notice, here is a blessing:
20880**
20881**    May you do good and not evil.
20882**    May you find forgiveness for yourself and forgive others.
20883**    May you share freely, never taking more than you give.
20884**
20885******************************************************************************
20886**
20887** This file contains code that is specific to Windows.
20888*/
20889#ifndef _OS_WIN_H_
20890#define _OS_WIN_H_
20891
20892/*
20893** Include the primary Windows SDK header file.
20894*/
20895#include "windows.h"
20896
20897#ifdef __CYGWIN__
20898# include <sys/cygwin.h>
20899# include <errno.h> /* amalgamator: dontcache */
20900#endif
20901
20902/*
20903** Determine if we are dealing with Windows NT.
20904**
20905** We ought to be able to determine if we are compiling for Windows 9x or
20906** Windows NT using the _WIN32_WINNT macro as follows:
20907**
20908** #if defined(_WIN32_WINNT)
20909** # define SQLITE_OS_WINNT 1
20910** #else
20911** # define SQLITE_OS_WINNT 0
20912** #endif
20913**
20914** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
20915** it ought to, so the above test does not work.  We'll just assume that
20916** everything is Windows NT unless the programmer explicitly says otherwise
20917** by setting SQLITE_OS_WINNT to 0.
20918*/
20919#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
20920# define SQLITE_OS_WINNT 1
20921#endif
20922
20923/*
20924** Determine if we are dealing with Windows CE - which has a much reduced
20925** API.
20926*/
20927#if defined(_WIN32_WCE)
20928# define SQLITE_OS_WINCE 1
20929#else
20930# define SQLITE_OS_WINCE 0
20931#endif
20932
20933/*
20934** Determine if we are dealing with WinRT, which provides only a subset of
20935** the full Win32 API.
20936*/
20937#if !defined(SQLITE_OS_WINRT)
20938# define SQLITE_OS_WINRT 0
20939#endif
20940
20941/*
20942** For WinCE, some API function parameters do not appear to be declared as
20943** volatile.
20944*/
20945#if SQLITE_OS_WINCE
20946# define SQLITE_WIN32_VOLATILE
20947#else
20948# define SQLITE_WIN32_VOLATILE volatile
20949#endif
20950
20951/*
20952** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
20953** functions are not available (e.g. those not using MSVC, Cygwin, etc).
20954*/
20955#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
20956    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
20957# define SQLITE_OS_WIN_THREADS 1
20958#else
20959# define SQLITE_OS_WIN_THREADS 0
20960#endif
20961
20962#endif /* _OS_WIN_H_ */
20963
20964/************** End of os_win.h **********************************************/
20965/************** Continuing where we left off in mutex_w32.c ******************/
20966#endif
20967
20968/*
20969** The code in this file is only used if we are compiling multithreaded
20970** on a Win32 system.
20971*/
20972#ifdef SQLITE_MUTEX_W32
20973
20974/*
20975** Each recursive mutex is an instance of the following structure.
20976*/
20977struct sqlite3_mutex {
20978  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
20979  int id;                    /* Mutex type */
20980#ifdef SQLITE_DEBUG
20981  volatile int nRef;         /* Number of enterances */
20982  volatile DWORD owner;      /* Thread holding this mutex */
20983  volatile int trace;        /* True to trace changes */
20984#endif
20985};
20986
20987/*
20988** These are the initializer values used when declaring a "static" mutex
20989** on Win32.  It should be noted that all mutexes require initialization
20990** on the Win32 platform.
20991*/
20992#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
20993
20994#ifdef SQLITE_DEBUG
20995#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
20996                                    0L, (DWORD)0, 0 }
20997#else
20998#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
20999#endif
21000
21001#ifdef SQLITE_DEBUG
21002/*
21003** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
21004** intended for use only inside assert() statements.
21005*/
21006static int winMutexHeld(sqlite3_mutex *p){
21007  return p->nRef!=0 && p->owner==GetCurrentThreadId();
21008}
21009
21010static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
21011  return p->nRef==0 || p->owner!=tid;
21012}
21013
21014static int winMutexNotheld(sqlite3_mutex *p){
21015  DWORD tid = GetCurrentThreadId();
21016  return winMutexNotheld2(p, tid);
21017}
21018#endif
21019
21020/*
21021** Try to provide a memory barrier operation, needed for initialization
21022** and also for the xShmBarrier method of the VFS in cases when SQLite is
21023** compiled without mutexes (SQLITE_THREADSAFE=0).
21024*/
21025SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
21026#if defined(SQLITE_MEMORY_BARRIER)
21027  SQLITE_MEMORY_BARRIER;
21028#elif defined(__GNUC__)
21029  __sync_synchronize();
21030#elif !defined(SQLITE_DISABLE_INTRINSIC) && \
21031      defined(_MSC_VER) && _MSC_VER>=1300
21032  _ReadWriteBarrier();
21033#elif defined(MemoryBarrier)
21034  MemoryBarrier();
21035#endif
21036}
21037
21038/*
21039** Initialize and deinitialize the mutex subsystem.
21040*/
21041static sqlite3_mutex winMutex_staticMutexes[] = {
21042  SQLITE3_MUTEX_INITIALIZER,
21043  SQLITE3_MUTEX_INITIALIZER,
21044  SQLITE3_MUTEX_INITIALIZER,
21045  SQLITE3_MUTEX_INITIALIZER,
21046  SQLITE3_MUTEX_INITIALIZER,
21047  SQLITE3_MUTEX_INITIALIZER,
21048  SQLITE3_MUTEX_INITIALIZER,
21049  SQLITE3_MUTEX_INITIALIZER,
21050  SQLITE3_MUTEX_INITIALIZER,
21051  SQLITE3_MUTEX_INITIALIZER,
21052  SQLITE3_MUTEX_INITIALIZER,
21053  SQLITE3_MUTEX_INITIALIZER
21054};
21055
21056static int winMutex_isInit = 0;
21057static int winMutex_isNt = -1; /* <0 means "need to query" */
21058
21059/* As the winMutexInit() and winMutexEnd() functions are called as part
21060** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
21061** "interlocked" magic used here is probably not strictly necessary.
21062*/
21063static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
21064
21065SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
21066SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
21067
21068static int winMutexInit(void){
21069  /* The first to increment to 1 does actual initialization */
21070  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
21071    int i;
21072    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
21073#if SQLITE_OS_WINRT
21074      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
21075#else
21076      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
21077#endif
21078    }
21079    winMutex_isInit = 1;
21080  }else{
21081    /* Another thread is (in the process of) initializing the static
21082    ** mutexes */
21083    while( !winMutex_isInit ){
21084      sqlite3_win32_sleep(1);
21085    }
21086  }
21087  return SQLITE_OK;
21088}
21089
21090static int winMutexEnd(void){
21091  /* The first to decrement to 0 does actual shutdown
21092  ** (which should be the last to shutdown.) */
21093  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
21094    if( winMutex_isInit==1 ){
21095      int i;
21096      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
21097        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
21098      }
21099      winMutex_isInit = 0;
21100    }
21101  }
21102  return SQLITE_OK;
21103}
21104
21105/*
21106** The sqlite3_mutex_alloc() routine allocates a new
21107** mutex and returns a pointer to it.  If it returns NULL
21108** that means that a mutex could not be allocated.  SQLite
21109** will unwind its stack and return an error.  The argument
21110** to sqlite3_mutex_alloc() is one of these integer constants:
21111**
21112** <ul>
21113** <li>  SQLITE_MUTEX_FAST
21114** <li>  SQLITE_MUTEX_RECURSIVE
21115** <li>  SQLITE_MUTEX_STATIC_MASTER
21116** <li>  SQLITE_MUTEX_STATIC_MEM
21117** <li>  SQLITE_MUTEX_STATIC_OPEN
21118** <li>  SQLITE_MUTEX_STATIC_PRNG
21119** <li>  SQLITE_MUTEX_STATIC_LRU
21120** <li>  SQLITE_MUTEX_STATIC_PMEM
21121** <li>  SQLITE_MUTEX_STATIC_APP1
21122** <li>  SQLITE_MUTEX_STATIC_APP2
21123** <li>  SQLITE_MUTEX_STATIC_APP3
21124** <li>  SQLITE_MUTEX_STATIC_VFS1
21125** <li>  SQLITE_MUTEX_STATIC_VFS2
21126** <li>  SQLITE_MUTEX_STATIC_VFS3
21127** </ul>
21128**
21129** The first two constants cause sqlite3_mutex_alloc() to create
21130** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
21131** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
21132** The mutex implementation does not need to make a distinction
21133** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
21134** not want to.  But SQLite will only request a recursive mutex in
21135** cases where it really needs one.  If a faster non-recursive mutex
21136** implementation is available on the host platform, the mutex subsystem
21137** might return such a mutex in response to SQLITE_MUTEX_FAST.
21138**
21139** The other allowed parameters to sqlite3_mutex_alloc() each return
21140** a pointer to a static preexisting mutex.  Six static mutexes are
21141** used by the current version of SQLite.  Future versions of SQLite
21142** may add additional static mutexes.  Static mutexes are for internal
21143** use by SQLite only.  Applications that use SQLite mutexes should
21144** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
21145** SQLITE_MUTEX_RECURSIVE.
21146**
21147** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
21148** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
21149** returns a different mutex on every call.  But for the static
21150** mutex types, the same mutex is returned on every call that has
21151** the same type number.
21152*/
21153static sqlite3_mutex *winMutexAlloc(int iType){
21154  sqlite3_mutex *p;
21155
21156  switch( iType ){
21157    case SQLITE_MUTEX_FAST:
21158    case SQLITE_MUTEX_RECURSIVE: {
21159      p = sqlite3MallocZero( sizeof(*p) );
21160      if( p ){
21161        p->id = iType;
21162#ifdef SQLITE_DEBUG
21163#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
21164        p->trace = 1;
21165#endif
21166#endif
21167#if SQLITE_OS_WINRT
21168        InitializeCriticalSectionEx(&p->mutex, 0, 0);
21169#else
21170        InitializeCriticalSection(&p->mutex);
21171#endif
21172      }
21173      break;
21174    }
21175    default: {
21176#ifdef SQLITE_ENABLE_API_ARMOR
21177      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
21178        (void)SQLITE_MISUSE_BKPT;
21179        return 0;
21180      }
21181#endif
21182      p = &winMutex_staticMutexes[iType-2];
21183      p->id = iType;
21184#ifdef SQLITE_DEBUG
21185#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
21186      p->trace = 1;
21187#endif
21188#endif
21189      break;
21190    }
21191  }
21192  return p;
21193}
21194
21195
21196/*
21197** This routine deallocates a previously
21198** allocated mutex.  SQLite is careful to deallocate every
21199** mutex that it allocates.
21200*/
21201static void winMutexFree(sqlite3_mutex *p){
21202  assert( p );
21203  assert( p->nRef==0 && p->owner==0 );
21204  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
21205    DeleteCriticalSection(&p->mutex);
21206    sqlite3_free(p);
21207  }else{
21208#ifdef SQLITE_ENABLE_API_ARMOR
21209    (void)SQLITE_MISUSE_BKPT;
21210#endif
21211  }
21212}
21213
21214/*
21215** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
21216** to enter a mutex.  If another thread is already within the mutex,
21217** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
21218** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
21219** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
21220** be entered multiple times by the same thread.  In such cases the,
21221** mutex must be exited an equal number of times before another thread
21222** can enter.  If the same thread tries to enter any other kind of mutex
21223** more than once, the behavior is undefined.
21224*/
21225static void winMutexEnter(sqlite3_mutex *p){
21226#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21227  DWORD tid = GetCurrentThreadId();
21228#endif
21229#ifdef SQLITE_DEBUG
21230  assert( p );
21231  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
21232#else
21233  assert( p );
21234#endif
21235  assert( winMutex_isInit==1 );
21236  EnterCriticalSection(&p->mutex);
21237#ifdef SQLITE_DEBUG
21238  assert( p->nRef>0 || p->owner==0 );
21239  p->owner = tid;
21240  p->nRef++;
21241  if( p->trace ){
21242    OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
21243             tid, p, p->trace, p->nRef));
21244  }
21245#endif
21246}
21247
21248static int winMutexTry(sqlite3_mutex *p){
21249#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21250  DWORD tid = GetCurrentThreadId();
21251#endif
21252  int rc = SQLITE_BUSY;
21253  assert( p );
21254  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
21255  /*
21256  ** The sqlite3_mutex_try() routine is very rarely used, and when it
21257  ** is used it is merely an optimization.  So it is OK for it to always
21258  ** fail.
21259  **
21260  ** The TryEnterCriticalSection() interface is only available on WinNT.
21261  ** And some windows compilers complain if you try to use it without
21262  ** first doing some #defines that prevent SQLite from building on Win98.
21263  ** For that reason, we will omit this optimization for now.  See
21264  ** ticket #2685.
21265  */
21266#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
21267  assert( winMutex_isInit==1 );
21268  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
21269  if( winMutex_isNt<0 ){
21270    winMutex_isNt = sqlite3_win32_is_nt();
21271  }
21272  assert( winMutex_isNt==0 || winMutex_isNt==1 );
21273  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
21274#ifdef SQLITE_DEBUG
21275    p->owner = tid;
21276    p->nRef++;
21277#endif
21278    rc = SQLITE_OK;
21279  }
21280#else
21281  UNUSED_PARAMETER(p);
21282#endif
21283#ifdef SQLITE_DEBUG
21284  if( p->trace ){
21285    OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
21286             tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
21287  }
21288#endif
21289  return rc;
21290}
21291
21292/*
21293** The sqlite3_mutex_leave() routine exits a mutex that was
21294** previously entered by the same thread.  The behavior
21295** is undefined if the mutex is not currently entered or
21296** is not currently allocated.  SQLite will never do either.
21297*/
21298static void winMutexLeave(sqlite3_mutex *p){
21299#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21300  DWORD tid = GetCurrentThreadId();
21301#endif
21302  assert( p );
21303#ifdef SQLITE_DEBUG
21304  assert( p->nRef>0 );
21305  assert( p->owner==tid );
21306  p->nRef--;
21307  if( p->nRef==0 ) p->owner = 0;
21308  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
21309#endif
21310  assert( winMutex_isInit==1 );
21311  LeaveCriticalSection(&p->mutex);
21312#ifdef SQLITE_DEBUG
21313  if( p->trace ){
21314    OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
21315             tid, p, p->trace, p->nRef));
21316  }
21317#endif
21318}
21319
21320SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
21321  static const sqlite3_mutex_methods sMutex = {
21322    winMutexInit,
21323    winMutexEnd,
21324    winMutexAlloc,
21325    winMutexFree,
21326    winMutexEnter,
21327    winMutexTry,
21328    winMutexLeave,
21329#ifdef SQLITE_DEBUG
21330    winMutexHeld,
21331    winMutexNotheld
21332#else
21333    0,
21334    0
21335#endif
21336  };
21337  return &sMutex;
21338}
21339
21340#endif /* SQLITE_MUTEX_W32 */
21341
21342/************** End of mutex_w32.c *******************************************/
21343/************** Begin file malloc.c ******************************************/
21344/*
21345** 2001 September 15
21346**
21347** The author disclaims copyright to this source code.  In place of
21348** a legal notice, here is a blessing:
21349**
21350**    May you do good and not evil.
21351**    May you find forgiveness for yourself and forgive others.
21352**    May you share freely, never taking more than you give.
21353**
21354*************************************************************************
21355**
21356** Memory allocation functions used throughout sqlite.
21357*/
21358/* #include "sqliteInt.h" */
21359/* #include <stdarg.h> */
21360
21361/*
21362** Attempt to release up to n bytes of non-essential memory currently
21363** held by SQLite. An example of non-essential memory is memory used to
21364** cache database pages that are not currently in use.
21365*/
21366SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
21367#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
21368  return sqlite3PcacheReleaseMemory(n);
21369#else
21370  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
21371  ** is a no-op returning zero if SQLite is not compiled with
21372  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
21373  UNUSED_PARAMETER(n);
21374  return 0;
21375#endif
21376}
21377
21378/*
21379** An instance of the following object records the location of
21380** each unused scratch buffer.
21381*/
21382typedef struct ScratchFreeslot {
21383  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
21384} ScratchFreeslot;
21385
21386/*
21387** State information local to the memory allocation subsystem.
21388*/
21389static SQLITE_WSD struct Mem0Global {
21390  sqlite3_mutex *mutex;         /* Mutex to serialize access */
21391  sqlite3_int64 alarmThreshold; /* The soft heap limit */
21392
21393  /*
21394  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
21395  ** (so that a range test can be used to determine if an allocation
21396  ** being freed came from pScratch) and a pointer to the list of
21397  ** unused scratch allocations.
21398  */
21399  void *pScratchEnd;
21400  ScratchFreeslot *pScratchFree;
21401  u32 nScratchFree;
21402
21403  /*
21404  ** True if heap is nearly "full" where "full" is defined by the
21405  ** sqlite3_soft_heap_limit() setting.
21406  */
21407  int nearlyFull;
21408} mem0 = { 0, 0, 0, 0, 0, 0 };
21409
21410#define mem0 GLOBAL(struct Mem0Global, mem0)
21411
21412/*
21413** Return the memory allocator mutex. sqlite3_status() needs it.
21414*/
21415SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
21416  return mem0.mutex;
21417}
21418
21419#ifndef SQLITE_OMIT_DEPRECATED
21420/*
21421** Deprecated external interface.  It used to set an alarm callback
21422** that was invoked when memory usage grew too large.  Now it is a
21423** no-op.
21424*/
21425SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
21426  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
21427  void *pArg,
21428  sqlite3_int64 iThreshold
21429){
21430  (void)xCallback;
21431  (void)pArg;
21432  (void)iThreshold;
21433  return SQLITE_OK;
21434}
21435#endif
21436
21437/*
21438** Set the soft heap-size limit for the library. Passing a zero or
21439** negative value indicates no limit.
21440*/
21441SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
21442  sqlite3_int64 priorLimit;
21443  sqlite3_int64 excess;
21444  sqlite3_int64 nUsed;
21445#ifndef SQLITE_OMIT_AUTOINIT
21446  int rc = sqlite3_initialize();
21447  if( rc ) return -1;
21448#endif
21449  sqlite3_mutex_enter(mem0.mutex);
21450  priorLimit = mem0.alarmThreshold;
21451  if( n<0 ){
21452    sqlite3_mutex_leave(mem0.mutex);
21453    return priorLimit;
21454  }
21455  mem0.alarmThreshold = n;
21456  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
21457  mem0.nearlyFull = (n>0 && n<=nUsed);
21458  sqlite3_mutex_leave(mem0.mutex);
21459  excess = sqlite3_memory_used() - n;
21460  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
21461  return priorLimit;
21462}
21463SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
21464  if( n<0 ) n = 0;
21465  sqlite3_soft_heap_limit64(n);
21466}
21467
21468/*
21469** Initialize the memory allocation subsystem.
21470*/
21471SQLITE_PRIVATE int sqlite3MallocInit(void){
21472  int rc;
21473  if( sqlite3GlobalConfig.m.xMalloc==0 ){
21474    sqlite3MemSetDefault();
21475  }
21476  memset(&mem0, 0, sizeof(mem0));
21477  if( sqlite3GlobalConfig.bCoreMutex ){
21478    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21479  }
21480  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
21481      && sqlite3GlobalConfig.nScratch>0 ){
21482    int i, n, sz;
21483    ScratchFreeslot *pSlot;
21484    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
21485    sqlite3GlobalConfig.szScratch = sz;
21486    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
21487    n = sqlite3GlobalConfig.nScratch;
21488    mem0.pScratchFree = pSlot;
21489    mem0.nScratchFree = n;
21490    for(i=0; i<n-1; i++){
21491      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
21492      pSlot = pSlot->pNext;
21493    }
21494    pSlot->pNext = 0;
21495    mem0.pScratchEnd = (void*)&pSlot[1];
21496  }else{
21497    mem0.pScratchEnd = 0;
21498    sqlite3GlobalConfig.pScratch = 0;
21499    sqlite3GlobalConfig.szScratch = 0;
21500    sqlite3GlobalConfig.nScratch = 0;
21501  }
21502  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
21503      || sqlite3GlobalConfig.nPage<=0 ){
21504    sqlite3GlobalConfig.pPage = 0;
21505    sqlite3GlobalConfig.szPage = 0;
21506  }
21507  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
21508  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
21509  return rc;
21510}
21511
21512/*
21513** Return true if the heap is currently under memory pressure - in other
21514** words if the amount of heap used is close to the limit set by
21515** sqlite3_soft_heap_limit().
21516*/
21517SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
21518  return mem0.nearlyFull;
21519}
21520
21521/*
21522** Deinitialize the memory allocation subsystem.
21523*/
21524SQLITE_PRIVATE void sqlite3MallocEnd(void){
21525  if( sqlite3GlobalConfig.m.xShutdown ){
21526    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
21527  }
21528  memset(&mem0, 0, sizeof(mem0));
21529}
21530
21531/*
21532** Return the amount of memory currently checked out.
21533*/
21534SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
21535  sqlite3_int64 res, mx;
21536  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
21537  return res;
21538}
21539
21540/*
21541** Return the maximum amount of memory that has ever been
21542** checked out since either the beginning of this process
21543** or since the most recent reset.
21544*/
21545SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
21546  sqlite3_int64 res, mx;
21547  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
21548  return mx;
21549}
21550
21551/*
21552** Trigger the alarm
21553*/
21554static void sqlite3MallocAlarm(int nByte){
21555  if( mem0.alarmThreshold<=0 ) return;
21556  sqlite3_mutex_leave(mem0.mutex);
21557  sqlite3_release_memory(nByte);
21558  sqlite3_mutex_enter(mem0.mutex);
21559}
21560
21561/*
21562** Do a memory allocation with statistics and alarms.  Assume the
21563** lock is already held.
21564*/
21565static int mallocWithAlarm(int n, void **pp){
21566  int nFull;
21567  void *p;
21568  assert( sqlite3_mutex_held(mem0.mutex) );
21569  nFull = sqlite3GlobalConfig.m.xRoundup(n);
21570  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
21571  if( mem0.alarmThreshold>0 ){
21572    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
21573    if( nUsed >= mem0.alarmThreshold - nFull ){
21574      mem0.nearlyFull = 1;
21575      sqlite3MallocAlarm(nFull);
21576    }else{
21577      mem0.nearlyFull = 0;
21578    }
21579  }
21580  p = sqlite3GlobalConfig.m.xMalloc(nFull);
21581#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
21582  if( p==0 && mem0.alarmThreshold>0 ){
21583    sqlite3MallocAlarm(nFull);
21584    p = sqlite3GlobalConfig.m.xMalloc(nFull);
21585  }
21586#endif
21587  if( p ){
21588    nFull = sqlite3MallocSize(p);
21589    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
21590    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
21591  }
21592  *pp = p;
21593  return nFull;
21594}
21595
21596/*
21597** Allocate memory.  This routine is like sqlite3_malloc() except that it
21598** assumes the memory subsystem has already been initialized.
21599*/
21600SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
21601  void *p;
21602  if( n==0 || n>=0x7fffff00 ){
21603    /* A memory allocation of a number of bytes which is near the maximum
21604    ** signed integer value might cause an integer overflow inside of the
21605    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
21606    ** 255 bytes of overhead.  SQLite itself will never use anything near
21607    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
21608    p = 0;
21609  }else if( sqlite3GlobalConfig.bMemstat ){
21610    sqlite3_mutex_enter(mem0.mutex);
21611    mallocWithAlarm((int)n, &p);
21612    sqlite3_mutex_leave(mem0.mutex);
21613  }else{
21614    p = sqlite3GlobalConfig.m.xMalloc((int)n);
21615  }
21616  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
21617  return p;
21618}
21619
21620/*
21621** This version of the memory allocation is for use by the application.
21622** First make sure the memory subsystem is initialized, then do the
21623** allocation.
21624*/
21625SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
21626#ifndef SQLITE_OMIT_AUTOINIT
21627  if( sqlite3_initialize() ) return 0;
21628#endif
21629  return n<=0 ? 0 : sqlite3Malloc(n);
21630}
21631SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
21632#ifndef SQLITE_OMIT_AUTOINIT
21633  if( sqlite3_initialize() ) return 0;
21634#endif
21635  return sqlite3Malloc(n);
21636}
21637
21638/*
21639** Each thread may only have a single outstanding allocation from
21640** xScratchMalloc().  We verify this constraint in the single-threaded
21641** case by setting scratchAllocOut to 1 when an allocation
21642** is outstanding clearing it when the allocation is freed.
21643*/
21644#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21645static int scratchAllocOut = 0;
21646#endif
21647
21648
21649/*
21650** Allocate memory that is to be used and released right away.
21651** This routine is similar to alloca() in that it is not intended
21652** for situations where the memory might be held long-term.  This
21653** routine is intended to get memory to old large transient data
21654** structures that would not normally fit on the stack of an
21655** embedded processor.
21656*/
21657SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
21658  void *p;
21659  assert( n>0 );
21660
21661  sqlite3_mutex_enter(mem0.mutex);
21662  sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
21663  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
21664    p = mem0.pScratchFree;
21665    mem0.pScratchFree = mem0.pScratchFree->pNext;
21666    mem0.nScratchFree--;
21667    sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
21668    sqlite3_mutex_leave(mem0.mutex);
21669  }else{
21670    sqlite3_mutex_leave(mem0.mutex);
21671    p = sqlite3Malloc(n);
21672    if( sqlite3GlobalConfig.bMemstat && p ){
21673      sqlite3_mutex_enter(mem0.mutex);
21674      sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
21675      sqlite3_mutex_leave(mem0.mutex);
21676    }
21677    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
21678  }
21679  assert( sqlite3_mutex_notheld(mem0.mutex) );
21680
21681
21682#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21683  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
21684  ** buffers per thread.
21685  **
21686  ** This can only be checked in single-threaded mode.
21687  */
21688  assert( scratchAllocOut==0 );
21689  if( p ) scratchAllocOut++;
21690#endif
21691
21692  return p;
21693}
21694SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
21695  if( p ){
21696
21697#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21698    /* Verify that no more than two scratch allocation per thread
21699    ** is outstanding at one time.  (This is only checked in the
21700    ** single-threaded case since checking in the multi-threaded case
21701    ** would be much more complicated.) */
21702    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
21703    scratchAllocOut--;
21704#endif
21705
21706    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
21707      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
21708      ScratchFreeslot *pSlot;
21709      pSlot = (ScratchFreeslot*)p;
21710      sqlite3_mutex_enter(mem0.mutex);
21711      pSlot->pNext = mem0.pScratchFree;
21712      mem0.pScratchFree = pSlot;
21713      mem0.nScratchFree++;
21714      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
21715      sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
21716      sqlite3_mutex_leave(mem0.mutex);
21717    }else{
21718      /* Release memory back to the heap */
21719      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
21720      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
21721      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21722      if( sqlite3GlobalConfig.bMemstat ){
21723        int iSize = sqlite3MallocSize(p);
21724        sqlite3_mutex_enter(mem0.mutex);
21725        sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
21726        sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
21727        sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
21728        sqlite3GlobalConfig.m.xFree(p);
21729        sqlite3_mutex_leave(mem0.mutex);
21730      }else{
21731        sqlite3GlobalConfig.m.xFree(p);
21732      }
21733    }
21734  }
21735}
21736
21737/*
21738** TRUE if p is a lookaside memory allocation from db
21739*/
21740#ifndef SQLITE_OMIT_LOOKASIDE
21741static int isLookaside(sqlite3 *db, void *p){
21742  return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
21743}
21744#else
21745#define isLookaside(A,B) 0
21746#endif
21747
21748/*
21749** Return the size of a memory allocation previously obtained from
21750** sqlite3Malloc() or sqlite3_malloc().
21751*/
21752SQLITE_PRIVATE int sqlite3MallocSize(void *p){
21753  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21754  return sqlite3GlobalConfig.m.xSize(p);
21755}
21756SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
21757  if( db==0 || !isLookaside(db,p) ){
21758#if SQLITE_DEBUG
21759    if( db==0 ){
21760      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
21761      assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21762    }else{
21763      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21764      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21765    }
21766#endif
21767    return sqlite3GlobalConfig.m.xSize(p);
21768  }else{
21769    assert( sqlite3_mutex_held(db->mutex) );
21770    return db->lookaside.sz;
21771  }
21772}
21773SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
21774  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
21775  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21776  return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
21777}
21778
21779/*
21780** Free memory previously obtained from sqlite3Malloc().
21781*/
21782SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
21783  if( p==0 ) return;  /* IMP: R-49053-54554 */
21784  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21785  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
21786  if( sqlite3GlobalConfig.bMemstat ){
21787    sqlite3_mutex_enter(mem0.mutex);
21788    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
21789    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
21790    sqlite3GlobalConfig.m.xFree(p);
21791    sqlite3_mutex_leave(mem0.mutex);
21792  }else{
21793    sqlite3GlobalConfig.m.xFree(p);
21794  }
21795}
21796
21797/*
21798** Add the size of memory allocation "p" to the count in
21799** *db->pnBytesFreed.
21800*/
21801static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
21802  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
21803}
21804
21805/*
21806** Free memory that might be associated with a particular database
21807** connection.
21808*/
21809SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
21810  assert( db==0 || sqlite3_mutex_held(db->mutex) );
21811  if( p==0 ) return;
21812  if( db ){
21813    if( db->pnBytesFreed ){
21814      measureAllocationSize(db, p);
21815      return;
21816    }
21817    if( isLookaside(db, p) ){
21818      LookasideSlot *pBuf = (LookasideSlot*)p;
21819#if SQLITE_DEBUG
21820      /* Trash all content in the buffer being freed */
21821      memset(p, 0xaa, db->lookaside.sz);
21822#endif
21823      pBuf->pNext = db->lookaside.pFree;
21824      db->lookaside.pFree = pBuf;
21825      db->lookaside.nOut--;
21826      return;
21827    }
21828  }
21829  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21830  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21831  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21832  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21833  sqlite3_free(p);
21834}
21835
21836/*
21837** Change the size of an existing memory allocation
21838*/
21839SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
21840  int nOld, nNew, nDiff;
21841  void *pNew;
21842  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
21843  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
21844  if( pOld==0 ){
21845    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
21846  }
21847  if( nBytes==0 ){
21848    sqlite3_free(pOld); /* IMP: R-26507-47431 */
21849    return 0;
21850  }
21851  if( nBytes>=0x7fffff00 ){
21852    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
21853    return 0;
21854  }
21855  nOld = sqlite3MallocSize(pOld);
21856  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
21857  ** argument to xRealloc is always a value returned by a prior call to
21858  ** xRoundup. */
21859  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
21860  if( nOld==nNew ){
21861    pNew = pOld;
21862  }else if( sqlite3GlobalConfig.bMemstat ){
21863    sqlite3_mutex_enter(mem0.mutex);
21864    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
21865    nDiff = nNew - nOld;
21866    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
21867          mem0.alarmThreshold-nDiff ){
21868      sqlite3MallocAlarm(nDiff);
21869    }
21870    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21871    if( pNew==0 && mem0.alarmThreshold>0 ){
21872      sqlite3MallocAlarm((int)nBytes);
21873      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21874    }
21875    if( pNew ){
21876      nNew = sqlite3MallocSize(pNew);
21877      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
21878    }
21879    sqlite3_mutex_leave(mem0.mutex);
21880  }else{
21881    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21882  }
21883  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
21884  return pNew;
21885}
21886
21887/*
21888** The public interface to sqlite3Realloc.  Make sure that the memory
21889** subsystem is initialized prior to invoking sqliteRealloc.
21890*/
21891SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
21892#ifndef SQLITE_OMIT_AUTOINIT
21893  if( sqlite3_initialize() ) return 0;
21894#endif
21895  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
21896  return sqlite3Realloc(pOld, n);
21897}
21898SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
21899#ifndef SQLITE_OMIT_AUTOINIT
21900  if( sqlite3_initialize() ) return 0;
21901#endif
21902  return sqlite3Realloc(pOld, n);
21903}
21904
21905
21906/*
21907** Allocate and zero memory.
21908*/
21909SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
21910  void *p = sqlite3Malloc(n);
21911  if( p ){
21912    memset(p, 0, (size_t)n);
21913  }
21914  return p;
21915}
21916
21917/*
21918** Allocate and zero memory.  If the allocation fails, make
21919** the mallocFailed flag in the connection pointer.
21920*/
21921SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
21922  void *p = sqlite3DbMallocRaw(db, n);
21923  if( p ){
21924    memset(p, 0, (size_t)n);
21925  }
21926  return p;
21927}
21928
21929/*
21930** Allocate and zero memory.  If the allocation fails, make
21931** the mallocFailed flag in the connection pointer.
21932**
21933** If db!=0 and db->mallocFailed is true (indicating a prior malloc
21934** failure on the same database connection) then always return 0.
21935** Hence for a particular database connection, once malloc starts
21936** failing, it fails consistently until mallocFailed is reset.
21937** This is an important assumption.  There are many places in the
21938** code that do things like this:
21939**
21940**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
21941**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
21942**         if( b ) a[10] = 9;
21943**
21944** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
21945** that all prior mallocs (ex: "a") worked too.
21946*/
21947SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
21948  void *p;
21949  assert( db==0 || sqlite3_mutex_held(db->mutex) );
21950  assert( db==0 || db->pnBytesFreed==0 );
21951#ifndef SQLITE_OMIT_LOOKASIDE
21952  if( db ){
21953    LookasideSlot *pBuf;
21954    if( db->mallocFailed ){
21955      return 0;
21956    }
21957    if( db->lookaside.bEnabled ){
21958      if( n>db->lookaside.sz ){
21959        db->lookaside.anStat[1]++;
21960      }else if( (pBuf = db->lookaside.pFree)==0 ){
21961        db->lookaside.anStat[2]++;
21962      }else{
21963        db->lookaside.pFree = pBuf->pNext;
21964        db->lookaside.nOut++;
21965        db->lookaside.anStat[0]++;
21966        if( db->lookaside.nOut>db->lookaside.mxOut ){
21967          db->lookaside.mxOut = db->lookaside.nOut;
21968        }
21969        return (void*)pBuf;
21970      }
21971    }
21972  }
21973#else
21974  if( db && db->mallocFailed ){
21975    return 0;
21976  }
21977#endif
21978  p = sqlite3Malloc(n);
21979  if( !p && db ){
21980    db->mallocFailed = 1;
21981  }
21982  sqlite3MemdebugSetType(p,
21983         (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
21984  return p;
21985}
21986
21987/*
21988** Resize the block of memory pointed to by p to n bytes. If the
21989** resize fails, set the mallocFailed flag in the connection object.
21990*/
21991SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
21992  void *pNew = 0;
21993  assert( db!=0 );
21994  assert( sqlite3_mutex_held(db->mutex) );
21995  if( db->mallocFailed==0 ){
21996    if( p==0 ){
21997      return sqlite3DbMallocRaw(db, n);
21998    }
21999    if( isLookaside(db, p) ){
22000      if( n<=db->lookaside.sz ){
22001        return p;
22002      }
22003      pNew = sqlite3DbMallocRaw(db, n);
22004      if( pNew ){
22005        memcpy(pNew, p, db->lookaside.sz);
22006        sqlite3DbFree(db, p);
22007      }
22008    }else{
22009      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
22010      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
22011      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
22012      pNew = sqlite3_realloc64(p, n);
22013      if( !pNew ){
22014        db->mallocFailed = 1;
22015      }
22016      sqlite3MemdebugSetType(pNew,
22017            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
22018    }
22019  }
22020  return pNew;
22021}
22022
22023/*
22024** Attempt to reallocate p.  If the reallocation fails, then free p
22025** and set the mallocFailed flag in the database connection.
22026*/
22027SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
22028  void *pNew;
22029  pNew = sqlite3DbRealloc(db, p, n);
22030  if( !pNew ){
22031    sqlite3DbFree(db, p);
22032  }
22033  return pNew;
22034}
22035
22036/*
22037** Make a copy of a string in memory obtained from sqliteMalloc(). These
22038** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
22039** is because when memory debugging is turned on, these two functions are
22040** called via macros that record the current file and line number in the
22041** ThreadData structure.
22042*/
22043SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
22044  char *zNew;
22045  size_t n;
22046  if( z==0 ){
22047    return 0;
22048  }
22049  n = sqlite3Strlen30(z) + 1;
22050  assert( (n&0x7fffffff)==n );
22051  zNew = sqlite3DbMallocRaw(db, (int)n);
22052  if( zNew ){
22053    memcpy(zNew, z, n);
22054  }
22055  return zNew;
22056}
22057SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
22058  char *zNew;
22059  if( z==0 ){
22060    return 0;
22061  }
22062  assert( (n&0x7fffffff)==n );
22063  zNew = sqlite3DbMallocRaw(db, n+1);
22064  if( zNew ){
22065    memcpy(zNew, z, (size_t)n);
22066    zNew[n] = 0;
22067  }
22068  return zNew;
22069}
22070
22071/*
22072** Free any prior content in *pz and replace it with a copy of zNew.
22073*/
22074SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
22075  sqlite3DbFree(db, *pz);
22076  *pz = sqlite3DbStrDup(db, zNew);
22077}
22078
22079/*
22080** Take actions at the end of an API call to indicate an OOM error
22081*/
22082static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
22083  db->mallocFailed = 0;
22084  sqlite3Error(db, SQLITE_NOMEM);
22085  return SQLITE_NOMEM;
22086}
22087
22088/*
22089** This function must be called before exiting any API function (i.e.
22090** returning control to the user) that has called sqlite3_malloc or
22091** sqlite3_realloc.
22092**
22093** The returned value is normally a copy of the second argument to this
22094** function. However, if a malloc() failure has occurred since the previous
22095** invocation SQLITE_NOMEM is returned instead.
22096**
22097** If an OOM as occurred, then the connection error-code (the value
22098** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
22099*/
22100SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
22101  /* If the db handle must hold the connection handle mutex here.
22102  ** Otherwise the read (and possible write) of db->mallocFailed
22103  ** is unsafe, as is the call to sqlite3Error().
22104  */
22105  assert( db!=0 );
22106  assert( sqlite3_mutex_held(db->mutex) );
22107  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
22108    return apiOomError(db);
22109  }
22110  return rc & db->errMask;
22111}
22112
22113/************** End of malloc.c **********************************************/
22114/************** Begin file printf.c ******************************************/
22115/*
22116** The "printf" code that follows dates from the 1980's.  It is in
22117** the public domain.
22118**
22119**************************************************************************
22120**
22121** This file contains code for a set of "printf"-like routines.  These
22122** routines format strings much like the printf() from the standard C
22123** library, though the implementation here has enhancements to support
22124** SQLite.
22125*/
22126/* #include "sqliteInt.h" */
22127
22128/*
22129** Conversion types fall into various categories as defined by the
22130** following enumeration.
22131*/
22132#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
22133#define etFLOAT       2 /* Floating point.  %f */
22134#define etEXP         3 /* Exponentional notation. %e and %E */
22135#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
22136#define etSIZE        5 /* Return number of characters processed so far. %n */
22137#define etSTRING      6 /* Strings. %s */
22138#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
22139#define etPERCENT     8 /* Percent symbol. %% */
22140#define etCHARX       9 /* Characters. %c */
22141/* The rest are extensions, not normally found in printf() */
22142#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
22143#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
22144                          NULL pointers replaced by SQL NULL.  %Q */
22145#define etTOKEN      12 /* a pointer to a Token structure */
22146#define etSRCLIST    13 /* a pointer to a SrcList */
22147#define etPOINTER    14 /* The %p conversion */
22148#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
22149#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
22150
22151#define etINVALID     0 /* Any unrecognized conversion type */
22152
22153
22154/*
22155** An "etByte" is an 8-bit unsigned value.
22156*/
22157typedef unsigned char etByte;
22158
22159/*
22160** Each builtin conversion character (ex: the 'd' in "%d") is described
22161** by an instance of the following structure
22162*/
22163typedef struct et_info {   /* Information about each format field */
22164  char fmttype;            /* The format field code letter */
22165  etByte base;             /* The base for radix conversion */
22166  etByte flags;            /* One or more of FLAG_ constants below */
22167  etByte type;             /* Conversion paradigm */
22168  etByte charset;          /* Offset into aDigits[] of the digits string */
22169  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
22170} et_info;
22171
22172/*
22173** Allowed values for et_info.flags
22174*/
22175#define FLAG_SIGNED  1     /* True if the value to convert is signed */
22176#define FLAG_INTERN  2     /* True if for internal use only */
22177#define FLAG_STRING  4     /* Allow infinity precision */
22178
22179
22180/*
22181** The following table is searched linearly, so it is good to put the
22182** most frequently used conversion types first.
22183*/
22184static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
22185static const char aPrefix[] = "-x0\000X0";
22186static const et_info fmtinfo[] = {
22187  {  'd', 10, 1, etRADIX,      0,  0 },
22188  {  's',  0, 4, etSTRING,     0,  0 },
22189  {  'g',  0, 1, etGENERIC,    30, 0 },
22190  {  'z',  0, 4, etDYNSTRING,  0,  0 },
22191  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
22192  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
22193  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
22194  {  'c',  0, 0, etCHARX,      0,  0 },
22195  {  'o',  8, 0, etRADIX,      0,  2 },
22196  {  'u', 10, 0, etRADIX,      0,  0 },
22197  {  'x', 16, 0, etRADIX,      16, 1 },
22198  {  'X', 16, 0, etRADIX,      0,  4 },
22199#ifndef SQLITE_OMIT_FLOATING_POINT
22200  {  'f',  0, 1, etFLOAT,      0,  0 },
22201  {  'e',  0, 1, etEXP,        30, 0 },
22202  {  'E',  0, 1, etEXP,        14, 0 },
22203  {  'G',  0, 1, etGENERIC,    14, 0 },
22204#endif
22205  {  'i', 10, 1, etRADIX,      0,  0 },
22206  {  'n',  0, 0, etSIZE,       0,  0 },
22207  {  '%',  0, 0, etPERCENT,    0,  0 },
22208  {  'p', 16, 0, etPOINTER,    0,  1 },
22209
22210/* All the rest have the FLAG_INTERN bit set and are thus for internal
22211** use only */
22212  {  'T',  0, 2, etTOKEN,      0,  0 },
22213  {  'S',  0, 2, etSRCLIST,    0,  0 },
22214  {  'r', 10, 3, etORDINAL,    0,  0 },
22215};
22216
22217/*
22218** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
22219** conversions will work.
22220*/
22221#ifndef SQLITE_OMIT_FLOATING_POINT
22222/*
22223** "*val" is a double such that 0.1 <= *val < 10.0
22224** Return the ascii code for the leading digit of *val, then
22225** multiply "*val" by 10.0 to renormalize.
22226**
22227** Example:
22228**     input:     *val = 3.14159
22229**     output:    *val = 1.4159    function return = '3'
22230**
22231** The counter *cnt is incremented each time.  After counter exceeds
22232** 16 (the number of significant digits in a 64-bit float) '0' is
22233** always returned.
22234*/
22235static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
22236  int digit;
22237  LONGDOUBLE_TYPE d;
22238  if( (*cnt)<=0 ) return '0';
22239  (*cnt)--;
22240  digit = (int)*val;
22241  d = digit;
22242  digit += '0';
22243  *val = (*val - d)*10.0;
22244  return (char)digit;
22245}
22246#endif /* SQLITE_OMIT_FLOATING_POINT */
22247
22248/*
22249** Set the StrAccum object to an error mode.
22250*/
22251static void setStrAccumError(StrAccum *p, u8 eError){
22252  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
22253  p->accError = eError;
22254  p->nAlloc = 0;
22255}
22256
22257/*
22258** Extra argument values from a PrintfArguments object
22259*/
22260static sqlite3_int64 getIntArg(PrintfArguments *p){
22261  if( p->nArg<=p->nUsed ) return 0;
22262  return sqlite3_value_int64(p->apArg[p->nUsed++]);
22263}
22264static double getDoubleArg(PrintfArguments *p){
22265  if( p->nArg<=p->nUsed ) return 0.0;
22266  return sqlite3_value_double(p->apArg[p->nUsed++]);
22267}
22268static char *getTextArg(PrintfArguments *p){
22269  if( p->nArg<=p->nUsed ) return 0;
22270  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
22271}
22272
22273
22274/*
22275** On machines with a small stack size, you can redefine the
22276** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
22277*/
22278#ifndef SQLITE_PRINT_BUF_SIZE
22279# define SQLITE_PRINT_BUF_SIZE 70
22280#endif
22281#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
22282
22283/*
22284** Render a string given by "fmt" into the StrAccum object.
22285*/
22286SQLITE_PRIVATE void sqlite3VXPrintf(
22287  StrAccum *pAccum,          /* Accumulate results here */
22288  u32 bFlags,                /* SQLITE_PRINTF_* flags */
22289  const char *fmt,           /* Format string */
22290  va_list ap                 /* arguments */
22291){
22292  int c;                     /* Next character in the format string */
22293  char *bufpt;               /* Pointer to the conversion buffer */
22294  int precision;             /* Precision of the current field */
22295  int length;                /* Length of the field */
22296  int idx;                   /* A general purpose loop counter */
22297  int width;                 /* Width of the current field */
22298  etByte flag_leftjustify;   /* True if "-" flag is present */
22299  etByte flag_plussign;      /* True if "+" flag is present */
22300  etByte flag_blanksign;     /* True if " " flag is present */
22301  etByte flag_alternateform; /* True if "#" flag is present */
22302  etByte flag_altform2;      /* True if "!" flag is present */
22303  etByte flag_zeropad;       /* True if field width constant starts with zero */
22304  etByte flag_long;          /* True if "l" flag is present */
22305  etByte flag_longlong;      /* True if the "ll" flag is present */
22306  etByte done;               /* Loop termination flag */
22307  etByte xtype = 0;          /* Conversion paradigm */
22308  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
22309  u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
22310  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
22311  sqlite_uint64 longvalue;   /* Value for integer types */
22312  LONGDOUBLE_TYPE realvalue; /* Value for real types */
22313  const et_info *infop;      /* Pointer to the appropriate info structure */
22314  char *zOut;                /* Rendering buffer */
22315  int nOut;                  /* Size of the rendering buffer */
22316  char *zExtra = 0;          /* Malloced memory used by some conversion */
22317#ifndef SQLITE_OMIT_FLOATING_POINT
22318  int  exp, e2;              /* exponent of real numbers */
22319  int nsd;                   /* Number of significant digits returned */
22320  double rounder;            /* Used for rounding floating point values */
22321  etByte flag_dp;            /* True if decimal point should be shown */
22322  etByte flag_rtz;           /* True if trailing zeros should be removed */
22323#endif
22324  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
22325  char buf[etBUFSIZE];       /* Conversion buffer */
22326
22327  bufpt = 0;
22328  if( bFlags ){
22329    if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
22330      pArgList = va_arg(ap, PrintfArguments*);
22331    }
22332    useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
22333  }else{
22334    bArgList = useIntern = 0;
22335  }
22336  for(; (c=(*fmt))!=0; ++fmt){
22337    if( c!='%' ){
22338      bufpt = (char *)fmt;
22339#if HAVE_STRCHRNUL
22340      fmt = strchrnul(fmt, '%');
22341#else
22342      do{ fmt++; }while( *fmt && *fmt != '%' );
22343#endif
22344      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
22345      if( *fmt==0 ) break;
22346    }
22347    if( (c=(*++fmt))==0 ){
22348      sqlite3StrAccumAppend(pAccum, "%", 1);
22349      break;
22350    }
22351    /* Find out what flags are present */
22352    flag_leftjustify = flag_plussign = flag_blanksign =
22353     flag_alternateform = flag_altform2 = flag_zeropad = 0;
22354    done = 0;
22355    do{
22356      switch( c ){
22357        case '-':   flag_leftjustify = 1;     break;
22358        case '+':   flag_plussign = 1;        break;
22359        case ' ':   flag_blanksign = 1;       break;
22360        case '#':   flag_alternateform = 1;   break;
22361        case '!':   flag_altform2 = 1;        break;
22362        case '0':   flag_zeropad = 1;         break;
22363        default:    done = 1;                 break;
22364      }
22365    }while( !done && (c=(*++fmt))!=0 );
22366    /* Get the field width */
22367    if( c=='*' ){
22368      if( bArgList ){
22369        width = (int)getIntArg(pArgList);
22370      }else{
22371        width = va_arg(ap,int);
22372      }
22373      if( width<0 ){
22374        flag_leftjustify = 1;
22375        width = width >= -2147483647 ? -width : 0;
22376      }
22377      c = *++fmt;
22378    }else{
22379      unsigned wx = 0;
22380      while( c>='0' && c<='9' ){
22381        wx = wx*10 + c - '0';
22382        c = *++fmt;
22383      }
22384      testcase( wx>0x7fffffff );
22385      width = wx & 0x7fffffff;
22386    }
22387
22388    /* Get the precision */
22389    if( c=='.' ){
22390      c = *++fmt;
22391      if( c=='*' ){
22392        if( bArgList ){
22393          precision = (int)getIntArg(pArgList);
22394        }else{
22395          precision = va_arg(ap,int);
22396        }
22397        c = *++fmt;
22398        if( precision<0 ){
22399          precision = precision >= -2147483647 ? -precision : -1;
22400        }
22401      }else{
22402        unsigned px = 0;
22403        while( c>='0' && c<='9' ){
22404          px = px*10 + c - '0';
22405          c = *++fmt;
22406        }
22407        testcase( px>0x7fffffff );
22408        precision = px & 0x7fffffff;
22409      }
22410    }else{
22411      precision = -1;
22412    }
22413    /* Get the conversion type modifier */
22414    if( c=='l' ){
22415      flag_long = 1;
22416      c = *++fmt;
22417      if( c=='l' ){
22418        flag_longlong = 1;
22419        c = *++fmt;
22420      }else{
22421        flag_longlong = 0;
22422      }
22423    }else{
22424      flag_long = flag_longlong = 0;
22425    }
22426    /* Fetch the info entry for the field */
22427    infop = &fmtinfo[0];
22428    xtype = etINVALID;
22429    for(idx=0; idx<ArraySize(fmtinfo); idx++){
22430      if( c==fmtinfo[idx].fmttype ){
22431        infop = &fmtinfo[idx];
22432        if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
22433          xtype = infop->type;
22434        }else{
22435          return;
22436        }
22437        break;
22438      }
22439    }
22440
22441    /*
22442    ** At this point, variables are initialized as follows:
22443    **
22444    **   flag_alternateform          TRUE if a '#' is present.
22445    **   flag_altform2               TRUE if a '!' is present.
22446    **   flag_plussign               TRUE if a '+' is present.
22447    **   flag_leftjustify            TRUE if a '-' is present or if the
22448    **                               field width was negative.
22449    **   flag_zeropad                TRUE if the width began with 0.
22450    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
22451    **                               the conversion character.
22452    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
22453    **                               the conversion character.
22454    **   flag_blanksign              TRUE if a ' ' is present.
22455    **   width                       The specified field width.  This is
22456    **                               always non-negative.  Zero is the default.
22457    **   precision                   The specified precision.  The default
22458    **                               is -1.
22459    **   xtype                       The class of the conversion.
22460    **   infop                       Pointer to the appropriate info struct.
22461    */
22462    switch( xtype ){
22463      case etPOINTER:
22464        flag_longlong = sizeof(char*)==sizeof(i64);
22465        flag_long = sizeof(char*)==sizeof(long int);
22466        /* Fall through into the next case */
22467      case etORDINAL:
22468      case etRADIX:
22469        if( infop->flags & FLAG_SIGNED ){
22470          i64 v;
22471          if( bArgList ){
22472            v = getIntArg(pArgList);
22473          }else if( flag_longlong ){
22474            v = va_arg(ap,i64);
22475          }else if( flag_long ){
22476            v = va_arg(ap,long int);
22477          }else{
22478            v = va_arg(ap,int);
22479          }
22480          if( v<0 ){
22481            if( v==SMALLEST_INT64 ){
22482              longvalue = ((u64)1)<<63;
22483            }else{
22484              longvalue = -v;
22485            }
22486            prefix = '-';
22487          }else{
22488            longvalue = v;
22489            if( flag_plussign )        prefix = '+';
22490            else if( flag_blanksign )  prefix = ' ';
22491            else                       prefix = 0;
22492          }
22493        }else{
22494          if( bArgList ){
22495            longvalue = (u64)getIntArg(pArgList);
22496          }else if( flag_longlong ){
22497            longvalue = va_arg(ap,u64);
22498          }else if( flag_long ){
22499            longvalue = va_arg(ap,unsigned long int);
22500          }else{
22501            longvalue = va_arg(ap,unsigned int);
22502          }
22503          prefix = 0;
22504        }
22505        if( longvalue==0 ) flag_alternateform = 0;
22506        if( flag_zeropad && precision<width-(prefix!=0) ){
22507          precision = width-(prefix!=0);
22508        }
22509        if( precision<etBUFSIZE-10 ){
22510          nOut = etBUFSIZE;
22511          zOut = buf;
22512        }else{
22513          nOut = precision + 10;
22514          zOut = zExtra = sqlite3Malloc( nOut );
22515          if( zOut==0 ){
22516            setStrAccumError(pAccum, STRACCUM_NOMEM);
22517            return;
22518          }
22519        }
22520        bufpt = &zOut[nOut-1];
22521        if( xtype==etORDINAL ){
22522          static const char zOrd[] = "thstndrd";
22523          int x = (int)(longvalue % 10);
22524          if( x>=4 || (longvalue/10)%10==1 ){
22525            x = 0;
22526          }
22527          *(--bufpt) = zOrd[x*2+1];
22528          *(--bufpt) = zOrd[x*2];
22529        }
22530        {
22531          const char *cset = &aDigits[infop->charset];
22532          u8 base = infop->base;
22533          do{                                           /* Convert to ascii */
22534            *(--bufpt) = cset[longvalue%base];
22535            longvalue = longvalue/base;
22536          }while( longvalue>0 );
22537        }
22538        length = (int)(&zOut[nOut-1]-bufpt);
22539        for(idx=precision-length; idx>0; idx--){
22540          *(--bufpt) = '0';                             /* Zero pad */
22541        }
22542        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
22543        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
22544          const char *pre;
22545          char x;
22546          pre = &aPrefix[infop->prefix];
22547          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
22548        }
22549        length = (int)(&zOut[nOut-1]-bufpt);
22550        break;
22551      case etFLOAT:
22552      case etEXP:
22553      case etGENERIC:
22554        if( bArgList ){
22555          realvalue = getDoubleArg(pArgList);
22556        }else{
22557          realvalue = va_arg(ap,double);
22558        }
22559#ifdef SQLITE_OMIT_FLOATING_POINT
22560        length = 0;
22561#else
22562        if( precision<0 ) precision = 6;         /* Set default precision */
22563        if( realvalue<0.0 ){
22564          realvalue = -realvalue;
22565          prefix = '-';
22566        }else{
22567          if( flag_plussign )          prefix = '+';
22568          else if( flag_blanksign )    prefix = ' ';
22569          else                         prefix = 0;
22570        }
22571        if( xtype==etGENERIC && precision>0 ) precision--;
22572        testcase( precision>0xfff );
22573        for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
22574        if( xtype==etFLOAT ) realvalue += rounder;
22575        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
22576        exp = 0;
22577        if( sqlite3IsNaN((double)realvalue) ){
22578          bufpt = "NaN";
22579          length = 3;
22580          break;
22581        }
22582        if( realvalue>0.0 ){
22583          LONGDOUBLE_TYPE scale = 1.0;
22584          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
22585          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
22586          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
22587          realvalue /= scale;
22588          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
22589          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
22590          if( exp>350 ){
22591            bufpt = buf;
22592            buf[0] = prefix;
22593            memcpy(buf+(prefix!=0),"Inf",4);
22594            length = 3+(prefix!=0);
22595            break;
22596          }
22597        }
22598        bufpt = buf;
22599        /*
22600        ** If the field type is etGENERIC, then convert to either etEXP
22601        ** or etFLOAT, as appropriate.
22602        */
22603        if( xtype!=etFLOAT ){
22604          realvalue += rounder;
22605          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
22606        }
22607        if( xtype==etGENERIC ){
22608          flag_rtz = !flag_alternateform;
22609          if( exp<-4 || exp>precision ){
22610            xtype = etEXP;
22611          }else{
22612            precision = precision - exp;
22613            xtype = etFLOAT;
22614          }
22615        }else{
22616          flag_rtz = flag_altform2;
22617        }
22618        if( xtype==etEXP ){
22619          e2 = 0;
22620        }else{
22621          e2 = exp;
22622        }
22623        if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
22624          bufpt = zExtra
22625              = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
22626          if( bufpt==0 ){
22627            setStrAccumError(pAccum, STRACCUM_NOMEM);
22628            return;
22629          }
22630        }
22631        zOut = bufpt;
22632        nsd = 16 + flag_altform2*10;
22633        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
22634        /* The sign in front of the number */
22635        if( prefix ){
22636          *(bufpt++) = prefix;
22637        }
22638        /* Digits prior to the decimal point */
22639        if( e2<0 ){
22640          *(bufpt++) = '0';
22641        }else{
22642          for(; e2>=0; e2--){
22643            *(bufpt++) = et_getdigit(&realvalue,&nsd);
22644          }
22645        }
22646        /* The decimal point */
22647        if( flag_dp ){
22648          *(bufpt++) = '.';
22649        }
22650        /* "0" digits after the decimal point but before the first
22651        ** significant digit of the number */
22652        for(e2++; e2<0; precision--, e2++){
22653          assert( precision>0 );
22654          *(bufpt++) = '0';
22655        }
22656        /* Significant digits after the decimal point */
22657        while( (precision--)>0 ){
22658          *(bufpt++) = et_getdigit(&realvalue,&nsd);
22659        }
22660        /* Remove trailing zeros and the "." if no digits follow the "." */
22661        if( flag_rtz && flag_dp ){
22662          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
22663          assert( bufpt>zOut );
22664          if( bufpt[-1]=='.' ){
22665            if( flag_altform2 ){
22666              *(bufpt++) = '0';
22667            }else{
22668              *(--bufpt) = 0;
22669            }
22670          }
22671        }
22672        /* Add the "eNNN" suffix */
22673        if( xtype==etEXP ){
22674          *(bufpt++) = aDigits[infop->charset];
22675          if( exp<0 ){
22676            *(bufpt++) = '-'; exp = -exp;
22677          }else{
22678            *(bufpt++) = '+';
22679          }
22680          if( exp>=100 ){
22681            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
22682            exp %= 100;
22683          }
22684          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
22685          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
22686        }
22687        *bufpt = 0;
22688
22689        /* The converted number is in buf[] and zero terminated. Output it.
22690        ** Note that the number is in the usual order, not reversed as with
22691        ** integer conversions. */
22692        length = (int)(bufpt-zOut);
22693        bufpt = zOut;
22694
22695        /* Special case:  Add leading zeros if the flag_zeropad flag is
22696        ** set and we are not left justified */
22697        if( flag_zeropad && !flag_leftjustify && length < width){
22698          int i;
22699          int nPad = width - length;
22700          for(i=width; i>=nPad; i--){
22701            bufpt[i] = bufpt[i-nPad];
22702          }
22703          i = prefix!=0;
22704          while( nPad-- ) bufpt[i++] = '0';
22705          length = width;
22706        }
22707#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
22708        break;
22709      case etSIZE:
22710        if( !bArgList ){
22711          *(va_arg(ap,int*)) = pAccum->nChar;
22712        }
22713        length = width = 0;
22714        break;
22715      case etPERCENT:
22716        buf[0] = '%';
22717        bufpt = buf;
22718        length = 1;
22719        break;
22720      case etCHARX:
22721        if( bArgList ){
22722          bufpt = getTextArg(pArgList);
22723          c = bufpt ? bufpt[0] : 0;
22724        }else{
22725          c = va_arg(ap,int);
22726        }
22727        if( precision>1 ){
22728          width -= precision-1;
22729          if( width>1 && !flag_leftjustify ){
22730            sqlite3AppendChar(pAccum, width-1, ' ');
22731            width = 0;
22732          }
22733          sqlite3AppendChar(pAccum, precision-1, c);
22734        }
22735        length = 1;
22736        buf[0] = c;
22737        bufpt = buf;
22738        break;
22739      case etSTRING:
22740      case etDYNSTRING:
22741        if( bArgList ){
22742          bufpt = getTextArg(pArgList);
22743          xtype = etSTRING;
22744        }else{
22745          bufpt = va_arg(ap,char*);
22746        }
22747        if( bufpt==0 ){
22748          bufpt = "";
22749        }else if( xtype==etDYNSTRING ){
22750          zExtra = bufpt;
22751        }
22752        if( precision>=0 ){
22753          for(length=0; length<precision && bufpt[length]; length++){}
22754        }else{
22755          length = sqlite3Strlen30(bufpt);
22756        }
22757        break;
22758      case etSQLESCAPE:           /* Escape ' characters */
22759      case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
22760      case etSQLESCAPE3: {        /* Escape " characters */
22761        int i, j, k, n, isnull;
22762        int needQuote;
22763        char ch;
22764        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
22765        char *escarg;
22766
22767        if( bArgList ){
22768          escarg = getTextArg(pArgList);
22769        }else{
22770          escarg = va_arg(ap,char*);
22771        }
22772        isnull = escarg==0;
22773        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
22774        k = precision;
22775        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
22776          if( ch==q )  n++;
22777        }
22778        needQuote = !isnull && xtype==etSQLESCAPE2;
22779        n += i + 3;
22780        if( n>etBUFSIZE ){
22781          bufpt = zExtra = sqlite3Malloc( n );
22782          if( bufpt==0 ){
22783            setStrAccumError(pAccum, STRACCUM_NOMEM);
22784            return;
22785          }
22786        }else{
22787          bufpt = buf;
22788        }
22789        j = 0;
22790        if( needQuote ) bufpt[j++] = q;
22791        k = i;
22792        for(i=0; i<k; i++){
22793          bufpt[j++] = ch = escarg[i];
22794          if( ch==q ) bufpt[j++] = ch;
22795        }
22796        if( needQuote ) bufpt[j++] = q;
22797        bufpt[j] = 0;
22798        length = j;
22799        /* The precision in %q and %Q means how many input characters to
22800        ** consume, not the length of the output...
22801        ** if( precision>=0 && precision<length ) length = precision; */
22802        break;
22803      }
22804      case etTOKEN: {
22805        Token *pToken = va_arg(ap, Token*);
22806        assert( bArgList==0 );
22807        if( pToken && pToken->n ){
22808          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
22809        }
22810        length = width = 0;
22811        break;
22812      }
22813      case etSRCLIST: {
22814        SrcList *pSrc = va_arg(ap, SrcList*);
22815        int k = va_arg(ap, int);
22816        struct SrcList_item *pItem = &pSrc->a[k];
22817        assert( bArgList==0 );
22818        assert( k>=0 && k<pSrc->nSrc );
22819        if( pItem->zDatabase ){
22820          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
22821          sqlite3StrAccumAppend(pAccum, ".", 1);
22822        }
22823        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
22824        length = width = 0;
22825        break;
22826      }
22827      default: {
22828        assert( xtype==etINVALID );
22829        return;
22830      }
22831    }/* End switch over the format type */
22832    /*
22833    ** The text of the conversion is pointed to by "bufpt" and is
22834    ** "length" characters long.  The field width is "width".  Do
22835    ** the output.
22836    */
22837    width -= length;
22838    if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
22839    sqlite3StrAccumAppend(pAccum, bufpt, length);
22840    if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
22841
22842    if( zExtra ){
22843      sqlite3_free(zExtra);
22844      zExtra = 0;
22845    }
22846  }/* End for loop over the format string */
22847} /* End of function */
22848
22849/*
22850** Enlarge the memory allocation on a StrAccum object so that it is
22851** able to accept at least N more bytes of text.
22852**
22853** Return the number of bytes of text that StrAccum is able to accept
22854** after the attempted enlargement.  The value returned might be zero.
22855*/
22856static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
22857  char *zNew;
22858  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
22859  if( p->accError ){
22860    testcase(p->accError==STRACCUM_TOOBIG);
22861    testcase(p->accError==STRACCUM_NOMEM);
22862    return 0;
22863  }
22864  if( p->mxAlloc==0 ){
22865    N = p->nAlloc - p->nChar - 1;
22866    setStrAccumError(p, STRACCUM_TOOBIG);
22867    return N;
22868  }else{
22869    char *zOld = (p->zText==p->zBase ? 0 : p->zText);
22870    i64 szNew = p->nChar;
22871    szNew += N + 1;
22872    if( szNew+p->nChar<=p->mxAlloc ){
22873      /* Force exponential buffer size growth as long as it does not overflow,
22874      ** to avoid having to call this routine too often */
22875      szNew += p->nChar;
22876    }
22877    if( szNew > p->mxAlloc ){
22878      sqlite3StrAccumReset(p);
22879      setStrAccumError(p, STRACCUM_TOOBIG);
22880      return 0;
22881    }else{
22882      p->nAlloc = (int)szNew;
22883    }
22884    if( p->db ){
22885      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
22886    }else{
22887      zNew = sqlite3_realloc64(zOld, p->nAlloc);
22888    }
22889    if( zNew ){
22890      assert( p->zText!=0 || p->nChar==0 );
22891      if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
22892      p->zText = zNew;
22893      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
22894    }else{
22895      sqlite3StrAccumReset(p);
22896      setStrAccumError(p, STRACCUM_NOMEM);
22897      return 0;
22898    }
22899  }
22900  return N;
22901}
22902
22903/*
22904** Append N copies of character c to the given string buffer.
22905*/
22906SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
22907  testcase( p->nChar + (i64)N > 0x7fffffff );
22908  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
22909    return;
22910  }
22911  while( (N--)>0 ) p->zText[p->nChar++] = c;
22912}
22913
22914/*
22915** The StrAccum "p" is not large enough to accept N new bytes of z[].
22916** So enlarge if first, then do the append.
22917**
22918** This is a helper routine to sqlite3StrAccumAppend() that does special-case
22919** work (enlarging the buffer) using tail recursion, so that the
22920** sqlite3StrAccumAppend() routine can use fast calling semantics.
22921*/
22922static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
22923  N = sqlite3StrAccumEnlarge(p, N);
22924  if( N>0 ){
22925    memcpy(&p->zText[p->nChar], z, N);
22926    p->nChar += N;
22927  }
22928}
22929
22930/*
22931** Append N bytes of text from z to the StrAccum object.  Increase the
22932** size of the memory allocation for StrAccum if necessary.
22933*/
22934SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
22935  assert( z!=0 || N==0 );
22936  assert( p->zText!=0 || p->nChar==0 || p->accError );
22937  assert( N>=0 );
22938  assert( p->accError==0 || p->nAlloc==0 );
22939  if( p->nChar+N >= p->nAlloc ){
22940    enlargeAndAppend(p,z,N);
22941  }else{
22942    assert( p->zText );
22943    p->nChar += N;
22944    memcpy(&p->zText[p->nChar-N], z, N);
22945  }
22946}
22947
22948/*
22949** Append the complete text of zero-terminated string z[] to the p string.
22950*/
22951SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
22952  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
22953}
22954
22955
22956/*
22957** Finish off a string by making sure it is zero-terminated.
22958** Return a pointer to the resulting string.  Return a NULL
22959** pointer if any kind of error was encountered.
22960*/
22961SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
22962  if( p->zText ){
22963    p->zText[p->nChar] = 0;
22964    if( p->mxAlloc>0 && p->zText==p->zBase ){
22965      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
22966      if( p->zText ){
22967        memcpy(p->zText, p->zBase, p->nChar+1);
22968      }else{
22969        setStrAccumError(p, STRACCUM_NOMEM);
22970      }
22971    }
22972  }
22973  return p->zText;
22974}
22975
22976/*
22977** Reset an StrAccum string.  Reclaim all malloced memory.
22978*/
22979SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
22980  if( p->zText!=p->zBase ){
22981    sqlite3DbFree(p->db, p->zText);
22982  }
22983  p->zText = 0;
22984}
22985
22986/*
22987** Initialize a string accumulator.
22988**
22989** p:     The accumulator to be initialized.
22990** db:    Pointer to a database connection.  May be NULL.  Lookaside
22991**        memory is used if not NULL. db->mallocFailed is set appropriately
22992**        when not NULL.
22993** zBase: An initial buffer.  May be NULL in which case the initial buffer
22994**        is malloced.
22995** n:     Size of zBase in bytes.  If total space requirements never exceed
22996**        n then no memory allocations ever occur.
22997** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
22998**        allocations will ever occur.
22999*/
23000SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
23001  p->zText = p->zBase = zBase;
23002  p->db = db;
23003  p->nChar = 0;
23004  p->nAlloc = n;
23005  p->mxAlloc = mx;
23006  p->accError = 0;
23007}
23008
23009/*
23010** Print into memory obtained from sqliteMalloc().  Use the internal
23011** %-conversion extensions.
23012*/
23013SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
23014  char *z;
23015  char zBase[SQLITE_PRINT_BUF_SIZE];
23016  StrAccum acc;
23017  assert( db!=0 );
23018  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
23019                      db->aLimit[SQLITE_LIMIT_LENGTH]);
23020  sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
23021  z = sqlite3StrAccumFinish(&acc);
23022  if( acc.accError==STRACCUM_NOMEM ){
23023    db->mallocFailed = 1;
23024  }
23025  return z;
23026}
23027
23028/*
23029** Print into memory obtained from sqliteMalloc().  Use the internal
23030** %-conversion extensions.
23031*/
23032SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
23033  va_list ap;
23034  char *z;
23035  va_start(ap, zFormat);
23036  z = sqlite3VMPrintf(db, zFormat, ap);
23037  va_end(ap);
23038  return z;
23039}
23040
23041/*
23042** Print into memory obtained from sqlite3_malloc().  Omit the internal
23043** %-conversion extensions.
23044*/
23045SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
23046  char *z;
23047  char zBase[SQLITE_PRINT_BUF_SIZE];
23048  StrAccum acc;
23049
23050#ifdef SQLITE_ENABLE_API_ARMOR
23051  if( zFormat==0 ){
23052    (void)SQLITE_MISUSE_BKPT;
23053    return 0;
23054  }
23055#endif
23056#ifndef SQLITE_OMIT_AUTOINIT
23057  if( sqlite3_initialize() ) return 0;
23058#endif
23059  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
23060  sqlite3VXPrintf(&acc, 0, zFormat, ap);
23061  z = sqlite3StrAccumFinish(&acc);
23062  return z;
23063}
23064
23065/*
23066** Print into memory obtained from sqlite3_malloc()().  Omit the internal
23067** %-conversion extensions.
23068*/
23069SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
23070  va_list ap;
23071  char *z;
23072#ifndef SQLITE_OMIT_AUTOINIT
23073  if( sqlite3_initialize() ) return 0;
23074#endif
23075  va_start(ap, zFormat);
23076  z = sqlite3_vmprintf(zFormat, ap);
23077  va_end(ap);
23078  return z;
23079}
23080
23081/*
23082** sqlite3_snprintf() works like snprintf() except that it ignores the
23083** current locale settings.  This is important for SQLite because we
23084** are not able to use a "," as the decimal point in place of "." as
23085** specified by some locales.
23086**
23087** Oops:  The first two arguments of sqlite3_snprintf() are backwards
23088** from the snprintf() standard.  Unfortunately, it is too late to change
23089** this without breaking compatibility, so we just have to live with the
23090** mistake.
23091**
23092** sqlite3_vsnprintf() is the varargs version.
23093*/
23094SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
23095  StrAccum acc;
23096  if( n<=0 ) return zBuf;
23097#ifdef SQLITE_ENABLE_API_ARMOR
23098  if( zBuf==0 || zFormat==0 ) {
23099    (void)SQLITE_MISUSE_BKPT;
23100    if( zBuf ) zBuf[0] = 0;
23101    return zBuf;
23102  }
23103#endif
23104  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
23105  sqlite3VXPrintf(&acc, 0, zFormat, ap);
23106  return sqlite3StrAccumFinish(&acc);
23107}
23108SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
23109  char *z;
23110  va_list ap;
23111  va_start(ap,zFormat);
23112  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
23113  va_end(ap);
23114  return z;
23115}
23116
23117/*
23118** This is the routine that actually formats the sqlite3_log() message.
23119** We house it in a separate routine from sqlite3_log() to avoid using
23120** stack space on small-stack systems when logging is disabled.
23121**
23122** sqlite3_log() must render into a static buffer.  It cannot dynamically
23123** allocate memory because it might be called while the memory allocator
23124** mutex is held.
23125**
23126** sqlite3VXPrintf() might ask for *temporary* memory allocations for
23127** certain format characters (%q) or for very large precisions or widths.
23128** Care must be taken that any sqlite3_log() calls that occur while the
23129** memory mutex is held do not use these mechanisms.
23130*/
23131static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
23132  StrAccum acc;                          /* String accumulator */
23133  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
23134
23135  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
23136  sqlite3VXPrintf(&acc, 0, zFormat, ap);
23137  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
23138                           sqlite3StrAccumFinish(&acc));
23139}
23140
23141/*
23142** Format and write a message to the log if logging is enabled.
23143*/
23144SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
23145  va_list ap;                             /* Vararg list */
23146  if( sqlite3GlobalConfig.xLog ){
23147    va_start(ap, zFormat);
23148    renderLogMsg(iErrCode, zFormat, ap);
23149    va_end(ap);
23150  }
23151}
23152
23153#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
23154/*
23155** A version of printf() that understands %lld.  Used for debugging.
23156** The printf() built into some versions of windows does not understand %lld
23157** and segfaults if you give it a long long int.
23158*/
23159SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
23160  va_list ap;
23161  StrAccum acc;
23162  char zBuf[500];
23163  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
23164  va_start(ap,zFormat);
23165  sqlite3VXPrintf(&acc, 0, zFormat, ap);
23166  va_end(ap);
23167  sqlite3StrAccumFinish(&acc);
23168  fprintf(stdout,"%s", zBuf);
23169  fflush(stdout);
23170}
23171#endif
23172
23173
23174/*
23175** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
23176** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
23177*/
23178SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
23179  va_list ap;
23180  va_start(ap,zFormat);
23181  sqlite3VXPrintf(p, bFlags, zFormat, ap);
23182  va_end(ap);
23183}
23184
23185/************** End of printf.c **********************************************/
23186/************** Begin file treeview.c ****************************************/
23187/*
23188** 2015-06-08
23189**
23190** The author disclaims copyright to this source code.  In place of
23191** a legal notice, here is a blessing:
23192**
23193**    May you do good and not evil.
23194**    May you find forgiveness for yourself and forgive others.
23195**    May you share freely, never taking more than you give.
23196**
23197*************************************************************************
23198**
23199** This file contains C code to implement the TreeView debugging routines.
23200** These routines print a parse tree to standard output for debugging and
23201** analysis.
23202**
23203** The interfaces in this file is only available when compiling
23204** with SQLITE_DEBUG.
23205*/
23206/* #include "sqliteInt.h" */
23207#ifdef SQLITE_DEBUG
23208
23209/*
23210** Add a new subitem to the tree.  The moreToFollow flag indicates that this
23211** is not the last item in the tree.
23212*/
23213static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
23214  if( p==0 ){
23215    p = sqlite3_malloc64( sizeof(*p) );
23216    if( p==0 ) return 0;
23217    memset(p, 0, sizeof(*p));
23218  }else{
23219    p->iLevel++;
23220  }
23221  assert( moreToFollow==0 || moreToFollow==1 );
23222  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
23223  return p;
23224}
23225
23226/*
23227** Finished with one layer of the tree
23228*/
23229static void sqlite3TreeViewPop(TreeView *p){
23230  if( p==0 ) return;
23231  p->iLevel--;
23232  if( p->iLevel<0 ) sqlite3_free(p);
23233}
23234
23235/*
23236** Generate a single line of output for the tree, with a prefix that contains
23237** all the appropriate tree lines
23238*/
23239static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
23240  va_list ap;
23241  int i;
23242  StrAccum acc;
23243  char zBuf[500];
23244  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
23245  if( p ){
23246    for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
23247      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
23248    }
23249    sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
23250  }
23251  va_start(ap, zFormat);
23252  sqlite3VXPrintf(&acc, 0, zFormat, ap);
23253  va_end(ap);
23254  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
23255  sqlite3StrAccumFinish(&acc);
23256  fprintf(stdout,"%s", zBuf);
23257  fflush(stdout);
23258}
23259
23260/*
23261** Shorthand for starting a new tree item that consists of a single label
23262*/
23263static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
23264  p = sqlite3TreeViewPush(p, moreFollows);
23265  sqlite3TreeViewLine(p, "%s", zLabel);
23266}
23267
23268
23269/*
23270** Generate a human-readable description of a the Select object.
23271*/
23272SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
23273  int n = 0;
23274  int cnt = 0;
23275  pView = sqlite3TreeViewPush(pView, moreToFollow);
23276  do{
23277    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x",
23278      ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
23279      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags
23280    );
23281    if( cnt++ ) sqlite3TreeViewPop(pView);
23282    if( p->pPrior ){
23283      n = 1000;
23284    }else{
23285      n = 0;
23286      if( p->pSrc && p->pSrc->nSrc ) n++;
23287      if( p->pWhere ) n++;
23288      if( p->pGroupBy ) n++;
23289      if( p->pHaving ) n++;
23290      if( p->pOrderBy ) n++;
23291      if( p->pLimit ) n++;
23292      if( p->pOffset ) n++;
23293    }
23294    sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
23295    if( p->pSrc && p->pSrc->nSrc ){
23296      int i;
23297      pView = sqlite3TreeViewPush(pView, (n--)>0);
23298      sqlite3TreeViewLine(pView, "FROM");
23299      for(i=0; i<p->pSrc->nSrc; i++){
23300        struct SrcList_item *pItem = &p->pSrc->a[i];
23301        StrAccum x;
23302        char zLine[100];
23303        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
23304        sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
23305        if( pItem->zDatabase ){
23306          sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
23307        }else if( pItem->zName ){
23308          sqlite3XPrintf(&x, 0, " %s", pItem->zName);
23309        }
23310        if( pItem->pTab ){
23311          sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
23312        }
23313        if( pItem->zAlias ){
23314          sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
23315        }
23316        if( pItem->fg.jointype & JT_LEFT ){
23317          sqlite3XPrintf(&x, 0, " LEFT-JOIN");
23318        }
23319        sqlite3StrAccumFinish(&x);
23320        sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
23321        if( pItem->pSelect ){
23322          sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
23323        }
23324        if( pItem->fg.isTabFunc ){
23325          sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
23326        }
23327        sqlite3TreeViewPop(pView);
23328      }
23329      sqlite3TreeViewPop(pView);
23330    }
23331    if( p->pWhere ){
23332      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
23333      sqlite3TreeViewExpr(pView, p->pWhere, 0);
23334      sqlite3TreeViewPop(pView);
23335    }
23336    if( p->pGroupBy ){
23337      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
23338    }
23339    if( p->pHaving ){
23340      sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
23341      sqlite3TreeViewExpr(pView, p->pHaving, 0);
23342      sqlite3TreeViewPop(pView);
23343    }
23344    if( p->pOrderBy ){
23345      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
23346    }
23347    if( p->pLimit ){
23348      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
23349      sqlite3TreeViewExpr(pView, p->pLimit, 0);
23350      sqlite3TreeViewPop(pView);
23351    }
23352    if( p->pOffset ){
23353      sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
23354      sqlite3TreeViewExpr(pView, p->pOffset, 0);
23355      sqlite3TreeViewPop(pView);
23356    }
23357    if( p->pPrior ){
23358      const char *zOp = "UNION";
23359      switch( p->op ){
23360        case TK_ALL:         zOp = "UNION ALL";  break;
23361        case TK_INTERSECT:   zOp = "INTERSECT";  break;
23362        case TK_EXCEPT:      zOp = "EXCEPT";     break;
23363      }
23364      sqlite3TreeViewItem(pView, zOp, 1);
23365    }
23366    p = p->pPrior;
23367  }while( p!=0 );
23368  sqlite3TreeViewPop(pView);
23369}
23370
23371/*
23372** Generate a human-readable explanation of an expression tree.
23373*/
23374SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
23375  const char *zBinOp = 0;   /* Binary operator */
23376  const char *zUniOp = 0;   /* Unary operator */
23377  char zFlgs[30];
23378  pView = sqlite3TreeViewPush(pView, moreToFollow);
23379  if( pExpr==0 ){
23380    sqlite3TreeViewLine(pView, "nil");
23381    sqlite3TreeViewPop(pView);
23382    return;
23383  }
23384  if( pExpr->flags ){
23385    sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
23386  }else{
23387    zFlgs[0] = 0;
23388  }
23389  switch( pExpr->op ){
23390    case TK_AGG_COLUMN: {
23391      sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
23392            pExpr->iTable, pExpr->iColumn, zFlgs);
23393      break;
23394    }
23395    case TK_COLUMN: {
23396      if( pExpr->iTable<0 ){
23397        /* This only happens when coding check constraints */
23398        sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
23399      }else{
23400        sqlite3TreeViewLine(pView, "{%d:%d}%s",
23401                             pExpr->iTable, pExpr->iColumn, zFlgs);
23402      }
23403      break;
23404    }
23405    case TK_INTEGER: {
23406      if( pExpr->flags & EP_IntValue ){
23407        sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
23408      }else{
23409        sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
23410      }
23411      break;
23412    }
23413#ifndef SQLITE_OMIT_FLOATING_POINT
23414    case TK_FLOAT: {
23415      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
23416      break;
23417    }
23418#endif
23419    case TK_STRING: {
23420      sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
23421      break;
23422    }
23423    case TK_NULL: {
23424      sqlite3TreeViewLine(pView,"NULL");
23425      break;
23426    }
23427#ifndef SQLITE_OMIT_BLOB_LITERAL
23428    case TK_BLOB: {
23429      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
23430      break;
23431    }
23432#endif
23433    case TK_VARIABLE: {
23434      sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
23435                          pExpr->u.zToken, pExpr->iColumn);
23436      break;
23437    }
23438    case TK_REGISTER: {
23439      sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
23440      break;
23441    }
23442    case TK_ID: {
23443      sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
23444      break;
23445    }
23446#ifndef SQLITE_OMIT_CAST
23447    case TK_CAST: {
23448      /* Expressions of the form:   CAST(pLeft AS token) */
23449      sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
23450      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
23451      break;
23452    }
23453#endif /* SQLITE_OMIT_CAST */
23454    case TK_LT:      zBinOp = "LT";     break;
23455    case TK_LE:      zBinOp = "LE";     break;
23456    case TK_GT:      zBinOp = "GT";     break;
23457    case TK_GE:      zBinOp = "GE";     break;
23458    case TK_NE:      zBinOp = "NE";     break;
23459    case TK_EQ:      zBinOp = "EQ";     break;
23460    case TK_IS:      zBinOp = "IS";     break;
23461    case TK_ISNOT:   zBinOp = "ISNOT";  break;
23462    case TK_AND:     zBinOp = "AND";    break;
23463    case TK_OR:      zBinOp = "OR";     break;
23464    case TK_PLUS:    zBinOp = "ADD";    break;
23465    case TK_STAR:    zBinOp = "MUL";    break;
23466    case TK_MINUS:   zBinOp = "SUB";    break;
23467    case TK_REM:     zBinOp = "REM";    break;
23468    case TK_BITAND:  zBinOp = "BITAND"; break;
23469    case TK_BITOR:   zBinOp = "BITOR";  break;
23470    case TK_SLASH:   zBinOp = "DIV";    break;
23471    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
23472    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
23473    case TK_CONCAT:  zBinOp = "CONCAT"; break;
23474    case TK_DOT:     zBinOp = "DOT";    break;
23475
23476    case TK_UMINUS:  zUniOp = "UMINUS"; break;
23477    case TK_UPLUS:   zUniOp = "UPLUS";  break;
23478    case TK_BITNOT:  zUniOp = "BITNOT"; break;
23479    case TK_NOT:     zUniOp = "NOT";    break;
23480    case TK_ISNULL:  zUniOp = "ISNULL"; break;
23481    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
23482
23483    case TK_COLLATE: {
23484      sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
23485      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
23486      break;
23487    }
23488
23489    case TK_AGG_FUNCTION:
23490    case TK_FUNCTION: {
23491      ExprList *pFarg;       /* List of function arguments */
23492      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
23493        pFarg = 0;
23494      }else{
23495        pFarg = pExpr->x.pList;
23496      }
23497      if( pExpr->op==TK_AGG_FUNCTION ){
23498        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
23499                             pExpr->op2, pExpr->u.zToken);
23500      }else{
23501        sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
23502      }
23503      if( pFarg ){
23504        sqlite3TreeViewExprList(pView, pFarg, 0, 0);
23505      }
23506      break;
23507    }
23508#ifndef SQLITE_OMIT_SUBQUERY
23509    case TK_EXISTS: {
23510      sqlite3TreeViewLine(pView, "EXISTS-expr");
23511      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
23512      break;
23513    }
23514    case TK_SELECT: {
23515      sqlite3TreeViewLine(pView, "SELECT-expr");
23516      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
23517      break;
23518    }
23519    case TK_IN: {
23520      sqlite3TreeViewLine(pView, "IN");
23521      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
23522      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
23523        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
23524      }else{
23525        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
23526      }
23527      break;
23528    }
23529#endif /* SQLITE_OMIT_SUBQUERY */
23530
23531    /*
23532    **    x BETWEEN y AND z
23533    **
23534    ** This is equivalent to
23535    **
23536    **    x>=y AND x<=z
23537    **
23538    ** X is stored in pExpr->pLeft.
23539    ** Y is stored in pExpr->pList->a[0].pExpr.
23540    ** Z is stored in pExpr->pList->a[1].pExpr.
23541    */
23542    case TK_BETWEEN: {
23543      Expr *pX = pExpr->pLeft;
23544      Expr *pY = pExpr->x.pList->a[0].pExpr;
23545      Expr *pZ = pExpr->x.pList->a[1].pExpr;
23546      sqlite3TreeViewLine(pView, "BETWEEN");
23547      sqlite3TreeViewExpr(pView, pX, 1);
23548      sqlite3TreeViewExpr(pView, pY, 1);
23549      sqlite3TreeViewExpr(pView, pZ, 0);
23550      break;
23551    }
23552    case TK_TRIGGER: {
23553      /* If the opcode is TK_TRIGGER, then the expression is a reference
23554      ** to a column in the new.* or old.* pseudo-tables available to
23555      ** trigger programs. In this case Expr.iTable is set to 1 for the
23556      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
23557      ** is set to the column of the pseudo-table to read, or to -1 to
23558      ** read the rowid field.
23559      */
23560      sqlite3TreeViewLine(pView, "%s(%d)",
23561          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
23562      break;
23563    }
23564    case TK_CASE: {
23565      sqlite3TreeViewLine(pView, "CASE");
23566      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
23567      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
23568      break;
23569    }
23570#ifndef SQLITE_OMIT_TRIGGER
23571    case TK_RAISE: {
23572      const char *zType = "unk";
23573      switch( pExpr->affinity ){
23574        case OE_Rollback:   zType = "rollback";  break;
23575        case OE_Abort:      zType = "abort";     break;
23576        case OE_Fail:       zType = "fail";      break;
23577        case OE_Ignore:     zType = "ignore";    break;
23578      }
23579      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
23580      break;
23581    }
23582#endif
23583    default: {
23584      sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
23585      break;
23586    }
23587  }
23588  if( zBinOp ){
23589    sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
23590    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
23591    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
23592  }else if( zUniOp ){
23593    sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
23594    sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
23595  }
23596  sqlite3TreeViewPop(pView);
23597}
23598
23599/*
23600** Generate a human-readable explanation of an expression list.
23601*/
23602SQLITE_PRIVATE void sqlite3TreeViewExprList(
23603  TreeView *pView,
23604  const ExprList *pList,
23605  u8 moreToFollow,
23606  const char *zLabel
23607){
23608  int i;
23609  pView = sqlite3TreeViewPush(pView, moreToFollow);
23610  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
23611  if( pList==0 ){
23612    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
23613  }else{
23614    sqlite3TreeViewLine(pView, "%s", zLabel);
23615    for(i=0; i<pList->nExpr; i++){
23616      int j = pList->a[i].u.x.iOrderByCol;
23617      if( j ){
23618        sqlite3TreeViewPush(pView, 0);
23619        sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
23620      }
23621      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
23622      if( j ) sqlite3TreeViewPop(pView);
23623    }
23624  }
23625  sqlite3TreeViewPop(pView);
23626}
23627
23628#endif /* SQLITE_DEBUG */
23629
23630/************** End of treeview.c ********************************************/
23631/************** Begin file random.c ******************************************/
23632/*
23633** 2001 September 15
23634**
23635** The author disclaims copyright to this source code.  In place of
23636** a legal notice, here is a blessing:
23637**
23638**    May you do good and not evil.
23639**    May you find forgiveness for yourself and forgive others.
23640**    May you share freely, never taking more than you give.
23641**
23642*************************************************************************
23643** This file contains code to implement a pseudo-random number
23644** generator (PRNG) for SQLite.
23645**
23646** Random numbers are used by some of the database backends in order
23647** to generate random integer keys for tables or random filenames.
23648*/
23649/* #include "sqliteInt.h" */
23650
23651
23652/* All threads share a single random number generator.
23653** This structure is the current state of the generator.
23654*/
23655static SQLITE_WSD struct sqlite3PrngType {
23656  unsigned char isInit;          /* True if initialized */
23657  unsigned char i, j;            /* State variables */
23658  unsigned char s[256];          /* State variables */
23659} sqlite3Prng;
23660
23661/*
23662** Return N random bytes.
23663*/
23664SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
23665  unsigned char t;
23666  unsigned char *zBuf = pBuf;
23667
23668  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
23669  ** state vector.  If writable static data is unsupported on the target,
23670  ** we have to locate the state vector at run-time.  In the more common
23671  ** case where writable static data is supported, wsdPrng can refer directly
23672  ** to the "sqlite3Prng" state vector declared above.
23673  */
23674#ifdef SQLITE_OMIT_WSD
23675  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
23676# define wsdPrng p[0]
23677#else
23678# define wsdPrng sqlite3Prng
23679#endif
23680
23681#if SQLITE_THREADSAFE
23682  sqlite3_mutex *mutex;
23683#endif
23684
23685#ifndef SQLITE_OMIT_AUTOINIT
23686  if( sqlite3_initialize() ) return;
23687#endif
23688
23689#if SQLITE_THREADSAFE
23690  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
23691#endif
23692
23693  sqlite3_mutex_enter(mutex);
23694  if( N<=0 || pBuf==0 ){
23695    wsdPrng.isInit = 0;
23696    sqlite3_mutex_leave(mutex);
23697    return;
23698  }
23699
23700  /* Initialize the state of the random number generator once,
23701  ** the first time this routine is called.  The seed value does
23702  ** not need to contain a lot of randomness since we are not
23703  ** trying to do secure encryption or anything like that...
23704  **
23705  ** Nothing in this file or anywhere else in SQLite does any kind of
23706  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
23707  ** number generator) not as an encryption device.
23708  */
23709  if( !wsdPrng.isInit ){
23710    int i;
23711    char k[256];
23712    wsdPrng.j = 0;
23713    wsdPrng.i = 0;
23714    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
23715    for(i=0; i<256; i++){
23716      wsdPrng.s[i] = (u8)i;
23717    }
23718    for(i=0; i<256; i++){
23719      wsdPrng.j += wsdPrng.s[i] + k[i];
23720      t = wsdPrng.s[wsdPrng.j];
23721      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
23722      wsdPrng.s[i] = t;
23723    }
23724    wsdPrng.isInit = 1;
23725  }
23726
23727  assert( N>0 );
23728  do{
23729    wsdPrng.i++;
23730    t = wsdPrng.s[wsdPrng.i];
23731    wsdPrng.j += t;
23732    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
23733    wsdPrng.s[wsdPrng.j] = t;
23734    t += wsdPrng.s[wsdPrng.i];
23735    *(zBuf++) = wsdPrng.s[t];
23736  }while( --N );
23737  sqlite3_mutex_leave(mutex);
23738}
23739
23740#ifndef SQLITE_OMIT_BUILTIN_TEST
23741/*
23742** For testing purposes, we sometimes want to preserve the state of
23743** PRNG and restore the PRNG to its saved state at a later time, or
23744** to reset the PRNG to its initial state.  These routines accomplish
23745** those tasks.
23746**
23747** The sqlite3_test_control() interface calls these routines to
23748** control the PRNG.
23749*/
23750static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
23751SQLITE_PRIVATE void sqlite3PrngSaveState(void){
23752  memcpy(
23753    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
23754    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
23755    sizeof(sqlite3Prng)
23756  );
23757}
23758SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
23759  memcpy(
23760    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
23761    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
23762    sizeof(sqlite3Prng)
23763  );
23764}
23765#endif /* SQLITE_OMIT_BUILTIN_TEST */
23766
23767/************** End of random.c **********************************************/
23768/************** Begin file threads.c *****************************************/
23769/*
23770** 2012 July 21
23771**
23772** The author disclaims copyright to this source code.  In place of
23773** a legal notice, here is a blessing:
23774**
23775**    May you do good and not evil.
23776**    May you find forgiveness for yourself and forgive others.
23777**    May you share freely, never taking more than you give.
23778**
23779******************************************************************************
23780**
23781** This file presents a simple cross-platform threading interface for
23782** use internally by SQLite.
23783**
23784** A "thread" can be created using sqlite3ThreadCreate().  This thread
23785** runs independently of its creator until it is joined using
23786** sqlite3ThreadJoin(), at which point it terminates.
23787**
23788** Threads do not have to be real.  It could be that the work of the
23789** "thread" is done by the main thread at either the sqlite3ThreadCreate()
23790** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
23791** single threaded systems.  Nothing in SQLite requires multiple threads.
23792** This interface exists so that applications that want to take advantage
23793** of multiple cores can do so, while also allowing applications to stay
23794** single-threaded if desired.
23795*/
23796/* #include "sqliteInt.h" */
23797#if SQLITE_OS_WIN
23798/* #  include "os_win.h" */
23799#endif
23800
23801#if SQLITE_MAX_WORKER_THREADS>0
23802
23803/********************************* Unix Pthreads ****************************/
23804#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
23805
23806#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
23807/* #include <pthread.h> */
23808
23809/* A running thread */
23810struct SQLiteThread {
23811  pthread_t tid;                 /* Thread ID */
23812  int done;                      /* Set to true when thread finishes */
23813  void *pOut;                    /* Result returned by the thread */
23814  void *(*xTask)(void*);         /* The thread routine */
23815  void *pIn;                     /* Argument to the thread */
23816};
23817
23818/* Create a new thread */
23819SQLITE_PRIVATE int sqlite3ThreadCreate(
23820  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
23821  void *(*xTask)(void*),    /* Routine to run in a separate thread */
23822  void *pIn                 /* Argument passed into xTask() */
23823){
23824  SQLiteThread *p;
23825  int rc;
23826
23827  assert( ppThread!=0 );
23828  assert( xTask!=0 );
23829  /* This routine is never used in single-threaded mode */
23830  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
23831
23832  *ppThread = 0;
23833  p = sqlite3Malloc(sizeof(*p));
23834  if( p==0 ) return SQLITE_NOMEM;
23835  memset(p, 0, sizeof(*p));
23836  p->xTask = xTask;
23837  p->pIn = pIn;
23838  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
23839  ** function that returns SQLITE_ERROR when passed the argument 200, that
23840  ** forces worker threads to run sequentially and deterministically
23841  ** for testing purposes. */
23842  if( sqlite3FaultSim(200) ){
23843    rc = 1;
23844  }else{
23845    rc = pthread_create(&p->tid, 0, xTask, pIn);
23846  }
23847  if( rc ){
23848    p->done = 1;
23849    p->pOut = xTask(pIn);
23850  }
23851  *ppThread = p;
23852  return SQLITE_OK;
23853}
23854
23855/* Get the results of the thread */
23856SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
23857  int rc;
23858
23859  assert( ppOut!=0 );
23860  if( NEVER(p==0) ) return SQLITE_NOMEM;
23861  if( p->done ){
23862    *ppOut = p->pOut;
23863    rc = SQLITE_OK;
23864  }else{
23865    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
23866  }
23867  sqlite3_free(p);
23868  return rc;
23869}
23870
23871#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
23872/******************************** End Unix Pthreads *************************/
23873
23874
23875/********************************* Win32 Threads ****************************/
23876#if SQLITE_OS_WIN_THREADS
23877
23878#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
23879#include <process.h>
23880
23881/* A running thread */
23882struct SQLiteThread {
23883  void *tid;               /* The thread handle */
23884  unsigned id;             /* The thread identifier */
23885  void *(*xTask)(void*);   /* The routine to run as a thread */
23886  void *pIn;               /* Argument to xTask */
23887  void *pResult;           /* Result of xTask */
23888};
23889
23890/* Thread procedure Win32 compatibility shim */
23891static unsigned __stdcall sqlite3ThreadProc(
23892  void *pArg  /* IN: Pointer to the SQLiteThread structure */
23893){
23894  SQLiteThread *p = (SQLiteThread *)pArg;
23895
23896  assert( p!=0 );
23897#if 0
23898  /*
23899  ** This assert appears to trigger spuriously on certain
23900  ** versions of Windows, possibly due to _beginthreadex()
23901  ** and/or CreateThread() not fully setting their thread
23902  ** ID parameter before starting the thread.
23903  */
23904  assert( p->id==GetCurrentThreadId() );
23905#endif
23906  assert( p->xTask!=0 );
23907  p->pResult = p->xTask(p->pIn);
23908
23909  _endthreadex(0);
23910  return 0; /* NOT REACHED */
23911}
23912
23913/* Create a new thread */
23914SQLITE_PRIVATE int sqlite3ThreadCreate(
23915  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
23916  void *(*xTask)(void*),    /* Routine to run in a separate thread */
23917  void *pIn                 /* Argument passed into xTask() */
23918){
23919  SQLiteThread *p;
23920
23921  assert( ppThread!=0 );
23922  assert( xTask!=0 );
23923  *ppThread = 0;
23924  p = sqlite3Malloc(sizeof(*p));
23925  if( p==0 ) return SQLITE_NOMEM;
23926  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
23927  ** function that returns SQLITE_ERROR when passed the argument 200, that
23928  ** forces worker threads to run sequentially and deterministically
23929  ** (via the sqlite3FaultSim() term of the conditional) for testing
23930  ** purposes. */
23931  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
23932    memset(p, 0, sizeof(*p));
23933  }else{
23934    p->xTask = xTask;
23935    p->pIn = pIn;
23936    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
23937    if( p->tid==0 ){
23938      memset(p, 0, sizeof(*p));
23939    }
23940  }
23941  if( p->xTask==0 ){
23942    p->id = GetCurrentThreadId();
23943    p->pResult = xTask(pIn);
23944  }
23945  *ppThread = p;
23946  return SQLITE_OK;
23947}
23948
23949SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
23950
23951/* Get the results of the thread */
23952SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
23953  DWORD rc;
23954  BOOL bRc;
23955
23956  assert( ppOut!=0 );
23957  if( NEVER(p==0) ) return SQLITE_NOMEM;
23958  if( p->xTask==0 ){
23959    /* assert( p->id==GetCurrentThreadId() ); */
23960    rc = WAIT_OBJECT_0;
23961    assert( p->tid==0 );
23962  }else{
23963    assert( p->id!=0 && p->id!=GetCurrentThreadId() );
23964    rc = sqlite3Win32Wait((HANDLE)p->tid);
23965    assert( rc!=WAIT_IO_COMPLETION );
23966    bRc = CloseHandle((HANDLE)p->tid);
23967    assert( bRc );
23968  }
23969  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
23970  sqlite3_free(p);
23971  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
23972}
23973
23974#endif /* SQLITE_OS_WIN_THREADS */
23975/******************************** End Win32 Threads *************************/
23976
23977
23978/********************************* Single-Threaded **************************/
23979#ifndef SQLITE_THREADS_IMPLEMENTED
23980/*
23981** This implementation does not actually create a new thread.  It does the
23982** work of the thread in the main thread, when either the thread is created
23983** or when it is joined
23984*/
23985
23986/* A running thread */
23987struct SQLiteThread {
23988  void *(*xTask)(void*);   /* The routine to run as a thread */
23989  void *pIn;               /* Argument to xTask */
23990  void *pResult;           /* Result of xTask */
23991};
23992
23993/* Create a new thread */
23994SQLITE_PRIVATE int sqlite3ThreadCreate(
23995  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
23996  void *(*xTask)(void*),    /* Routine to run in a separate thread */
23997  void *pIn                 /* Argument passed into xTask() */
23998){
23999  SQLiteThread *p;
24000
24001  assert( ppThread!=0 );
24002  assert( xTask!=0 );
24003  *ppThread = 0;
24004  p = sqlite3Malloc(sizeof(*p));
24005  if( p==0 ) return SQLITE_NOMEM;
24006  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
24007    p->xTask = xTask;
24008    p->pIn = pIn;
24009  }else{
24010    p->xTask = 0;
24011    p->pResult = xTask(pIn);
24012  }
24013  *ppThread = p;
24014  return SQLITE_OK;
24015}
24016
24017/* Get the results of the thread */
24018SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
24019
24020  assert( ppOut!=0 );
24021  if( NEVER(p==0) ) return SQLITE_NOMEM;
24022  if( p->xTask ){
24023    *ppOut = p->xTask(p->pIn);
24024  }else{
24025    *ppOut = p->pResult;
24026  }
24027  sqlite3_free(p);
24028
24029#if defined(SQLITE_TEST)
24030  {
24031    void *pTstAlloc = sqlite3Malloc(10);
24032    if (!pTstAlloc) return SQLITE_NOMEM;
24033    sqlite3_free(pTstAlloc);
24034  }
24035#endif
24036
24037  return SQLITE_OK;
24038}
24039
24040#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
24041/****************************** End Single-Threaded *************************/
24042#endif /* SQLITE_MAX_WORKER_THREADS>0 */
24043
24044/************** End of threads.c *********************************************/
24045/************** Begin file utf.c *********************************************/
24046/*
24047** 2004 April 13
24048**
24049** The author disclaims copyright to this source code.  In place of
24050** a legal notice, here is a blessing:
24051**
24052**    May you do good and not evil.
24053**    May you find forgiveness for yourself and forgive others.
24054**    May you share freely, never taking more than you give.
24055**
24056*************************************************************************
24057** This file contains routines used to translate between UTF-8,
24058** UTF-16, UTF-16BE, and UTF-16LE.
24059**
24060** Notes on UTF-8:
24061**
24062**   Byte-0    Byte-1    Byte-2    Byte-3    Value
24063**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
24064**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
24065**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
24066**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
24067**
24068**
24069** Notes on UTF-16:  (with wwww+1==uuuuu)
24070**
24071**      Word-0               Word-1          Value
24072**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
24073**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
24074**
24075**
24076** BOM or Byte Order Mark:
24077**     0xff 0xfe   little-endian utf-16 follows
24078**     0xfe 0xff   big-endian utf-16 follows
24079**
24080*/
24081/* #include "sqliteInt.h" */
24082/* #include <assert.h> */
24083/* #include "vdbeInt.h" */
24084
24085#ifndef SQLITE_AMALGAMATION
24086/*
24087** The following constant value is used by the SQLITE_BIGENDIAN and
24088** SQLITE_LITTLEENDIAN macros.
24089*/
24090SQLITE_PRIVATE const int sqlite3one = 1;
24091#endif /* SQLITE_AMALGAMATION */
24092
24093/*
24094** This lookup table is used to help decode the first byte of
24095** a multi-byte UTF8 character.
24096*/
24097static const unsigned char sqlite3Utf8Trans1[] = {
24098  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
24099  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
24100  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
24101  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
24102  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
24103  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
24104  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
24105  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
24106};
24107
24108
24109#define WRITE_UTF8(zOut, c) {                          \
24110  if( c<0x00080 ){                                     \
24111    *zOut++ = (u8)(c&0xFF);                            \
24112  }                                                    \
24113  else if( c<0x00800 ){                                \
24114    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
24115    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
24116  }                                                    \
24117  else if( c<0x10000 ){                                \
24118    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
24119    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
24120    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
24121  }else{                                               \
24122    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
24123    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
24124    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
24125    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
24126  }                                                    \
24127}
24128
24129#define WRITE_UTF16LE(zOut, c) {                                    \
24130  if( c<=0xFFFF ){                                                  \
24131    *zOut++ = (u8)(c&0x00FF);                                       \
24132    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
24133  }else{                                                            \
24134    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
24135    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
24136    *zOut++ = (u8)(c&0x00FF);                                       \
24137    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
24138  }                                                                 \
24139}
24140
24141#define WRITE_UTF16BE(zOut, c) {                                    \
24142  if( c<=0xFFFF ){                                                  \
24143    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
24144    *zOut++ = (u8)(c&0x00FF);                                       \
24145  }else{                                                            \
24146    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
24147    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
24148    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
24149    *zOut++ = (u8)(c&0x00FF);                                       \
24150  }                                                                 \
24151}
24152
24153#define READ_UTF16LE(zIn, TERM, c){                                   \
24154  c = (*zIn++);                                                       \
24155  c += ((*zIn++)<<8);                                                 \
24156  if( c>=0xD800 && c<0xE000 && TERM ){                                \
24157    int c2 = (*zIn++);                                                \
24158    c2 += ((*zIn++)<<8);                                              \
24159    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
24160  }                                                                   \
24161}
24162
24163#define READ_UTF16BE(zIn, TERM, c){                                   \
24164  c = ((*zIn++)<<8);                                                  \
24165  c += (*zIn++);                                                      \
24166  if( c>=0xD800 && c<0xE000 && TERM ){                                \
24167    int c2 = ((*zIn++)<<8);                                           \
24168    c2 += (*zIn++);                                                   \
24169    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
24170  }                                                                   \
24171}
24172
24173/*
24174** Translate a single UTF-8 character.  Return the unicode value.
24175**
24176** During translation, assume that the byte that zTerm points
24177** is a 0x00.
24178**
24179** Write a pointer to the next unread byte back into *pzNext.
24180**
24181** Notes On Invalid UTF-8:
24182**
24183**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
24184**     be encoded as a multi-byte character.  Any multi-byte character that
24185**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
24186**
24187**  *  This routine never allows a UTF16 surrogate value to be encoded.
24188**     If a multi-byte character attempts to encode a value between
24189**     0xd800 and 0xe000 then it is rendered as 0xfffd.
24190**
24191**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
24192**     byte of a character are interpreted as single-byte characters
24193**     and rendered as themselves even though they are technically
24194**     invalid characters.
24195**
24196**  *  This routine accepts over-length UTF8 encodings
24197**     for unicode values 0x80 and greater.  It does not change over-length
24198**     encodings to 0xfffd as some systems recommend.
24199*/
24200#define READ_UTF8(zIn, zTerm, c)                           \
24201  c = *(zIn++);                                            \
24202  if( c>=0xc0 ){                                           \
24203    c = sqlite3Utf8Trans1[c-0xc0];                         \
24204    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
24205      c = (c<<6) + (0x3f & *(zIn++));                      \
24206    }                                                      \
24207    if( c<0x80                                             \
24208        || (c&0xFFFFF800)==0xD800                          \
24209        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
24210  }
24211SQLITE_PRIVATE u32 sqlite3Utf8Read(
24212  const unsigned char **pz    /* Pointer to string from which to read char */
24213){
24214  unsigned int c;
24215
24216  /* Same as READ_UTF8() above but without the zTerm parameter.
24217  ** For this routine, we assume the UTF8 string is always zero-terminated.
24218  */
24219  c = *((*pz)++);
24220  if( c>=0xc0 ){
24221    c = sqlite3Utf8Trans1[c-0xc0];
24222    while( (*(*pz) & 0xc0)==0x80 ){
24223      c = (c<<6) + (0x3f & *((*pz)++));
24224    }
24225    if( c<0x80
24226        || (c&0xFFFFF800)==0xD800
24227        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
24228  }
24229  return c;
24230}
24231
24232
24233
24234
24235/*
24236** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
24237** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
24238*/
24239/* #define TRANSLATE_TRACE 1 */
24240
24241#ifndef SQLITE_OMIT_UTF16
24242/*
24243** This routine transforms the internal text encoding used by pMem to
24244** desiredEnc. It is an error if the string is already of the desired
24245** encoding, or if *pMem does not contain a string value.
24246*/
24247SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
24248  int len;                    /* Maximum length of output string in bytes */
24249  unsigned char *zOut;                  /* Output buffer */
24250  unsigned char *zIn;                   /* Input iterator */
24251  unsigned char *zTerm;                 /* End of input */
24252  unsigned char *z;                     /* Output iterator */
24253  unsigned int c;
24254
24255  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
24256  assert( pMem->flags&MEM_Str );
24257  assert( pMem->enc!=desiredEnc );
24258  assert( pMem->enc!=0 );
24259  assert( pMem->n>=0 );
24260
24261#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
24262  {
24263    char zBuf[100];
24264    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
24265    fprintf(stderr, "INPUT:  %s\n", zBuf);
24266  }
24267#endif
24268
24269  /* If the translation is between UTF-16 little and big endian, then
24270  ** all that is required is to swap the byte order. This case is handled
24271  ** differently from the others.
24272  */
24273  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
24274    u8 temp;
24275    int rc;
24276    rc = sqlite3VdbeMemMakeWriteable(pMem);
24277    if( rc!=SQLITE_OK ){
24278      assert( rc==SQLITE_NOMEM );
24279      return SQLITE_NOMEM;
24280    }
24281    zIn = (u8*)pMem->z;
24282    zTerm = &zIn[pMem->n&~1];
24283    while( zIn<zTerm ){
24284      temp = *zIn;
24285      *zIn = *(zIn+1);
24286      zIn++;
24287      *zIn++ = temp;
24288    }
24289    pMem->enc = desiredEnc;
24290    goto translate_out;
24291  }
24292
24293  /* Set len to the maximum number of bytes required in the output buffer. */
24294  if( desiredEnc==SQLITE_UTF8 ){
24295    /* When converting from UTF-16, the maximum growth results from
24296    ** translating a 2-byte character to a 4-byte UTF-8 character.
24297    ** A single byte is required for the output string
24298    ** nul-terminator.
24299    */
24300    pMem->n &= ~1;
24301    len = pMem->n * 2 + 1;
24302  }else{
24303    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
24304    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
24305    ** character. Two bytes are required in the output buffer for the
24306    ** nul-terminator.
24307    */
24308    len = pMem->n * 2 + 2;
24309  }
24310
24311  /* Set zIn to point at the start of the input buffer and zTerm to point 1
24312  ** byte past the end.
24313  **
24314  ** Variable zOut is set to point at the output buffer, space obtained
24315  ** from sqlite3_malloc().
24316  */
24317  zIn = (u8*)pMem->z;
24318  zTerm = &zIn[pMem->n];
24319  zOut = sqlite3DbMallocRaw(pMem->db, len);
24320  if( !zOut ){
24321    return SQLITE_NOMEM;
24322  }
24323  z = zOut;
24324
24325  if( pMem->enc==SQLITE_UTF8 ){
24326    if( desiredEnc==SQLITE_UTF16LE ){
24327      /* UTF-8 -> UTF-16 Little-endian */
24328      while( zIn<zTerm ){
24329        READ_UTF8(zIn, zTerm, c);
24330        WRITE_UTF16LE(z, c);
24331      }
24332    }else{
24333      assert( desiredEnc==SQLITE_UTF16BE );
24334      /* UTF-8 -> UTF-16 Big-endian */
24335      while( zIn<zTerm ){
24336        READ_UTF8(zIn, zTerm, c);
24337        WRITE_UTF16BE(z, c);
24338      }
24339    }
24340    pMem->n = (int)(z - zOut);
24341    *z++ = 0;
24342  }else{
24343    assert( desiredEnc==SQLITE_UTF8 );
24344    if( pMem->enc==SQLITE_UTF16LE ){
24345      /* UTF-16 Little-endian -> UTF-8 */
24346      while( zIn<zTerm ){
24347        READ_UTF16LE(zIn, zIn<zTerm, c);
24348        WRITE_UTF8(z, c);
24349      }
24350    }else{
24351      /* UTF-16 Big-endian -> UTF-8 */
24352      while( zIn<zTerm ){
24353        READ_UTF16BE(zIn, zIn<zTerm, c);
24354        WRITE_UTF8(z, c);
24355      }
24356    }
24357    pMem->n = (int)(z - zOut);
24358  }
24359  *z = 0;
24360  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
24361
24362  c = pMem->flags;
24363  sqlite3VdbeMemRelease(pMem);
24364  pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
24365  pMem->enc = desiredEnc;
24366  pMem->z = (char*)zOut;
24367  pMem->zMalloc = pMem->z;
24368  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
24369
24370translate_out:
24371#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
24372  {
24373    char zBuf[100];
24374    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
24375    fprintf(stderr, "OUTPUT: %s\n", zBuf);
24376  }
24377#endif
24378  return SQLITE_OK;
24379}
24380
24381/*
24382** This routine checks for a byte-order mark at the beginning of the
24383** UTF-16 string stored in *pMem. If one is present, it is removed and
24384** the encoding of the Mem adjusted. This routine does not do any
24385** byte-swapping, it just sets Mem.enc appropriately.
24386**
24387** The allocation (static, dynamic etc.) and encoding of the Mem may be
24388** changed by this function.
24389*/
24390SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
24391  int rc = SQLITE_OK;
24392  u8 bom = 0;
24393
24394  assert( pMem->n>=0 );
24395  if( pMem->n>1 ){
24396    u8 b1 = *(u8 *)pMem->z;
24397    u8 b2 = *(((u8 *)pMem->z) + 1);
24398    if( b1==0xFE && b2==0xFF ){
24399      bom = SQLITE_UTF16BE;
24400    }
24401    if( b1==0xFF && b2==0xFE ){
24402      bom = SQLITE_UTF16LE;
24403    }
24404  }
24405
24406  if( bom ){
24407    rc = sqlite3VdbeMemMakeWriteable(pMem);
24408    if( rc==SQLITE_OK ){
24409      pMem->n -= 2;
24410      memmove(pMem->z, &pMem->z[2], pMem->n);
24411      pMem->z[pMem->n] = '\0';
24412      pMem->z[pMem->n+1] = '\0';
24413      pMem->flags |= MEM_Term;
24414      pMem->enc = bom;
24415    }
24416  }
24417  return rc;
24418}
24419#endif /* SQLITE_OMIT_UTF16 */
24420
24421/*
24422** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
24423** return the number of unicode characters in pZ up to (but not including)
24424** the first 0x00 byte. If nByte is not less than zero, return the
24425** number of unicode characters in the first nByte of pZ (or up to
24426** the first 0x00, whichever comes first).
24427*/
24428SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
24429  int r = 0;
24430  const u8 *z = (const u8*)zIn;
24431  const u8 *zTerm;
24432  if( nByte>=0 ){
24433    zTerm = &z[nByte];
24434  }else{
24435    zTerm = (const u8*)(-1);
24436  }
24437  assert( z<=zTerm );
24438  while( *z!=0 && z<zTerm ){
24439    SQLITE_SKIP_UTF8(z);
24440    r++;
24441  }
24442  return r;
24443}
24444
24445/* This test function is not currently used by the automated test-suite.
24446** Hence it is only available in debug builds.
24447*/
24448#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24449/*
24450** Translate UTF-8 to UTF-8.
24451**
24452** This has the effect of making sure that the string is well-formed
24453** UTF-8.  Miscoded characters are removed.
24454**
24455** The translation is done in-place and aborted if the output
24456** overruns the input.
24457*/
24458SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
24459  unsigned char *zOut = zIn;
24460  unsigned char *zStart = zIn;
24461  u32 c;
24462
24463  while( zIn[0] && zOut<=zIn ){
24464    c = sqlite3Utf8Read((const u8**)&zIn);
24465    if( c!=0xfffd ){
24466      WRITE_UTF8(zOut, c);
24467    }
24468  }
24469  *zOut = 0;
24470  return (int)(zOut - zStart);
24471}
24472#endif
24473
24474#ifndef SQLITE_OMIT_UTF16
24475/*
24476** Convert a UTF-16 string in the native encoding into a UTF-8 string.
24477** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
24478** be freed by the calling function.
24479**
24480** NULL is returned if there is an allocation error.
24481*/
24482SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
24483  Mem m;
24484  memset(&m, 0, sizeof(m));
24485  m.db = db;
24486  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
24487  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
24488  if( db->mallocFailed ){
24489    sqlite3VdbeMemRelease(&m);
24490    m.z = 0;
24491  }
24492  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
24493  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
24494  assert( m.z || db->mallocFailed );
24495  return m.z;
24496}
24497
24498/*
24499** zIn is a UTF-16 encoded unicode string at least nChar characters long.
24500** Return the number of bytes in the first nChar unicode characters
24501** in pZ.  nChar must be non-negative.
24502*/
24503SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
24504  int c;
24505  unsigned char const *z = zIn;
24506  int n = 0;
24507
24508  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
24509    while( n<nChar ){
24510      READ_UTF16BE(z, 1, c);
24511      n++;
24512    }
24513  }else{
24514    while( n<nChar ){
24515      READ_UTF16LE(z, 1, c);
24516      n++;
24517    }
24518  }
24519  return (int)(z-(unsigned char const *)zIn);
24520}
24521
24522#if defined(SQLITE_TEST)
24523/*
24524** This routine is called from the TCL test function "translate_selftest".
24525** It checks that the primitives for serializing and deserializing
24526** characters in each encoding are inverses of each other.
24527*/
24528SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
24529  unsigned int i, t;
24530  unsigned char zBuf[20];
24531  unsigned char *z;
24532  int n;
24533  unsigned int c;
24534
24535  for(i=0; i<0x00110000; i++){
24536    z = zBuf;
24537    WRITE_UTF8(z, i);
24538    n = (int)(z-zBuf);
24539    assert( n>0 && n<=4 );
24540    z[0] = 0;
24541    z = zBuf;
24542    c = sqlite3Utf8Read((const u8**)&z);
24543    t = i;
24544    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
24545    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
24546    assert( c==t );
24547    assert( (z-zBuf)==n );
24548  }
24549  for(i=0; i<0x00110000; i++){
24550    if( i>=0xD800 && i<0xE000 ) continue;
24551    z = zBuf;
24552    WRITE_UTF16LE(z, i);
24553    n = (int)(z-zBuf);
24554    assert( n>0 && n<=4 );
24555    z[0] = 0;
24556    z = zBuf;
24557    READ_UTF16LE(z, 1, c);
24558    assert( c==i );
24559    assert( (z-zBuf)==n );
24560  }
24561  for(i=0; i<0x00110000; i++){
24562    if( i>=0xD800 && i<0xE000 ) continue;
24563    z = zBuf;
24564    WRITE_UTF16BE(z, i);
24565    n = (int)(z-zBuf);
24566    assert( n>0 && n<=4 );
24567    z[0] = 0;
24568    z = zBuf;
24569    READ_UTF16BE(z, 1, c);
24570    assert( c==i );
24571    assert( (z-zBuf)==n );
24572  }
24573}
24574#endif /* SQLITE_TEST */
24575#endif /* SQLITE_OMIT_UTF16 */
24576
24577/************** End of utf.c *************************************************/
24578/************** Begin file util.c ********************************************/
24579/*
24580** 2001 September 15
24581**
24582** The author disclaims copyright to this source code.  In place of
24583** a legal notice, here is a blessing:
24584**
24585**    May you do good and not evil.
24586**    May you find forgiveness for yourself and forgive others.
24587**    May you share freely, never taking more than you give.
24588**
24589*************************************************************************
24590** Utility functions used throughout sqlite.
24591**
24592** This file contains functions for allocating memory, comparing
24593** strings, and stuff like that.
24594**
24595*/
24596/* #include "sqliteInt.h" */
24597/* #include <stdarg.h> */
24598#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
24599# include <math.h>
24600#endif
24601
24602/*
24603** Routine needed to support the testcase() macro.
24604*/
24605#ifdef SQLITE_COVERAGE_TEST
24606SQLITE_PRIVATE void sqlite3Coverage(int x){
24607  static unsigned dummy = 0;
24608  dummy += (unsigned)x;
24609}
24610#endif
24611
24612/*
24613** Give a callback to the test harness that can be used to simulate faults
24614** in places where it is difficult or expensive to do so purely by means
24615** of inputs.
24616**
24617** The intent of the integer argument is to let the fault simulator know
24618** which of multiple sqlite3FaultSim() calls has been hit.
24619**
24620** Return whatever integer value the test callback returns, or return
24621** SQLITE_OK if no test callback is installed.
24622*/
24623#ifndef SQLITE_OMIT_BUILTIN_TEST
24624SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
24625  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
24626  return xCallback ? xCallback(iTest) : SQLITE_OK;
24627}
24628#endif
24629
24630#ifndef SQLITE_OMIT_FLOATING_POINT
24631/*
24632** Return true if the floating point value is Not a Number (NaN).
24633**
24634** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
24635** Otherwise, we have our own implementation that works on most systems.
24636*/
24637SQLITE_PRIVATE int sqlite3IsNaN(double x){
24638  int rc;   /* The value return */
24639#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
24640  /*
24641  ** Systems that support the isnan() library function should probably
24642  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
24643  ** found that many systems do not have a working isnan() function so
24644  ** this implementation is provided as an alternative.
24645  **
24646  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
24647  ** On the other hand, the use of -ffast-math comes with the following
24648  ** warning:
24649  **
24650  **      This option [-ffast-math] should never be turned on by any
24651  **      -O option since it can result in incorrect output for programs
24652  **      which depend on an exact implementation of IEEE or ISO
24653  **      rules/specifications for math functions.
24654  **
24655  ** Under MSVC, this NaN test may fail if compiled with a floating-
24656  ** point precision mode other than /fp:precise.  From the MSDN
24657  ** documentation:
24658  **
24659  **      The compiler [with /fp:precise] will properly handle comparisons
24660  **      involving NaN. For example, x != x evaluates to true if x is NaN
24661  **      ...
24662  */
24663#ifdef __FAST_MATH__
24664# error SQLite will not work correctly with the -ffast-math option of GCC.
24665#endif
24666  volatile double y = x;
24667  volatile double z = y;
24668  rc = (y!=z);
24669#else  /* if HAVE_ISNAN */
24670  rc = isnan(x);
24671#endif /* HAVE_ISNAN */
24672  testcase( rc );
24673  return rc;
24674}
24675#endif /* SQLITE_OMIT_FLOATING_POINT */
24676
24677/*
24678** Compute a string length that is limited to what can be stored in
24679** lower 30 bits of a 32-bit signed integer.
24680**
24681** The value returned will never be negative.  Nor will it ever be greater
24682** than the actual length of the string.  For very long strings (greater
24683** than 1GiB) the value returned might be less than the true string length.
24684*/
24685SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
24686  if( z==0 ) return 0;
24687  return 0x3fffffff & (int)strlen(z);
24688}
24689
24690/*
24691** Set the current error code to err_code and clear any prior error message.
24692*/
24693SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
24694  assert( db!=0 );
24695  db->errCode = err_code;
24696  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
24697}
24698
24699/*
24700** Set the most recent error code and error string for the sqlite
24701** handle "db". The error code is set to "err_code".
24702**
24703** If it is not NULL, string zFormat specifies the format of the
24704** error string in the style of the printf functions: The following
24705** format characters are allowed:
24706**
24707**      %s      Insert a string
24708**      %z      A string that should be freed after use
24709**      %d      Insert an integer
24710**      %T      Insert a token
24711**      %S      Insert the first element of a SrcList
24712**
24713** zFormat and any string tokens that follow it are assumed to be
24714** encoded in UTF-8.
24715**
24716** To clear the most recent error for sqlite handle "db", sqlite3Error
24717** should be called with err_code set to SQLITE_OK and zFormat set
24718** to NULL.
24719*/
24720SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
24721  assert( db!=0 );
24722  db->errCode = err_code;
24723  if( zFormat==0 ){
24724    sqlite3Error(db, err_code);
24725  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
24726    char *z;
24727    va_list ap;
24728    va_start(ap, zFormat);
24729    z = sqlite3VMPrintf(db, zFormat, ap);
24730    va_end(ap);
24731    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
24732  }
24733}
24734
24735/*
24736** Add an error message to pParse->zErrMsg and increment pParse->nErr.
24737** The following formatting characters are allowed:
24738**
24739**      %s      Insert a string
24740**      %z      A string that should be freed after use
24741**      %d      Insert an integer
24742**      %T      Insert a token
24743**      %S      Insert the first element of a SrcList
24744**
24745** This function should be used to report any error that occurs while
24746** compiling an SQL statement (i.e. within sqlite3_prepare()). The
24747** last thing the sqlite3_prepare() function does is copy the error
24748** stored by this function into the database handle using sqlite3Error().
24749** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
24750** during statement execution (sqlite3_step() etc.).
24751*/
24752SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
24753  char *zMsg;
24754  va_list ap;
24755  sqlite3 *db = pParse->db;
24756  va_start(ap, zFormat);
24757  zMsg = sqlite3VMPrintf(db, zFormat, ap);
24758  va_end(ap);
24759  if( db->suppressErr ){
24760    sqlite3DbFree(db, zMsg);
24761  }else{
24762    pParse->nErr++;
24763    sqlite3DbFree(db, pParse->zErrMsg);
24764    pParse->zErrMsg = zMsg;
24765    pParse->rc = SQLITE_ERROR;
24766  }
24767}
24768
24769/*
24770** Convert an SQL-style quoted string into a normal string by removing
24771** the quote characters.  The conversion is done in-place.  If the
24772** input does not begin with a quote character, then this routine
24773** is a no-op.
24774**
24775** The input string must be zero-terminated.  A new zero-terminator
24776** is added to the dequoted string.
24777**
24778** The return value is -1 if no dequoting occurs or the length of the
24779** dequoted string, exclusive of the zero terminator, if dequoting does
24780** occur.
24781**
24782** 2002-Feb-14: This routine is extended to remove MS-Access style
24783** brackets from around identifiers.  For example:  "[a-b-c]" becomes
24784** "a-b-c".
24785*/
24786SQLITE_PRIVATE int sqlite3Dequote(char *z){
24787  char quote;
24788  int i, j;
24789  if( z==0 ) return -1;
24790  quote = z[0];
24791  switch( quote ){
24792    case '\'':  break;
24793    case '"':   break;
24794    case '`':   break;                /* For MySQL compatibility */
24795    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
24796    default:    return -1;
24797  }
24798  for(i=1, j=0;; i++){
24799    assert( z[i] );
24800    if( z[i]==quote ){
24801      if( z[i+1]==quote ){
24802        z[j++] = quote;
24803        i++;
24804      }else{
24805        break;
24806      }
24807    }else{
24808      z[j++] = z[i];
24809    }
24810  }
24811  z[j] = 0;
24812  return j;
24813}
24814
24815/* Convenient short-hand */
24816#define UpperToLower sqlite3UpperToLower
24817
24818/*
24819** Some systems have stricmp().  Others have strcasecmp().  Because
24820** there is no consistency, we will define our own.
24821**
24822** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
24823** sqlite3_strnicmp() APIs allow applications and extensions to compare
24824** the contents of two buffers containing UTF-8 strings in a
24825** case-independent fashion, using the same definition of "case
24826** independence" that SQLite uses internally when comparing identifiers.
24827*/
24828SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
24829  register unsigned char *a, *b;
24830  if( zLeft==0 ){
24831    return zRight ? -1 : 0;
24832  }else if( zRight==0 ){
24833    return 1;
24834  }
24835  a = (unsigned char *)zLeft;
24836  b = (unsigned char *)zRight;
24837  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
24838  return UpperToLower[*a] - UpperToLower[*b];
24839}
24840SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
24841  register unsigned char *a, *b;
24842  if( zLeft==0 ){
24843    return zRight ? -1 : 0;
24844  }else if( zRight==0 ){
24845    return 1;
24846  }
24847  a = (unsigned char *)zLeft;
24848  b = (unsigned char *)zRight;
24849  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
24850  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
24851}
24852
24853/*
24854** The string z[] is an text representation of a real number.
24855** Convert this string to a double and write it into *pResult.
24856**
24857** The string z[] is length bytes in length (bytes, not characters) and
24858** uses the encoding enc.  The string is not necessarily zero-terminated.
24859**
24860** Return TRUE if the result is a valid real number (or integer) and FALSE
24861** if the string is empty or contains extraneous text.  Valid numbers
24862** are in one of these formats:
24863**
24864**    [+-]digits[E[+-]digits]
24865**    [+-]digits.[digits][E[+-]digits]
24866**    [+-].digits[E[+-]digits]
24867**
24868** Leading and trailing whitespace is ignored for the purpose of determining
24869** validity.
24870**
24871** If some prefix of the input string is a valid number, this routine
24872** returns FALSE but it still converts the prefix and writes the result
24873** into *pResult.
24874*/
24875SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
24876#ifndef SQLITE_OMIT_FLOATING_POINT
24877  int incr;
24878  const char *zEnd = z + length;
24879  /* sign * significand * (10 ^ (esign * exponent)) */
24880  int sign = 1;    /* sign of significand */
24881  i64 s = 0;       /* significand */
24882  int d = 0;       /* adjust exponent for shifting decimal point */
24883  int esign = 1;   /* sign of exponent */
24884  int e = 0;       /* exponent */
24885  int eValid = 1;  /* True exponent is either not used or is well-formed */
24886  double result;
24887  int nDigits = 0;
24888  int nonNum = 0;
24889
24890  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
24891  *pResult = 0.0;   /* Default return value, in case of an error */
24892
24893  if( enc==SQLITE_UTF8 ){
24894    incr = 1;
24895  }else{
24896    int i;
24897    incr = 2;
24898    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
24899    for(i=3-enc; i<length && z[i]==0; i+=2){}
24900    nonNum = i<length;
24901    zEnd = z+i+enc-3;
24902    z += (enc&1);
24903  }
24904
24905  /* skip leading spaces */
24906  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
24907  if( z>=zEnd ) return 0;
24908
24909  /* get sign of significand */
24910  if( *z=='-' ){
24911    sign = -1;
24912    z+=incr;
24913  }else if( *z=='+' ){
24914    z+=incr;
24915  }
24916
24917  /* skip leading zeroes */
24918  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
24919
24920  /* copy max significant digits to significand */
24921  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
24922    s = s*10 + (*z - '0');
24923    z+=incr, nDigits++;
24924  }
24925
24926  /* skip non-significant significand digits
24927  ** (increase exponent by d to shift decimal left) */
24928  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
24929  if( z>=zEnd ) goto do_atof_calc;
24930
24931  /* if decimal point is present */
24932  if( *z=='.' ){
24933    z+=incr;
24934    /* copy digits from after decimal to significand
24935    ** (decrease exponent by d to shift decimal right) */
24936    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
24937      s = s*10 + (*z - '0');
24938      z+=incr, nDigits++, d--;
24939    }
24940    /* skip non-significant digits */
24941    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
24942  }
24943  if( z>=zEnd ) goto do_atof_calc;
24944
24945  /* if exponent is present */
24946  if( *z=='e' || *z=='E' ){
24947    z+=incr;
24948    eValid = 0;
24949    if( z>=zEnd ) goto do_atof_calc;
24950    /* get sign of exponent */
24951    if( *z=='-' ){
24952      esign = -1;
24953      z+=incr;
24954    }else if( *z=='+' ){
24955      z+=incr;
24956    }
24957    /* copy digits to exponent */
24958    while( z<zEnd && sqlite3Isdigit(*z) ){
24959      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
24960      z+=incr;
24961      eValid = 1;
24962    }
24963  }
24964
24965  /* skip trailing spaces */
24966  if( nDigits && eValid ){
24967    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
24968  }
24969
24970do_atof_calc:
24971  /* adjust exponent by d, and update sign */
24972  e = (e*esign) + d;
24973  if( e<0 ) {
24974    esign = -1;
24975    e *= -1;
24976  } else {
24977    esign = 1;
24978  }
24979
24980  /* if 0 significand */
24981  if( !s ) {
24982    /* In the IEEE 754 standard, zero is signed.
24983    ** Add the sign if we've seen at least one digit */
24984    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
24985  } else {
24986    /* attempt to reduce exponent */
24987    if( esign>0 ){
24988      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
24989    }else{
24990      while( !(s%10) && e>0 ) e--,s/=10;
24991    }
24992
24993    /* adjust the sign of significand */
24994    s = sign<0 ? -s : s;
24995
24996    /* if exponent, scale significand as appropriate
24997    ** and store in result. */
24998    if( e ){
24999      LONGDOUBLE_TYPE scale = 1.0;
25000      /* attempt to handle extremely small/large numbers better */
25001      if( e>307 && e<342 ){
25002        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
25003        if( esign<0 ){
25004          result = s / scale;
25005          result /= 1.0e+308;
25006        }else{
25007          result = s * scale;
25008          result *= 1.0e+308;
25009        }
25010      }else if( e>=342 ){
25011        if( esign<0 ){
25012          result = 0.0*s;
25013        }else{
25014          result = 1e308*1e308*s;  /* Infinity */
25015        }
25016      }else{
25017        /* 1.0e+22 is the largest power of 10 than can be
25018        ** represented exactly. */
25019        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
25020        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
25021        if( esign<0 ){
25022          result = s / scale;
25023        }else{
25024          result = s * scale;
25025        }
25026      }
25027    } else {
25028      result = (double)s;
25029    }
25030  }
25031
25032  /* store the result */
25033  *pResult = result;
25034
25035  /* return true if number and no extra non-whitespace chracters after */
25036  return z>=zEnd && nDigits>0 && eValid && nonNum==0;
25037#else
25038  return !sqlite3Atoi64(z, pResult, length, enc);
25039#endif /* SQLITE_OMIT_FLOATING_POINT */
25040}
25041
25042/*
25043** Compare the 19-character string zNum against the text representation
25044** value 2^63:  9223372036854775808.  Return negative, zero, or positive
25045** if zNum is less than, equal to, or greater than the string.
25046** Note that zNum must contain exactly 19 characters.
25047**
25048** Unlike memcmp() this routine is guaranteed to return the difference
25049** in the values of the last digit if the only difference is in the
25050** last digit.  So, for example,
25051**
25052**      compare2pow63("9223372036854775800", 1)
25053**
25054** will return -8.
25055*/
25056static int compare2pow63(const char *zNum, int incr){
25057  int c = 0;
25058  int i;
25059                    /* 012345678901234567 */
25060  const char *pow63 = "922337203685477580";
25061  for(i=0; c==0 && i<18; i++){
25062    c = (zNum[i*incr]-pow63[i])*10;
25063  }
25064  if( c==0 ){
25065    c = zNum[18*incr] - '8';
25066    testcase( c==(-1) );
25067    testcase( c==0 );
25068    testcase( c==(+1) );
25069  }
25070  return c;
25071}
25072
25073/*
25074** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
25075** routine does *not* accept hexadecimal notation.
25076**
25077** If the zNum value is representable as a 64-bit twos-complement
25078** integer, then write that value into *pNum and return 0.
25079**
25080** If zNum is exactly 9223372036854775808, return 2.  This special
25081** case is broken out because while 9223372036854775808 cannot be a
25082** signed 64-bit integer, its negative -9223372036854775808 can be.
25083**
25084** If zNum is too big for a 64-bit integer and is not
25085** 9223372036854775808  or if zNum contains any non-numeric text,
25086** then return 1.
25087**
25088** length is the number of bytes in the string (bytes, not characters).
25089** The string is not necessarily zero-terminated.  The encoding is
25090** given by enc.
25091*/
25092SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
25093  int incr;
25094  u64 u = 0;
25095  int neg = 0; /* assume positive */
25096  int i;
25097  int c = 0;
25098  int nonNum = 0;
25099  const char *zStart;
25100  const char *zEnd = zNum + length;
25101  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
25102  if( enc==SQLITE_UTF8 ){
25103    incr = 1;
25104  }else{
25105    incr = 2;
25106    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
25107    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
25108    nonNum = i<length;
25109    zEnd = zNum+i+enc-3;
25110    zNum += (enc&1);
25111  }
25112  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
25113  if( zNum<zEnd ){
25114    if( *zNum=='-' ){
25115      neg = 1;
25116      zNum+=incr;
25117    }else if( *zNum=='+' ){
25118      zNum+=incr;
25119    }
25120  }
25121  zStart = zNum;
25122  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
25123  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
25124    u = u*10 + c - '0';
25125  }
25126  if( u>LARGEST_INT64 ){
25127    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
25128  }else if( neg ){
25129    *pNum = -(i64)u;
25130  }else{
25131    *pNum = (i64)u;
25132  }
25133  testcase( i==18 );
25134  testcase( i==19 );
25135  testcase( i==20 );
25136  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
25137    /* zNum is empty or contains non-numeric text or is longer
25138    ** than 19 digits (thus guaranteeing that it is too large) */
25139    return 1;
25140  }else if( i<19*incr ){
25141    /* Less than 19 digits, so we know that it fits in 64 bits */
25142    assert( u<=LARGEST_INT64 );
25143    return 0;
25144  }else{
25145    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
25146    c = compare2pow63(zNum, incr);
25147    if( c<0 ){
25148      /* zNum is less than 9223372036854775808 so it fits */
25149      assert( u<=LARGEST_INT64 );
25150      return 0;
25151    }else if( c>0 ){
25152      /* zNum is greater than 9223372036854775808 so it overflows */
25153      return 1;
25154    }else{
25155      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
25156      ** special case 2 overflow if positive */
25157      assert( u-1==LARGEST_INT64 );
25158      return neg ? 0 : 2;
25159    }
25160  }
25161}
25162
25163/*
25164** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
25165** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
25166** whereas sqlite3Atoi64() does not.
25167**
25168** Returns:
25169**
25170**     0    Successful transformation.  Fits in a 64-bit signed integer.
25171**     1    Integer too large for a 64-bit signed integer or is malformed
25172**     2    Special case of 9223372036854775808
25173*/
25174SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
25175#ifndef SQLITE_OMIT_HEX_INTEGER
25176  if( z[0]=='0'
25177   && (z[1]=='x' || z[1]=='X')
25178   && sqlite3Isxdigit(z[2])
25179  ){
25180    u64 u = 0;
25181    int i, k;
25182    for(i=2; z[i]=='0'; i++){}
25183    for(k=i; sqlite3Isxdigit(z[k]); k++){
25184      u = u*16 + sqlite3HexToInt(z[k]);
25185    }
25186    memcpy(pOut, &u, 8);
25187    return (z[k]==0 && k-i<=16) ? 0 : 1;
25188  }else
25189#endif /* SQLITE_OMIT_HEX_INTEGER */
25190  {
25191    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
25192  }
25193}
25194
25195/*
25196** If zNum represents an integer that will fit in 32-bits, then set
25197** *pValue to that integer and return true.  Otherwise return false.
25198**
25199** This routine accepts both decimal and hexadecimal notation for integers.
25200**
25201** Any non-numeric characters that following zNum are ignored.
25202** This is different from sqlite3Atoi64() which requires the
25203** input number to be zero-terminated.
25204*/
25205SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
25206  sqlite_int64 v = 0;
25207  int i, c;
25208  int neg = 0;
25209  if( zNum[0]=='-' ){
25210    neg = 1;
25211    zNum++;
25212  }else if( zNum[0]=='+' ){
25213    zNum++;
25214  }
25215#ifndef SQLITE_OMIT_HEX_INTEGER
25216  else if( zNum[0]=='0'
25217        && (zNum[1]=='x' || zNum[1]=='X')
25218        && sqlite3Isxdigit(zNum[2])
25219  ){
25220    u32 u = 0;
25221    zNum += 2;
25222    while( zNum[0]=='0' ) zNum++;
25223    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
25224      u = u*16 + sqlite3HexToInt(zNum[i]);
25225    }
25226    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
25227      memcpy(pValue, &u, 4);
25228      return 1;
25229    }else{
25230      return 0;
25231    }
25232  }
25233#endif
25234  while( zNum[0]=='0' ) zNum++;
25235  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
25236    v = v*10 + c;
25237  }
25238
25239  /* The longest decimal representation of a 32 bit integer is 10 digits:
25240  **
25241  **             1234567890
25242  **     2^31 -> 2147483648
25243  */
25244  testcase( i==10 );
25245  if( i>10 ){
25246    return 0;
25247  }
25248  testcase( v-neg==2147483647 );
25249  if( v-neg>2147483647 ){
25250    return 0;
25251  }
25252  if( neg ){
25253    v = -v;
25254  }
25255  *pValue = (int)v;
25256  return 1;
25257}
25258
25259/*
25260** Return a 32-bit integer value extracted from a string.  If the
25261** string is not an integer, just return 0.
25262*/
25263SQLITE_PRIVATE int sqlite3Atoi(const char *z){
25264  int x = 0;
25265  if( z ) sqlite3GetInt32(z, &x);
25266  return x;
25267}
25268
25269/*
25270** The variable-length integer encoding is as follows:
25271**
25272** KEY:
25273**         A = 0xxxxxxx    7 bits of data and one flag bit
25274**         B = 1xxxxxxx    7 bits of data and one flag bit
25275**         C = xxxxxxxx    8 bits of data
25276**
25277**  7 bits - A
25278** 14 bits - BA
25279** 21 bits - BBA
25280** 28 bits - BBBA
25281** 35 bits - BBBBA
25282** 42 bits - BBBBBA
25283** 49 bits - BBBBBBA
25284** 56 bits - BBBBBBBA
25285** 64 bits - BBBBBBBBC
25286*/
25287
25288/*
25289** Write a 64-bit variable-length integer to memory starting at p[0].
25290** The length of data write will be between 1 and 9 bytes.  The number
25291** of bytes written is returned.
25292**
25293** A variable-length integer consists of the lower 7 bits of each byte
25294** for all bytes that have the 8th bit set and one byte with the 8th
25295** bit clear.  Except, if we get to the 9th byte, it stores the full
25296** 8 bits and is the last byte.
25297*/
25298static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
25299  int i, j, n;
25300  u8 buf[10];
25301  if( v & (((u64)0xff000000)<<32) ){
25302    p[8] = (u8)v;
25303    v >>= 8;
25304    for(i=7; i>=0; i--){
25305      p[i] = (u8)((v & 0x7f) | 0x80);
25306      v >>= 7;
25307    }
25308    return 9;
25309  }
25310  n = 0;
25311  do{
25312    buf[n++] = (u8)((v & 0x7f) | 0x80);
25313    v >>= 7;
25314  }while( v!=0 );
25315  buf[0] &= 0x7f;
25316  assert( n<=9 );
25317  for(i=0, j=n-1; j>=0; j--, i++){
25318    p[i] = buf[j];
25319  }
25320  return n;
25321}
25322SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
25323  if( v<=0x7f ){
25324    p[0] = v&0x7f;
25325    return 1;
25326  }
25327  if( v<=0x3fff ){
25328    p[0] = ((v>>7)&0x7f)|0x80;
25329    p[1] = v&0x7f;
25330    return 2;
25331  }
25332  return putVarint64(p,v);
25333}
25334
25335/*
25336** Bitmasks used by sqlite3GetVarint().  These precomputed constants
25337** are defined here rather than simply putting the constant expressions
25338** inline in order to work around bugs in the RVT compiler.
25339**
25340** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
25341**
25342** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
25343*/
25344#define SLOT_2_0     0x001fc07f
25345#define SLOT_4_2_0   0xf01fc07f
25346
25347
25348/*
25349** Read a 64-bit variable-length integer from memory starting at p[0].
25350** Return the number of bytes read.  The value is stored in *v.
25351*/
25352SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
25353  u32 a,b,s;
25354
25355  a = *p;
25356  /* a: p0 (unmasked) */
25357  if (!(a&0x80))
25358  {
25359    *v = a;
25360    return 1;
25361  }
25362
25363  p++;
25364  b = *p;
25365  /* b: p1 (unmasked) */
25366  if (!(b&0x80))
25367  {
25368    a &= 0x7f;
25369    a = a<<7;
25370    a |= b;
25371    *v = a;
25372    return 2;
25373  }
25374
25375  /* Verify that constants are precomputed correctly */
25376  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
25377  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
25378
25379  p++;
25380  a = a<<14;
25381  a |= *p;
25382  /* a: p0<<14 | p2 (unmasked) */
25383  if (!(a&0x80))
25384  {
25385    a &= SLOT_2_0;
25386    b &= 0x7f;
25387    b = b<<7;
25388    a |= b;
25389    *v = a;
25390    return 3;
25391  }
25392
25393  /* CSE1 from below */
25394  a &= SLOT_2_0;
25395  p++;
25396  b = b<<14;
25397  b |= *p;
25398  /* b: p1<<14 | p3 (unmasked) */
25399  if (!(b&0x80))
25400  {
25401    b &= SLOT_2_0;
25402    /* moved CSE1 up */
25403    /* a &= (0x7f<<14)|(0x7f); */
25404    a = a<<7;
25405    a |= b;
25406    *v = a;
25407    return 4;
25408  }
25409
25410  /* a: p0<<14 | p2 (masked) */
25411  /* b: p1<<14 | p3 (unmasked) */
25412  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
25413  /* moved CSE1 up */
25414  /* a &= (0x7f<<14)|(0x7f); */
25415  b &= SLOT_2_0;
25416  s = a;
25417  /* s: p0<<14 | p2 (masked) */
25418
25419  p++;
25420  a = a<<14;
25421  a |= *p;
25422  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
25423  if (!(a&0x80))
25424  {
25425    /* we can skip these cause they were (effectively) done above in calc'ing s */
25426    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
25427    /* b &= (0x7f<<14)|(0x7f); */
25428    b = b<<7;
25429    a |= b;
25430    s = s>>18;
25431    *v = ((u64)s)<<32 | a;
25432    return 5;
25433  }
25434
25435  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
25436  s = s<<7;
25437  s |= b;
25438  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
25439
25440  p++;
25441  b = b<<14;
25442  b |= *p;
25443  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
25444  if (!(b&0x80))
25445  {
25446    /* we can skip this cause it was (effectively) done above in calc'ing s */
25447    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
25448    a &= SLOT_2_0;
25449    a = a<<7;
25450    a |= b;
25451    s = s>>18;
25452    *v = ((u64)s)<<32 | a;
25453    return 6;
25454  }
25455
25456  p++;
25457  a = a<<14;
25458  a |= *p;
25459  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
25460  if (!(a&0x80))
25461  {
25462    a &= SLOT_4_2_0;
25463    b &= SLOT_2_0;
25464    b = b<<7;
25465    a |= b;
25466    s = s>>11;
25467    *v = ((u64)s)<<32 | a;
25468    return 7;
25469  }
25470
25471  /* CSE2 from below */
25472  a &= SLOT_2_0;
25473  p++;
25474  b = b<<14;
25475  b |= *p;
25476  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
25477  if (!(b&0x80))
25478  {
25479    b &= SLOT_4_2_0;
25480    /* moved CSE2 up */
25481    /* a &= (0x7f<<14)|(0x7f); */
25482    a = a<<7;
25483    a |= b;
25484    s = s>>4;
25485    *v = ((u64)s)<<32 | a;
25486    return 8;
25487  }
25488
25489  p++;
25490  a = a<<15;
25491  a |= *p;
25492  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
25493
25494  /* moved CSE2 up */
25495  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
25496  b &= SLOT_2_0;
25497  b = b<<8;
25498  a |= b;
25499
25500  s = s<<4;
25501  b = p[-4];
25502  b &= 0x7f;
25503  b = b>>3;
25504  s |= b;
25505
25506  *v = ((u64)s)<<32 | a;
25507
25508  return 9;
25509}
25510
25511/*
25512** Read a 32-bit variable-length integer from memory starting at p[0].
25513** Return the number of bytes read.  The value is stored in *v.
25514**
25515** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
25516** integer, then set *v to 0xffffffff.
25517**
25518** A MACRO version, getVarint32, is provided which inlines the
25519** single-byte case.  All code should use the MACRO version as
25520** this function assumes the single-byte case has already been handled.
25521*/
25522SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
25523  u32 a,b;
25524
25525  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
25526  ** by the getVarin32() macro */
25527  a = *p;
25528  /* a: p0 (unmasked) */
25529#ifndef getVarint32
25530  if (!(a&0x80))
25531  {
25532    /* Values between 0 and 127 */
25533    *v = a;
25534    return 1;
25535  }
25536#endif
25537
25538  /* The 2-byte case */
25539  p++;
25540  b = *p;
25541  /* b: p1 (unmasked) */
25542  if (!(b&0x80))
25543  {
25544    /* Values between 128 and 16383 */
25545    a &= 0x7f;
25546    a = a<<7;
25547    *v = a | b;
25548    return 2;
25549  }
25550
25551  /* The 3-byte case */
25552  p++;
25553  a = a<<14;
25554  a |= *p;
25555  /* a: p0<<14 | p2 (unmasked) */
25556  if (!(a&0x80))
25557  {
25558    /* Values between 16384 and 2097151 */
25559    a &= (0x7f<<14)|(0x7f);
25560    b &= 0x7f;
25561    b = b<<7;
25562    *v = a | b;
25563    return 3;
25564  }
25565
25566  /* A 32-bit varint is used to store size information in btrees.
25567  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
25568  ** A 3-byte varint is sufficient, for example, to record the size
25569  ** of a 1048569-byte BLOB or string.
25570  **
25571  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
25572  ** rare larger cases can be handled by the slower 64-bit varint
25573  ** routine.
25574  */
25575#if 1
25576  {
25577    u64 v64;
25578    u8 n;
25579
25580    p -= 2;
25581    n = sqlite3GetVarint(p, &v64);
25582    assert( n>3 && n<=9 );
25583    if( (v64 & SQLITE_MAX_U32)!=v64 ){
25584      *v = 0xffffffff;
25585    }else{
25586      *v = (u32)v64;
25587    }
25588    return n;
25589  }
25590
25591#else
25592  /* For following code (kept for historical record only) shows an
25593  ** unrolling for the 3- and 4-byte varint cases.  This code is
25594  ** slightly faster, but it is also larger and much harder to test.
25595  */
25596  p++;
25597  b = b<<14;
25598  b |= *p;
25599  /* b: p1<<14 | p3 (unmasked) */
25600  if (!(b&0x80))
25601  {
25602    /* Values between 2097152 and 268435455 */
25603    b &= (0x7f<<14)|(0x7f);
25604    a &= (0x7f<<14)|(0x7f);
25605    a = a<<7;
25606    *v = a | b;
25607    return 4;
25608  }
25609
25610  p++;
25611  a = a<<14;
25612  a |= *p;
25613  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
25614  if (!(a&0x80))
25615  {
25616    /* Values  between 268435456 and 34359738367 */
25617    a &= SLOT_4_2_0;
25618    b &= SLOT_4_2_0;
25619    b = b<<7;
25620    *v = a | b;
25621    return 5;
25622  }
25623
25624  /* We can only reach this point when reading a corrupt database
25625  ** file.  In that case we are not in any hurry.  Use the (relatively
25626  ** slow) general-purpose sqlite3GetVarint() routine to extract the
25627  ** value. */
25628  {
25629    u64 v64;
25630    u8 n;
25631
25632    p -= 4;
25633    n = sqlite3GetVarint(p, &v64);
25634    assert( n>5 && n<=9 );
25635    *v = (u32)v64;
25636    return n;
25637  }
25638#endif
25639}
25640
25641/*
25642** Return the number of bytes that will be needed to store the given
25643** 64-bit integer.
25644*/
25645SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
25646  int i;
25647  for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
25648  return i;
25649}
25650
25651
25652/*
25653** Read or write a four-byte big-endian integer value.
25654*/
25655SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
25656#if SQLITE_BYTEORDER==4321
25657  u32 x;
25658  memcpy(&x,p,4);
25659  return x;
25660#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
25661    && defined(__GNUC__) && GCC_VERSION>=4003000
25662  u32 x;
25663  memcpy(&x,p,4);
25664  return __builtin_bswap32(x);
25665#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
25666    && defined(_MSC_VER) && _MSC_VER>=1300
25667  u32 x;
25668  memcpy(&x,p,4);
25669  return _byteswap_ulong(x);
25670#else
25671  testcase( p[0]&0x80 );
25672  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
25673#endif
25674}
25675SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
25676#if SQLITE_BYTEORDER==4321
25677  memcpy(p,&v,4);
25678#elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
25679  u32 x = __builtin_bswap32(v);
25680  memcpy(p,&x,4);
25681#elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
25682  u32 x = _byteswap_ulong(v);
25683  memcpy(p,&x,4);
25684#else
25685  p[0] = (u8)(v>>24);
25686  p[1] = (u8)(v>>16);
25687  p[2] = (u8)(v>>8);
25688  p[3] = (u8)v;
25689#endif
25690}
25691
25692
25693
25694/*
25695** Translate a single byte of Hex into an integer.
25696** This routine only works if h really is a valid hexadecimal
25697** character:  0..9a..fA..F
25698*/
25699SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
25700  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
25701#ifdef SQLITE_ASCII
25702  h += 9*(1&(h>>6));
25703#endif
25704#ifdef SQLITE_EBCDIC
25705  h += 9*(1&~(h>>4));
25706#endif
25707  return (u8)(h & 0xf);
25708}
25709
25710#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
25711/*
25712** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
25713** value.  Return a pointer to its binary value.  Space to hold the
25714** binary value has been obtained from malloc and must be freed by
25715** the calling routine.
25716*/
25717SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
25718  char *zBlob;
25719  int i;
25720
25721  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
25722  n--;
25723  if( zBlob ){
25724    for(i=0; i<n; i+=2){
25725      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
25726    }
25727    zBlob[i/2] = 0;
25728  }
25729  return zBlob;
25730}
25731#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
25732
25733/*
25734** Log an error that is an API call on a connection pointer that should
25735** not have been used.  The "type" of connection pointer is given as the
25736** argument.  The zType is a word like "NULL" or "closed" or "invalid".
25737*/
25738static void logBadConnection(const char *zType){
25739  sqlite3_log(SQLITE_MISUSE,
25740     "API call with %s database connection pointer",
25741     zType
25742  );
25743}
25744
25745/*
25746** Check to make sure we have a valid db pointer.  This test is not
25747** foolproof but it does provide some measure of protection against
25748** misuse of the interface such as passing in db pointers that are
25749** NULL or which have been previously closed.  If this routine returns
25750** 1 it means that the db pointer is valid and 0 if it should not be
25751** dereferenced for any reason.  The calling function should invoke
25752** SQLITE_MISUSE immediately.
25753**
25754** sqlite3SafetyCheckOk() requires that the db pointer be valid for
25755** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
25756** open properly and is not fit for general use but which can be
25757** used as an argument to sqlite3_errmsg() or sqlite3_close().
25758*/
25759SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
25760  u32 magic;
25761  if( db==0 ){
25762    logBadConnection("NULL");
25763    return 0;
25764  }
25765  magic = db->magic;
25766  if( magic!=SQLITE_MAGIC_OPEN ){
25767    if( sqlite3SafetyCheckSickOrOk(db) ){
25768      testcase( sqlite3GlobalConfig.xLog!=0 );
25769      logBadConnection("unopened");
25770    }
25771    return 0;
25772  }else{
25773    return 1;
25774  }
25775}
25776SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
25777  u32 magic;
25778  magic = db->magic;
25779  if( magic!=SQLITE_MAGIC_SICK &&
25780      magic!=SQLITE_MAGIC_OPEN &&
25781      magic!=SQLITE_MAGIC_BUSY ){
25782    testcase( sqlite3GlobalConfig.xLog!=0 );
25783    logBadConnection("invalid");
25784    return 0;
25785  }else{
25786    return 1;
25787  }
25788}
25789
25790/*
25791** Attempt to add, substract, or multiply the 64-bit signed value iB against
25792** the other 64-bit signed integer at *pA and store the result in *pA.
25793** Return 0 on success.  Or if the operation would have resulted in an
25794** overflow, leave *pA unchanged and return 1.
25795*/
25796SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
25797  i64 iA = *pA;
25798  testcase( iA==0 ); testcase( iA==1 );
25799  testcase( iB==-1 ); testcase( iB==0 );
25800  if( iB>=0 ){
25801    testcase( iA>0 && LARGEST_INT64 - iA == iB );
25802    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
25803    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
25804  }else{
25805    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
25806    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
25807    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
25808  }
25809  *pA += iB;
25810  return 0;
25811}
25812SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
25813  testcase( iB==SMALLEST_INT64+1 );
25814  if( iB==SMALLEST_INT64 ){
25815    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
25816    if( (*pA)>=0 ) return 1;
25817    *pA -= iB;
25818    return 0;
25819  }else{
25820    return sqlite3AddInt64(pA, -iB);
25821  }
25822}
25823#define TWOPOWER32 (((i64)1)<<32)
25824#define TWOPOWER31 (((i64)1)<<31)
25825SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
25826  i64 iA = *pA;
25827  i64 iA1, iA0, iB1, iB0, r;
25828
25829  iA1 = iA/TWOPOWER32;
25830  iA0 = iA % TWOPOWER32;
25831  iB1 = iB/TWOPOWER32;
25832  iB0 = iB % TWOPOWER32;
25833  if( iA1==0 ){
25834    if( iB1==0 ){
25835      *pA *= iB;
25836      return 0;
25837    }
25838    r = iA0*iB1;
25839  }else if( iB1==0 ){
25840    r = iA1*iB0;
25841  }else{
25842    /* If both iA1 and iB1 are non-zero, overflow will result */
25843    return 1;
25844  }
25845  testcase( r==(-TWOPOWER31)-1 );
25846  testcase( r==(-TWOPOWER31) );
25847  testcase( r==TWOPOWER31 );
25848  testcase( r==TWOPOWER31-1 );
25849  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
25850  r *= TWOPOWER32;
25851  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
25852  *pA = r;
25853  return 0;
25854}
25855
25856/*
25857** Compute the absolute value of a 32-bit signed integer, of possible.  Or
25858** if the integer has a value of -2147483648, return +2147483647
25859*/
25860SQLITE_PRIVATE int sqlite3AbsInt32(int x){
25861  if( x>=0 ) return x;
25862  if( x==(int)0x80000000 ) return 0x7fffffff;
25863  return -x;
25864}
25865
25866#ifdef SQLITE_ENABLE_8_3_NAMES
25867/*
25868** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
25869** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
25870** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
25871** three characters, then shorten the suffix on z[] to be the last three
25872** characters of the original suffix.
25873**
25874** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
25875** do the suffix shortening regardless of URI parameter.
25876**
25877** Examples:
25878**
25879**     test.db-journal    =>   test.nal
25880**     test.db-wal        =>   test.wal
25881**     test.db-shm        =>   test.shm
25882**     test.db-mj7f3319fa =>   test.9fa
25883*/
25884SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
25885#if SQLITE_ENABLE_8_3_NAMES<2
25886  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
25887#endif
25888  {
25889    int i, sz;
25890    sz = sqlite3Strlen30(z);
25891    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
25892    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
25893  }
25894}
25895#endif
25896
25897/*
25898** Find (an approximate) sum of two LogEst values.  This computation is
25899** not a simple "+" operator because LogEst is stored as a logarithmic
25900** value.
25901**
25902*/
25903SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
25904  static const unsigned char x[] = {
25905     10, 10,                         /* 0,1 */
25906      9, 9,                          /* 2,3 */
25907      8, 8,                          /* 4,5 */
25908      7, 7, 7,                       /* 6,7,8 */
25909      6, 6, 6,                       /* 9,10,11 */
25910      5, 5, 5,                       /* 12-14 */
25911      4, 4, 4, 4,                    /* 15-18 */
25912      3, 3, 3, 3, 3, 3,              /* 19-24 */
25913      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
25914  };
25915  if( a>=b ){
25916    if( a>b+49 ) return a;
25917    if( a>b+31 ) return a+1;
25918    return a+x[a-b];
25919  }else{
25920    if( b>a+49 ) return b;
25921    if( b>a+31 ) return b+1;
25922    return b+x[b-a];
25923  }
25924}
25925
25926/*
25927** Convert an integer into a LogEst.  In other words, compute an
25928** approximation for 10*log2(x).
25929*/
25930SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
25931  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
25932  LogEst y = 40;
25933  if( x<8 ){
25934    if( x<2 ) return 0;
25935    while( x<8 ){  y -= 10; x <<= 1; }
25936  }else{
25937    while( x>255 ){ y += 40; x >>= 4; }
25938    while( x>15 ){  y += 10; x >>= 1; }
25939  }
25940  return a[x&7] + y - 10;
25941}
25942
25943#ifndef SQLITE_OMIT_VIRTUALTABLE
25944/*
25945** Convert a double into a LogEst
25946** In other words, compute an approximation for 10*log2(x).
25947*/
25948SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
25949  u64 a;
25950  LogEst e;
25951  assert( sizeof(x)==8 && sizeof(a)==8 );
25952  if( x<=1 ) return 0;
25953  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
25954  memcpy(&a, &x, 8);
25955  e = (a>>52) - 1022;
25956  return e*10;
25957}
25958#endif /* SQLITE_OMIT_VIRTUALTABLE */
25959
25960/*
25961** Convert a LogEst into an integer.
25962*/
25963SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
25964  u64 n;
25965  if( x<10 ) return 1;
25966  n = x%10;
25967  x /= 10;
25968  if( n>=5 ) n -= 2;
25969  else if( n>=1 ) n -= 1;
25970  if( x>=3 ){
25971    return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
25972  }
25973  return (n+8)>>(3-x);
25974}
25975
25976/************** End of util.c ************************************************/
25977/************** Begin file hash.c ********************************************/
25978/*
25979** 2001 September 22
25980**
25981** The author disclaims copyright to this source code.  In place of
25982** a legal notice, here is a blessing:
25983**
25984**    May you do good and not evil.
25985**    May you find forgiveness for yourself and forgive others.
25986**    May you share freely, never taking more than you give.
25987**
25988*************************************************************************
25989** This is the implementation of generic hash-tables
25990** used in SQLite.
25991*/
25992/* #include "sqliteInt.h" */
25993/* #include <assert.h> */
25994
25995/* Turn bulk memory into a hash table object by initializing the
25996** fields of the Hash structure.
25997**
25998** "pNew" is a pointer to the hash table that is to be initialized.
25999*/
26000SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
26001  assert( pNew!=0 );
26002  pNew->first = 0;
26003  pNew->count = 0;
26004  pNew->htsize = 0;
26005  pNew->ht = 0;
26006}
26007
26008/* Remove all entries from a hash table.  Reclaim all memory.
26009** Call this routine to delete a hash table or to reset a hash table
26010** to the empty state.
26011*/
26012SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
26013  HashElem *elem;         /* For looping over all elements of the table */
26014
26015  assert( pH!=0 );
26016  elem = pH->first;
26017  pH->first = 0;
26018  sqlite3_free(pH->ht);
26019  pH->ht = 0;
26020  pH->htsize = 0;
26021  while( elem ){
26022    HashElem *next_elem = elem->next;
26023    sqlite3_free(elem);
26024    elem = next_elem;
26025  }
26026  pH->count = 0;
26027}
26028
26029/*
26030** The hashing function.
26031*/
26032static unsigned int strHash(const char *z){
26033  unsigned int h = 0;
26034  unsigned char c;
26035  while( (c = (unsigned char)*z++)!=0 ){
26036    h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
26037  }
26038  return h;
26039}
26040
26041
26042/* Link pNew element into the hash table pH.  If pEntry!=0 then also
26043** insert pNew into the pEntry hash bucket.
26044*/
26045static void insertElement(
26046  Hash *pH,              /* The complete hash table */
26047  struct _ht *pEntry,    /* The entry into which pNew is inserted */
26048  HashElem *pNew         /* The element to be inserted */
26049){
26050  HashElem *pHead;       /* First element already in pEntry */
26051  if( pEntry ){
26052    pHead = pEntry->count ? pEntry->chain : 0;
26053    pEntry->count++;
26054    pEntry->chain = pNew;
26055  }else{
26056    pHead = 0;
26057  }
26058  if( pHead ){
26059    pNew->next = pHead;
26060    pNew->prev = pHead->prev;
26061    if( pHead->prev ){ pHead->prev->next = pNew; }
26062    else             { pH->first = pNew; }
26063    pHead->prev = pNew;
26064  }else{
26065    pNew->next = pH->first;
26066    if( pH->first ){ pH->first->prev = pNew; }
26067    pNew->prev = 0;
26068    pH->first = pNew;
26069  }
26070}
26071
26072
26073/* Resize the hash table so that it cantains "new_size" buckets.
26074**
26075** The hash table might fail to resize if sqlite3_malloc() fails or
26076** if the new size is the same as the prior size.
26077** Return TRUE if the resize occurs and false if not.
26078*/
26079static int rehash(Hash *pH, unsigned int new_size){
26080  struct _ht *new_ht;            /* The new hash table */
26081  HashElem *elem, *next_elem;    /* For looping over existing elements */
26082
26083#if SQLITE_MALLOC_SOFT_LIMIT>0
26084  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
26085    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
26086  }
26087  if( new_size==pH->htsize ) return 0;
26088#endif
26089
26090  /* The inability to allocates space for a larger hash table is
26091  ** a performance hit but it is not a fatal error.  So mark the
26092  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
26093  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
26094  ** only zeroes the requested number of bytes whereas this module will
26095  ** use the actual amount of space allocated for the hash table (which
26096  ** may be larger than the requested amount).
26097  */
26098  sqlite3BeginBenignMalloc();
26099  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
26100  sqlite3EndBenignMalloc();
26101
26102  if( new_ht==0 ) return 0;
26103  sqlite3_free(pH->ht);
26104  pH->ht = new_ht;
26105  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
26106  memset(new_ht, 0, new_size*sizeof(struct _ht));
26107  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
26108    unsigned int h = strHash(elem->pKey) % new_size;
26109    next_elem = elem->next;
26110    insertElement(pH, &new_ht[h], elem);
26111  }
26112  return 1;
26113}
26114
26115/* This function (for internal use only) locates an element in an
26116** hash table that matches the given key.  The hash for this key is
26117** also computed and returned in the *pH parameter.
26118*/
26119static HashElem *findElementWithHash(
26120  const Hash *pH,     /* The pH to be searched */
26121  const char *pKey,   /* The key we are searching for */
26122  unsigned int *pHash /* Write the hash value here */
26123){
26124  HashElem *elem;                /* Used to loop thru the element list */
26125  int count;                     /* Number of elements left to test */
26126  unsigned int h;                /* The computed hash */
26127
26128  if( pH->ht ){
26129    struct _ht *pEntry;
26130    h = strHash(pKey) % pH->htsize;
26131    pEntry = &pH->ht[h];
26132    elem = pEntry->chain;
26133    count = pEntry->count;
26134  }else{
26135    h = 0;
26136    elem = pH->first;
26137    count = pH->count;
26138  }
26139  *pHash = h;
26140  while( count-- ){
26141    assert( elem!=0 );
26142    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
26143      return elem;
26144    }
26145    elem = elem->next;
26146  }
26147  return 0;
26148}
26149
26150/* Remove a single entry from the hash table given a pointer to that
26151** element and a hash on the element's key.
26152*/
26153static void removeElementGivenHash(
26154  Hash *pH,         /* The pH containing "elem" */
26155  HashElem* elem,   /* The element to be removed from the pH */
26156  unsigned int h    /* Hash value for the element */
26157){
26158  struct _ht *pEntry;
26159  if( elem->prev ){
26160    elem->prev->next = elem->next;
26161  }else{
26162    pH->first = elem->next;
26163  }
26164  if( elem->next ){
26165    elem->next->prev = elem->prev;
26166  }
26167  if( pH->ht ){
26168    pEntry = &pH->ht[h];
26169    if( pEntry->chain==elem ){
26170      pEntry->chain = elem->next;
26171    }
26172    pEntry->count--;
26173    assert( pEntry->count>=0 );
26174  }
26175  sqlite3_free( elem );
26176  pH->count--;
26177  if( pH->count==0 ){
26178    assert( pH->first==0 );
26179    assert( pH->count==0 );
26180    sqlite3HashClear(pH);
26181  }
26182}
26183
26184/* Attempt to locate an element of the hash table pH with a key
26185** that matches pKey.  Return the data for this element if it is
26186** found, or NULL if there is no match.
26187*/
26188SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
26189  HashElem *elem;    /* The element that matches key */
26190  unsigned int h;    /* A hash on key */
26191
26192  assert( pH!=0 );
26193  assert( pKey!=0 );
26194  elem = findElementWithHash(pH, pKey, &h);
26195  return elem ? elem->data : 0;
26196}
26197
26198/* Insert an element into the hash table pH.  The key is pKey
26199** and the data is "data".
26200**
26201** If no element exists with a matching key, then a new
26202** element is created and NULL is returned.
26203**
26204** If another element already exists with the same key, then the
26205** new data replaces the old data and the old data is returned.
26206** The key is not copied in this instance.  If a malloc fails, then
26207** the new data is returned and the hash table is unchanged.
26208**
26209** If the "data" parameter to this function is NULL, then the
26210** element corresponding to "key" is removed from the hash table.
26211*/
26212SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
26213  unsigned int h;       /* the hash of the key modulo hash table size */
26214  HashElem *elem;       /* Used to loop thru the element list */
26215  HashElem *new_elem;   /* New element added to the pH */
26216
26217  assert( pH!=0 );
26218  assert( pKey!=0 );
26219  elem = findElementWithHash(pH,pKey,&h);
26220  if( elem ){
26221    void *old_data = elem->data;
26222    if( data==0 ){
26223      removeElementGivenHash(pH,elem,h);
26224    }else{
26225      elem->data = data;
26226      elem->pKey = pKey;
26227    }
26228    return old_data;
26229  }
26230  if( data==0 ) return 0;
26231  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
26232  if( new_elem==0 ) return data;
26233  new_elem->pKey = pKey;
26234  new_elem->data = data;
26235  pH->count++;
26236  if( pH->count>=10 && pH->count > 2*pH->htsize ){
26237    if( rehash(pH, pH->count*2) ){
26238      assert( pH->htsize>0 );
26239      h = strHash(pKey) % pH->htsize;
26240    }
26241  }
26242  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
26243  return 0;
26244}
26245
26246/************** End of hash.c ************************************************/
26247/************** Begin file opcodes.c *****************************************/
26248/* Automatically generated.  Do not edit */
26249/* See the mkopcodec.awk script for details. */
26250#if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
26251#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
26252# define OpHelp(X) "\0" X
26253#else
26254# define OpHelp(X)
26255#endif
26256SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
26257 static const char *const azName[] = { "?",
26258     /*   1 */ "Savepoint"        OpHelp(""),
26259     /*   2 */ "AutoCommit"       OpHelp(""),
26260     /*   3 */ "Transaction"      OpHelp(""),
26261     /*   4 */ "SorterNext"       OpHelp(""),
26262     /*   5 */ "PrevIfOpen"       OpHelp(""),
26263     /*   6 */ "NextIfOpen"       OpHelp(""),
26264     /*   7 */ "Prev"             OpHelp(""),
26265     /*   8 */ "Next"             OpHelp(""),
26266     /*   9 */ "Checkpoint"       OpHelp(""),
26267     /*  10 */ "JournalMode"      OpHelp(""),
26268     /*  11 */ "Vacuum"           OpHelp(""),
26269     /*  12 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
26270     /*  13 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
26271     /*  14 */ "Goto"             OpHelp(""),
26272     /*  15 */ "Gosub"            OpHelp(""),
26273     /*  16 */ "Return"           OpHelp(""),
26274     /*  17 */ "InitCoroutine"    OpHelp(""),
26275     /*  18 */ "EndCoroutine"     OpHelp(""),
26276     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
26277     /*  20 */ "Yield"            OpHelp(""),
26278     /*  21 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
26279     /*  22 */ "Halt"             OpHelp(""),
26280     /*  23 */ "Integer"          OpHelp("r[P2]=P1"),
26281     /*  24 */ "Int64"            OpHelp("r[P2]=P4"),
26282     /*  25 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
26283     /*  26 */ "Null"             OpHelp("r[P2..P3]=NULL"),
26284     /*  27 */ "SoftNull"         OpHelp("r[P1]=NULL"),
26285     /*  28 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
26286     /*  29 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
26287     /*  30 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
26288     /*  31 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
26289     /*  32 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
26290     /*  33 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
26291     /*  34 */ "CollSeq"          OpHelp(""),
26292     /*  35 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
26293     /*  36 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
26294     /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
26295     /*  38 */ "MustBeInt"        OpHelp(""),
26296     /*  39 */ "RealAffinity"     OpHelp(""),
26297     /*  40 */ "Cast"             OpHelp("affinity(r[P1])"),
26298     /*  41 */ "Permutation"      OpHelp(""),
26299     /*  42 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
26300     /*  43 */ "Jump"             OpHelp(""),
26301     /*  44 */ "Once"             OpHelp(""),
26302     /*  45 */ "If"               OpHelp(""),
26303     /*  46 */ "IfNot"            OpHelp(""),
26304     /*  47 */ "Column"           OpHelp("r[P3]=PX"),
26305     /*  48 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
26306     /*  49 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
26307     /*  50 */ "Count"            OpHelp("r[P2]=count()"),
26308     /*  51 */ "ReadCookie"       OpHelp(""),
26309     /*  52 */ "SetCookie"        OpHelp(""),
26310     /*  53 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
26311     /*  54 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
26312     /*  55 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
26313     /*  56 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
26314     /*  57 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
26315     /*  58 */ "SorterOpen"       OpHelp(""),
26316     /*  59 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
26317     /*  60 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
26318     /*  61 */ "Close"            OpHelp(""),
26319     /*  62 */ "ColumnsUsed"      OpHelp(""),
26320     /*  63 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
26321     /*  64 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
26322     /*  65 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
26323     /*  66 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
26324     /*  67 */ "Seek"             OpHelp("intkey=r[P2]"),
26325     /*  68 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
26326     /*  69 */ "NotFound"         OpHelp("key=r[P3@P4]"),
26327     /*  70 */ "Found"            OpHelp("key=r[P3@P4]"),
26328     /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
26329     /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
26330     /*  73 */ "NotExists"        OpHelp("intkey=r[P3]"),
26331     /*  74 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
26332     /*  75 */ "NewRowid"         OpHelp("r[P2]=rowid"),
26333     /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
26334     /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
26335     /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
26336     /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
26337     /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
26338     /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
26339     /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
26340     /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
26341     /*  84 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
26342     /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
26343     /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
26344     /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
26345     /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
26346     /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
26347     /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
26348     /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
26349     /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
26350     /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
26351     /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
26352     /*  95 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
26353     /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
26354     /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
26355     /*  98 */ "Delete"           OpHelp(""),
26356     /*  99 */ "ResetCount"       OpHelp(""),
26357     /* 100 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
26358     /* 101 */ "SorterData"       OpHelp("r[P2]=data"),
26359     /* 102 */ "RowKey"           OpHelp("r[P2]=key"),
26360     /* 103 */ "RowData"          OpHelp("r[P2]=data"),
26361     /* 104 */ "Rowid"            OpHelp("r[P2]=rowid"),
26362     /* 105 */ "NullRow"          OpHelp(""),
26363     /* 106 */ "Last"             OpHelp(""),
26364     /* 107 */ "SorterSort"       OpHelp(""),
26365     /* 108 */ "Sort"             OpHelp(""),
26366     /* 109 */ "Rewind"           OpHelp(""),
26367     /* 110 */ "SorterInsert"     OpHelp(""),
26368     /* 111 */ "IdxInsert"        OpHelp("key=r[P2]"),
26369     /* 112 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
26370     /* 113 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
26371     /* 114 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
26372     /* 115 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
26373     /* 116 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
26374     /* 117 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
26375     /* 118 */ "Destroy"          OpHelp(""),
26376     /* 119 */ "Clear"            OpHelp(""),
26377     /* 120 */ "ResetSorter"      OpHelp(""),
26378     /* 121 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
26379     /* 122 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
26380     /* 123 */ "ParseSchema"      OpHelp(""),
26381     /* 124 */ "LoadAnalysis"     OpHelp(""),
26382     /* 125 */ "DropTable"        OpHelp(""),
26383     /* 126 */ "DropIndex"        OpHelp(""),
26384     /* 127 */ "DropTrigger"      OpHelp(""),
26385     /* 128 */ "IntegrityCk"      OpHelp(""),
26386     /* 129 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
26387     /* 130 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
26388     /* 131 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
26389     /* 132 */ "Program"          OpHelp(""),
26390     /* 133 */ "Real"             OpHelp("r[P2]=P4"),
26391     /* 134 */ "Param"            OpHelp(""),
26392     /* 135 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
26393     /* 136 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
26394     /* 137 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
26395     /* 138 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
26396     /* 139 */ "SetIfNotPos"      OpHelp("if r[P1]<=0 then r[P2]=P3"),
26397     /* 140 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
26398     /* 141 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
26399     /* 142 */ "JumpZeroIncr"     OpHelp("if (r[P1]++)==0 ) goto P2"),
26400     /* 143 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
26401     /* 144 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
26402     /* 145 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
26403     /* 146 */ "IncrVacuum"       OpHelp(""),
26404     /* 147 */ "Expire"           OpHelp(""),
26405     /* 148 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
26406     /* 149 */ "VBegin"           OpHelp(""),
26407     /* 150 */ "VCreate"          OpHelp(""),
26408     /* 151 */ "VDestroy"         OpHelp(""),
26409     /* 152 */ "VOpen"            OpHelp(""),
26410     /* 153 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
26411     /* 154 */ "VNext"            OpHelp(""),
26412     /* 155 */ "VRename"          OpHelp(""),
26413     /* 156 */ "Pagecount"        OpHelp(""),
26414     /* 157 */ "MaxPgcnt"         OpHelp(""),
26415     /* 158 */ "Init"             OpHelp("Start at P2"),
26416     /* 159 */ "Noop"             OpHelp(""),
26417     /* 160 */ "Explain"          OpHelp(""),
26418  };
26419  return azName[i];
26420}
26421#endif
26422
26423/************** End of opcodes.c *********************************************/
26424/************** Begin file os_unix.c *****************************************/
26425/*
26426** 2004 May 22
26427**
26428** The author disclaims copyright to this source code.  In place of
26429** a legal notice, here is a blessing:
26430**
26431**    May you do good and not evil.
26432**    May you find forgiveness for yourself and forgive others.
26433**    May you share freely, never taking more than you give.
26434**
26435******************************************************************************
26436**
26437** This file contains the VFS implementation for unix-like operating systems
26438** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
26439**
26440** There are actually several different VFS implementations in this file.
26441** The differences are in the way that file locking is done.  The default
26442** implementation uses Posix Advisory Locks.  Alternative implementations
26443** use flock(), dot-files, various proprietary locking schemas, or simply
26444** skip locking all together.
26445**
26446** This source file is organized into divisions where the logic for various
26447** subfunctions is contained within the appropriate division.  PLEASE
26448** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
26449** in the correct division and should be clearly labeled.
26450**
26451** The layout of divisions is as follows:
26452**
26453**   *  General-purpose declarations and utility functions.
26454**   *  Unique file ID logic used by VxWorks.
26455**   *  Various locking primitive implementations (all except proxy locking):
26456**      + for Posix Advisory Locks
26457**      + for no-op locks
26458**      + for dot-file locks
26459**      + for flock() locking
26460**      + for named semaphore locks (VxWorks only)
26461**      + for AFP filesystem locks (MacOSX only)
26462**   *  sqlite3_file methods not associated with locking.
26463**   *  Definitions of sqlite3_io_methods objects for all locking
26464**      methods plus "finder" functions for each locking method.
26465**   *  sqlite3_vfs method implementations.
26466**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
26467**   *  Definitions of sqlite3_vfs objects for all locking methods
26468**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
26469*/
26470/* #include "sqliteInt.h" */
26471#if SQLITE_OS_UNIX              /* This file is used on unix only */
26472
26473/*
26474** There are various methods for file locking used for concurrency
26475** control:
26476**
26477**   1. POSIX locking (the default),
26478**   2. No locking,
26479**   3. Dot-file locking,
26480**   4. flock() locking,
26481**   5. AFP locking (OSX only),
26482**   6. Named POSIX semaphores (VXWorks only),
26483**   7. proxy locking. (OSX only)
26484**
26485** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
26486** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
26487** selection of the appropriate locking style based on the filesystem
26488** where the database is located.
26489*/
26490#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
26491#  if defined(__APPLE__)
26492#    define SQLITE_ENABLE_LOCKING_STYLE 1
26493#  else
26494#    define SQLITE_ENABLE_LOCKING_STYLE 0
26495#  endif
26496#endif
26497
26498/*
26499** standard include files.
26500*/
26501#include <sys/types.h>
26502#include <sys/stat.h>
26503#include <fcntl.h>
26504#include <unistd.h>
26505/* #include <time.h> */
26506#include <sys/time.h>
26507#include <errno.h>
26508#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
26509# include <sys/mman.h>
26510#endif
26511
26512#if SQLITE_ENABLE_LOCKING_STYLE
26513# include <sys/ioctl.h>
26514# include <sys/file.h>
26515# include <sys/param.h>
26516#endif /* SQLITE_ENABLE_LOCKING_STYLE */
26517
26518#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
26519                           (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
26520#  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
26521       && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
26522#    define HAVE_GETHOSTUUID 1
26523#  else
26524#    warning "gethostuuid() is disabled."
26525#  endif
26526#endif
26527
26528
26529#if OS_VXWORKS
26530/* # include <sys/ioctl.h> */
26531# include <semaphore.h>
26532# include <limits.h>
26533#endif /* OS_VXWORKS */
26534
26535#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
26536# include <sys/mount.h>
26537#endif
26538
26539#ifdef HAVE_UTIME
26540# include <utime.h>
26541#endif
26542
26543/*
26544** Allowed values of unixFile.fsFlags
26545*/
26546#define SQLITE_FSFLAGS_IS_MSDOS     0x1
26547
26548/*
26549** If we are to be thread-safe, include the pthreads header and define
26550** the SQLITE_UNIX_THREADS macro.
26551*/
26552#if SQLITE_THREADSAFE
26553/* # include <pthread.h> */
26554# define SQLITE_UNIX_THREADS 1
26555#endif
26556
26557/*
26558** Default permissions when creating a new file
26559*/
26560#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
26561# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
26562#endif
26563
26564/*
26565** Default permissions when creating auto proxy dir
26566*/
26567#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26568# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
26569#endif
26570
26571/*
26572** Maximum supported path-length.
26573*/
26574#define MAX_PATHNAME 512
26575
26576/* Always cast the getpid() return type for compatibility with
26577** kernel modules in VxWorks. */
26578#define osGetpid(X) (pid_t)getpid()
26579
26580/*
26581** Only set the lastErrno if the error code is a real error and not
26582** a normal expected return code of SQLITE_BUSY or SQLITE_OK
26583*/
26584#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
26585
26586/* Forward references */
26587typedef struct unixShm unixShm;               /* Connection shared memory */
26588typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
26589typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
26590typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
26591
26592/*
26593** Sometimes, after a file handle is closed by SQLite, the file descriptor
26594** cannot be closed immediately. In these cases, instances of the following
26595** structure are used to store the file descriptor while waiting for an
26596** opportunity to either close or reuse it.
26597*/
26598struct UnixUnusedFd {
26599  int fd;                   /* File descriptor to close */
26600  int flags;                /* Flags this file descriptor was opened with */
26601  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
26602};
26603
26604/*
26605** The unixFile structure is subclass of sqlite3_file specific to the unix
26606** VFS implementations.
26607*/
26608typedef struct unixFile unixFile;
26609struct unixFile {
26610  sqlite3_io_methods const *pMethod;  /* Always the first entry */
26611  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
26612  unixInodeInfo *pInode;              /* Info about locks on this inode */
26613  int h;                              /* The file descriptor */
26614  unsigned char eFileLock;            /* The type of lock held on this fd */
26615  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
26616  int lastErrno;                      /* The unix errno from last I/O error */
26617  void *lockingContext;               /* Locking style specific state */
26618  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
26619  const char *zPath;                  /* Name of the file */
26620  unixShm *pShm;                      /* Shared memory segment information */
26621  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
26622#if SQLITE_MAX_MMAP_SIZE>0
26623  int nFetchOut;                      /* Number of outstanding xFetch refs */
26624  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
26625  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
26626  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
26627  void *pMapRegion;                   /* Memory mapped region */
26628#endif
26629#ifdef __QNXNTO__
26630  int sectorSize;                     /* Device sector size */
26631  int deviceCharacteristics;          /* Precomputed device characteristics */
26632#endif
26633#if SQLITE_ENABLE_LOCKING_STYLE
26634  int openFlags;                      /* The flags specified at open() */
26635#endif
26636#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
26637  unsigned fsFlags;                   /* cached details from statfs() */
26638#endif
26639#if OS_VXWORKS
26640  struct vxworksFileId *pId;          /* Unique file ID */
26641#endif
26642#ifdef SQLITE_DEBUG
26643  /* The next group of variables are used to track whether or not the
26644  ** transaction counter in bytes 24-27 of database files are updated
26645  ** whenever any part of the database changes.  An assertion fault will
26646  ** occur if a file is updated without also updating the transaction
26647  ** counter.  This test is made to avoid new problems similar to the
26648  ** one described by ticket #3584.
26649  */
26650  unsigned char transCntrChng;   /* True if the transaction counter changed */
26651  unsigned char dbUpdate;        /* True if any part of database file changed */
26652  unsigned char inNormalWrite;   /* True if in a normal write operation */
26653
26654#endif
26655
26656#ifdef SQLITE_TEST
26657  /* In test mode, increase the size of this structure a bit so that
26658  ** it is larger than the struct CrashFile defined in test6.c.
26659  */
26660  char aPadding[32];
26661#endif
26662};
26663
26664/* This variable holds the process id (pid) from when the xRandomness()
26665** method was called.  If xOpen() is called from a different process id,
26666** indicating that a fork() has occurred, the PRNG will be reset.
26667*/
26668static pid_t randomnessPid = 0;
26669
26670/*
26671** Allowed values for the unixFile.ctrlFlags bitmask:
26672*/
26673#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
26674#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
26675#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
26676#ifndef SQLITE_DISABLE_DIRSYNC
26677# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
26678#else
26679# define UNIXFILE_DIRSYNC    0x00
26680#endif
26681#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
26682#define UNIXFILE_DELETE      0x20     /* Delete on close */
26683#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
26684#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
26685#define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings issued */
26686#define UNIXFILE_BLOCK     0x0200     /* Next SHM lock might block */
26687
26688/*
26689** Include code that is common to all os_*.c files
26690*/
26691/************** Include os_common.h in the middle of os_unix.c ***************/
26692/************** Begin file os_common.h ***************************************/
26693/*
26694** 2004 May 22
26695**
26696** The author disclaims copyright to this source code.  In place of
26697** a legal notice, here is a blessing:
26698**
26699**    May you do good and not evil.
26700**    May you find forgiveness for yourself and forgive others.
26701**    May you share freely, never taking more than you give.
26702**
26703******************************************************************************
26704**
26705** This file contains macros and a little bit of code that is common to
26706** all of the platform-specific files (os_*.c) and is #included into those
26707** files.
26708**
26709** This file should be #included by the os_*.c files only.  It is not a
26710** general purpose header file.
26711*/
26712#ifndef _OS_COMMON_H_
26713#define _OS_COMMON_H_
26714
26715/*
26716** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26717** macro to SQLITE_DEBUG and some older makefiles have not yet made the
26718** switch.  The following code should catch this problem at compile-time.
26719*/
26720#ifdef MEMORY_DEBUG
26721# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
26722#endif
26723
26724/*
26725** Macros for performance tracing.  Normally turned off.  Only works
26726** on i486 hardware.
26727*/
26728#ifdef SQLITE_PERFORMANCE_TRACE
26729
26730/*
26731** hwtime.h contains inline assembler code for implementing
26732** high-performance timing routines.
26733*/
26734/************** Include hwtime.h in the middle of os_common.h ****************/
26735/************** Begin file hwtime.h ******************************************/
26736/*
26737** 2008 May 27
26738**
26739** The author disclaims copyright to this source code.  In place of
26740** a legal notice, here is a blessing:
26741**
26742**    May you do good and not evil.
26743**    May you find forgiveness for yourself and forgive others.
26744**    May you share freely, never taking more than you give.
26745**
26746******************************************************************************
26747**
26748** This file contains inline asm code for retrieving "high-performance"
26749** counters for x86 class CPUs.
26750*/
26751#ifndef _HWTIME_H_
26752#define _HWTIME_H_
26753
26754/*
26755** The following routine only works on pentium-class (or newer) processors.
26756** It uses the RDTSC opcode to read the cycle count value out of the
26757** processor and returns that value.  This can be used for high-res
26758** profiling.
26759*/
26760#if (defined(__GNUC__) || defined(_MSC_VER)) && \
26761      (defined(i386) || defined(__i386__) || defined(_M_IX86))
26762
26763  #if defined(__GNUC__)
26764
26765  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26766     unsigned int lo, hi;
26767     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
26768     return (sqlite_uint64)hi << 32 | lo;
26769  }
26770
26771  #elif defined(_MSC_VER)
26772
26773  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
26774     __asm {
26775        rdtsc
26776        ret       ; return value at EDX:EAX
26777     }
26778  }
26779
26780  #endif
26781
26782#elif (defined(__GNUC__) && defined(__x86_64__))
26783
26784  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26785      unsigned long val;
26786      __asm__ __volatile__ ("rdtsc" : "=A" (val));
26787      return val;
26788  }
26789
26790#elif (defined(__GNUC__) && defined(__ppc__))
26791
26792  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26793      unsigned long long retval;
26794      unsigned long junk;
26795      __asm__ __volatile__ ("\n\
26796          1:      mftbu   %1\n\
26797                  mftb    %L0\n\
26798                  mftbu   %0\n\
26799                  cmpw    %0,%1\n\
26800                  bne     1b"
26801                  : "=r" (retval), "=r" (junk));
26802      return retval;
26803  }
26804
26805#else
26806
26807  #error Need implementation of sqlite3Hwtime() for your platform.
26808
26809  /*
26810  ** To compile without implementing sqlite3Hwtime() for your platform,
26811  ** you can remove the above #error and use the following
26812  ** stub function.  You will lose timing support for many
26813  ** of the debugging and testing utilities, but it should at
26814  ** least compile and run.
26815  */
26816SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
26817
26818#endif
26819
26820#endif /* !defined(_HWTIME_H_) */
26821
26822/************** End of hwtime.h **********************************************/
26823/************** Continuing where we left off in os_common.h ******************/
26824
26825static sqlite_uint64 g_start;
26826static sqlite_uint64 g_elapsed;
26827#define TIMER_START       g_start=sqlite3Hwtime()
26828#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
26829#define TIMER_ELAPSED     g_elapsed
26830#else
26831#define TIMER_START
26832#define TIMER_END
26833#define TIMER_ELAPSED     ((sqlite_uint64)0)
26834#endif
26835
26836/*
26837** If we compile with the SQLITE_TEST macro set, then the following block
26838** of code will give us the ability to simulate a disk I/O error.  This
26839** is used for testing the I/O recovery logic.
26840*/
26841#ifdef SQLITE_TEST
26842SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
26843SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
26844SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
26845SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
26846SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
26847SQLITE_API int sqlite3_diskfull_pending = 0;
26848SQLITE_API int sqlite3_diskfull = 0;
26849#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
26850#define SimulateIOError(CODE)  \
26851  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
26852       || sqlite3_io_error_pending-- == 1 )  \
26853              { local_ioerr(); CODE; }
26854static void local_ioerr(){
26855  IOTRACE(("IOERR\n"));
26856  sqlite3_io_error_hit++;
26857  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
26858}
26859#define SimulateDiskfullError(CODE) \
26860   if( sqlite3_diskfull_pending ){ \
26861     if( sqlite3_diskfull_pending == 1 ){ \
26862       local_ioerr(); \
26863       sqlite3_diskfull = 1; \
26864       sqlite3_io_error_hit = 1; \
26865       CODE; \
26866     }else{ \
26867       sqlite3_diskfull_pending--; \
26868     } \
26869   }
26870#else
26871#define SimulateIOErrorBenign(X)
26872#define SimulateIOError(A)
26873#define SimulateDiskfullError(A)
26874#endif
26875
26876/*
26877** When testing, keep a count of the number of open files.
26878*/
26879#ifdef SQLITE_TEST
26880SQLITE_API int sqlite3_open_file_count = 0;
26881#define OpenCounter(X)  sqlite3_open_file_count+=(X)
26882#else
26883#define OpenCounter(X)
26884#endif
26885
26886#endif /* !defined(_OS_COMMON_H_) */
26887
26888/************** End of os_common.h *******************************************/
26889/************** Continuing where we left off in os_unix.c ********************/
26890
26891/*
26892** Define various macros that are missing from some systems.
26893*/
26894#ifndef O_LARGEFILE
26895# define O_LARGEFILE 0
26896#endif
26897#ifdef SQLITE_DISABLE_LFS
26898# undef O_LARGEFILE
26899# define O_LARGEFILE 0
26900#endif
26901#ifndef O_NOFOLLOW
26902# define O_NOFOLLOW 0
26903#endif
26904#ifndef O_BINARY
26905# define O_BINARY 0
26906#endif
26907
26908/*
26909** The threadid macro resolves to the thread-id or to 0.  Used for
26910** testing and debugging only.
26911*/
26912#if SQLITE_THREADSAFE
26913#define threadid pthread_self()
26914#else
26915#define threadid 0
26916#endif
26917
26918/*
26919** HAVE_MREMAP defaults to true on Linux and false everywhere else.
26920*/
26921#if !defined(HAVE_MREMAP)
26922# if defined(__linux__) && defined(_GNU_SOURCE)
26923#  define HAVE_MREMAP 1
26924# else
26925#  define HAVE_MREMAP 0
26926# endif
26927#endif
26928
26929/*
26930** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
26931** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
26932*/
26933#ifdef __ANDROID__
26934# define lseek lseek64
26935#endif
26936
26937/*
26938** Different Unix systems declare open() in different ways.  Same use
26939** open(const char*,int,mode_t).  Others use open(const char*,int,...).
26940** The difference is important when using a pointer to the function.
26941**
26942** The safest way to deal with the problem is to always use this wrapper
26943** which always has the same well-defined interface.
26944*/
26945static int posixOpen(const char *zFile, int flags, int mode){
26946  return open(zFile, flags, mode);
26947}
26948
26949/*
26950** On some systems, calls to fchown() will trigger a message in a security
26951** log if they come from non-root processes.  So avoid calling fchown() if
26952** we are not running as root.
26953*/
26954static int posixFchown(int fd, uid_t uid, gid_t gid){
26955#if OS_VXWORKS
26956  return 0;
26957#else
26958  return geteuid() ? 0 : fchown(fd,uid,gid);
26959#endif
26960}
26961
26962/* Forward reference */
26963static int openDirectory(const char*, int*);
26964static int unixGetpagesize(void);
26965
26966/*
26967** Many system calls are accessed through pointer-to-functions so that
26968** they may be overridden at runtime to facilitate fault injection during
26969** testing and sandboxing.  The following array holds the names and pointers
26970** to all overrideable system calls.
26971*/
26972static struct unix_syscall {
26973  const char *zName;            /* Name of the system call */
26974  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
26975  sqlite3_syscall_ptr pDefault; /* Default value */
26976} aSyscall[] = {
26977  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
26978#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
26979
26980  { "close",        (sqlite3_syscall_ptr)close,      0  },
26981#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
26982
26983  { "access",       (sqlite3_syscall_ptr)access,     0  },
26984#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
26985
26986  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
26987#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
26988
26989  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
26990#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
26991
26992/*
26993** The DJGPP compiler environment looks mostly like Unix, but it
26994** lacks the fcntl() system call.  So redefine fcntl() to be something
26995** that always succeeds.  This means that locking does not occur under
26996** DJGPP.  But it is DOS - what did you expect?
26997*/
26998#ifdef __DJGPP__
26999  { "fstat",        0,                 0  },
27000#define osFstat(a,b,c)    0
27001#else
27002  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
27003#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
27004#endif
27005
27006  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
27007#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
27008
27009  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
27010#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
27011
27012  { "read",         (sqlite3_syscall_ptr)read,       0  },
27013#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
27014
27015#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
27016  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
27017#else
27018  { "pread",        (sqlite3_syscall_ptr)0,          0  },
27019#endif
27020#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
27021
27022#if defined(USE_PREAD64)
27023  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
27024#else
27025  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
27026#endif
27027#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
27028
27029  { "write",        (sqlite3_syscall_ptr)write,      0  },
27030#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
27031
27032#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
27033  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
27034#else
27035  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
27036#endif
27037#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
27038                    aSyscall[12].pCurrent)
27039
27040#if defined(USE_PREAD64)
27041  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
27042#else
27043  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
27044#endif
27045#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
27046                    aSyscall[13].pCurrent)
27047
27048  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
27049#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
27050
27051#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27052  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
27053#else
27054  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
27055#endif
27056#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
27057
27058  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
27059#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
27060
27061  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
27062#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
27063
27064  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
27065#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
27066
27067  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
27068#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
27069
27070  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
27071#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
27072
27073#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
27074  { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
27075#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
27076
27077  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
27078#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
27079
27080#if HAVE_MREMAP
27081  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
27082#else
27083  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
27084#endif
27085#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
27086  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
27087#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
27088
27089#endif
27090
27091}; /* End of the overrideable system calls */
27092
27093/*
27094** This is the xSetSystemCall() method of sqlite3_vfs for all of the
27095** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
27096** system call pointer, or SQLITE_NOTFOUND if there is no configurable
27097** system call named zName.
27098*/
27099static int unixSetSystemCall(
27100  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
27101  const char *zName,            /* Name of system call to override */
27102  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
27103){
27104  unsigned int i;
27105  int rc = SQLITE_NOTFOUND;
27106
27107  UNUSED_PARAMETER(pNotUsed);
27108  if( zName==0 ){
27109    /* If no zName is given, restore all system calls to their default
27110    ** settings and return NULL
27111    */
27112    rc = SQLITE_OK;
27113    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27114      if( aSyscall[i].pDefault ){
27115        aSyscall[i].pCurrent = aSyscall[i].pDefault;
27116      }
27117    }
27118  }else{
27119    /* If zName is specified, operate on only the one system call
27120    ** specified.
27121    */
27122    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27123      if( strcmp(zName, aSyscall[i].zName)==0 ){
27124        if( aSyscall[i].pDefault==0 ){
27125          aSyscall[i].pDefault = aSyscall[i].pCurrent;
27126        }
27127        rc = SQLITE_OK;
27128        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
27129        aSyscall[i].pCurrent = pNewFunc;
27130        break;
27131      }
27132    }
27133  }
27134  return rc;
27135}
27136
27137/*
27138** Return the value of a system call.  Return NULL if zName is not a
27139** recognized system call name.  NULL is also returned if the system call
27140** is currently undefined.
27141*/
27142static sqlite3_syscall_ptr unixGetSystemCall(
27143  sqlite3_vfs *pNotUsed,
27144  const char *zName
27145){
27146  unsigned int i;
27147
27148  UNUSED_PARAMETER(pNotUsed);
27149  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27150    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
27151  }
27152  return 0;
27153}
27154
27155/*
27156** Return the name of the first system call after zName.  If zName==NULL
27157** then return the name of the first system call.  Return NULL if zName
27158** is the last system call or if zName is not the name of a valid
27159** system call.
27160*/
27161static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
27162  int i = -1;
27163
27164  UNUSED_PARAMETER(p);
27165  if( zName ){
27166    for(i=0; i<ArraySize(aSyscall)-1; i++){
27167      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
27168    }
27169  }
27170  for(i++; i<ArraySize(aSyscall); i++){
27171    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
27172  }
27173  return 0;
27174}
27175
27176/*
27177** Do not accept any file descriptor less than this value, in order to avoid
27178** opening database file using file descriptors that are commonly used for
27179** standard input, output, and error.
27180*/
27181#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
27182# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
27183#endif
27184
27185/*
27186** Invoke open().  Do so multiple times, until it either succeeds or
27187** fails for some reason other than EINTR.
27188**
27189** If the file creation mode "m" is 0 then set it to the default for
27190** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
27191** 0644) as modified by the system umask.  If m is not 0, then
27192** make the file creation mode be exactly m ignoring the umask.
27193**
27194** The m parameter will be non-zero only when creating -wal, -journal,
27195** and -shm files.  We want those files to have *exactly* the same
27196** permissions as their original database, unadulterated by the umask.
27197** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
27198** transaction crashes and leaves behind hot journals, then any
27199** process that is able to write to the database will also be able to
27200** recover the hot journals.
27201*/
27202static int robust_open(const char *z, int f, mode_t m){
27203  int fd;
27204  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
27205  while(1){
27206#if defined(O_CLOEXEC)
27207    fd = osOpen(z,f|O_CLOEXEC,m2);
27208#else
27209    fd = osOpen(z,f,m2);
27210#endif
27211    if( fd<0 ){
27212      if( errno==EINTR ) continue;
27213      break;
27214    }
27215    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
27216    osClose(fd);
27217    sqlite3_log(SQLITE_WARNING,
27218                "attempt to open \"%s\" as file descriptor %d", z, fd);
27219    fd = -1;
27220    if( osOpen("/dev/null", f, m)<0 ) break;
27221  }
27222  if( fd>=0 ){
27223    if( m!=0 ){
27224      struct stat statbuf;
27225      if( osFstat(fd, &statbuf)==0
27226       && statbuf.st_size==0
27227       && (statbuf.st_mode&0777)!=m
27228      ){
27229        osFchmod(fd, m);
27230      }
27231    }
27232#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
27233    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27234#endif
27235  }
27236  return fd;
27237}
27238
27239/*
27240** Helper functions to obtain and relinquish the global mutex. The
27241** global mutex is used to protect the unixInodeInfo and
27242** vxworksFileId objects used by this file, all of which may be
27243** shared by multiple threads.
27244**
27245** Function unixMutexHeld() is used to assert() that the global mutex
27246** is held when required. This function is only used as part of assert()
27247** statements. e.g.
27248**
27249**   unixEnterMutex()
27250**     assert( unixMutexHeld() );
27251**   unixEnterLeave()
27252*/
27253static void unixEnterMutex(void){
27254  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27255}
27256static void unixLeaveMutex(void){
27257  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27258}
27259#ifdef SQLITE_DEBUG
27260static int unixMutexHeld(void) {
27261  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27262}
27263#endif
27264
27265
27266#ifdef SQLITE_HAVE_OS_TRACE
27267/*
27268** Helper function for printing out trace information from debugging
27269** binaries. This returns the string representation of the supplied
27270** integer lock-type.
27271*/
27272static const char *azFileLock(int eFileLock){
27273  switch( eFileLock ){
27274    case NO_LOCK: return "NONE";
27275    case SHARED_LOCK: return "SHARED";
27276    case RESERVED_LOCK: return "RESERVED";
27277    case PENDING_LOCK: return "PENDING";
27278    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
27279  }
27280  return "ERROR";
27281}
27282#endif
27283
27284#ifdef SQLITE_LOCK_TRACE
27285/*
27286** Print out information about all locking operations.
27287**
27288** This routine is used for troubleshooting locks on multithreaded
27289** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
27290** command-line option on the compiler.  This code is normally
27291** turned off.
27292*/
27293static int lockTrace(int fd, int op, struct flock *p){
27294  char *zOpName, *zType;
27295  int s;
27296  int savedErrno;
27297  if( op==F_GETLK ){
27298    zOpName = "GETLK";
27299  }else if( op==F_SETLK ){
27300    zOpName = "SETLK";
27301  }else{
27302    s = osFcntl(fd, op, p);
27303    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
27304    return s;
27305  }
27306  if( p->l_type==F_RDLCK ){
27307    zType = "RDLCK";
27308  }else if( p->l_type==F_WRLCK ){
27309    zType = "WRLCK";
27310  }else if( p->l_type==F_UNLCK ){
27311    zType = "UNLCK";
27312  }else{
27313    assert( 0 );
27314  }
27315  assert( p->l_whence==SEEK_SET );
27316  s = osFcntl(fd, op, p);
27317  savedErrno = errno;
27318  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
27319     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
27320     (int)p->l_pid, s);
27321  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
27322    struct flock l2;
27323    l2 = *p;
27324    osFcntl(fd, F_GETLK, &l2);
27325    if( l2.l_type==F_RDLCK ){
27326      zType = "RDLCK";
27327    }else if( l2.l_type==F_WRLCK ){
27328      zType = "WRLCK";
27329    }else if( l2.l_type==F_UNLCK ){
27330      zType = "UNLCK";
27331    }else{
27332      assert( 0 );
27333    }
27334    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
27335       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
27336  }
27337  errno = savedErrno;
27338  return s;
27339}
27340#undef osFcntl
27341#define osFcntl lockTrace
27342#endif /* SQLITE_LOCK_TRACE */
27343
27344/*
27345** Retry ftruncate() calls that fail due to EINTR
27346**
27347** All calls to ftruncate() within this file should be made through
27348** this wrapper.  On the Android platform, bypassing the logic below
27349** could lead to a corrupt database.
27350*/
27351static int robust_ftruncate(int h, sqlite3_int64 sz){
27352  int rc;
27353#ifdef __ANDROID__
27354  /* On Android, ftruncate() always uses 32-bit offsets, even if
27355  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
27356  ** truncate a file to any size larger than 2GiB. Silently ignore any
27357  ** such attempts.  */
27358  if( sz>(sqlite3_int64)0x7FFFFFFF ){
27359    rc = SQLITE_OK;
27360  }else
27361#endif
27362  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
27363  return rc;
27364}
27365
27366/*
27367** This routine translates a standard POSIX errno code into something
27368** useful to the clients of the sqlite3 functions.  Specifically, it is
27369** intended to translate a variety of "try again" errors into SQLITE_BUSY
27370** and a variety of "please close the file descriptor NOW" errors into
27371** SQLITE_IOERR
27372**
27373** Errors during initialization of locks, or file system support for locks,
27374** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
27375*/
27376static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
27377  switch (posixError) {
27378#if 0
27379  /* At one point this code was not commented out. In theory, this branch
27380  ** should never be hit, as this function should only be called after
27381  ** a locking-related function (i.e. fcntl()) has returned non-zero with
27382  ** the value of errno as the first argument. Since a system call has failed,
27383  ** errno should be non-zero.
27384  **
27385  ** Despite this, if errno really is zero, we still don't want to return
27386  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
27387  ** propagated back to the caller. Commenting this branch out means errno==0
27388  ** will be handled by the "default:" case below.
27389  */
27390  case 0:
27391    return SQLITE_OK;
27392#endif
27393
27394  case EAGAIN:
27395  case ETIMEDOUT:
27396  case EBUSY:
27397  case EINTR:
27398  case ENOLCK:
27399    /* random NFS retry error, unless during file system support
27400     * introspection, in which it actually means what it says */
27401    return SQLITE_BUSY;
27402
27403  case EACCES:
27404    /* EACCES is like EAGAIN during locking operations, but not any other time*/
27405    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
27406        (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
27407        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
27408        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
27409      return SQLITE_BUSY;
27410    }
27411    /* else fall through */
27412  case EPERM:
27413    return SQLITE_PERM;
27414
27415#if EOPNOTSUPP!=ENOTSUP
27416  case EOPNOTSUPP:
27417    /* something went terribly awry, unless during file system support
27418     * introspection, in which it actually means what it says */
27419#endif
27420#ifdef ENOTSUP
27421  case ENOTSUP:
27422    /* invalid fd, unless during file system support introspection, in which
27423     * it actually means what it says */
27424#endif
27425  case EIO:
27426  case EBADF:
27427  case EINVAL:
27428  case ENOTCONN:
27429  case ENODEV:
27430  case ENXIO:
27431  case ENOENT:
27432#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
27433  case ESTALE:
27434#endif
27435  case ENOSYS:
27436    /* these should force the client to close the file and reconnect */
27437
27438  default:
27439    return sqliteIOErr;
27440  }
27441}
27442
27443
27444/******************************************************************************
27445****************** Begin Unique File ID Utility Used By VxWorks ***************
27446**
27447** On most versions of unix, we can get a unique ID for a file by concatenating
27448** the device number and the inode number.  But this does not work on VxWorks.
27449** On VxWorks, a unique file id must be based on the canonical filename.
27450**
27451** A pointer to an instance of the following structure can be used as a
27452** unique file ID in VxWorks.  Each instance of this structure contains
27453** a copy of the canonical filename.  There is also a reference count.
27454** The structure is reclaimed when the number of pointers to it drops to
27455** zero.
27456**
27457** There are never very many files open at one time and lookups are not
27458** a performance-critical path, so it is sufficient to put these
27459** structures on a linked list.
27460*/
27461struct vxworksFileId {
27462  struct vxworksFileId *pNext;  /* Next in a list of them all */
27463  int nRef;                     /* Number of references to this one */
27464  int nName;                    /* Length of the zCanonicalName[] string */
27465  char *zCanonicalName;         /* Canonical filename */
27466};
27467
27468#if OS_VXWORKS
27469/*
27470** All unique filenames are held on a linked list headed by this
27471** variable:
27472*/
27473static struct vxworksFileId *vxworksFileList = 0;
27474
27475/*
27476** Simplify a filename into its canonical form
27477** by making the following changes:
27478**
27479**  * removing any trailing and duplicate /
27480**  * convert /./ into just /
27481**  * convert /A/../ where A is any simple name into just /
27482**
27483** Changes are made in-place.  Return the new name length.
27484**
27485** The original filename is in z[0..n-1].  Return the number of
27486** characters in the simplified name.
27487*/
27488static int vxworksSimplifyName(char *z, int n){
27489  int i, j;
27490  while( n>1 && z[n-1]=='/' ){ n--; }
27491  for(i=j=0; i<n; i++){
27492    if( z[i]=='/' ){
27493      if( z[i+1]=='/' ) continue;
27494      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
27495        i += 1;
27496        continue;
27497      }
27498      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
27499        while( j>0 && z[j-1]!='/' ){ j--; }
27500        if( j>0 ){ j--; }
27501        i += 2;
27502        continue;
27503      }
27504    }
27505    z[j++] = z[i];
27506  }
27507  z[j] = 0;
27508  return j;
27509}
27510
27511/*
27512** Find a unique file ID for the given absolute pathname.  Return
27513** a pointer to the vxworksFileId object.  This pointer is the unique
27514** file ID.
27515**
27516** The nRef field of the vxworksFileId object is incremented before
27517** the object is returned.  A new vxworksFileId object is created
27518** and added to the global list if necessary.
27519**
27520** If a memory allocation error occurs, return NULL.
27521*/
27522static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
27523  struct vxworksFileId *pNew;         /* search key and new file ID */
27524  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
27525  int n;                              /* Length of zAbsoluteName string */
27526
27527  assert( zAbsoluteName[0]=='/' );
27528  n = (int)strlen(zAbsoluteName);
27529  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
27530  if( pNew==0 ) return 0;
27531  pNew->zCanonicalName = (char*)&pNew[1];
27532  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
27533  n = vxworksSimplifyName(pNew->zCanonicalName, n);
27534
27535  /* Search for an existing entry that matching the canonical name.
27536  ** If found, increment the reference count and return a pointer to
27537  ** the existing file ID.
27538  */
27539  unixEnterMutex();
27540  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
27541    if( pCandidate->nName==n
27542     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
27543    ){
27544       sqlite3_free(pNew);
27545       pCandidate->nRef++;
27546       unixLeaveMutex();
27547       return pCandidate;
27548    }
27549  }
27550
27551  /* No match was found.  We will make a new file ID */
27552  pNew->nRef = 1;
27553  pNew->nName = n;
27554  pNew->pNext = vxworksFileList;
27555  vxworksFileList = pNew;
27556  unixLeaveMutex();
27557  return pNew;
27558}
27559
27560/*
27561** Decrement the reference count on a vxworksFileId object.  Free
27562** the object when the reference count reaches zero.
27563*/
27564static void vxworksReleaseFileId(struct vxworksFileId *pId){
27565  unixEnterMutex();
27566  assert( pId->nRef>0 );
27567  pId->nRef--;
27568  if( pId->nRef==0 ){
27569    struct vxworksFileId **pp;
27570    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
27571    assert( *pp==pId );
27572    *pp = pId->pNext;
27573    sqlite3_free(pId);
27574  }
27575  unixLeaveMutex();
27576}
27577#endif /* OS_VXWORKS */
27578/*************** End of Unique File ID Utility Used By VxWorks ****************
27579******************************************************************************/
27580
27581
27582/******************************************************************************
27583*************************** Posix Advisory Locking ****************************
27584**
27585** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
27586** section 6.5.2.2 lines 483 through 490 specify that when a process
27587** sets or clears a lock, that operation overrides any prior locks set
27588** by the same process.  It does not explicitly say so, but this implies
27589** that it overrides locks set by the same process using a different
27590** file descriptor.  Consider this test case:
27591**
27592**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
27593**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
27594**
27595** Suppose ./file1 and ./file2 are really the same file (because
27596** one is a hard or symbolic link to the other) then if you set
27597** an exclusive lock on fd1, then try to get an exclusive lock
27598** on fd2, it works.  I would have expected the second lock to
27599** fail since there was already a lock on the file due to fd1.
27600** But not so.  Since both locks came from the same process, the
27601** second overrides the first, even though they were on different
27602** file descriptors opened on different file names.
27603**
27604** This means that we cannot use POSIX locks to synchronize file access
27605** among competing threads of the same process.  POSIX locks will work fine
27606** to synchronize access for threads in separate processes, but not
27607** threads within the same process.
27608**
27609** To work around the problem, SQLite has to manage file locks internally
27610** on its own.  Whenever a new database is opened, we have to find the
27611** specific inode of the database file (the inode is determined by the
27612** st_dev and st_ino fields of the stat structure that fstat() fills in)
27613** and check for locks already existing on that inode.  When locks are
27614** created or removed, we have to look at our own internal record of the
27615** locks to see if another thread has previously set a lock on that same
27616** inode.
27617**
27618** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
27619** For VxWorks, we have to use the alternative unique ID system based on
27620** canonical filename and implemented in the previous division.)
27621**
27622** The sqlite3_file structure for POSIX is no longer just an integer file
27623** descriptor.  It is now a structure that holds the integer file
27624** descriptor and a pointer to a structure that describes the internal
27625** locks on the corresponding inode.  There is one locking structure
27626** per inode, so if the same inode is opened twice, both unixFile structures
27627** point to the same locking structure.  The locking structure keeps
27628** a reference count (so we will know when to delete it) and a "cnt"
27629** field that tells us its internal lock status.  cnt==0 means the
27630** file is unlocked.  cnt==-1 means the file has an exclusive lock.
27631** cnt>0 means there are cnt shared locks on the file.
27632**
27633** Any attempt to lock or unlock a file first checks the locking
27634** structure.  The fcntl() system call is only invoked to set a
27635** POSIX lock if the internal lock structure transitions between
27636** a locked and an unlocked state.
27637**
27638** But wait:  there are yet more problems with POSIX advisory locks.
27639**
27640** If you close a file descriptor that points to a file that has locks,
27641** all locks on that file that are owned by the current process are
27642** released.  To work around this problem, each unixInodeInfo object
27643** maintains a count of the number of pending locks on tha inode.
27644** When an attempt is made to close an unixFile, if there are
27645** other unixFile open on the same inode that are holding locks, the call
27646** to close() the file descriptor is deferred until all of the locks clear.
27647** The unixInodeInfo structure keeps a list of file descriptors that need to
27648** be closed and that list is walked (and cleared) when the last lock
27649** clears.
27650**
27651** Yet another problem:  LinuxThreads do not play well with posix locks.
27652**
27653** Many older versions of linux use the LinuxThreads library which is
27654** not posix compliant.  Under LinuxThreads, a lock created by thread
27655** A cannot be modified or overridden by a different thread B.
27656** Only thread A can modify the lock.  Locking behavior is correct
27657** if the appliation uses the newer Native Posix Thread Library (NPTL)
27658** on linux - with NPTL a lock created by thread A can override locks
27659** in thread B.  But there is no way to know at compile-time which
27660** threading library is being used.  So there is no way to know at
27661** compile-time whether or not thread A can override locks on thread B.
27662** One has to do a run-time check to discover the behavior of the
27663** current process.
27664**
27665** SQLite used to support LinuxThreads.  But support for LinuxThreads
27666** was dropped beginning with version 3.7.0.  SQLite will still work with
27667** LinuxThreads provided that (1) there is no more than one connection
27668** per database file in the same process and (2) database connections
27669** do not move across threads.
27670*/
27671
27672/*
27673** An instance of the following structure serves as the key used
27674** to locate a particular unixInodeInfo object.
27675*/
27676struct unixFileId {
27677  dev_t dev;                  /* Device number */
27678#if OS_VXWORKS
27679  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
27680#else
27681  ino_t ino;                  /* Inode number */
27682#endif
27683};
27684
27685/*
27686** An instance of the following structure is allocated for each open
27687** inode.  Or, on LinuxThreads, there is one of these structures for
27688** each inode opened by each thread.
27689**
27690** A single inode can have multiple file descriptors, so each unixFile
27691** structure contains a pointer to an instance of this object and this
27692** object keeps a count of the number of unixFile pointing to it.
27693*/
27694struct unixInodeInfo {
27695  struct unixFileId fileId;       /* The lookup key */
27696  int nShared;                    /* Number of SHARED locks held */
27697  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
27698  unsigned char bProcessLock;     /* An exclusive process lock is held */
27699  int nRef;                       /* Number of pointers to this structure */
27700  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
27701  int nLock;                      /* Number of outstanding file locks */
27702  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
27703  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
27704  unixInodeInfo *pPrev;           /*    .... doubly linked */
27705#if SQLITE_ENABLE_LOCKING_STYLE
27706  unsigned long long sharedByte;  /* for AFP simulated shared lock */
27707#endif
27708#if OS_VXWORKS
27709  sem_t *pSem;                    /* Named POSIX semaphore */
27710  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
27711#endif
27712};
27713
27714/*
27715** A lists of all unixInodeInfo objects.
27716*/
27717static unixInodeInfo *inodeList = 0;
27718
27719/*
27720**
27721** This function - unixLogError_x(), is only ever called via the macro
27722** unixLogError().
27723**
27724** It is invoked after an error occurs in an OS function and errno has been
27725** set. It logs a message using sqlite3_log() containing the current value of
27726** errno and, if possible, the human-readable equivalent from strerror() or
27727** strerror_r().
27728**
27729** The first argument passed to the macro should be the error code that
27730** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
27731** The two subsequent arguments should be the name of the OS function that
27732** failed (e.g. "unlink", "open") and the associated file-system path,
27733** if any.
27734*/
27735#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
27736static int unixLogErrorAtLine(
27737  int errcode,                    /* SQLite error code */
27738  const char *zFunc,              /* Name of OS function that failed */
27739  const char *zPath,              /* File path associated with error */
27740  int iLine                       /* Source line number where error occurred */
27741){
27742  char *zErr;                     /* Message from strerror() or equivalent */
27743  int iErrno = errno;             /* Saved syscall error number */
27744
27745  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
27746  ** the strerror() function to obtain the human-readable error message
27747  ** equivalent to errno. Otherwise, use strerror_r().
27748  */
27749#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
27750  char aErr[80];
27751  memset(aErr, 0, sizeof(aErr));
27752  zErr = aErr;
27753
27754  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
27755  ** assume that the system provides the GNU version of strerror_r() that
27756  ** returns a pointer to a buffer containing the error message. That pointer
27757  ** may point to aErr[], or it may point to some static storage somewhere.
27758  ** Otherwise, assume that the system provides the POSIX version of
27759  ** strerror_r(), which always writes an error message into aErr[].
27760  **
27761  ** If the code incorrectly assumes that it is the POSIX version that is
27762  ** available, the error message will often be an empty string. Not a
27763  ** huge problem. Incorrectly concluding that the GNU version is available
27764  ** could lead to a segfault though.
27765  */
27766#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
27767  zErr =
27768# endif
27769  strerror_r(iErrno, aErr, sizeof(aErr)-1);
27770
27771#elif SQLITE_THREADSAFE
27772  /* This is a threadsafe build, but strerror_r() is not available. */
27773  zErr = "";
27774#else
27775  /* Non-threadsafe build, use strerror(). */
27776  zErr = strerror(iErrno);
27777#endif
27778
27779  if( zPath==0 ) zPath = "";
27780  sqlite3_log(errcode,
27781      "os_unix.c:%d: (%d) %s(%s) - %s",
27782      iLine, iErrno, zFunc, zPath, zErr
27783  );
27784
27785  return errcode;
27786}
27787
27788/*
27789** Close a file descriptor.
27790**
27791** We assume that close() almost always works, since it is only in a
27792** very sick application or on a very sick platform that it might fail.
27793** If it does fail, simply leak the file descriptor, but do log the
27794** error.
27795**
27796** Note that it is not safe to retry close() after EINTR since the
27797** file descriptor might have already been reused by another thread.
27798** So we don't even try to recover from an EINTR.  Just log the error
27799** and move on.
27800*/
27801static void robust_close(unixFile *pFile, int h, int lineno){
27802  if( osClose(h) ){
27803    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
27804                       pFile ? pFile->zPath : 0, lineno);
27805  }
27806}
27807
27808/*
27809** Set the pFile->lastErrno.  Do this in a subroutine as that provides
27810** a convenient place to set a breakpoint.
27811*/
27812static void storeLastErrno(unixFile *pFile, int error){
27813  pFile->lastErrno = error;
27814}
27815
27816/*
27817** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
27818*/
27819static void closePendingFds(unixFile *pFile){
27820  unixInodeInfo *pInode = pFile->pInode;
27821  UnixUnusedFd *p;
27822  UnixUnusedFd *pNext;
27823  for(p=pInode->pUnused; p; p=pNext){
27824    pNext = p->pNext;
27825    robust_close(pFile, p->fd, __LINE__);
27826    sqlite3_free(p);
27827  }
27828  pInode->pUnused = 0;
27829}
27830
27831/*
27832** Release a unixInodeInfo structure previously allocated by findInodeInfo().
27833**
27834** The mutex entered using the unixEnterMutex() function must be held
27835** when this function is called.
27836*/
27837static void releaseInodeInfo(unixFile *pFile){
27838  unixInodeInfo *pInode = pFile->pInode;
27839  assert( unixMutexHeld() );
27840  if( ALWAYS(pInode) ){
27841    pInode->nRef--;
27842    if( pInode->nRef==0 ){
27843      assert( pInode->pShmNode==0 );
27844      closePendingFds(pFile);
27845      if( pInode->pPrev ){
27846        assert( pInode->pPrev->pNext==pInode );
27847        pInode->pPrev->pNext = pInode->pNext;
27848      }else{
27849        assert( inodeList==pInode );
27850        inodeList = pInode->pNext;
27851      }
27852      if( pInode->pNext ){
27853        assert( pInode->pNext->pPrev==pInode );
27854        pInode->pNext->pPrev = pInode->pPrev;
27855      }
27856      sqlite3_free(pInode);
27857    }
27858  }
27859}
27860
27861/*
27862** Given a file descriptor, locate the unixInodeInfo object that
27863** describes that file descriptor.  Create a new one if necessary.  The
27864** return value might be uninitialized if an error occurs.
27865**
27866** The mutex entered using the unixEnterMutex() function must be held
27867** when this function is called.
27868**
27869** Return an appropriate error code.
27870*/
27871static int findInodeInfo(
27872  unixFile *pFile,               /* Unix file with file desc used in the key */
27873  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
27874){
27875  int rc;                        /* System call return code */
27876  int fd;                        /* The file descriptor for pFile */
27877  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
27878  struct stat statbuf;           /* Low-level file information */
27879  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
27880
27881  assert( unixMutexHeld() );
27882
27883  /* Get low-level information about the file that we can used to
27884  ** create a unique name for the file.
27885  */
27886  fd = pFile->h;
27887  rc = osFstat(fd, &statbuf);
27888  if( rc!=0 ){
27889    storeLastErrno(pFile, errno);
27890#ifdef EOVERFLOW
27891    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
27892#endif
27893    return SQLITE_IOERR;
27894  }
27895
27896#ifdef __APPLE__
27897  /* On OS X on an msdos filesystem, the inode number is reported
27898  ** incorrectly for zero-size files.  See ticket #3260.  To work
27899  ** around this problem (we consider it a bug in OS X, not SQLite)
27900  ** we always increase the file size to 1 by writing a single byte
27901  ** prior to accessing the inode number.  The one byte written is
27902  ** an ASCII 'S' character which also happens to be the first byte
27903  ** in the header of every SQLite database.  In this way, if there
27904  ** is a race condition such that another thread has already populated
27905  ** the first page of the database, no damage is done.
27906  */
27907  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
27908    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
27909    if( rc!=1 ){
27910      storeLastErrno(pFile, errno);
27911      return SQLITE_IOERR;
27912    }
27913    rc = osFstat(fd, &statbuf);
27914    if( rc!=0 ){
27915      storeLastErrno(pFile, errno);
27916      return SQLITE_IOERR;
27917    }
27918  }
27919#endif
27920
27921  memset(&fileId, 0, sizeof(fileId));
27922  fileId.dev = statbuf.st_dev;
27923#if OS_VXWORKS
27924  fileId.pId = pFile->pId;
27925#else
27926  fileId.ino = statbuf.st_ino;
27927#endif
27928  pInode = inodeList;
27929  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
27930    pInode = pInode->pNext;
27931  }
27932  if( pInode==0 ){
27933    pInode = sqlite3_malloc64( sizeof(*pInode) );
27934    if( pInode==0 ){
27935      return SQLITE_NOMEM;
27936    }
27937    memset(pInode, 0, sizeof(*pInode));
27938    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
27939    pInode->nRef = 1;
27940    pInode->pNext = inodeList;
27941    pInode->pPrev = 0;
27942    if( inodeList ) inodeList->pPrev = pInode;
27943    inodeList = pInode;
27944  }else{
27945    pInode->nRef++;
27946  }
27947  *ppInode = pInode;
27948  return SQLITE_OK;
27949}
27950
27951/*
27952** Return TRUE if pFile has been renamed or unlinked since it was first opened.
27953*/
27954static int fileHasMoved(unixFile *pFile){
27955#if OS_VXWORKS
27956  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
27957#else
27958  struct stat buf;
27959  return pFile->pInode!=0 &&
27960      (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
27961#endif
27962}
27963
27964
27965/*
27966** Check a unixFile that is a database.  Verify the following:
27967**
27968** (1) There is exactly one hard link on the file
27969** (2) The file is not a symbolic link
27970** (3) The file has not been renamed or unlinked
27971**
27972** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
27973*/
27974static void verifyDbFile(unixFile *pFile){
27975  struct stat buf;
27976  int rc;
27977  if( pFile->ctrlFlags & UNIXFILE_WARNED ){
27978    /* One or more of the following warnings have already been issued.  Do not
27979    ** repeat them so as not to clutter the error log */
27980    return;
27981  }
27982  rc = osFstat(pFile->h, &buf);
27983  if( rc!=0 ){
27984    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
27985    pFile->ctrlFlags |= UNIXFILE_WARNED;
27986    return;
27987  }
27988  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
27989    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
27990    pFile->ctrlFlags |= UNIXFILE_WARNED;
27991    return;
27992  }
27993  if( buf.st_nlink>1 ){
27994    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
27995    pFile->ctrlFlags |= UNIXFILE_WARNED;
27996    return;
27997  }
27998  if( fileHasMoved(pFile) ){
27999    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
28000    pFile->ctrlFlags |= UNIXFILE_WARNED;
28001    return;
28002  }
28003}
28004
28005
28006/*
28007** This routine checks if there is a RESERVED lock held on the specified
28008** file by this or any other process. If such a lock is held, set *pResOut
28009** to a non-zero value otherwise *pResOut is set to zero.  The return value
28010** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28011*/
28012static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
28013  int rc = SQLITE_OK;
28014  int reserved = 0;
28015  unixFile *pFile = (unixFile*)id;
28016
28017  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28018
28019  assert( pFile );
28020  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
28021
28022  /* Check if a thread in this process holds such a lock */
28023  if( pFile->pInode->eFileLock>SHARED_LOCK ){
28024    reserved = 1;
28025  }
28026
28027  /* Otherwise see if some other process holds it.
28028  */
28029#ifndef __DJGPP__
28030  if( !reserved && !pFile->pInode->bProcessLock ){
28031    struct flock lock;
28032    lock.l_whence = SEEK_SET;
28033    lock.l_start = RESERVED_BYTE;
28034    lock.l_len = 1;
28035    lock.l_type = F_WRLCK;
28036    if( osFcntl(pFile->h, F_GETLK, &lock) ){
28037      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
28038      storeLastErrno(pFile, errno);
28039    } else if( lock.l_type!=F_UNLCK ){
28040      reserved = 1;
28041    }
28042  }
28043#endif
28044
28045  unixLeaveMutex();
28046  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
28047
28048  *pResOut = reserved;
28049  return rc;
28050}
28051
28052/*
28053** Attempt to set a system-lock on the file pFile.  The lock is
28054** described by pLock.
28055**
28056** If the pFile was opened read/write from unix-excl, then the only lock
28057** ever obtained is an exclusive lock, and it is obtained exactly once
28058** the first time any lock is attempted.  All subsequent system locking
28059** operations become no-ops.  Locking operations still happen internally,
28060** in order to coordinate access between separate database connections
28061** within this process, but all of that is handled in memory and the
28062** operating system does not participate.
28063**
28064** This function is a pass-through to fcntl(F_SETLK) if pFile is using
28065** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
28066** and is read-only.
28067**
28068** Zero is returned if the call completes successfully, or -1 if a call
28069** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
28070*/
28071static int unixFileLock(unixFile *pFile, struct flock *pLock){
28072  int rc;
28073  unixInodeInfo *pInode = pFile->pInode;
28074  assert( unixMutexHeld() );
28075  assert( pInode!=0 );
28076  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
28077   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
28078  ){
28079    if( pInode->bProcessLock==0 ){
28080      struct flock lock;
28081      assert( pInode->nLock==0 );
28082      lock.l_whence = SEEK_SET;
28083      lock.l_start = SHARED_FIRST;
28084      lock.l_len = SHARED_SIZE;
28085      lock.l_type = F_WRLCK;
28086      rc = osFcntl(pFile->h, F_SETLK, &lock);
28087      if( rc<0 ) return rc;
28088      pInode->bProcessLock = 1;
28089      pInode->nLock++;
28090    }else{
28091      rc = 0;
28092    }
28093  }else{
28094    rc = osFcntl(pFile->h, F_SETLK, pLock);
28095  }
28096  return rc;
28097}
28098
28099/*
28100** Lock the file with the lock specified by parameter eFileLock - one
28101** of the following:
28102**
28103**     (1) SHARED_LOCK
28104**     (2) RESERVED_LOCK
28105**     (3) PENDING_LOCK
28106**     (4) EXCLUSIVE_LOCK
28107**
28108** Sometimes when requesting one lock state, additional lock states
28109** are inserted in between.  The locking might fail on one of the later
28110** transitions leaving the lock state different from what it started but
28111** still short of its goal.  The following chart shows the allowed
28112** transitions and the inserted intermediate states:
28113**
28114**    UNLOCKED -> SHARED
28115**    SHARED -> RESERVED
28116**    SHARED -> (PENDING) -> EXCLUSIVE
28117**    RESERVED -> (PENDING) -> EXCLUSIVE
28118**    PENDING -> EXCLUSIVE
28119**
28120** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28121** routine to lower a locking level.
28122*/
28123static int unixLock(sqlite3_file *id, int eFileLock){
28124  /* The following describes the implementation of the various locks and
28125  ** lock transitions in terms of the POSIX advisory shared and exclusive
28126  ** lock primitives (called read-locks and write-locks below, to avoid
28127  ** confusion with SQLite lock names). The algorithms are complicated
28128  ** slightly in order to be compatible with windows systems simultaneously
28129  ** accessing the same database file, in case that is ever required.
28130  **
28131  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
28132  ** byte', each single bytes at well known offsets, and the 'shared byte
28133  ** range', a range of 510 bytes at a well known offset.
28134  **
28135  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
28136  ** byte'.  If this is successful, a random byte from the 'shared byte
28137  ** range' is read-locked and the lock on the 'pending byte' released.
28138  **
28139  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
28140  ** A RESERVED lock is implemented by grabbing a write-lock on the
28141  ** 'reserved byte'.
28142  **
28143  ** A process may only obtain a PENDING lock after it has obtained a
28144  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
28145  ** on the 'pending byte'. This ensures that no new SHARED locks can be
28146  ** obtained, but existing SHARED locks are allowed to persist. A process
28147  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
28148  ** This property is used by the algorithm for rolling back a journal file
28149  ** after a crash.
28150  **
28151  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
28152  ** implemented by obtaining a write-lock on the entire 'shared byte
28153  ** range'. Since all other locks require a read-lock on one of the bytes
28154  ** within this range, this ensures that no other locks are held on the
28155  ** database.
28156  **
28157  ** The reason a single byte cannot be used instead of the 'shared byte
28158  ** range' is that some versions of windows do not support read-locks. By
28159  ** locking a random byte from a range, concurrent SHARED locks may exist
28160  ** even if the locking primitive used is always a write-lock.
28161  */
28162  int rc = SQLITE_OK;
28163  unixFile *pFile = (unixFile*)id;
28164  unixInodeInfo *pInode;
28165  struct flock lock;
28166  int tErrno = 0;
28167
28168  assert( pFile );
28169  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
28170      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28171      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
28172      osGetpid(0)));
28173
28174  /* If there is already a lock of this type or more restrictive on the
28175  ** unixFile, do nothing. Don't use the end_lock: exit path, as
28176  ** unixEnterMutex() hasn't been called yet.
28177  */
28178  if( pFile->eFileLock>=eFileLock ){
28179    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
28180            azFileLock(eFileLock)));
28181    return SQLITE_OK;
28182  }
28183
28184  /* Make sure the locking sequence is correct.
28185  **  (1) We never move from unlocked to anything higher than shared lock.
28186  **  (2) SQLite never explicitly requests a pendig lock.
28187  **  (3) A shared lock is always held when a reserve lock is requested.
28188  */
28189  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28190  assert( eFileLock!=PENDING_LOCK );
28191  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28192
28193  /* This mutex is needed because pFile->pInode is shared across threads
28194  */
28195  unixEnterMutex();
28196  pInode = pFile->pInode;
28197
28198  /* If some thread using this PID has a lock via a different unixFile*
28199  ** handle that precludes the requested lock, return BUSY.
28200  */
28201  if( (pFile->eFileLock!=pInode->eFileLock &&
28202          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28203  ){
28204    rc = SQLITE_BUSY;
28205    goto end_lock;
28206  }
28207
28208  /* If a SHARED lock is requested, and some thread using this PID already
28209  ** has a SHARED or RESERVED lock, then increment reference counts and
28210  ** return SQLITE_OK.
28211  */
28212  if( eFileLock==SHARED_LOCK &&
28213      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28214    assert( eFileLock==SHARED_LOCK );
28215    assert( pFile->eFileLock==0 );
28216    assert( pInode->nShared>0 );
28217    pFile->eFileLock = SHARED_LOCK;
28218    pInode->nShared++;
28219    pInode->nLock++;
28220    goto end_lock;
28221  }
28222
28223
28224  /* A PENDING lock is needed before acquiring a SHARED lock and before
28225  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28226  ** be released.
28227  */
28228  lock.l_len = 1L;
28229  lock.l_whence = SEEK_SET;
28230  if( eFileLock==SHARED_LOCK
28231      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28232  ){
28233    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
28234    lock.l_start = PENDING_BYTE;
28235    if( unixFileLock(pFile, &lock) ){
28236      tErrno = errno;
28237      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28238      if( rc!=SQLITE_BUSY ){
28239        storeLastErrno(pFile, tErrno);
28240      }
28241      goto end_lock;
28242    }
28243  }
28244
28245
28246  /* If control gets to this point, then actually go ahead and make
28247  ** operating system calls for the specified lock.
28248  */
28249  if( eFileLock==SHARED_LOCK ){
28250    assert( pInode->nShared==0 );
28251    assert( pInode->eFileLock==0 );
28252    assert( rc==SQLITE_OK );
28253
28254    /* Now get the read-lock */
28255    lock.l_start = SHARED_FIRST;
28256    lock.l_len = SHARED_SIZE;
28257    if( unixFileLock(pFile, &lock) ){
28258      tErrno = errno;
28259      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28260    }
28261
28262    /* Drop the temporary PENDING lock */
28263    lock.l_start = PENDING_BYTE;
28264    lock.l_len = 1L;
28265    lock.l_type = F_UNLCK;
28266    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
28267      /* This could happen with a network mount */
28268      tErrno = errno;
28269      rc = SQLITE_IOERR_UNLOCK;
28270    }
28271
28272    if( rc ){
28273      if( rc!=SQLITE_BUSY ){
28274        storeLastErrno(pFile, tErrno);
28275      }
28276      goto end_lock;
28277    }else{
28278      pFile->eFileLock = SHARED_LOCK;
28279      pInode->nLock++;
28280      pInode->nShared = 1;
28281    }
28282  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28283    /* We are trying for an exclusive lock but another thread in this
28284    ** same process is still holding a shared lock. */
28285    rc = SQLITE_BUSY;
28286  }else{
28287    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28288    ** assumed that there is a SHARED or greater lock on the file
28289    ** already.
28290    */
28291    assert( 0!=pFile->eFileLock );
28292    lock.l_type = F_WRLCK;
28293
28294    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
28295    if( eFileLock==RESERVED_LOCK ){
28296      lock.l_start = RESERVED_BYTE;
28297      lock.l_len = 1L;
28298    }else{
28299      lock.l_start = SHARED_FIRST;
28300      lock.l_len = SHARED_SIZE;
28301    }
28302
28303    if( unixFileLock(pFile, &lock) ){
28304      tErrno = errno;
28305      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28306      if( rc!=SQLITE_BUSY ){
28307        storeLastErrno(pFile, tErrno);
28308      }
28309    }
28310  }
28311
28312
28313#ifdef SQLITE_DEBUG
28314  /* Set up the transaction-counter change checking flags when
28315  ** transitioning from a SHARED to a RESERVED lock.  The change
28316  ** from SHARED to RESERVED marks the beginning of a normal
28317  ** write operation (not a hot journal rollback).
28318  */
28319  if( rc==SQLITE_OK
28320   && pFile->eFileLock<=SHARED_LOCK
28321   && eFileLock==RESERVED_LOCK
28322  ){
28323    pFile->transCntrChng = 0;
28324    pFile->dbUpdate = 0;
28325    pFile->inNormalWrite = 1;
28326  }
28327#endif
28328
28329
28330  if( rc==SQLITE_OK ){
28331    pFile->eFileLock = eFileLock;
28332    pInode->eFileLock = eFileLock;
28333  }else if( eFileLock==EXCLUSIVE_LOCK ){
28334    pFile->eFileLock = PENDING_LOCK;
28335    pInode->eFileLock = PENDING_LOCK;
28336  }
28337
28338end_lock:
28339  unixLeaveMutex();
28340  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
28341      rc==SQLITE_OK ? "ok" : "failed"));
28342  return rc;
28343}
28344
28345/*
28346** Add the file descriptor used by file handle pFile to the corresponding
28347** pUnused list.
28348*/
28349static void setPendingFd(unixFile *pFile){
28350  unixInodeInfo *pInode = pFile->pInode;
28351  UnixUnusedFd *p = pFile->pUnused;
28352  p->pNext = pInode->pUnused;
28353  pInode->pUnused = p;
28354  pFile->h = -1;
28355  pFile->pUnused = 0;
28356}
28357
28358/*
28359** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28360** must be either NO_LOCK or SHARED_LOCK.
28361**
28362** If the locking level of the file descriptor is already at or below
28363** the requested locking level, this routine is a no-op.
28364**
28365** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
28366** the byte range is divided into 2 parts and the first part is unlocked then
28367** set to a read lock, then the other part is simply unlocked.  This works
28368** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
28369** remove the write lock on a region when a read lock is set.
28370*/
28371static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
28372  unixFile *pFile = (unixFile*)id;
28373  unixInodeInfo *pInode;
28374  struct flock lock;
28375  int rc = SQLITE_OK;
28376
28377  assert( pFile );
28378  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
28379      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28380      osGetpid(0)));
28381
28382  assert( eFileLock<=SHARED_LOCK );
28383  if( pFile->eFileLock<=eFileLock ){
28384    return SQLITE_OK;
28385  }
28386  unixEnterMutex();
28387  pInode = pFile->pInode;
28388  assert( pInode->nShared!=0 );
28389  if( pFile->eFileLock>SHARED_LOCK ){
28390    assert( pInode->eFileLock==pFile->eFileLock );
28391
28392#ifdef SQLITE_DEBUG
28393    /* When reducing a lock such that other processes can start
28394    ** reading the database file again, make sure that the
28395    ** transaction counter was updated if any part of the database
28396    ** file changed.  If the transaction counter is not updated,
28397    ** other connections to the same file might not realize that
28398    ** the file has changed and hence might not know to flush their
28399    ** cache.  The use of a stale cache can lead to database corruption.
28400    */
28401    pFile->inNormalWrite = 0;
28402#endif
28403
28404    /* downgrading to a shared lock on NFS involves clearing the write lock
28405    ** before establishing the readlock - to avoid a race condition we downgrade
28406    ** the lock in 2 blocks, so that part of the range will be covered by a
28407    ** write lock until the rest is covered by a read lock:
28408    **  1:   [WWWWW]
28409    **  2:   [....W]
28410    **  3:   [RRRRW]
28411    **  4:   [RRRR.]
28412    */
28413    if( eFileLock==SHARED_LOCK ){
28414#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
28415      (void)handleNFSUnlock;
28416      assert( handleNFSUnlock==0 );
28417#endif
28418#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28419      if( handleNFSUnlock ){
28420        int tErrno;               /* Error code from system call errors */
28421        off_t divSize = SHARED_SIZE - 1;
28422
28423        lock.l_type = F_UNLCK;
28424        lock.l_whence = SEEK_SET;
28425        lock.l_start = SHARED_FIRST;
28426        lock.l_len = divSize;
28427        if( unixFileLock(pFile, &lock)==(-1) ){
28428          tErrno = errno;
28429          rc = SQLITE_IOERR_UNLOCK;
28430          if( IS_LOCK_ERROR(rc) ){
28431            storeLastErrno(pFile, tErrno);
28432          }
28433          goto end_unlock;
28434        }
28435        lock.l_type = F_RDLCK;
28436        lock.l_whence = SEEK_SET;
28437        lock.l_start = SHARED_FIRST;
28438        lock.l_len = divSize;
28439        if( unixFileLock(pFile, &lock)==(-1) ){
28440          tErrno = errno;
28441          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
28442          if( IS_LOCK_ERROR(rc) ){
28443            storeLastErrno(pFile, tErrno);
28444          }
28445          goto end_unlock;
28446        }
28447        lock.l_type = F_UNLCK;
28448        lock.l_whence = SEEK_SET;
28449        lock.l_start = SHARED_FIRST+divSize;
28450        lock.l_len = SHARED_SIZE-divSize;
28451        if( unixFileLock(pFile, &lock)==(-1) ){
28452          tErrno = errno;
28453          rc = SQLITE_IOERR_UNLOCK;
28454          if( IS_LOCK_ERROR(rc) ){
28455            storeLastErrno(pFile, tErrno);
28456          }
28457          goto end_unlock;
28458        }
28459      }else
28460#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28461      {
28462        lock.l_type = F_RDLCK;
28463        lock.l_whence = SEEK_SET;
28464        lock.l_start = SHARED_FIRST;
28465        lock.l_len = SHARED_SIZE;
28466        if( unixFileLock(pFile, &lock) ){
28467          /* In theory, the call to unixFileLock() cannot fail because another
28468          ** process is holding an incompatible lock. If it does, this
28469          ** indicates that the other process is not following the locking
28470          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
28471          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
28472          ** an assert to fail). */
28473          rc = SQLITE_IOERR_RDLOCK;
28474          storeLastErrno(pFile, errno);
28475          goto end_unlock;
28476        }
28477      }
28478    }
28479    lock.l_type = F_UNLCK;
28480    lock.l_whence = SEEK_SET;
28481    lock.l_start = PENDING_BYTE;
28482    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
28483    if( unixFileLock(pFile, &lock)==0 ){
28484      pInode->eFileLock = SHARED_LOCK;
28485    }else{
28486      rc = SQLITE_IOERR_UNLOCK;
28487      storeLastErrno(pFile, errno);
28488      goto end_unlock;
28489    }
28490  }
28491  if( eFileLock==NO_LOCK ){
28492    /* Decrement the shared lock counter.  Release the lock using an
28493    ** OS call only when all threads in this same process have released
28494    ** the lock.
28495    */
28496    pInode->nShared--;
28497    if( pInode->nShared==0 ){
28498      lock.l_type = F_UNLCK;
28499      lock.l_whence = SEEK_SET;
28500      lock.l_start = lock.l_len = 0L;
28501      if( unixFileLock(pFile, &lock)==0 ){
28502        pInode->eFileLock = NO_LOCK;
28503      }else{
28504        rc = SQLITE_IOERR_UNLOCK;
28505        storeLastErrno(pFile, errno);
28506        pInode->eFileLock = NO_LOCK;
28507        pFile->eFileLock = NO_LOCK;
28508      }
28509    }
28510
28511    /* Decrement the count of locks against this same file.  When the
28512    ** count reaches zero, close any other file descriptors whose close
28513    ** was deferred because of outstanding locks.
28514    */
28515    pInode->nLock--;
28516    assert( pInode->nLock>=0 );
28517    if( pInode->nLock==0 ){
28518      closePendingFds(pFile);
28519    }
28520  }
28521
28522end_unlock:
28523  unixLeaveMutex();
28524  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28525  return rc;
28526}
28527
28528/*
28529** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28530** must be either NO_LOCK or SHARED_LOCK.
28531**
28532** If the locking level of the file descriptor is already at or below
28533** the requested locking level, this routine is a no-op.
28534*/
28535static int unixUnlock(sqlite3_file *id, int eFileLock){
28536#if SQLITE_MAX_MMAP_SIZE>0
28537  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
28538#endif
28539  return posixUnlock(id, eFileLock, 0);
28540}
28541
28542#if SQLITE_MAX_MMAP_SIZE>0
28543static int unixMapfile(unixFile *pFd, i64 nByte);
28544static void unixUnmapfile(unixFile *pFd);
28545#endif
28546
28547/*
28548** This function performs the parts of the "close file" operation
28549** common to all locking schemes. It closes the directory and file
28550** handles, if they are valid, and sets all fields of the unixFile
28551** structure to 0.
28552**
28553** It is *not* necessary to hold the mutex when this routine is called,
28554** even on VxWorks.  A mutex will be acquired on VxWorks by the
28555** vxworksReleaseFileId() routine.
28556*/
28557static int closeUnixFile(sqlite3_file *id){
28558  unixFile *pFile = (unixFile*)id;
28559#if SQLITE_MAX_MMAP_SIZE>0
28560  unixUnmapfile(pFile);
28561#endif
28562  if( pFile->h>=0 ){
28563    robust_close(pFile, pFile->h, __LINE__);
28564    pFile->h = -1;
28565  }
28566#if OS_VXWORKS
28567  if( pFile->pId ){
28568    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
28569      osUnlink(pFile->pId->zCanonicalName);
28570    }
28571    vxworksReleaseFileId(pFile->pId);
28572    pFile->pId = 0;
28573  }
28574#endif
28575#ifdef SQLITE_UNLINK_AFTER_CLOSE
28576  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
28577    osUnlink(pFile->zPath);
28578    sqlite3_free(*(char**)&pFile->zPath);
28579    pFile->zPath = 0;
28580  }
28581#endif
28582  OSTRACE(("CLOSE   %-3d\n", pFile->h));
28583  OpenCounter(-1);
28584  sqlite3_free(pFile->pUnused);
28585  memset(pFile, 0, sizeof(unixFile));
28586  return SQLITE_OK;
28587}
28588
28589/*
28590** Close a file.
28591*/
28592static int unixClose(sqlite3_file *id){
28593  int rc = SQLITE_OK;
28594  unixFile *pFile = (unixFile *)id;
28595  verifyDbFile(pFile);
28596  unixUnlock(id, NO_LOCK);
28597  unixEnterMutex();
28598
28599  /* unixFile.pInode is always valid here. Otherwise, a different close
28600  ** routine (e.g. nolockClose()) would be called instead.
28601  */
28602  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
28603  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
28604    /* If there are outstanding locks, do not actually close the file just
28605    ** yet because that would clear those locks.  Instead, add the file
28606    ** descriptor to pInode->pUnused list.  It will be automatically closed
28607    ** when the last lock is cleared.
28608    */
28609    setPendingFd(pFile);
28610  }
28611  releaseInodeInfo(pFile);
28612  rc = closeUnixFile(id);
28613  unixLeaveMutex();
28614  return rc;
28615}
28616
28617/************** End of the posix advisory lock implementation *****************
28618******************************************************************************/
28619
28620/******************************************************************************
28621****************************** No-op Locking **********************************
28622**
28623** Of the various locking implementations available, this is by far the
28624** simplest:  locking is ignored.  No attempt is made to lock the database
28625** file for reading or writing.
28626**
28627** This locking mode is appropriate for use on read-only databases
28628** (ex: databases that are burned into CD-ROM, for example.)  It can
28629** also be used if the application employs some external mechanism to
28630** prevent simultaneous access of the same database by two or more
28631** database connections.  But there is a serious risk of database
28632** corruption if this locking mode is used in situations where multiple
28633** database connections are accessing the same database file at the same
28634** time and one or more of those connections are writing.
28635*/
28636
28637static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
28638  UNUSED_PARAMETER(NotUsed);
28639  *pResOut = 0;
28640  return SQLITE_OK;
28641}
28642static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
28643  UNUSED_PARAMETER2(NotUsed, NotUsed2);
28644  return SQLITE_OK;
28645}
28646static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
28647  UNUSED_PARAMETER2(NotUsed, NotUsed2);
28648  return SQLITE_OK;
28649}
28650
28651/*
28652** Close the file.
28653*/
28654static int nolockClose(sqlite3_file *id) {
28655  return closeUnixFile(id);
28656}
28657
28658/******************* End of the no-op lock implementation *********************
28659******************************************************************************/
28660
28661/******************************************************************************
28662************************* Begin dot-file Locking ******************************
28663**
28664** The dotfile locking implementation uses the existence of separate lock
28665** files (really a directory) to control access to the database.  This works
28666** on just about every filesystem imaginable.  But there are serious downsides:
28667**
28668**    (1)  There is zero concurrency.  A single reader blocks all other
28669**         connections from reading or writing the database.
28670**
28671**    (2)  An application crash or power loss can leave stale lock files
28672**         sitting around that need to be cleared manually.
28673**
28674** Nevertheless, a dotlock is an appropriate locking mode for use if no
28675** other locking strategy is available.
28676**
28677** Dotfile locking works by creating a subdirectory in the same directory as
28678** the database and with the same name but with a ".lock" extension added.
28679** The existence of a lock directory implies an EXCLUSIVE lock.  All other
28680** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
28681*/
28682
28683/*
28684** The file suffix added to the data base filename in order to create the
28685** lock directory.
28686*/
28687#define DOTLOCK_SUFFIX ".lock"
28688
28689/*
28690** This routine checks if there is a RESERVED lock held on the specified
28691** file by this or any other process. If such a lock is held, set *pResOut
28692** to a non-zero value otherwise *pResOut is set to zero.  The return value
28693** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28694**
28695** In dotfile locking, either a lock exists or it does not.  So in this
28696** variation of CheckReservedLock(), *pResOut is set to true if any lock
28697** is held on the file and false if the file is unlocked.
28698*/
28699static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
28700  int rc = SQLITE_OK;
28701  int reserved = 0;
28702  unixFile *pFile = (unixFile*)id;
28703
28704  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28705
28706  assert( pFile );
28707
28708  /* Check if a thread in this process holds such a lock */
28709  if( pFile->eFileLock>SHARED_LOCK ){
28710    /* Either this connection or some other connection in the same process
28711    ** holds a lock on the file.  No need to check further. */
28712    reserved = 1;
28713  }else{
28714    /* The lock is held if and only if the lockfile exists */
28715    const char *zLockFile = (const char*)pFile->lockingContext;
28716    reserved = osAccess(zLockFile, 0)==0;
28717  }
28718  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
28719  *pResOut = reserved;
28720  return rc;
28721}
28722
28723/*
28724** Lock the file with the lock specified by parameter eFileLock - one
28725** of the following:
28726**
28727**     (1) SHARED_LOCK
28728**     (2) RESERVED_LOCK
28729**     (3) PENDING_LOCK
28730**     (4) EXCLUSIVE_LOCK
28731**
28732** Sometimes when requesting one lock state, additional lock states
28733** are inserted in between.  The locking might fail on one of the later
28734** transitions leaving the lock state different from what it started but
28735** still short of its goal.  The following chart shows the allowed
28736** transitions and the inserted intermediate states:
28737**
28738**    UNLOCKED -> SHARED
28739**    SHARED -> RESERVED
28740**    SHARED -> (PENDING) -> EXCLUSIVE
28741**    RESERVED -> (PENDING) -> EXCLUSIVE
28742**    PENDING -> EXCLUSIVE
28743**
28744** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28745** routine to lower a locking level.
28746**
28747** With dotfile locking, we really only support state (4): EXCLUSIVE.
28748** But we track the other locking levels internally.
28749*/
28750static int dotlockLock(sqlite3_file *id, int eFileLock) {
28751  unixFile *pFile = (unixFile*)id;
28752  char *zLockFile = (char *)pFile->lockingContext;
28753  int rc = SQLITE_OK;
28754
28755
28756  /* If we have any lock, then the lock file already exists.  All we have
28757  ** to do is adjust our internal record of the lock level.
28758  */
28759  if( pFile->eFileLock > NO_LOCK ){
28760    pFile->eFileLock = eFileLock;
28761    /* Always update the timestamp on the old file */
28762#ifdef HAVE_UTIME
28763    utime(zLockFile, NULL);
28764#else
28765    utimes(zLockFile, NULL);
28766#endif
28767    return SQLITE_OK;
28768  }
28769
28770  /* grab an exclusive lock */
28771  rc = osMkdir(zLockFile, 0777);
28772  if( rc<0 ){
28773    /* failed to open/create the lock directory */
28774    int tErrno = errno;
28775    if( EEXIST == tErrno ){
28776      rc = SQLITE_BUSY;
28777    } else {
28778      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28779      if( IS_LOCK_ERROR(rc) ){
28780        storeLastErrno(pFile, tErrno);
28781      }
28782    }
28783    return rc;
28784  }
28785
28786  /* got it, set the type and return ok */
28787  pFile->eFileLock = eFileLock;
28788  return rc;
28789}
28790
28791/*
28792** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28793** must be either NO_LOCK or SHARED_LOCK.
28794**
28795** If the locking level of the file descriptor is already at or below
28796** the requested locking level, this routine is a no-op.
28797**
28798** When the locking level reaches NO_LOCK, delete the lock file.
28799*/
28800static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
28801  unixFile *pFile = (unixFile*)id;
28802  char *zLockFile = (char *)pFile->lockingContext;
28803  int rc;
28804
28805  assert( pFile );
28806  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
28807           pFile->eFileLock, osGetpid(0)));
28808  assert( eFileLock<=SHARED_LOCK );
28809
28810  /* no-op if possible */
28811  if( pFile->eFileLock==eFileLock ){
28812    return SQLITE_OK;
28813  }
28814
28815  /* To downgrade to shared, simply update our internal notion of the
28816  ** lock state.  No need to mess with the file on disk.
28817  */
28818  if( eFileLock==SHARED_LOCK ){
28819    pFile->eFileLock = SHARED_LOCK;
28820    return SQLITE_OK;
28821  }
28822
28823  /* To fully unlock the database, delete the lock file */
28824  assert( eFileLock==NO_LOCK );
28825  rc = osRmdir(zLockFile);
28826  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
28827  if( rc<0 ){
28828    int tErrno = errno;
28829    rc = 0;
28830    if( ENOENT != tErrno ){
28831      rc = SQLITE_IOERR_UNLOCK;
28832    }
28833    if( IS_LOCK_ERROR(rc) ){
28834      storeLastErrno(pFile, tErrno);
28835    }
28836    return rc;
28837  }
28838  pFile->eFileLock = NO_LOCK;
28839  return SQLITE_OK;
28840}
28841
28842/*
28843** Close a file.  Make sure the lock has been released before closing.
28844*/
28845static int dotlockClose(sqlite3_file *id) {
28846  int rc = SQLITE_OK;
28847  if( id ){
28848    unixFile *pFile = (unixFile*)id;
28849    dotlockUnlock(id, NO_LOCK);
28850    sqlite3_free(pFile->lockingContext);
28851    rc = closeUnixFile(id);
28852  }
28853  return rc;
28854}
28855/****************** End of the dot-file lock implementation *******************
28856******************************************************************************/
28857
28858/******************************************************************************
28859************************** Begin flock Locking ********************************
28860**
28861** Use the flock() system call to do file locking.
28862**
28863** flock() locking is like dot-file locking in that the various
28864** fine-grain locking levels supported by SQLite are collapsed into
28865** a single exclusive lock.  In other words, SHARED, RESERVED, and
28866** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
28867** still works when you do this, but concurrency is reduced since
28868** only a single process can be reading the database at a time.
28869**
28870** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
28871*/
28872#if SQLITE_ENABLE_LOCKING_STYLE
28873
28874/*
28875** Retry flock() calls that fail with EINTR
28876*/
28877#ifdef EINTR
28878static int robust_flock(int fd, int op){
28879  int rc;
28880  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
28881  return rc;
28882}
28883#else
28884# define robust_flock(a,b) flock(a,b)
28885#endif
28886
28887
28888/*
28889** This routine checks if there is a RESERVED lock held on the specified
28890** file by this or any other process. If such a lock is held, set *pResOut
28891** to a non-zero value otherwise *pResOut is set to zero.  The return value
28892** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28893*/
28894static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
28895  int rc = SQLITE_OK;
28896  int reserved = 0;
28897  unixFile *pFile = (unixFile*)id;
28898
28899  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28900
28901  assert( pFile );
28902
28903  /* Check if a thread in this process holds such a lock */
28904  if( pFile->eFileLock>SHARED_LOCK ){
28905    reserved = 1;
28906  }
28907
28908  /* Otherwise see if some other process holds it. */
28909  if( !reserved ){
28910    /* attempt to get the lock */
28911    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
28912    if( !lrc ){
28913      /* got the lock, unlock it */
28914      lrc = robust_flock(pFile->h, LOCK_UN);
28915      if ( lrc ) {
28916        int tErrno = errno;
28917        /* unlock failed with an error */
28918        lrc = SQLITE_IOERR_UNLOCK;
28919        if( IS_LOCK_ERROR(lrc) ){
28920          storeLastErrno(pFile, tErrno);
28921          rc = lrc;
28922        }
28923      }
28924    } else {
28925      int tErrno = errno;
28926      reserved = 1;
28927      /* someone else might have it reserved */
28928      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28929      if( IS_LOCK_ERROR(lrc) ){
28930        storeLastErrno(pFile, tErrno);
28931        rc = lrc;
28932      }
28933    }
28934  }
28935  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
28936
28937#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
28938  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
28939    rc = SQLITE_OK;
28940    reserved=1;
28941  }
28942#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
28943  *pResOut = reserved;
28944  return rc;
28945}
28946
28947/*
28948** Lock the file with the lock specified by parameter eFileLock - one
28949** of the following:
28950**
28951**     (1) SHARED_LOCK
28952**     (2) RESERVED_LOCK
28953**     (3) PENDING_LOCK
28954**     (4) EXCLUSIVE_LOCK
28955**
28956** Sometimes when requesting one lock state, additional lock states
28957** are inserted in between.  The locking might fail on one of the later
28958** transitions leaving the lock state different from what it started but
28959** still short of its goal.  The following chart shows the allowed
28960** transitions and the inserted intermediate states:
28961**
28962**    UNLOCKED -> SHARED
28963**    SHARED -> RESERVED
28964**    SHARED -> (PENDING) -> EXCLUSIVE
28965**    RESERVED -> (PENDING) -> EXCLUSIVE
28966**    PENDING -> EXCLUSIVE
28967**
28968** flock() only really support EXCLUSIVE locks.  We track intermediate
28969** lock states in the sqlite3_file structure, but all locks SHARED or
28970** above are really EXCLUSIVE locks and exclude all other processes from
28971** access the file.
28972**
28973** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28974** routine to lower a locking level.
28975*/
28976static int flockLock(sqlite3_file *id, int eFileLock) {
28977  int rc = SQLITE_OK;
28978  unixFile *pFile = (unixFile*)id;
28979
28980  assert( pFile );
28981
28982  /* if we already have a lock, it is exclusive.
28983  ** Just adjust level and punt on outta here. */
28984  if (pFile->eFileLock > NO_LOCK) {
28985    pFile->eFileLock = eFileLock;
28986    return SQLITE_OK;
28987  }
28988
28989  /* grab an exclusive lock */
28990
28991  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
28992    int tErrno = errno;
28993    /* didn't get, must be busy */
28994    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28995    if( IS_LOCK_ERROR(rc) ){
28996      storeLastErrno(pFile, tErrno);
28997    }
28998  } else {
28999    /* got it, set the type and return ok */
29000    pFile->eFileLock = eFileLock;
29001  }
29002  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
29003           rc==SQLITE_OK ? "ok" : "failed"));
29004#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
29005  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
29006    rc = SQLITE_BUSY;
29007  }
29008#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
29009  return rc;
29010}
29011
29012
29013/*
29014** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29015** must be either NO_LOCK or SHARED_LOCK.
29016**
29017** If the locking level of the file descriptor is already at or below
29018** the requested locking level, this routine is a no-op.
29019*/
29020static int flockUnlock(sqlite3_file *id, int eFileLock) {
29021  unixFile *pFile = (unixFile*)id;
29022
29023  assert( pFile );
29024  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
29025           pFile->eFileLock, osGetpid(0)));
29026  assert( eFileLock<=SHARED_LOCK );
29027
29028  /* no-op if possible */
29029  if( pFile->eFileLock==eFileLock ){
29030    return SQLITE_OK;
29031  }
29032
29033  /* shared can just be set because we always have an exclusive */
29034  if (eFileLock==SHARED_LOCK) {
29035    pFile->eFileLock = eFileLock;
29036    return SQLITE_OK;
29037  }
29038
29039  /* no, really, unlock. */
29040  if( robust_flock(pFile->h, LOCK_UN) ){
29041#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
29042    return SQLITE_OK;
29043#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
29044    return SQLITE_IOERR_UNLOCK;
29045  }else{
29046    pFile->eFileLock = NO_LOCK;
29047    return SQLITE_OK;
29048  }
29049}
29050
29051/*
29052** Close a file.
29053*/
29054static int flockClose(sqlite3_file *id) {
29055  int rc = SQLITE_OK;
29056  if( id ){
29057    flockUnlock(id, NO_LOCK);
29058    rc = closeUnixFile(id);
29059  }
29060  return rc;
29061}
29062
29063#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
29064
29065/******************* End of the flock lock implementation *********************
29066******************************************************************************/
29067
29068/******************************************************************************
29069************************ Begin Named Semaphore Locking ************************
29070**
29071** Named semaphore locking is only supported on VxWorks.
29072**
29073** Semaphore locking is like dot-lock and flock in that it really only
29074** supports EXCLUSIVE locking.  Only a single process can read or write
29075** the database file at a time.  This reduces potential concurrency, but
29076** makes the lock implementation much easier.
29077*/
29078#if OS_VXWORKS
29079
29080/*
29081** This routine checks if there is a RESERVED lock held on the specified
29082** file by this or any other process. If such a lock is held, set *pResOut
29083** to a non-zero value otherwise *pResOut is set to zero.  The return value
29084** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29085*/
29086static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
29087  int rc = SQLITE_OK;
29088  int reserved = 0;
29089  unixFile *pFile = (unixFile*)id;
29090
29091  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29092
29093  assert( pFile );
29094
29095  /* Check if a thread in this process holds such a lock */
29096  if( pFile->eFileLock>SHARED_LOCK ){
29097    reserved = 1;
29098  }
29099
29100  /* Otherwise see if some other process holds it. */
29101  if( !reserved ){
29102    sem_t *pSem = pFile->pInode->pSem;
29103
29104    if( sem_trywait(pSem)==-1 ){
29105      int tErrno = errno;
29106      if( EAGAIN != tErrno ){
29107        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
29108        storeLastErrno(pFile, tErrno);
29109      } else {
29110        /* someone else has the lock when we are in NO_LOCK */
29111        reserved = (pFile->eFileLock < SHARED_LOCK);
29112      }
29113    }else{
29114      /* we could have it if we want it */
29115      sem_post(pSem);
29116    }
29117  }
29118  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
29119
29120  *pResOut = reserved;
29121  return rc;
29122}
29123
29124/*
29125** Lock the file with the lock specified by parameter eFileLock - one
29126** of the following:
29127**
29128**     (1) SHARED_LOCK
29129**     (2) RESERVED_LOCK
29130**     (3) PENDING_LOCK
29131**     (4) EXCLUSIVE_LOCK
29132**
29133** Sometimes when requesting one lock state, additional lock states
29134** are inserted in between.  The locking might fail on one of the later
29135** transitions leaving the lock state different from what it started but
29136** still short of its goal.  The following chart shows the allowed
29137** transitions and the inserted intermediate states:
29138**
29139**    UNLOCKED -> SHARED
29140**    SHARED -> RESERVED
29141**    SHARED -> (PENDING) -> EXCLUSIVE
29142**    RESERVED -> (PENDING) -> EXCLUSIVE
29143**    PENDING -> EXCLUSIVE
29144**
29145** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
29146** lock states in the sqlite3_file structure, but all locks SHARED or
29147** above are really EXCLUSIVE locks and exclude all other processes from
29148** access the file.
29149**
29150** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29151** routine to lower a locking level.
29152*/
29153static int semXLock(sqlite3_file *id, int eFileLock) {
29154  unixFile *pFile = (unixFile*)id;
29155  sem_t *pSem = pFile->pInode->pSem;
29156  int rc = SQLITE_OK;
29157
29158  /* if we already have a lock, it is exclusive.
29159  ** Just adjust level and punt on outta here. */
29160  if (pFile->eFileLock > NO_LOCK) {
29161    pFile->eFileLock = eFileLock;
29162    rc = SQLITE_OK;
29163    goto sem_end_lock;
29164  }
29165
29166  /* lock semaphore now but bail out when already locked. */
29167  if( sem_trywait(pSem)==-1 ){
29168    rc = SQLITE_BUSY;
29169    goto sem_end_lock;
29170  }
29171
29172  /* got it, set the type and return ok */
29173  pFile->eFileLock = eFileLock;
29174
29175 sem_end_lock:
29176  return rc;
29177}
29178
29179/*
29180** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29181** must be either NO_LOCK or SHARED_LOCK.
29182**
29183** If the locking level of the file descriptor is already at or below
29184** the requested locking level, this routine is a no-op.
29185*/
29186static int semXUnlock(sqlite3_file *id, int eFileLock) {
29187  unixFile *pFile = (unixFile*)id;
29188  sem_t *pSem = pFile->pInode->pSem;
29189
29190  assert( pFile );
29191  assert( pSem );
29192  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
29193           pFile->eFileLock, osGetpid(0)));
29194  assert( eFileLock<=SHARED_LOCK );
29195
29196  /* no-op if possible */
29197  if( pFile->eFileLock==eFileLock ){
29198    return SQLITE_OK;
29199  }
29200
29201  /* shared can just be set because we always have an exclusive */
29202  if (eFileLock==SHARED_LOCK) {
29203    pFile->eFileLock = eFileLock;
29204    return SQLITE_OK;
29205  }
29206
29207  /* no, really unlock. */
29208  if ( sem_post(pSem)==-1 ) {
29209    int rc, tErrno = errno;
29210    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
29211    if( IS_LOCK_ERROR(rc) ){
29212      storeLastErrno(pFile, tErrno);
29213    }
29214    return rc;
29215  }
29216  pFile->eFileLock = NO_LOCK;
29217  return SQLITE_OK;
29218}
29219
29220/*
29221 ** Close a file.
29222 */
29223static int semXClose(sqlite3_file *id) {
29224  if( id ){
29225    unixFile *pFile = (unixFile*)id;
29226    semXUnlock(id, NO_LOCK);
29227    assert( pFile );
29228    unixEnterMutex();
29229    releaseInodeInfo(pFile);
29230    unixLeaveMutex();
29231    closeUnixFile(id);
29232  }
29233  return SQLITE_OK;
29234}
29235
29236#endif /* OS_VXWORKS */
29237/*
29238** Named semaphore locking is only available on VxWorks.
29239**
29240*************** End of the named semaphore lock implementation ****************
29241******************************************************************************/
29242
29243
29244/******************************************************************************
29245*************************** Begin AFP Locking *********************************
29246**
29247** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
29248** on Apple Macintosh computers - both OS9 and OSX.
29249**
29250** Third-party implementations of AFP are available.  But this code here
29251** only works on OSX.
29252*/
29253
29254#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29255/*
29256** The afpLockingContext structure contains all afp lock specific state
29257*/
29258typedef struct afpLockingContext afpLockingContext;
29259struct afpLockingContext {
29260  int reserved;
29261  const char *dbPath;             /* Name of the open file */
29262};
29263
29264struct ByteRangeLockPB2
29265{
29266  unsigned long long offset;        /* offset to first byte to lock */
29267  unsigned long long length;        /* nbr of bytes to lock */
29268  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
29269  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
29270  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
29271  int fd;                           /* file desc to assoc this lock with */
29272};
29273
29274#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
29275
29276/*
29277** This is a utility for setting or clearing a bit-range lock on an
29278** AFP filesystem.
29279**
29280** Return SQLITE_OK on success, SQLITE_BUSY on failure.
29281*/
29282static int afpSetLock(
29283  const char *path,              /* Name of the file to be locked or unlocked */
29284  unixFile *pFile,               /* Open file descriptor on path */
29285  unsigned long long offset,     /* First byte to be locked */
29286  unsigned long long length,     /* Number of bytes to lock */
29287  int setLockFlag                /* True to set lock.  False to clear lock */
29288){
29289  struct ByteRangeLockPB2 pb;
29290  int err;
29291
29292  pb.unLockFlag = setLockFlag ? 0 : 1;
29293  pb.startEndFlag = 0;
29294  pb.offset = offset;
29295  pb.length = length;
29296  pb.fd = pFile->h;
29297
29298  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
29299    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
29300    offset, length));
29301  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
29302  if ( err==-1 ) {
29303    int rc;
29304    int tErrno = errno;
29305    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
29306             path, tErrno, strerror(tErrno)));
29307#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
29308    rc = SQLITE_BUSY;
29309#else
29310    rc = sqliteErrorFromPosixError(tErrno,
29311                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
29312#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
29313    if( IS_LOCK_ERROR(rc) ){
29314      storeLastErrno(pFile, tErrno);
29315    }
29316    return rc;
29317  } else {
29318    return SQLITE_OK;
29319  }
29320}
29321
29322/*
29323** This routine checks if there is a RESERVED lock held on the specified
29324** file by this or any other process. If such a lock is held, set *pResOut
29325** to a non-zero value otherwise *pResOut is set to zero.  The return value
29326** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29327*/
29328static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
29329  int rc = SQLITE_OK;
29330  int reserved = 0;
29331  unixFile *pFile = (unixFile*)id;
29332  afpLockingContext *context;
29333
29334  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29335
29336  assert( pFile );
29337  context = (afpLockingContext *) pFile->lockingContext;
29338  if( context->reserved ){
29339    *pResOut = 1;
29340    return SQLITE_OK;
29341  }
29342  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
29343
29344  /* Check if a thread in this process holds such a lock */
29345  if( pFile->pInode->eFileLock>SHARED_LOCK ){
29346    reserved = 1;
29347  }
29348
29349  /* Otherwise see if some other process holds it.
29350   */
29351  if( !reserved ){
29352    /* lock the RESERVED byte */
29353    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29354    if( SQLITE_OK==lrc ){
29355      /* if we succeeded in taking the reserved lock, unlock it to restore
29356      ** the original state */
29357      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29358    } else {
29359      /* if we failed to get the lock then someone else must have it */
29360      reserved = 1;
29361    }
29362    if( IS_LOCK_ERROR(lrc) ){
29363      rc=lrc;
29364    }
29365  }
29366
29367  unixLeaveMutex();
29368  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
29369
29370  *pResOut = reserved;
29371  return rc;
29372}
29373
29374/*
29375** Lock the file with the lock specified by parameter eFileLock - one
29376** of the following:
29377**
29378**     (1) SHARED_LOCK
29379**     (2) RESERVED_LOCK
29380**     (3) PENDING_LOCK
29381**     (4) EXCLUSIVE_LOCK
29382**
29383** Sometimes when requesting one lock state, additional lock states
29384** are inserted in between.  The locking might fail on one of the later
29385** transitions leaving the lock state different from what it started but
29386** still short of its goal.  The following chart shows the allowed
29387** transitions and the inserted intermediate states:
29388**
29389**    UNLOCKED -> SHARED
29390**    SHARED -> RESERVED
29391**    SHARED -> (PENDING) -> EXCLUSIVE
29392**    RESERVED -> (PENDING) -> EXCLUSIVE
29393**    PENDING -> EXCLUSIVE
29394**
29395** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29396** routine to lower a locking level.
29397*/
29398static int afpLock(sqlite3_file *id, int eFileLock){
29399  int rc = SQLITE_OK;
29400  unixFile *pFile = (unixFile*)id;
29401  unixInodeInfo *pInode = pFile->pInode;
29402  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29403
29404  assert( pFile );
29405  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
29406           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
29407           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
29408
29409  /* If there is already a lock of this type or more restrictive on the
29410  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
29411  ** unixEnterMutex() hasn't been called yet.
29412  */
29413  if( pFile->eFileLock>=eFileLock ){
29414    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
29415           azFileLock(eFileLock)));
29416    return SQLITE_OK;
29417  }
29418
29419  /* Make sure the locking sequence is correct
29420  **  (1) We never move from unlocked to anything higher than shared lock.
29421  **  (2) SQLite never explicitly requests a pendig lock.
29422  **  (3) A shared lock is always held when a reserve lock is requested.
29423  */
29424  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
29425  assert( eFileLock!=PENDING_LOCK );
29426  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
29427
29428  /* This mutex is needed because pFile->pInode is shared across threads
29429  */
29430  unixEnterMutex();
29431  pInode = pFile->pInode;
29432
29433  /* If some thread using this PID has a lock via a different unixFile*
29434  ** handle that precludes the requested lock, return BUSY.
29435  */
29436  if( (pFile->eFileLock!=pInode->eFileLock &&
29437       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
29438     ){
29439    rc = SQLITE_BUSY;
29440    goto afp_end_lock;
29441  }
29442
29443  /* If a SHARED lock is requested, and some thread using this PID already
29444  ** has a SHARED or RESERVED lock, then increment reference counts and
29445  ** return SQLITE_OK.
29446  */
29447  if( eFileLock==SHARED_LOCK &&
29448     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
29449    assert( eFileLock==SHARED_LOCK );
29450    assert( pFile->eFileLock==0 );
29451    assert( pInode->nShared>0 );
29452    pFile->eFileLock = SHARED_LOCK;
29453    pInode->nShared++;
29454    pInode->nLock++;
29455    goto afp_end_lock;
29456  }
29457
29458  /* A PENDING lock is needed before acquiring a SHARED lock and before
29459  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
29460  ** be released.
29461  */
29462  if( eFileLock==SHARED_LOCK
29463      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
29464  ){
29465    int failed;
29466    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
29467    if (failed) {
29468      rc = failed;
29469      goto afp_end_lock;
29470    }
29471  }
29472
29473  /* If control gets to this point, then actually go ahead and make
29474  ** operating system calls for the specified lock.
29475  */
29476  if( eFileLock==SHARED_LOCK ){
29477    int lrc1, lrc2, lrc1Errno = 0;
29478    long lk, mask;
29479
29480    assert( pInode->nShared==0 );
29481    assert( pInode->eFileLock==0 );
29482
29483    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
29484    /* Now get the read-lock SHARED_LOCK */
29485    /* note that the quality of the randomness doesn't matter that much */
29486    lk = random();
29487    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
29488    lrc1 = afpSetLock(context->dbPath, pFile,
29489          SHARED_FIRST+pInode->sharedByte, 1, 1);
29490    if( IS_LOCK_ERROR(lrc1) ){
29491      lrc1Errno = pFile->lastErrno;
29492    }
29493    /* Drop the temporary PENDING lock */
29494    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29495
29496    if( IS_LOCK_ERROR(lrc1) ) {
29497      storeLastErrno(pFile, lrc1Errno);
29498      rc = lrc1;
29499      goto afp_end_lock;
29500    } else if( IS_LOCK_ERROR(lrc2) ){
29501      rc = lrc2;
29502      goto afp_end_lock;
29503    } else if( lrc1 != SQLITE_OK ) {
29504      rc = lrc1;
29505    } else {
29506      pFile->eFileLock = SHARED_LOCK;
29507      pInode->nLock++;
29508      pInode->nShared = 1;
29509    }
29510  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
29511    /* We are trying for an exclusive lock but another thread in this
29512     ** same process is still holding a shared lock. */
29513    rc = SQLITE_BUSY;
29514  }else{
29515    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
29516    ** assumed that there is a SHARED or greater lock on the file
29517    ** already.
29518    */
29519    int failed = 0;
29520    assert( 0!=pFile->eFileLock );
29521    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
29522        /* Acquire a RESERVED lock */
29523        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29524      if( !failed ){
29525        context->reserved = 1;
29526      }
29527    }
29528    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
29529      /* Acquire an EXCLUSIVE lock */
29530
29531      /* Remove the shared lock before trying the range.  we'll need to
29532      ** reestablish the shared lock if we can't get the  afpUnlock
29533      */
29534      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
29535                         pInode->sharedByte, 1, 0)) ){
29536        int failed2 = SQLITE_OK;
29537        /* now attemmpt to get the exclusive lock range */
29538        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
29539                               SHARED_SIZE, 1);
29540        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
29541                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
29542          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
29543          ** a critical I/O error
29544          */
29545          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
29546               SQLITE_IOERR_LOCK;
29547          goto afp_end_lock;
29548        }
29549      }else{
29550        rc = failed;
29551      }
29552    }
29553    if( failed ){
29554      rc = failed;
29555    }
29556  }
29557
29558  if( rc==SQLITE_OK ){
29559    pFile->eFileLock = eFileLock;
29560    pInode->eFileLock = eFileLock;
29561  }else if( eFileLock==EXCLUSIVE_LOCK ){
29562    pFile->eFileLock = PENDING_LOCK;
29563    pInode->eFileLock = PENDING_LOCK;
29564  }
29565
29566afp_end_lock:
29567  unixLeaveMutex();
29568  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
29569         rc==SQLITE_OK ? "ok" : "failed"));
29570  return rc;
29571}
29572
29573/*
29574** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29575** must be either NO_LOCK or SHARED_LOCK.
29576**
29577** If the locking level of the file descriptor is already at or below
29578** the requested locking level, this routine is a no-op.
29579*/
29580static int afpUnlock(sqlite3_file *id, int eFileLock) {
29581  int rc = SQLITE_OK;
29582  unixFile *pFile = (unixFile*)id;
29583  unixInodeInfo *pInode;
29584  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29585  int skipShared = 0;
29586#ifdef SQLITE_TEST
29587  int h = pFile->h;
29588#endif
29589
29590  assert( pFile );
29591  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
29592           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
29593           osGetpid(0)));
29594
29595  assert( eFileLock<=SHARED_LOCK );
29596  if( pFile->eFileLock<=eFileLock ){
29597    return SQLITE_OK;
29598  }
29599  unixEnterMutex();
29600  pInode = pFile->pInode;
29601  assert( pInode->nShared!=0 );
29602  if( pFile->eFileLock>SHARED_LOCK ){
29603    assert( pInode->eFileLock==pFile->eFileLock );
29604    SimulateIOErrorBenign(1);
29605    SimulateIOError( h=(-1) )
29606    SimulateIOErrorBenign(0);
29607
29608#ifdef SQLITE_DEBUG
29609    /* When reducing a lock such that other processes can start
29610    ** reading the database file again, make sure that the
29611    ** transaction counter was updated if any part of the database
29612    ** file changed.  If the transaction counter is not updated,
29613    ** other connections to the same file might not realize that
29614    ** the file has changed and hence might not know to flush their
29615    ** cache.  The use of a stale cache can lead to database corruption.
29616    */
29617    assert( pFile->inNormalWrite==0
29618           || pFile->dbUpdate==0
29619           || pFile->transCntrChng==1 );
29620    pFile->inNormalWrite = 0;
29621#endif
29622
29623    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
29624      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
29625      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
29626        /* only re-establish the shared lock if necessary */
29627        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29628        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
29629      } else {
29630        skipShared = 1;
29631      }
29632    }
29633    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
29634      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29635    }
29636    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
29637      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29638      if( !rc ){
29639        context->reserved = 0;
29640      }
29641    }
29642    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
29643      pInode->eFileLock = SHARED_LOCK;
29644    }
29645  }
29646  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
29647
29648    /* Decrement the shared lock counter.  Release the lock using an
29649    ** OS call only when all threads in this same process have released
29650    ** the lock.
29651    */
29652    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29653    pInode->nShared--;
29654    if( pInode->nShared==0 ){
29655      SimulateIOErrorBenign(1);
29656      SimulateIOError( h=(-1) )
29657      SimulateIOErrorBenign(0);
29658      if( !skipShared ){
29659        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
29660      }
29661      if( !rc ){
29662        pInode->eFileLock = NO_LOCK;
29663        pFile->eFileLock = NO_LOCK;
29664      }
29665    }
29666    if( rc==SQLITE_OK ){
29667      pInode->nLock--;
29668      assert( pInode->nLock>=0 );
29669      if( pInode->nLock==0 ){
29670        closePendingFds(pFile);
29671      }
29672    }
29673  }
29674
29675  unixLeaveMutex();
29676  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
29677  return rc;
29678}
29679
29680/*
29681** Close a file & cleanup AFP specific locking context
29682*/
29683static int afpClose(sqlite3_file *id) {
29684  int rc = SQLITE_OK;
29685  if( id ){
29686    unixFile *pFile = (unixFile*)id;
29687    afpUnlock(id, NO_LOCK);
29688    unixEnterMutex();
29689    if( pFile->pInode && pFile->pInode->nLock ){
29690      /* If there are outstanding locks, do not actually close the file just
29691      ** yet because that would clear those locks.  Instead, add the file
29692      ** descriptor to pInode->aPending.  It will be automatically closed when
29693      ** the last lock is cleared.
29694      */
29695      setPendingFd(pFile);
29696    }
29697    releaseInodeInfo(pFile);
29698    sqlite3_free(pFile->lockingContext);
29699    rc = closeUnixFile(id);
29700    unixLeaveMutex();
29701  }
29702  return rc;
29703}
29704
29705#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29706/*
29707** The code above is the AFP lock implementation.  The code is specific
29708** to MacOSX and does not work on other unix platforms.  No alternative
29709** is available.  If you don't compile for a mac, then the "unix-afp"
29710** VFS is not available.
29711**
29712********************* End of the AFP lock implementation **********************
29713******************************************************************************/
29714
29715/******************************************************************************
29716*************************** Begin NFS Locking ********************************/
29717
29718#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29719/*
29720 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29721 ** must be either NO_LOCK or SHARED_LOCK.
29722 **
29723 ** If the locking level of the file descriptor is already at or below
29724 ** the requested locking level, this routine is a no-op.
29725 */
29726static int nfsUnlock(sqlite3_file *id, int eFileLock){
29727  return posixUnlock(id, eFileLock, 1);
29728}
29729
29730#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29731/*
29732** The code above is the NFS lock implementation.  The code is specific
29733** to MacOSX and does not work on other unix platforms.  No alternative
29734** is available.
29735**
29736********************* End of the NFS lock implementation **********************
29737******************************************************************************/
29738
29739/******************************************************************************
29740**************** Non-locking sqlite3_file methods *****************************
29741**
29742** The next division contains implementations for all methods of the
29743** sqlite3_file object other than the locking methods.  The locking
29744** methods were defined in divisions above (one locking method per
29745** division).  Those methods that are common to all locking modes
29746** are gather together into this division.
29747*/
29748
29749/*
29750** Seek to the offset passed as the second argument, then read cnt
29751** bytes into pBuf. Return the number of bytes actually read.
29752**
29753** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
29754** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
29755** one system to another.  Since SQLite does not define USE_PREAD
29756** in any form by default, we will not attempt to define _XOPEN_SOURCE.
29757** See tickets #2741 and #2681.
29758**
29759** To avoid stomping the errno value on a failed read the lastErrno value
29760** is set before returning.
29761*/
29762static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
29763  int got;
29764  int prior = 0;
29765#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29766  i64 newOffset;
29767#endif
29768  TIMER_START;
29769  assert( cnt==(cnt&0x1ffff) );
29770  assert( id->h>2 );
29771  do{
29772#if defined(USE_PREAD)
29773    got = osPread(id->h, pBuf, cnt, offset);
29774    SimulateIOError( got = -1 );
29775#elif defined(USE_PREAD64)
29776    got = osPread64(id->h, pBuf, cnt, offset);
29777    SimulateIOError( got = -1 );
29778#else
29779    newOffset = lseek(id->h, offset, SEEK_SET);
29780    SimulateIOError( newOffset-- );
29781    if( newOffset!=offset ){
29782      if( newOffset == -1 ){
29783        storeLastErrno((unixFile*)id, errno);
29784      }else{
29785        storeLastErrno((unixFile*)id, 0);
29786      }
29787      return -1;
29788    }
29789    got = osRead(id->h, pBuf, cnt);
29790#endif
29791    if( got==cnt ) break;
29792    if( got<0 ){
29793      if( errno==EINTR ){ got = 1; continue; }
29794      prior = 0;
29795      storeLastErrno((unixFile*)id,  errno);
29796      break;
29797    }else if( got>0 ){
29798      cnt -= got;
29799      offset += got;
29800      prior += got;
29801      pBuf = (void*)(got + (char*)pBuf);
29802    }
29803  }while( got>0 );
29804  TIMER_END;
29805  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
29806            id->h, got+prior, offset-prior, TIMER_ELAPSED));
29807  return got+prior;
29808}
29809
29810/*
29811** Read data from a file into a buffer.  Return SQLITE_OK if all
29812** bytes were read successfully and SQLITE_IOERR if anything goes
29813** wrong.
29814*/
29815static int unixRead(
29816  sqlite3_file *id,
29817  void *pBuf,
29818  int amt,
29819  sqlite3_int64 offset
29820){
29821  unixFile *pFile = (unixFile *)id;
29822  int got;
29823  assert( id );
29824  assert( offset>=0 );
29825  assert( amt>0 );
29826
29827  /* If this is a database file (not a journal, master-journal or temp
29828  ** file), the bytes in the locking range should never be read or written. */
29829#if 0
29830  assert( pFile->pUnused==0
29831       || offset>=PENDING_BYTE+512
29832       || offset+amt<=PENDING_BYTE
29833  );
29834#endif
29835
29836#if SQLITE_MAX_MMAP_SIZE>0
29837  /* Deal with as much of this read request as possible by transfering
29838  ** data from the memory mapping using memcpy().  */
29839  if( offset<pFile->mmapSize ){
29840    if( offset+amt <= pFile->mmapSize ){
29841      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
29842      return SQLITE_OK;
29843    }else{
29844      int nCopy = pFile->mmapSize - offset;
29845      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
29846      pBuf = &((u8 *)pBuf)[nCopy];
29847      amt -= nCopy;
29848      offset += nCopy;
29849    }
29850  }
29851#endif
29852
29853  got = seekAndRead(pFile, offset, pBuf, amt);
29854  if( got==amt ){
29855    return SQLITE_OK;
29856  }else if( got<0 ){
29857    /* lastErrno set by seekAndRead */
29858    return SQLITE_IOERR_READ;
29859  }else{
29860    storeLastErrno(pFile, 0);   /* not a system error */
29861    /* Unread parts of the buffer must be zero-filled */
29862    memset(&((char*)pBuf)[got], 0, amt-got);
29863    return SQLITE_IOERR_SHORT_READ;
29864  }
29865}
29866
29867/*
29868** Attempt to seek the file-descriptor passed as the first argument to
29869** absolute offset iOff, then attempt to write nBuf bytes of data from
29870** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
29871** return the actual number of bytes written (which may be less than
29872** nBuf).
29873*/
29874static int seekAndWriteFd(
29875  int fd,                         /* File descriptor to write to */
29876  i64 iOff,                       /* File offset to begin writing at */
29877  const void *pBuf,               /* Copy data from this buffer to the file */
29878  int nBuf,                       /* Size of buffer pBuf in bytes */
29879  int *piErrno                    /* OUT: Error number if error occurs */
29880){
29881  int rc = 0;                     /* Value returned by system call */
29882
29883  assert( nBuf==(nBuf&0x1ffff) );
29884  assert( fd>2 );
29885  nBuf &= 0x1ffff;
29886  TIMER_START;
29887
29888#if defined(USE_PREAD)
29889  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
29890#elif defined(USE_PREAD64)
29891  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
29892#else
29893  do{
29894    i64 iSeek = lseek(fd, iOff, SEEK_SET);
29895    SimulateIOError( iSeek-- );
29896
29897    if( iSeek!=iOff ){
29898      if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
29899      return -1;
29900    }
29901    rc = osWrite(fd, pBuf, nBuf);
29902  }while( rc<0 && errno==EINTR );
29903#endif
29904
29905  TIMER_END;
29906  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
29907
29908  if( rc<0 && piErrno ) *piErrno = errno;
29909  return rc;
29910}
29911
29912
29913/*
29914** Seek to the offset in id->offset then read cnt bytes into pBuf.
29915** Return the number of bytes actually read.  Update the offset.
29916**
29917** To avoid stomping the errno value on a failed write the lastErrno value
29918** is set before returning.
29919*/
29920static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
29921  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
29922}
29923
29924
29925/*
29926** Write data from a buffer into a file.  Return SQLITE_OK on success
29927** or some other error code on failure.
29928*/
29929static int unixWrite(
29930  sqlite3_file *id,
29931  const void *pBuf,
29932  int amt,
29933  sqlite3_int64 offset
29934){
29935  unixFile *pFile = (unixFile*)id;
29936  int wrote = 0;
29937  assert( id );
29938  assert( amt>0 );
29939
29940  /* If this is a database file (not a journal, master-journal or temp
29941  ** file), the bytes in the locking range should never be read or written. */
29942#if 0
29943  assert( pFile->pUnused==0
29944       || offset>=PENDING_BYTE+512
29945       || offset+amt<=PENDING_BYTE
29946  );
29947#endif
29948
29949#ifdef SQLITE_DEBUG
29950  /* If we are doing a normal write to a database file (as opposed to
29951  ** doing a hot-journal rollback or a write to some file other than a
29952  ** normal database file) then record the fact that the database
29953  ** has changed.  If the transaction counter is modified, record that
29954  ** fact too.
29955  */
29956  if( pFile->inNormalWrite ){
29957    pFile->dbUpdate = 1;  /* The database has been modified */
29958    if( offset<=24 && offset+amt>=27 ){
29959      int rc;
29960      char oldCntr[4];
29961      SimulateIOErrorBenign(1);
29962      rc = seekAndRead(pFile, 24, oldCntr, 4);
29963      SimulateIOErrorBenign(0);
29964      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
29965        pFile->transCntrChng = 1;  /* The transaction counter has changed */
29966      }
29967    }
29968  }
29969#endif
29970
29971#if SQLITE_MAX_MMAP_SIZE>0
29972  /* Deal with as much of this write request as possible by transfering
29973  ** data from the memory mapping using memcpy().  */
29974  if( offset<pFile->mmapSize ){
29975    if( offset+amt <= pFile->mmapSize ){
29976      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
29977      return SQLITE_OK;
29978    }else{
29979      int nCopy = pFile->mmapSize - offset;
29980      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
29981      pBuf = &((u8 *)pBuf)[nCopy];
29982      amt -= nCopy;
29983      offset += nCopy;
29984    }
29985  }
29986#endif
29987
29988  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
29989    amt -= wrote;
29990    offset += wrote;
29991    pBuf = &((char*)pBuf)[wrote];
29992  }
29993  SimulateIOError(( wrote=(-1), amt=1 ));
29994  SimulateDiskfullError(( wrote=0, amt=1 ));
29995
29996  if( amt>wrote ){
29997    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
29998      /* lastErrno set by seekAndWrite */
29999      return SQLITE_IOERR_WRITE;
30000    }else{
30001      storeLastErrno(pFile, 0); /* not a system error */
30002      return SQLITE_FULL;
30003    }
30004  }
30005
30006  return SQLITE_OK;
30007}
30008
30009#ifdef SQLITE_TEST
30010/*
30011** Count the number of fullsyncs and normal syncs.  This is used to test
30012** that syncs and fullsyncs are occurring at the right times.
30013*/
30014SQLITE_API int sqlite3_sync_count = 0;
30015SQLITE_API int sqlite3_fullsync_count = 0;
30016#endif
30017
30018/*
30019** We do not trust systems to provide a working fdatasync().  Some do.
30020** Others do no.  To be safe, we will stick with the (slightly slower)
30021** fsync(). If you know that your system does support fdatasync() correctly,
30022** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
30023*/
30024#if !defined(fdatasync) && !HAVE_FDATASYNC
30025# define fdatasync fsync
30026#endif
30027
30028/*
30029** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
30030** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
30031** only available on Mac OS X.  But that could change.
30032*/
30033#ifdef F_FULLFSYNC
30034# define HAVE_FULLFSYNC 1
30035#else
30036# define HAVE_FULLFSYNC 0
30037#endif
30038
30039
30040/*
30041** The fsync() system call does not work as advertised on many
30042** unix systems.  The following procedure is an attempt to make
30043** it work better.
30044**
30045** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
30046** for testing when we want to run through the test suite quickly.
30047** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
30048** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
30049** or power failure will likely corrupt the database file.
30050**
30051** SQLite sets the dataOnly flag if the size of the file is unchanged.
30052** The idea behind dataOnly is that it should only write the file content
30053** to disk, not the inode.  We only set dataOnly if the file size is
30054** unchanged since the file size is part of the inode.  However,
30055** Ted Ts'o tells us that fdatasync() will also write the inode if the
30056** file size has changed.  The only real difference between fdatasync()
30057** and fsync(), Ted tells us, is that fdatasync() will not flush the
30058** inode if the mtime or owner or other inode attributes have changed.
30059** We only care about the file size, not the other file attributes, so
30060** as far as SQLite is concerned, an fdatasync() is always adequate.
30061** So, we always use fdatasync() if it is available, regardless of
30062** the value of the dataOnly flag.
30063*/
30064static int full_fsync(int fd, int fullSync, int dataOnly){
30065  int rc;
30066
30067  /* The following "ifdef/elif/else/" block has the same structure as
30068  ** the one below. It is replicated here solely to avoid cluttering
30069  ** up the real code with the UNUSED_PARAMETER() macros.
30070  */
30071#ifdef SQLITE_NO_SYNC
30072  UNUSED_PARAMETER(fd);
30073  UNUSED_PARAMETER(fullSync);
30074  UNUSED_PARAMETER(dataOnly);
30075#elif HAVE_FULLFSYNC
30076  UNUSED_PARAMETER(dataOnly);
30077#else
30078  UNUSED_PARAMETER(fullSync);
30079  UNUSED_PARAMETER(dataOnly);
30080#endif
30081
30082  /* Record the number of times that we do a normal fsync() and
30083  ** FULLSYNC.  This is used during testing to verify that this procedure
30084  ** gets called with the correct arguments.
30085  */
30086#ifdef SQLITE_TEST
30087  if( fullSync ) sqlite3_fullsync_count++;
30088  sqlite3_sync_count++;
30089#endif
30090
30091  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
30092  ** no-op
30093  */
30094#ifdef SQLITE_NO_SYNC
30095  rc = SQLITE_OK;
30096#elif HAVE_FULLFSYNC
30097  if( fullSync ){
30098    rc = osFcntl(fd, F_FULLFSYNC, 0);
30099  }else{
30100    rc = 1;
30101  }
30102  /* If the FULLFSYNC failed, fall back to attempting an fsync().
30103  ** It shouldn't be possible for fullfsync to fail on the local
30104  ** file system (on OSX), so failure indicates that FULLFSYNC
30105  ** isn't supported for this file system. So, attempt an fsync
30106  ** and (for now) ignore the overhead of a superfluous fcntl call.
30107  ** It'd be better to detect fullfsync support once and avoid
30108  ** the fcntl call every time sync is called.
30109  */
30110  if( rc ) rc = fsync(fd);
30111
30112#elif defined(__APPLE__)
30113  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
30114  ** so currently we default to the macro that redefines fdatasync to fsync
30115  */
30116  rc = fsync(fd);
30117#else
30118  rc = fdatasync(fd);
30119#if OS_VXWORKS
30120  if( rc==-1 && errno==ENOTSUP ){
30121    rc = fsync(fd);
30122  }
30123#endif /* OS_VXWORKS */
30124#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
30125
30126  if( OS_VXWORKS && rc!= -1 ){
30127    rc = 0;
30128  }
30129  return rc;
30130}
30131
30132/*
30133** Open a file descriptor to the directory containing file zFilename.
30134** If successful, *pFd is set to the opened file descriptor and
30135** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
30136** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
30137** value.
30138**
30139** The directory file descriptor is used for only one thing - to
30140** fsync() a directory to make sure file creation and deletion events
30141** are flushed to disk.  Such fsyncs are not needed on newer
30142** journaling filesystems, but are required on older filesystems.
30143**
30144** This routine can be overridden using the xSetSysCall interface.
30145** The ability to override this routine was added in support of the
30146** chromium sandbox.  Opening a directory is a security risk (we are
30147** told) so making it overrideable allows the chromium sandbox to
30148** replace this routine with a harmless no-op.  To make this routine
30149** a no-op, replace it with a stub that returns SQLITE_OK but leaves
30150** *pFd set to a negative number.
30151**
30152** If SQLITE_OK is returned, the caller is responsible for closing
30153** the file descriptor *pFd using close().
30154*/
30155static int openDirectory(const char *zFilename, int *pFd){
30156  int ii;
30157  int fd = -1;
30158  char zDirname[MAX_PATHNAME+1];
30159
30160  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
30161  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
30162  if( ii>0 ){
30163    zDirname[ii] = '\0';
30164    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
30165    if( fd>=0 ){
30166      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
30167    }
30168  }
30169  *pFd = fd;
30170  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
30171}
30172
30173/*
30174** Make sure all writes to a particular file are committed to disk.
30175**
30176** If dataOnly==0 then both the file itself and its metadata (file
30177** size, access time, etc) are synced.  If dataOnly!=0 then only the
30178** file data is synced.
30179**
30180** Under Unix, also make sure that the directory entry for the file
30181** has been created by fsync-ing the directory that contains the file.
30182** If we do not do this and we encounter a power failure, the directory
30183** entry for the journal might not exist after we reboot.  The next
30184** SQLite to access the file will not know that the journal exists (because
30185** the directory entry for the journal was never created) and the transaction
30186** will not roll back - possibly leading to database corruption.
30187*/
30188static int unixSync(sqlite3_file *id, int flags){
30189  int rc;
30190  unixFile *pFile = (unixFile*)id;
30191
30192  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
30193  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
30194
30195  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
30196  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
30197      || (flags&0x0F)==SQLITE_SYNC_FULL
30198  );
30199
30200  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
30201  ** line is to test that doing so does not cause any problems.
30202  */
30203  SimulateDiskfullError( return SQLITE_FULL );
30204
30205  assert( pFile );
30206  OSTRACE(("SYNC    %-3d\n", pFile->h));
30207  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
30208  SimulateIOError( rc=1 );
30209  if( rc ){
30210    storeLastErrno(pFile, errno);
30211    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
30212  }
30213
30214  /* Also fsync the directory containing the file if the DIRSYNC flag
30215  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
30216  ** are unable to fsync a directory, so ignore errors on the fsync.
30217  */
30218  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
30219    int dirfd;
30220    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
30221            HAVE_FULLFSYNC, isFullsync));
30222    rc = osOpenDirectory(pFile->zPath, &dirfd);
30223    if( rc==SQLITE_OK && dirfd>=0 ){
30224      full_fsync(dirfd, 0, 0);
30225      robust_close(pFile, dirfd, __LINE__);
30226    }else if( rc==SQLITE_CANTOPEN ){
30227      rc = SQLITE_OK;
30228    }
30229    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
30230  }
30231  return rc;
30232}
30233
30234/*
30235** Truncate an open file to a specified size
30236*/
30237static int unixTruncate(sqlite3_file *id, i64 nByte){
30238  unixFile *pFile = (unixFile *)id;
30239  int rc;
30240  assert( pFile );
30241  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
30242
30243  /* If the user has configured a chunk-size for this file, truncate the
30244  ** file so that it consists of an integer number of chunks (i.e. the
30245  ** actual file size after the operation may be larger than the requested
30246  ** size).
30247  */
30248  if( pFile->szChunk>0 ){
30249    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30250  }
30251
30252  rc = robust_ftruncate(pFile->h, nByte);
30253  if( rc ){
30254    storeLastErrno(pFile, errno);
30255    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30256  }else{
30257#ifdef SQLITE_DEBUG
30258    /* If we are doing a normal write to a database file (as opposed to
30259    ** doing a hot-journal rollback or a write to some file other than a
30260    ** normal database file) and we truncate the file to zero length,
30261    ** that effectively updates the change counter.  This might happen
30262    ** when restoring a database using the backup API from a zero-length
30263    ** source.
30264    */
30265    if( pFile->inNormalWrite && nByte==0 ){
30266      pFile->transCntrChng = 1;
30267    }
30268#endif
30269
30270#if SQLITE_MAX_MMAP_SIZE>0
30271    /* If the file was just truncated to a size smaller than the currently
30272    ** mapped region, reduce the effective mapping size as well. SQLite will
30273    ** use read() and write() to access data beyond this point from now on.
30274    */
30275    if( nByte<pFile->mmapSize ){
30276      pFile->mmapSize = nByte;
30277    }
30278#endif
30279
30280    return SQLITE_OK;
30281  }
30282}
30283
30284/*
30285** Determine the current size of a file in bytes
30286*/
30287static int unixFileSize(sqlite3_file *id, i64 *pSize){
30288  int rc;
30289  struct stat buf;
30290  assert( id );
30291  rc = osFstat(((unixFile*)id)->h, &buf);
30292  SimulateIOError( rc=1 );
30293  if( rc!=0 ){
30294    storeLastErrno((unixFile*)id, errno);
30295    return SQLITE_IOERR_FSTAT;
30296  }
30297  *pSize = buf.st_size;
30298
30299  /* When opening a zero-size database, the findInodeInfo() procedure
30300  ** writes a single byte into that file in order to work around a bug
30301  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
30302  ** layers, we need to report this file size as zero even though it is
30303  ** really 1.   Ticket #3260.
30304  */
30305  if( *pSize==1 ) *pSize = 0;
30306
30307
30308  return SQLITE_OK;
30309}
30310
30311#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30312/*
30313** Handler for proxy-locking file-control verbs.  Defined below in the
30314** proxying locking division.
30315*/
30316static int proxyFileControl(sqlite3_file*,int,void*);
30317#endif
30318
30319/*
30320** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
30321** file-control operation.  Enlarge the database to nBytes in size
30322** (rounded up to the next chunk-size).  If the database is already
30323** nBytes or larger, this routine is a no-op.
30324*/
30325static int fcntlSizeHint(unixFile *pFile, i64 nByte){
30326  if( pFile->szChunk>0 ){
30327    i64 nSize;                    /* Required file size */
30328    struct stat buf;              /* Used to hold return values of fstat() */
30329
30330    if( osFstat(pFile->h, &buf) ){
30331      return SQLITE_IOERR_FSTAT;
30332    }
30333
30334    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
30335    if( nSize>(i64)buf.st_size ){
30336
30337#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30338      /* The code below is handling the return value of osFallocate()
30339      ** correctly. posix_fallocate() is defined to "returns zero on success,
30340      ** or an error number on  failure". See the manpage for details. */
30341      int err;
30342      do{
30343        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
30344      }while( err==EINTR );
30345      if( err ) return SQLITE_IOERR_WRITE;
30346#else
30347      /* If the OS does not have posix_fallocate(), fake it. Write a
30348      ** single byte to the last byte in each block that falls entirely
30349      ** within the extended region. Then, if required, a single byte
30350      ** at offset (nSize-1), to set the size of the file correctly.
30351      ** This is a similar technique to that used by glibc on systems
30352      ** that do not have a real fallocate() call.
30353      */
30354      int nBlk = buf.st_blksize;  /* File-system block size */
30355      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
30356      i64 iWrite;                 /* Next offset to write to */
30357
30358      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
30359      assert( iWrite>=buf.st_size );
30360      assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
30361      assert( ((iWrite+1)%nBlk)==0 );
30362      for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
30363        nWrite = seekAndWrite(pFile, iWrite, "", 1);
30364        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
30365      }
30366      if( nWrite==0 || (nSize%nBlk) ){
30367        nWrite = seekAndWrite(pFile, nSize-1, "", 1);
30368        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
30369      }
30370#endif
30371    }
30372  }
30373
30374#if SQLITE_MAX_MMAP_SIZE>0
30375  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
30376    int rc;
30377    if( pFile->szChunk<=0 ){
30378      if( robust_ftruncate(pFile->h, nByte) ){
30379        storeLastErrno(pFile, errno);
30380        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30381      }
30382    }
30383
30384    rc = unixMapfile(pFile, nByte);
30385    return rc;
30386  }
30387#endif
30388
30389  return SQLITE_OK;
30390}
30391
30392/*
30393** If *pArg is initially negative then this is a query.  Set *pArg to
30394** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
30395**
30396** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
30397*/
30398static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
30399  if( *pArg<0 ){
30400    *pArg = (pFile->ctrlFlags & mask)!=0;
30401  }else if( (*pArg)==0 ){
30402    pFile->ctrlFlags &= ~mask;
30403  }else{
30404    pFile->ctrlFlags |= mask;
30405  }
30406}
30407
30408/* Forward declaration */
30409static int unixGetTempname(int nBuf, char *zBuf);
30410
30411/*
30412** Information and control of an open file handle.
30413*/
30414static int unixFileControl(sqlite3_file *id, int op, void *pArg){
30415  unixFile *pFile = (unixFile*)id;
30416  switch( op ){
30417    case SQLITE_FCNTL_WAL_BLOCK: {
30418      /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
30419      return SQLITE_OK;
30420    }
30421    case SQLITE_FCNTL_LOCKSTATE: {
30422      *(int*)pArg = pFile->eFileLock;
30423      return SQLITE_OK;
30424    }
30425    case SQLITE_FCNTL_LAST_ERRNO: {
30426      *(int*)pArg = pFile->lastErrno;
30427      return SQLITE_OK;
30428    }
30429    case SQLITE_FCNTL_CHUNK_SIZE: {
30430      pFile->szChunk = *(int *)pArg;
30431      return SQLITE_OK;
30432    }
30433    case SQLITE_FCNTL_SIZE_HINT: {
30434      int rc;
30435      SimulateIOErrorBenign(1);
30436      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
30437      SimulateIOErrorBenign(0);
30438      return rc;
30439    }
30440    case SQLITE_FCNTL_PERSIST_WAL: {
30441      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
30442      return SQLITE_OK;
30443    }
30444    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
30445      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
30446      return SQLITE_OK;
30447    }
30448    case SQLITE_FCNTL_VFSNAME: {
30449      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
30450      return SQLITE_OK;
30451    }
30452    case SQLITE_FCNTL_TEMPFILENAME: {
30453      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
30454      if( zTFile ){
30455        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
30456        *(char**)pArg = zTFile;
30457      }
30458      return SQLITE_OK;
30459    }
30460    case SQLITE_FCNTL_HAS_MOVED: {
30461      *(int*)pArg = fileHasMoved(pFile);
30462      return SQLITE_OK;
30463    }
30464#if SQLITE_MAX_MMAP_SIZE>0
30465    case SQLITE_FCNTL_MMAP_SIZE: {
30466      i64 newLimit = *(i64*)pArg;
30467      int rc = SQLITE_OK;
30468      if( newLimit>sqlite3GlobalConfig.mxMmap ){
30469        newLimit = sqlite3GlobalConfig.mxMmap;
30470      }
30471      *(i64*)pArg = pFile->mmapSizeMax;
30472      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
30473        pFile->mmapSizeMax = newLimit;
30474        if( pFile->mmapSize>0 ){
30475          unixUnmapfile(pFile);
30476          rc = unixMapfile(pFile, -1);
30477        }
30478      }
30479      return rc;
30480    }
30481#endif
30482#ifdef SQLITE_DEBUG
30483    /* The pager calls this method to signal that it has done
30484    ** a rollback and that the database is therefore unchanged and
30485    ** it hence it is OK for the transaction change counter to be
30486    ** unchanged.
30487    */
30488    case SQLITE_FCNTL_DB_UNCHANGED: {
30489      ((unixFile*)id)->dbUpdate = 0;
30490      return SQLITE_OK;
30491    }
30492#endif
30493#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30494    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
30495    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
30496      return proxyFileControl(id,op,pArg);
30497    }
30498#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
30499  }
30500  return SQLITE_NOTFOUND;
30501}
30502
30503/*
30504** Return the sector size in bytes of the underlying block device for
30505** the specified file. This is almost always 512 bytes, but may be
30506** larger for some devices.
30507**
30508** SQLite code assumes this function cannot fail. It also assumes that
30509** if two files are created in the same file-system directory (i.e.
30510** a database and its journal file) that the sector size will be the
30511** same for both.
30512*/
30513#ifndef __QNXNTO__
30514static int unixSectorSize(sqlite3_file *NotUsed){
30515  UNUSED_PARAMETER(NotUsed);
30516  return SQLITE_DEFAULT_SECTOR_SIZE;
30517}
30518#endif
30519
30520/*
30521** The following version of unixSectorSize() is optimized for QNX.
30522*/
30523#ifdef __QNXNTO__
30524#include <sys/dcmd_blk.h>
30525#include <sys/statvfs.h>
30526static int unixSectorSize(sqlite3_file *id){
30527  unixFile *pFile = (unixFile*)id;
30528  if( pFile->sectorSize == 0 ){
30529    struct statvfs fsInfo;
30530
30531    /* Set defaults for non-supported filesystems */
30532    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
30533    pFile->deviceCharacteristics = 0;
30534    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
30535      return pFile->sectorSize;
30536    }
30537
30538    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
30539      pFile->sectorSize = fsInfo.f_bsize;
30540      pFile->deviceCharacteristics =
30541        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
30542        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30543                                      ** the write succeeds */
30544        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30545                                      ** so it is ordered */
30546        0;
30547    }else if( strstr(fsInfo.f_basetype, "etfs") ){
30548      pFile->sectorSize = fsInfo.f_bsize;
30549      pFile->deviceCharacteristics =
30550        /* etfs cluster size writes are atomic */
30551        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
30552        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30553                                      ** the write succeeds */
30554        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30555                                      ** so it is ordered */
30556        0;
30557    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
30558      pFile->sectorSize = fsInfo.f_bsize;
30559      pFile->deviceCharacteristics =
30560        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
30561        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30562                                      ** the write succeeds */
30563        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30564                                      ** so it is ordered */
30565        0;
30566    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
30567      pFile->sectorSize = fsInfo.f_bsize;
30568      pFile->deviceCharacteristics =
30569        /* full bitset of atomics from max sector size and smaller */
30570        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
30571        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30572                                      ** so it is ordered */
30573        0;
30574    }else if( strstr(fsInfo.f_basetype, "dos") ){
30575      pFile->sectorSize = fsInfo.f_bsize;
30576      pFile->deviceCharacteristics =
30577        /* full bitset of atomics from max sector size and smaller */
30578        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
30579        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30580                                      ** so it is ordered */
30581        0;
30582    }else{
30583      pFile->deviceCharacteristics =
30584        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
30585        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30586                                      ** the write succeeds */
30587        0;
30588    }
30589  }
30590  /* Last chance verification.  If the sector size isn't a multiple of 512
30591  ** then it isn't valid.*/
30592  if( pFile->sectorSize % 512 != 0 ){
30593    pFile->deviceCharacteristics = 0;
30594    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
30595  }
30596  return pFile->sectorSize;
30597}
30598#endif /* __QNXNTO__ */
30599
30600/*
30601** Return the device characteristics for the file.
30602**
30603** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
30604** However, that choice is controversial since technically the underlying
30605** file system does not always provide powersafe overwrites.  (In other
30606** words, after a power-loss event, parts of the file that were never
30607** written might end up being altered.)  However, non-PSOW behavior is very,
30608** very rare.  And asserting PSOW makes a large reduction in the amount
30609** of required I/O for journaling, since a lot of padding is eliminated.
30610**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
30611** available to turn it off and URI query parameter available to turn it off.
30612*/
30613static int unixDeviceCharacteristics(sqlite3_file *id){
30614  unixFile *p = (unixFile*)id;
30615  int rc = 0;
30616#ifdef __QNXNTO__
30617  if( p->sectorSize==0 ) unixSectorSize(id);
30618  rc = p->deviceCharacteristics;
30619#endif
30620  if( p->ctrlFlags & UNIXFILE_PSOW ){
30621    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
30622  }
30623  return rc;
30624}
30625
30626#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30627
30628/*
30629** Return the system page size.
30630**
30631** This function should not be called directly by other code in this file.
30632** Instead, it should be called via macro osGetpagesize().
30633*/
30634static int unixGetpagesize(void){
30635#if OS_VXWORKS
30636  return 1024;
30637#elif defined(_BSD_SOURCE)
30638  return getpagesize();
30639#else
30640  return (int)sysconf(_SC_PAGESIZE);
30641#endif
30642}
30643
30644#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
30645
30646#ifndef SQLITE_OMIT_WAL
30647
30648/*
30649** Object used to represent an shared memory buffer.
30650**
30651** When multiple threads all reference the same wal-index, each thread
30652** has its own unixShm object, but they all point to a single instance
30653** of this unixShmNode object.  In other words, each wal-index is opened
30654** only once per process.
30655**
30656** Each unixShmNode object is connected to a single unixInodeInfo object.
30657** We could coalesce this object into unixInodeInfo, but that would mean
30658** every open file that does not use shared memory (in other words, most
30659** open files) would have to carry around this extra information.  So
30660** the unixInodeInfo object contains a pointer to this unixShmNode object
30661** and the unixShmNode object is created only when needed.
30662**
30663** unixMutexHeld() must be true when creating or destroying
30664** this object or while reading or writing the following fields:
30665**
30666**      nRef
30667**
30668** The following fields are read-only after the object is created:
30669**
30670**      fid
30671**      zFilename
30672**
30673** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
30674** unixMutexHeld() is true when reading or writing any other field
30675** in this structure.
30676*/
30677struct unixShmNode {
30678  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
30679  sqlite3_mutex *mutex;      /* Mutex to access this object */
30680  char *zFilename;           /* Name of the mmapped file */
30681  int h;                     /* Open file descriptor */
30682  int szRegion;              /* Size of shared-memory regions */
30683  u16 nRegion;               /* Size of array apRegion */
30684  u8 isReadonly;             /* True if read-only */
30685  char **apRegion;           /* Array of mapped shared-memory regions */
30686  int nRef;                  /* Number of unixShm objects pointing to this */
30687  unixShm *pFirst;           /* All unixShm objects pointing to this */
30688#ifdef SQLITE_DEBUG
30689  u8 exclMask;               /* Mask of exclusive locks held */
30690  u8 sharedMask;             /* Mask of shared locks held */
30691  u8 nextShmId;              /* Next available unixShm.id value */
30692#endif
30693};
30694
30695/*
30696** Structure used internally by this VFS to record the state of an
30697** open shared memory connection.
30698**
30699** The following fields are initialized when this object is created and
30700** are read-only thereafter:
30701**
30702**    unixShm.pFile
30703**    unixShm.id
30704**
30705** All other fields are read/write.  The unixShm.pFile->mutex must be held
30706** while accessing any read/write fields.
30707*/
30708struct unixShm {
30709  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
30710  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
30711  u8 hasMutex;               /* True if holding the unixShmNode mutex */
30712  u8 id;                     /* Id of this connection within its unixShmNode */
30713  u16 sharedMask;            /* Mask of shared locks held */
30714  u16 exclMask;              /* Mask of exclusive locks held */
30715};
30716
30717/*
30718** Constants used for locking
30719*/
30720#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
30721#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30722
30723/*
30724** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
30725**
30726** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
30727** otherwise.
30728*/
30729static int unixShmSystemLock(
30730  unixFile *pFile,       /* Open connection to the WAL file */
30731  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
30732  int ofst,              /* First byte of the locking range */
30733  int n                  /* Number of bytes to lock */
30734){
30735  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
30736  struct flock f;        /* The posix advisory locking structure */
30737  int rc = SQLITE_OK;    /* Result code form fcntl() */
30738
30739  /* Access to the unixShmNode object is serialized by the caller */
30740  pShmNode = pFile->pInode->pShmNode;
30741  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
30742
30743  /* Shared locks never span more than one byte */
30744  assert( n==1 || lockType!=F_RDLCK );
30745
30746  /* Locks are within range */
30747  assert( n>=1 && n<SQLITE_SHM_NLOCK );
30748
30749  if( pShmNode->h>=0 ){
30750    int lkType;
30751    /* Initialize the locking parameters */
30752    memset(&f, 0, sizeof(f));
30753    f.l_type = lockType;
30754    f.l_whence = SEEK_SET;
30755    f.l_start = ofst;
30756    f.l_len = n;
30757
30758    lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
30759    rc = osFcntl(pShmNode->h, lkType, &f);
30760    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
30761    pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
30762  }
30763
30764  /* Update the global lock state and do debug tracing */
30765#ifdef SQLITE_DEBUG
30766  { u16 mask;
30767  OSTRACE(("SHM-LOCK "));
30768  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
30769  if( rc==SQLITE_OK ){
30770    if( lockType==F_UNLCK ){
30771      OSTRACE(("unlock %d ok", ofst));
30772      pShmNode->exclMask &= ~mask;
30773      pShmNode->sharedMask &= ~mask;
30774    }else if( lockType==F_RDLCK ){
30775      OSTRACE(("read-lock %d ok", ofst));
30776      pShmNode->exclMask &= ~mask;
30777      pShmNode->sharedMask |= mask;
30778    }else{
30779      assert( lockType==F_WRLCK );
30780      OSTRACE(("write-lock %d ok", ofst));
30781      pShmNode->exclMask |= mask;
30782      pShmNode->sharedMask &= ~mask;
30783    }
30784  }else{
30785    if( lockType==F_UNLCK ){
30786      OSTRACE(("unlock %d failed", ofst));
30787    }else if( lockType==F_RDLCK ){
30788      OSTRACE(("read-lock failed"));
30789    }else{
30790      assert( lockType==F_WRLCK );
30791      OSTRACE(("write-lock %d failed", ofst));
30792    }
30793  }
30794  OSTRACE((" - afterwards %03x,%03x\n",
30795           pShmNode->sharedMask, pShmNode->exclMask));
30796  }
30797#endif
30798
30799  return rc;
30800}
30801
30802/*
30803** Return the minimum number of 32KB shm regions that should be mapped at
30804** a time, assuming that each mapping must be an integer multiple of the
30805** current system page-size.
30806**
30807** Usually, this is 1. The exception seems to be systems that are configured
30808** to use 64KB pages - in this case each mapping must cover at least two
30809** shm regions.
30810*/
30811static int unixShmRegionPerMap(void){
30812  int shmsz = 32*1024;            /* SHM region size */
30813  int pgsz = osGetpagesize();   /* System page size */
30814  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
30815  if( pgsz<shmsz ) return 1;
30816  return pgsz/shmsz;
30817}
30818
30819/*
30820** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
30821**
30822** This is not a VFS shared-memory method; it is a utility function called
30823** by VFS shared-memory methods.
30824*/
30825static void unixShmPurge(unixFile *pFd){
30826  unixShmNode *p = pFd->pInode->pShmNode;
30827  assert( unixMutexHeld() );
30828  if( p && p->nRef==0 ){
30829    int nShmPerMap = unixShmRegionPerMap();
30830    int i;
30831    assert( p->pInode==pFd->pInode );
30832    sqlite3_mutex_free(p->mutex);
30833    for(i=0; i<p->nRegion; i+=nShmPerMap){
30834      if( p->h>=0 ){
30835        osMunmap(p->apRegion[i], p->szRegion);
30836      }else{
30837        sqlite3_free(p->apRegion[i]);
30838      }
30839    }
30840    sqlite3_free(p->apRegion);
30841    if( p->h>=0 ){
30842      robust_close(pFd, p->h, __LINE__);
30843      p->h = -1;
30844    }
30845    p->pInode->pShmNode = 0;
30846    sqlite3_free(p);
30847  }
30848}
30849
30850/*
30851** Open a shared-memory area associated with open database file pDbFd.
30852** This particular implementation uses mmapped files.
30853**
30854** The file used to implement shared-memory is in the same directory
30855** as the open database file and has the same name as the open database
30856** file with the "-shm" suffix added.  For example, if the database file
30857** is "/home/user1/config.db" then the file that is created and mmapped
30858** for shared memory will be called "/home/user1/config.db-shm".
30859**
30860** Another approach to is to use files in /dev/shm or /dev/tmp or an
30861** some other tmpfs mount. But if a file in a different directory
30862** from the database file is used, then differing access permissions
30863** or a chroot() might cause two different processes on the same
30864** database to end up using different files for shared memory -
30865** meaning that their memory would not really be shared - resulting
30866** in database corruption.  Nevertheless, this tmpfs file usage
30867** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
30868** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
30869** option results in an incompatible build of SQLite;  builds of SQLite
30870** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
30871** same database file at the same time, database corruption will likely
30872** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
30873** "unsupported" and may go away in a future SQLite release.
30874**
30875** When opening a new shared-memory file, if no other instances of that
30876** file are currently open, in this process or in other processes, then
30877** the file must be truncated to zero length or have its header cleared.
30878**
30879** If the original database file (pDbFd) is using the "unix-excl" VFS
30880** that means that an exclusive lock is held on the database file and
30881** that no other processes are able to read or write the database.  In
30882** that case, we do not really need shared memory.  No shared memory
30883** file is created.  The shared memory will be simulated with heap memory.
30884*/
30885static int unixOpenSharedMemory(unixFile *pDbFd){
30886  struct unixShm *p = 0;          /* The connection to be opened */
30887  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
30888  int rc;                         /* Result code */
30889  unixInodeInfo *pInode;          /* The inode of fd */
30890  char *zShmFilename;             /* Name of the file used for SHM */
30891  int nShmFilename;               /* Size of the SHM filename in bytes */
30892
30893  /* Allocate space for the new unixShm object. */
30894  p = sqlite3_malloc64( sizeof(*p) );
30895  if( p==0 ) return SQLITE_NOMEM;
30896  memset(p, 0, sizeof(*p));
30897  assert( pDbFd->pShm==0 );
30898
30899  /* Check to see if a unixShmNode object already exists. Reuse an existing
30900  ** one if present. Create a new one if necessary.
30901  */
30902  unixEnterMutex();
30903  pInode = pDbFd->pInode;
30904  pShmNode = pInode->pShmNode;
30905  if( pShmNode==0 ){
30906    struct stat sStat;                 /* fstat() info for database file */
30907#ifndef SQLITE_SHM_DIRECTORY
30908    const char *zBasePath = pDbFd->zPath;
30909#endif
30910
30911    /* Call fstat() to figure out the permissions on the database file. If
30912    ** a new *-shm file is created, an attempt will be made to create it
30913    ** with the same permissions.
30914    */
30915    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
30916      rc = SQLITE_IOERR_FSTAT;
30917      goto shm_open_err;
30918    }
30919
30920#ifdef SQLITE_SHM_DIRECTORY
30921    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
30922#else
30923    nShmFilename = 6 + (int)strlen(zBasePath);
30924#endif
30925    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
30926    if( pShmNode==0 ){
30927      rc = SQLITE_NOMEM;
30928      goto shm_open_err;
30929    }
30930    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
30931    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
30932#ifdef SQLITE_SHM_DIRECTORY
30933    sqlite3_snprintf(nShmFilename, zShmFilename,
30934                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
30935                     (u32)sStat.st_ino, (u32)sStat.st_dev);
30936#else
30937    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
30938    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
30939#endif
30940    pShmNode->h = -1;
30941    pDbFd->pInode->pShmNode = pShmNode;
30942    pShmNode->pInode = pDbFd->pInode;
30943    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30944    if( pShmNode->mutex==0 ){
30945      rc = SQLITE_NOMEM;
30946      goto shm_open_err;
30947    }
30948
30949    if( pInode->bProcessLock==0 ){
30950      int openFlags = O_RDWR | O_CREAT;
30951      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
30952        openFlags = O_RDONLY;
30953        pShmNode->isReadonly = 1;
30954      }
30955      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
30956      if( pShmNode->h<0 ){
30957        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
30958        goto shm_open_err;
30959      }
30960
30961      /* If this process is running as root, make sure that the SHM file
30962      ** is owned by the same user that owns the original database.  Otherwise,
30963      ** the original owner will not be able to connect.
30964      */
30965      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
30966
30967      /* Check to see if another process is holding the dead-man switch.
30968      ** If not, truncate the file to zero length.
30969      */
30970      rc = SQLITE_OK;
30971      if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
30972        if( robust_ftruncate(pShmNode->h, 0) ){
30973          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
30974        }
30975      }
30976      if( rc==SQLITE_OK ){
30977        rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
30978      }
30979      if( rc ) goto shm_open_err;
30980    }
30981  }
30982
30983  /* Make the new connection a child of the unixShmNode */
30984  p->pShmNode = pShmNode;
30985#ifdef SQLITE_DEBUG
30986  p->id = pShmNode->nextShmId++;
30987#endif
30988  pShmNode->nRef++;
30989  pDbFd->pShm = p;
30990  unixLeaveMutex();
30991
30992  /* The reference count on pShmNode has already been incremented under
30993  ** the cover of the unixEnterMutex() mutex and the pointer from the
30994  ** new (struct unixShm) object to the pShmNode has been set. All that is
30995  ** left to do is to link the new object into the linked list starting
30996  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
30997  ** mutex.
30998  */
30999  sqlite3_mutex_enter(pShmNode->mutex);
31000  p->pNext = pShmNode->pFirst;
31001  pShmNode->pFirst = p;
31002  sqlite3_mutex_leave(pShmNode->mutex);
31003  return SQLITE_OK;
31004
31005  /* Jump here on any error */
31006shm_open_err:
31007  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
31008  sqlite3_free(p);
31009  unixLeaveMutex();
31010  return rc;
31011}
31012
31013/*
31014** This function is called to obtain a pointer to region iRegion of the
31015** shared-memory associated with the database file fd. Shared-memory regions
31016** are numbered starting from zero. Each shared-memory region is szRegion
31017** bytes in size.
31018**
31019** If an error occurs, an error code is returned and *pp is set to NULL.
31020**
31021** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
31022** region has not been allocated (by any client, including one running in a
31023** separate process), then *pp is set to NULL and SQLITE_OK returned. If
31024** bExtend is non-zero and the requested shared-memory region has not yet
31025** been allocated, it is allocated by this function.
31026**
31027** If the shared-memory region has already been allocated or is allocated by
31028** this call as described above, then it is mapped into this processes
31029** address space (if it is not already), *pp is set to point to the mapped
31030** memory and SQLITE_OK returned.
31031*/
31032static int unixShmMap(
31033  sqlite3_file *fd,               /* Handle open on database file */
31034  int iRegion,                    /* Region to retrieve */
31035  int szRegion,                   /* Size of regions */
31036  int bExtend,                    /* True to extend file if necessary */
31037  void volatile **pp              /* OUT: Mapped memory */
31038){
31039  unixFile *pDbFd = (unixFile*)fd;
31040  unixShm *p;
31041  unixShmNode *pShmNode;
31042  int rc = SQLITE_OK;
31043  int nShmPerMap = unixShmRegionPerMap();
31044  int nReqRegion;
31045
31046  /* If the shared-memory file has not yet been opened, open it now. */
31047  if( pDbFd->pShm==0 ){
31048    rc = unixOpenSharedMemory(pDbFd);
31049    if( rc!=SQLITE_OK ) return rc;
31050  }
31051
31052  p = pDbFd->pShm;
31053  pShmNode = p->pShmNode;
31054  sqlite3_mutex_enter(pShmNode->mutex);
31055  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
31056  assert( pShmNode->pInode==pDbFd->pInode );
31057  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
31058  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
31059
31060  /* Minimum number of regions required to be mapped. */
31061  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
31062
31063  if( pShmNode->nRegion<nReqRegion ){
31064    char **apNew;                      /* New apRegion[] array */
31065    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
31066    struct stat sStat;                 /* Used by fstat() */
31067
31068    pShmNode->szRegion = szRegion;
31069
31070    if( pShmNode->h>=0 ){
31071      /* The requested region is not mapped into this processes address space.
31072      ** Check to see if it has been allocated (i.e. if the wal-index file is
31073      ** large enough to contain the requested region).
31074      */
31075      if( osFstat(pShmNode->h, &sStat) ){
31076        rc = SQLITE_IOERR_SHMSIZE;
31077        goto shmpage_out;
31078      }
31079
31080      if( sStat.st_size<nByte ){
31081        /* The requested memory region does not exist. If bExtend is set to
31082        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
31083        */
31084        if( !bExtend ){
31085          goto shmpage_out;
31086        }
31087
31088        /* Alternatively, if bExtend is true, extend the file. Do this by
31089        ** writing a single byte to the end of each (OS) page being
31090        ** allocated or extended. Technically, we need only write to the
31091        ** last page in order to extend the file. But writing to all new
31092        ** pages forces the OS to allocate them immediately, which reduces
31093        ** the chances of SIGBUS while accessing the mapped region later on.
31094        */
31095        else{
31096          static const int pgsz = 4096;
31097          int iPg;
31098
31099          /* Write to the last byte of each newly allocated or extended page */
31100          assert( (nByte % pgsz)==0 );
31101          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
31102            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
31103              const char *zFile = pShmNode->zFilename;
31104              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
31105              goto shmpage_out;
31106            }
31107          }
31108        }
31109      }
31110    }
31111
31112    /* Map the requested memory region into this processes address space. */
31113    apNew = (char **)sqlite3_realloc(
31114        pShmNode->apRegion, nReqRegion*sizeof(char *)
31115    );
31116    if( !apNew ){
31117      rc = SQLITE_IOERR_NOMEM;
31118      goto shmpage_out;
31119    }
31120    pShmNode->apRegion = apNew;
31121    while( pShmNode->nRegion<nReqRegion ){
31122      int nMap = szRegion*nShmPerMap;
31123      int i;
31124      void *pMem;
31125      if( pShmNode->h>=0 ){
31126        pMem = osMmap(0, nMap,
31127            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
31128            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
31129        );
31130        if( pMem==MAP_FAILED ){
31131          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
31132          goto shmpage_out;
31133        }
31134      }else{
31135        pMem = sqlite3_malloc64(szRegion);
31136        if( pMem==0 ){
31137          rc = SQLITE_NOMEM;
31138          goto shmpage_out;
31139        }
31140        memset(pMem, 0, szRegion);
31141      }
31142
31143      for(i=0; i<nShmPerMap; i++){
31144        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
31145      }
31146      pShmNode->nRegion += nShmPerMap;
31147    }
31148  }
31149
31150shmpage_out:
31151  if( pShmNode->nRegion>iRegion ){
31152    *pp = pShmNode->apRegion[iRegion];
31153  }else{
31154    *pp = 0;
31155  }
31156  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
31157  sqlite3_mutex_leave(pShmNode->mutex);
31158  return rc;
31159}
31160
31161/*
31162** Change the lock state for a shared-memory segment.
31163**
31164** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
31165** different here than in posix.  In xShmLock(), one can go from unlocked
31166** to shared and back or from unlocked to exclusive and back.  But one may
31167** not go from shared to exclusive or from exclusive to shared.
31168*/
31169static int unixShmLock(
31170  sqlite3_file *fd,          /* Database file holding the shared memory */
31171  int ofst,                  /* First lock to acquire or release */
31172  int n,                     /* Number of locks to acquire or release */
31173  int flags                  /* What to do with the lock */
31174){
31175  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
31176  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
31177  unixShm *pX;                          /* For looping over all siblings */
31178  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
31179  int rc = SQLITE_OK;                   /* Result code */
31180  u16 mask;                             /* Mask of locks to take or release */
31181
31182  assert( pShmNode==pDbFd->pInode->pShmNode );
31183  assert( pShmNode->pInode==pDbFd->pInode );
31184  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
31185  assert( n>=1 );
31186  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
31187       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
31188       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
31189       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
31190  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
31191  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
31192  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
31193
31194  mask = (1<<(ofst+n)) - (1<<ofst);
31195  assert( n>1 || mask==(1<<ofst) );
31196  sqlite3_mutex_enter(pShmNode->mutex);
31197  if( flags & SQLITE_SHM_UNLOCK ){
31198    u16 allMask = 0; /* Mask of locks held by siblings */
31199
31200    /* See if any siblings hold this same lock */
31201    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31202      if( pX==p ) continue;
31203      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
31204      allMask |= pX->sharedMask;
31205    }
31206
31207    /* Unlock the system-level locks */
31208    if( (mask & allMask)==0 ){
31209      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
31210    }else{
31211      rc = SQLITE_OK;
31212    }
31213
31214    /* Undo the local locks */
31215    if( rc==SQLITE_OK ){
31216      p->exclMask &= ~mask;
31217      p->sharedMask &= ~mask;
31218    }
31219  }else if( flags & SQLITE_SHM_SHARED ){
31220    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
31221
31222    /* Find out which shared locks are already held by sibling connections.
31223    ** If any sibling already holds an exclusive lock, go ahead and return
31224    ** SQLITE_BUSY.
31225    */
31226    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31227      if( (pX->exclMask & mask)!=0 ){
31228        rc = SQLITE_BUSY;
31229        break;
31230      }
31231      allShared |= pX->sharedMask;
31232    }
31233
31234    /* Get shared locks at the system level, if necessary */
31235    if( rc==SQLITE_OK ){
31236      if( (allShared & mask)==0 ){
31237        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
31238      }else{
31239        rc = SQLITE_OK;
31240      }
31241    }
31242
31243    /* Get the local shared locks */
31244    if( rc==SQLITE_OK ){
31245      p->sharedMask |= mask;
31246    }
31247  }else{
31248    /* Make sure no sibling connections hold locks that will block this
31249    ** lock.  If any do, return SQLITE_BUSY right away.
31250    */
31251    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31252      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
31253        rc = SQLITE_BUSY;
31254        break;
31255      }
31256    }
31257
31258    /* Get the exclusive locks at the system level.  Then if successful
31259    ** also mark the local connection as being locked.
31260    */
31261    if( rc==SQLITE_OK ){
31262      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
31263      if( rc==SQLITE_OK ){
31264        assert( (p->sharedMask & mask)==0 );
31265        p->exclMask |= mask;
31266      }
31267    }
31268  }
31269  sqlite3_mutex_leave(pShmNode->mutex);
31270  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
31271           p->id, osGetpid(0), p->sharedMask, p->exclMask));
31272  return rc;
31273}
31274
31275/*
31276** Implement a memory barrier or memory fence on shared memory.
31277**
31278** All loads and stores begun before the barrier must complete before
31279** any load or store begun after the barrier.
31280*/
31281static void unixShmBarrier(
31282  sqlite3_file *fd                /* Database file holding the shared memory */
31283){
31284  UNUSED_PARAMETER(fd);
31285  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
31286  unixEnterMutex();               /* Also mutex, for redundancy */
31287  unixLeaveMutex();
31288}
31289
31290/*
31291** Close a connection to shared-memory.  Delete the underlying
31292** storage if deleteFlag is true.
31293**
31294** If there is no shared memory associated with the connection then this
31295** routine is a harmless no-op.
31296*/
31297static int unixShmUnmap(
31298  sqlite3_file *fd,               /* The underlying database file */
31299  int deleteFlag                  /* Delete shared-memory if true */
31300){
31301  unixShm *p;                     /* The connection to be closed */
31302  unixShmNode *pShmNode;          /* The underlying shared-memory file */
31303  unixShm **pp;                   /* For looping over sibling connections */
31304  unixFile *pDbFd;                /* The underlying database file */
31305
31306  pDbFd = (unixFile*)fd;
31307  p = pDbFd->pShm;
31308  if( p==0 ) return SQLITE_OK;
31309  pShmNode = p->pShmNode;
31310
31311  assert( pShmNode==pDbFd->pInode->pShmNode );
31312  assert( pShmNode->pInode==pDbFd->pInode );
31313
31314  /* Remove connection p from the set of connections associated
31315  ** with pShmNode */
31316  sqlite3_mutex_enter(pShmNode->mutex);
31317  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
31318  *pp = p->pNext;
31319
31320  /* Free the connection p */
31321  sqlite3_free(p);
31322  pDbFd->pShm = 0;
31323  sqlite3_mutex_leave(pShmNode->mutex);
31324
31325  /* If pShmNode->nRef has reached 0, then close the underlying
31326  ** shared-memory file, too */
31327  unixEnterMutex();
31328  assert( pShmNode->nRef>0 );
31329  pShmNode->nRef--;
31330  if( pShmNode->nRef==0 ){
31331    if( deleteFlag && pShmNode->h>=0 ){
31332      osUnlink(pShmNode->zFilename);
31333    }
31334    unixShmPurge(pDbFd);
31335  }
31336  unixLeaveMutex();
31337
31338  return SQLITE_OK;
31339}
31340
31341
31342#else
31343# define unixShmMap     0
31344# define unixShmLock    0
31345# define unixShmBarrier 0
31346# define unixShmUnmap   0
31347#endif /* #ifndef SQLITE_OMIT_WAL */
31348
31349#if SQLITE_MAX_MMAP_SIZE>0
31350/*
31351** If it is currently memory mapped, unmap file pFd.
31352*/
31353static void unixUnmapfile(unixFile *pFd){
31354  assert( pFd->nFetchOut==0 );
31355  if( pFd->pMapRegion ){
31356    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
31357    pFd->pMapRegion = 0;
31358    pFd->mmapSize = 0;
31359    pFd->mmapSizeActual = 0;
31360  }
31361}
31362
31363/*
31364** Attempt to set the size of the memory mapping maintained by file
31365** descriptor pFd to nNew bytes. Any existing mapping is discarded.
31366**
31367** If successful, this function sets the following variables:
31368**
31369**       unixFile.pMapRegion
31370**       unixFile.mmapSize
31371**       unixFile.mmapSizeActual
31372**
31373** If unsuccessful, an error message is logged via sqlite3_log() and
31374** the three variables above are zeroed. In this case SQLite should
31375** continue accessing the database using the xRead() and xWrite()
31376** methods.
31377*/
31378static void unixRemapfile(
31379  unixFile *pFd,                  /* File descriptor object */
31380  i64 nNew                        /* Required mapping size */
31381){
31382  const char *zErr = "mmap";
31383  int h = pFd->h;                      /* File descriptor open on db file */
31384  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
31385  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
31386  u8 *pNew = 0;                        /* Location of new mapping */
31387  int flags = PROT_READ;               /* Flags to pass to mmap() */
31388
31389  assert( pFd->nFetchOut==0 );
31390  assert( nNew>pFd->mmapSize );
31391  assert( nNew<=pFd->mmapSizeMax );
31392  assert( nNew>0 );
31393  assert( pFd->mmapSizeActual>=pFd->mmapSize );
31394  assert( MAP_FAILED!=0 );
31395
31396  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
31397
31398  if( pOrig ){
31399#if HAVE_MREMAP
31400    i64 nReuse = pFd->mmapSize;
31401#else
31402    const int szSyspage = osGetpagesize();
31403    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
31404#endif
31405    u8 *pReq = &pOrig[nReuse];
31406
31407    /* Unmap any pages of the existing mapping that cannot be reused. */
31408    if( nReuse!=nOrig ){
31409      osMunmap(pReq, nOrig-nReuse);
31410    }
31411
31412#if HAVE_MREMAP
31413    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
31414    zErr = "mremap";
31415#else
31416    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
31417    if( pNew!=MAP_FAILED ){
31418      if( pNew!=pReq ){
31419        osMunmap(pNew, nNew - nReuse);
31420        pNew = 0;
31421      }else{
31422        pNew = pOrig;
31423      }
31424    }
31425#endif
31426
31427    /* The attempt to extend the existing mapping failed. Free it. */
31428    if( pNew==MAP_FAILED || pNew==0 ){
31429      osMunmap(pOrig, nReuse);
31430    }
31431  }
31432
31433  /* If pNew is still NULL, try to create an entirely new mapping. */
31434  if( pNew==0 ){
31435    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
31436  }
31437
31438  if( pNew==MAP_FAILED ){
31439    pNew = 0;
31440    nNew = 0;
31441    unixLogError(SQLITE_OK, zErr, pFd->zPath);
31442
31443    /* If the mmap() above failed, assume that all subsequent mmap() calls
31444    ** will probably fail too. Fall back to using xRead/xWrite exclusively
31445    ** in this case.  */
31446    pFd->mmapSizeMax = 0;
31447  }
31448  pFd->pMapRegion = (void *)pNew;
31449  pFd->mmapSize = pFd->mmapSizeActual = nNew;
31450}
31451
31452/*
31453** Memory map or remap the file opened by file-descriptor pFd (if the file
31454** is already mapped, the existing mapping is replaced by the new). Or, if
31455** there already exists a mapping for this file, and there are still
31456** outstanding xFetch() references to it, this function is a no-op.
31457**
31458** If parameter nByte is non-negative, then it is the requested size of
31459** the mapping to create. Otherwise, if nByte is less than zero, then the
31460** requested size is the size of the file on disk. The actual size of the
31461** created mapping is either the requested size or the value configured
31462** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
31463**
31464** SQLITE_OK is returned if no error occurs (even if the mapping is not
31465** recreated as a result of outstanding references) or an SQLite error
31466** code otherwise.
31467*/
31468static int unixMapfile(unixFile *pFd, i64 nByte){
31469  i64 nMap = nByte;
31470  int rc;
31471
31472  assert( nMap>=0 || pFd->nFetchOut==0 );
31473  if( pFd->nFetchOut>0 ) return SQLITE_OK;
31474
31475  if( nMap<0 ){
31476    struct stat statbuf;          /* Low-level file information */
31477    rc = osFstat(pFd->h, &statbuf);
31478    if( rc!=SQLITE_OK ){
31479      return SQLITE_IOERR_FSTAT;
31480    }
31481    nMap = statbuf.st_size;
31482  }
31483  if( nMap>pFd->mmapSizeMax ){
31484    nMap = pFd->mmapSizeMax;
31485  }
31486
31487  if( nMap!=pFd->mmapSize ){
31488    if( nMap>0 ){
31489      unixRemapfile(pFd, nMap);
31490    }else{
31491      unixUnmapfile(pFd);
31492    }
31493  }
31494
31495  return SQLITE_OK;
31496}
31497#endif /* SQLITE_MAX_MMAP_SIZE>0 */
31498
31499/*
31500** If possible, return a pointer to a mapping of file fd starting at offset
31501** iOff. The mapping must be valid for at least nAmt bytes.
31502**
31503** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
31504** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
31505** Finally, if an error does occur, return an SQLite error code. The final
31506** value of *pp is undefined in this case.
31507**
31508** If this function does return a pointer, the caller must eventually
31509** release the reference by calling unixUnfetch().
31510*/
31511static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
31512#if SQLITE_MAX_MMAP_SIZE>0
31513  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
31514#endif
31515  *pp = 0;
31516
31517#if SQLITE_MAX_MMAP_SIZE>0
31518  if( pFd->mmapSizeMax>0 ){
31519    if( pFd->pMapRegion==0 ){
31520      int rc = unixMapfile(pFd, -1);
31521      if( rc!=SQLITE_OK ) return rc;
31522    }
31523    if( pFd->mmapSize >= iOff+nAmt ){
31524      *pp = &((u8 *)pFd->pMapRegion)[iOff];
31525      pFd->nFetchOut++;
31526    }
31527  }
31528#endif
31529  return SQLITE_OK;
31530}
31531
31532/*
31533** If the third argument is non-NULL, then this function releases a
31534** reference obtained by an earlier call to unixFetch(). The second
31535** argument passed to this function must be the same as the corresponding
31536** argument that was passed to the unixFetch() invocation.
31537**
31538** Or, if the third argument is NULL, then this function is being called
31539** to inform the VFS layer that, according to POSIX, any existing mapping
31540** may now be invalid and should be unmapped.
31541*/
31542static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
31543#if SQLITE_MAX_MMAP_SIZE>0
31544  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
31545  UNUSED_PARAMETER(iOff);
31546
31547  /* If p==0 (unmap the entire file) then there must be no outstanding
31548  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
31549  ** then there must be at least one outstanding.  */
31550  assert( (p==0)==(pFd->nFetchOut==0) );
31551
31552  /* If p!=0, it must match the iOff value. */
31553  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
31554
31555  if( p ){
31556    pFd->nFetchOut--;
31557  }else{
31558    unixUnmapfile(pFd);
31559  }
31560
31561  assert( pFd->nFetchOut>=0 );
31562#else
31563  UNUSED_PARAMETER(fd);
31564  UNUSED_PARAMETER(p);
31565  UNUSED_PARAMETER(iOff);
31566#endif
31567  return SQLITE_OK;
31568}
31569
31570/*
31571** Here ends the implementation of all sqlite3_file methods.
31572**
31573********************** End sqlite3_file Methods *******************************
31574******************************************************************************/
31575
31576/*
31577** This division contains definitions of sqlite3_io_methods objects that
31578** implement various file locking strategies.  It also contains definitions
31579** of "finder" functions.  A finder-function is used to locate the appropriate
31580** sqlite3_io_methods object for a particular database file.  The pAppData
31581** field of the sqlite3_vfs VFS objects are initialized to be pointers to
31582** the correct finder-function for that VFS.
31583**
31584** Most finder functions return a pointer to a fixed sqlite3_io_methods
31585** object.  The only interesting finder-function is autolockIoFinder, which
31586** looks at the filesystem type and tries to guess the best locking
31587** strategy from that.
31588**
31589** For finder-function F, two objects are created:
31590**
31591**    (1) The real finder-function named "FImpt()".
31592**
31593**    (2) A constant pointer to this function named just "F".
31594**
31595**
31596** A pointer to the F pointer is used as the pAppData value for VFS
31597** objects.  We have to do this instead of letting pAppData point
31598** directly at the finder-function since C90 rules prevent a void*
31599** from be cast into a function pointer.
31600**
31601**
31602** Each instance of this macro generates two objects:
31603**
31604**   *  A constant sqlite3_io_methods object call METHOD that has locking
31605**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
31606**
31607**   *  An I/O method finder function called FINDER that returns a pointer
31608**      to the METHOD object in the previous bullet.
31609*/
31610#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
31611static const sqlite3_io_methods METHOD = {                                   \
31612   VERSION,                    /* iVersion */                                \
31613   CLOSE,                      /* xClose */                                  \
31614   unixRead,                   /* xRead */                                   \
31615   unixWrite,                  /* xWrite */                                  \
31616   unixTruncate,               /* xTruncate */                               \
31617   unixSync,                   /* xSync */                                   \
31618   unixFileSize,               /* xFileSize */                               \
31619   LOCK,                       /* xLock */                                   \
31620   UNLOCK,                     /* xUnlock */                                 \
31621   CKLOCK,                     /* xCheckReservedLock */                      \
31622   unixFileControl,            /* xFileControl */                            \
31623   unixSectorSize,             /* xSectorSize */                             \
31624   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
31625   SHMMAP,                     /* xShmMap */                                 \
31626   unixShmLock,                /* xShmLock */                                \
31627   unixShmBarrier,             /* xShmBarrier */                             \
31628   unixShmUnmap,               /* xShmUnmap */                               \
31629   unixFetch,                  /* xFetch */                                  \
31630   unixUnfetch,                /* xUnfetch */                                \
31631};                                                                           \
31632static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
31633  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
31634  return &METHOD;                                                            \
31635}                                                                            \
31636static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
31637    = FINDER##Impl;
31638
31639/*
31640** Here are all of the sqlite3_io_methods objects for each of the
31641** locking strategies.  Functions that return pointers to these methods
31642** are also created.
31643*/
31644IOMETHODS(
31645  posixIoFinder,            /* Finder function name */
31646  posixIoMethods,           /* sqlite3_io_methods object name */
31647  3,                        /* shared memory and mmap are enabled */
31648  unixClose,                /* xClose method */
31649  unixLock,                 /* xLock method */
31650  unixUnlock,               /* xUnlock method */
31651  unixCheckReservedLock,    /* xCheckReservedLock method */
31652  unixShmMap                /* xShmMap method */
31653)
31654IOMETHODS(
31655  nolockIoFinder,           /* Finder function name */
31656  nolockIoMethods,          /* sqlite3_io_methods object name */
31657  3,                        /* shared memory is disabled */
31658  nolockClose,              /* xClose method */
31659  nolockLock,               /* xLock method */
31660  nolockUnlock,             /* xUnlock method */
31661  nolockCheckReservedLock,  /* xCheckReservedLock method */
31662  0                         /* xShmMap method */
31663)
31664IOMETHODS(
31665  dotlockIoFinder,          /* Finder function name */
31666  dotlockIoMethods,         /* sqlite3_io_methods object name */
31667  1,                        /* shared memory is disabled */
31668  dotlockClose,             /* xClose method */
31669  dotlockLock,              /* xLock method */
31670  dotlockUnlock,            /* xUnlock method */
31671  dotlockCheckReservedLock, /* xCheckReservedLock method */
31672  0                         /* xShmMap method */
31673)
31674
31675#if SQLITE_ENABLE_LOCKING_STYLE
31676IOMETHODS(
31677  flockIoFinder,            /* Finder function name */
31678  flockIoMethods,           /* sqlite3_io_methods object name */
31679  1,                        /* shared memory is disabled */
31680  flockClose,               /* xClose method */
31681  flockLock,                /* xLock method */
31682  flockUnlock,              /* xUnlock method */
31683  flockCheckReservedLock,   /* xCheckReservedLock method */
31684  0                         /* xShmMap method */
31685)
31686#endif
31687
31688#if OS_VXWORKS
31689IOMETHODS(
31690  semIoFinder,              /* Finder function name */
31691  semIoMethods,             /* sqlite3_io_methods object name */
31692  1,                        /* shared memory is disabled */
31693  semXClose,                /* xClose method */
31694  semXLock,                 /* xLock method */
31695  semXUnlock,               /* xUnlock method */
31696  semXCheckReservedLock,    /* xCheckReservedLock method */
31697  0                         /* xShmMap method */
31698)
31699#endif
31700
31701#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31702IOMETHODS(
31703  afpIoFinder,              /* Finder function name */
31704  afpIoMethods,             /* sqlite3_io_methods object name */
31705  1,                        /* shared memory is disabled */
31706  afpClose,                 /* xClose method */
31707  afpLock,                  /* xLock method */
31708  afpUnlock,                /* xUnlock method */
31709  afpCheckReservedLock,     /* xCheckReservedLock method */
31710  0                         /* xShmMap method */
31711)
31712#endif
31713
31714/*
31715** The proxy locking method is a "super-method" in the sense that it
31716** opens secondary file descriptors for the conch and lock files and
31717** it uses proxy, dot-file, AFP, and flock() locking methods on those
31718** secondary files.  For this reason, the division that implements
31719** proxy locking is located much further down in the file.  But we need
31720** to go ahead and define the sqlite3_io_methods and finder function
31721** for proxy locking here.  So we forward declare the I/O methods.
31722*/
31723#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31724static int proxyClose(sqlite3_file*);
31725static int proxyLock(sqlite3_file*, int);
31726static int proxyUnlock(sqlite3_file*, int);
31727static int proxyCheckReservedLock(sqlite3_file*, int*);
31728IOMETHODS(
31729  proxyIoFinder,            /* Finder function name */
31730  proxyIoMethods,           /* sqlite3_io_methods object name */
31731  1,                        /* shared memory is disabled */
31732  proxyClose,               /* xClose method */
31733  proxyLock,                /* xLock method */
31734  proxyUnlock,              /* xUnlock method */
31735  proxyCheckReservedLock,   /* xCheckReservedLock method */
31736  0                         /* xShmMap method */
31737)
31738#endif
31739
31740/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
31741#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31742IOMETHODS(
31743  nfsIoFinder,               /* Finder function name */
31744  nfsIoMethods,              /* sqlite3_io_methods object name */
31745  1,                         /* shared memory is disabled */
31746  unixClose,                 /* xClose method */
31747  unixLock,                  /* xLock method */
31748  nfsUnlock,                 /* xUnlock method */
31749  unixCheckReservedLock,     /* xCheckReservedLock method */
31750  0                          /* xShmMap method */
31751)
31752#endif
31753
31754#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31755/*
31756** This "finder" function attempts to determine the best locking strategy
31757** for the database file "filePath".  It then returns the sqlite3_io_methods
31758** object that implements that strategy.
31759**
31760** This is for MacOSX only.
31761*/
31762static const sqlite3_io_methods *autolockIoFinderImpl(
31763  const char *filePath,    /* name of the database file */
31764  unixFile *pNew           /* open file object for the database file */
31765){
31766  static const struct Mapping {
31767    const char *zFilesystem;              /* Filesystem type name */
31768    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
31769  } aMap[] = {
31770    { "hfs",    &posixIoMethods },
31771    { "ufs",    &posixIoMethods },
31772    { "afpfs",  &afpIoMethods },
31773    { "smbfs",  &afpIoMethods },
31774    { "webdav", &nolockIoMethods },
31775    { 0, 0 }
31776  };
31777  int i;
31778  struct statfs fsInfo;
31779  struct flock lockInfo;
31780
31781  if( !filePath ){
31782    /* If filePath==NULL that means we are dealing with a transient file
31783    ** that does not need to be locked. */
31784    return &nolockIoMethods;
31785  }
31786  if( statfs(filePath, &fsInfo) != -1 ){
31787    if( fsInfo.f_flags & MNT_RDONLY ){
31788      return &nolockIoMethods;
31789    }
31790    for(i=0; aMap[i].zFilesystem; i++){
31791      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
31792        return aMap[i].pMethods;
31793      }
31794    }
31795  }
31796
31797  /* Default case. Handles, amongst others, "nfs".
31798  ** Test byte-range lock using fcntl(). If the call succeeds,
31799  ** assume that the file-system supports POSIX style locks.
31800  */
31801  lockInfo.l_len = 1;
31802  lockInfo.l_start = 0;
31803  lockInfo.l_whence = SEEK_SET;
31804  lockInfo.l_type = F_RDLCK;
31805  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31806    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
31807      return &nfsIoMethods;
31808    } else {
31809      return &posixIoMethods;
31810    }
31811  }else{
31812    return &dotlockIoMethods;
31813  }
31814}
31815static const sqlite3_io_methods
31816  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31817
31818#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31819
31820#if OS_VXWORKS
31821/*
31822** This "finder" function for VxWorks checks to see if posix advisory
31823** locking works.  If it does, then that is what is used.  If it does not
31824** work, then fallback to named semaphore locking.
31825*/
31826static const sqlite3_io_methods *vxworksIoFinderImpl(
31827  const char *filePath,    /* name of the database file */
31828  unixFile *pNew           /* the open file object */
31829){
31830  struct flock lockInfo;
31831
31832  if( !filePath ){
31833    /* If filePath==NULL that means we are dealing with a transient file
31834    ** that does not need to be locked. */
31835    return &nolockIoMethods;
31836  }
31837
31838  /* Test if fcntl() is supported and use POSIX style locks.
31839  ** Otherwise fall back to the named semaphore method.
31840  */
31841  lockInfo.l_len = 1;
31842  lockInfo.l_start = 0;
31843  lockInfo.l_whence = SEEK_SET;
31844  lockInfo.l_type = F_RDLCK;
31845  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31846    return &posixIoMethods;
31847  }else{
31848    return &semIoMethods;
31849  }
31850}
31851static const sqlite3_io_methods
31852  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
31853
31854#endif /* OS_VXWORKS */
31855
31856/*
31857** An abstract type for a pointer to an IO method finder function:
31858*/
31859typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
31860
31861
31862/****************************************************************************
31863**************************** sqlite3_vfs methods ****************************
31864**
31865** This division contains the implementation of methods on the
31866** sqlite3_vfs object.
31867*/
31868
31869/*
31870** Initialize the contents of the unixFile structure pointed to by pId.
31871*/
31872static int fillInUnixFile(
31873  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
31874  int h,                  /* Open file descriptor of file being opened */
31875  sqlite3_file *pId,      /* Write to the unixFile structure here */
31876  const char *zFilename,  /* Name of the file being opened */
31877  int ctrlFlags           /* Zero or more UNIXFILE_* values */
31878){
31879  const sqlite3_io_methods *pLockingStyle;
31880  unixFile *pNew = (unixFile *)pId;
31881  int rc = SQLITE_OK;
31882
31883  assert( pNew->pInode==NULL );
31884
31885  /* Usually the path zFilename should not be a relative pathname. The
31886  ** exception is when opening the proxy "conch" file in builds that
31887  ** include the special Apple locking styles.
31888  */
31889#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31890  assert( zFilename==0 || zFilename[0]=='/'
31891    || pVfs->pAppData==(void*)&autolockIoFinder );
31892#else
31893  assert( zFilename==0 || zFilename[0]=='/' );
31894#endif
31895
31896  /* No locking occurs in temporary files */
31897  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
31898
31899  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
31900  pNew->h = h;
31901  pNew->pVfs = pVfs;
31902  pNew->zPath = zFilename;
31903  pNew->ctrlFlags = (u8)ctrlFlags;
31904#if SQLITE_MAX_MMAP_SIZE>0
31905  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
31906#endif
31907  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
31908                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
31909    pNew->ctrlFlags |= UNIXFILE_PSOW;
31910  }
31911  if( strcmp(pVfs->zName,"unix-excl")==0 ){
31912    pNew->ctrlFlags |= UNIXFILE_EXCL;
31913  }
31914
31915#if OS_VXWORKS
31916  pNew->pId = vxworksFindFileId(zFilename);
31917  if( pNew->pId==0 ){
31918    ctrlFlags |= UNIXFILE_NOLOCK;
31919    rc = SQLITE_NOMEM;
31920  }
31921#endif
31922
31923  if( ctrlFlags & UNIXFILE_NOLOCK ){
31924    pLockingStyle = &nolockIoMethods;
31925  }else{
31926    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
31927#if SQLITE_ENABLE_LOCKING_STYLE
31928    /* Cache zFilename in the locking context (AFP and dotlock override) for
31929    ** proxyLock activation is possible (remote proxy is based on db name)
31930    ** zFilename remains valid until file is closed, to support */
31931    pNew->lockingContext = (void*)zFilename;
31932#endif
31933  }
31934
31935  if( pLockingStyle == &posixIoMethods
31936#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31937    || pLockingStyle == &nfsIoMethods
31938#endif
31939  ){
31940    unixEnterMutex();
31941    rc = findInodeInfo(pNew, &pNew->pInode);
31942    if( rc!=SQLITE_OK ){
31943      /* If an error occurred in findInodeInfo(), close the file descriptor
31944      ** immediately, before releasing the mutex. findInodeInfo() may fail
31945      ** in two scenarios:
31946      **
31947      **   (a) A call to fstat() failed.
31948      **   (b) A malloc failed.
31949      **
31950      ** Scenario (b) may only occur if the process is holding no other
31951      ** file descriptors open on the same file. If there were other file
31952      ** descriptors on this file, then no malloc would be required by
31953      ** findInodeInfo(). If this is the case, it is quite safe to close
31954      ** handle h - as it is guaranteed that no posix locks will be released
31955      ** by doing so.
31956      **
31957      ** If scenario (a) caused the error then things are not so safe. The
31958      ** implicit assumption here is that if fstat() fails, things are in
31959      ** such bad shape that dropping a lock or two doesn't matter much.
31960      */
31961      robust_close(pNew, h, __LINE__);
31962      h = -1;
31963    }
31964    unixLeaveMutex();
31965  }
31966
31967#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31968  else if( pLockingStyle == &afpIoMethods ){
31969    /* AFP locking uses the file path so it needs to be included in
31970    ** the afpLockingContext.
31971    */
31972    afpLockingContext *pCtx;
31973    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
31974    if( pCtx==0 ){
31975      rc = SQLITE_NOMEM;
31976    }else{
31977      /* NB: zFilename exists and remains valid until the file is closed
31978      ** according to requirement F11141.  So we do not need to make a
31979      ** copy of the filename. */
31980      pCtx->dbPath = zFilename;
31981      pCtx->reserved = 0;
31982      srandomdev();
31983      unixEnterMutex();
31984      rc = findInodeInfo(pNew, &pNew->pInode);
31985      if( rc!=SQLITE_OK ){
31986        sqlite3_free(pNew->lockingContext);
31987        robust_close(pNew, h, __LINE__);
31988        h = -1;
31989      }
31990      unixLeaveMutex();
31991    }
31992  }
31993#endif
31994
31995  else if( pLockingStyle == &dotlockIoMethods ){
31996    /* Dotfile locking uses the file path so it needs to be included in
31997    ** the dotlockLockingContext
31998    */
31999    char *zLockFile;
32000    int nFilename;
32001    assert( zFilename!=0 );
32002    nFilename = (int)strlen(zFilename) + 6;
32003    zLockFile = (char *)sqlite3_malloc64(nFilename);
32004    if( zLockFile==0 ){
32005      rc = SQLITE_NOMEM;
32006    }else{
32007      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
32008    }
32009    pNew->lockingContext = zLockFile;
32010  }
32011
32012#if OS_VXWORKS
32013  else if( pLockingStyle == &semIoMethods ){
32014    /* Named semaphore locking uses the file path so it needs to be
32015    ** included in the semLockingContext
32016    */
32017    unixEnterMutex();
32018    rc = findInodeInfo(pNew, &pNew->pInode);
32019    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
32020      char *zSemName = pNew->pInode->aSemName;
32021      int n;
32022      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
32023                       pNew->pId->zCanonicalName);
32024      for( n=1; zSemName[n]; n++ )
32025        if( zSemName[n]=='/' ) zSemName[n] = '_';
32026      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
32027      if( pNew->pInode->pSem == SEM_FAILED ){
32028        rc = SQLITE_NOMEM;
32029        pNew->pInode->aSemName[0] = '\0';
32030      }
32031    }
32032    unixLeaveMutex();
32033  }
32034#endif
32035
32036  storeLastErrno(pNew, 0);
32037#if OS_VXWORKS
32038  if( rc!=SQLITE_OK ){
32039    if( h>=0 ) robust_close(pNew, h, __LINE__);
32040    h = -1;
32041    osUnlink(zFilename);
32042    pNew->ctrlFlags |= UNIXFILE_DELETE;
32043  }
32044#endif
32045  if( rc!=SQLITE_OK ){
32046    if( h>=0 ) robust_close(pNew, h, __LINE__);
32047  }else{
32048    pNew->pMethod = pLockingStyle;
32049    OpenCounter(+1);
32050    verifyDbFile(pNew);
32051  }
32052  return rc;
32053}
32054
32055/*
32056** Return the name of a directory in which to put temporary files.
32057** If no suitable temporary file directory can be found, return NULL.
32058*/
32059static const char *unixTempFileDir(void){
32060  static const char *azDirs[] = {
32061     0,
32062     0,
32063     0,
32064     "/var/tmp",
32065     "/usr/tmp",
32066     "/tmp",
32067     0        /* List terminator */
32068  };
32069  unsigned int i;
32070  struct stat buf;
32071  const char *zDir = 0;
32072
32073  azDirs[0] = sqlite3_temp_directory;
32074  if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
32075  if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
32076  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
32077    if( zDir==0 ) continue;
32078    if( osStat(zDir, &buf) ) continue;
32079    if( !S_ISDIR(buf.st_mode) ) continue;
32080    if( osAccess(zDir, 07) ) continue;
32081    break;
32082  }
32083  return zDir;
32084}
32085
32086/*
32087** Create a temporary file name in zBuf.  zBuf must be allocated
32088** by the calling process and must be big enough to hold at least
32089** pVfs->mxPathname bytes.
32090*/
32091static int unixGetTempname(int nBuf, char *zBuf){
32092  static const unsigned char zChars[] =
32093    "abcdefghijklmnopqrstuvwxyz"
32094    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32095    "0123456789";
32096  unsigned int i, j;
32097  const char *zDir;
32098
32099  /* It's odd to simulate an io-error here, but really this is just
32100  ** using the io-error infrastructure to test that SQLite handles this
32101  ** function failing.
32102  */
32103  SimulateIOError( return SQLITE_IOERR );
32104
32105  zDir = unixTempFileDir();
32106  if( zDir==0 ) zDir = ".";
32107
32108  /* Check that the output buffer is large enough for the temporary file
32109  ** name. If it is not, return SQLITE_ERROR.
32110  */
32111  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
32112    return SQLITE_ERROR;
32113  }
32114
32115  do{
32116    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
32117    j = (int)strlen(zBuf);
32118    sqlite3_randomness(15, &zBuf[j]);
32119    for(i=0; i<15; i++, j++){
32120      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
32121    }
32122    zBuf[j] = 0;
32123    zBuf[j+1] = 0;
32124  }while( osAccess(zBuf,0)==0 );
32125  return SQLITE_OK;
32126}
32127
32128#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32129/*
32130** Routine to transform a unixFile into a proxy-locking unixFile.
32131** Implementation in the proxy-lock division, but used by unixOpen()
32132** if SQLITE_PREFER_PROXY_LOCKING is defined.
32133*/
32134static int proxyTransformUnixFile(unixFile*, const char*);
32135#endif
32136
32137/*
32138** Search for an unused file descriptor that was opened on the database
32139** file (not a journal or master-journal file) identified by pathname
32140** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
32141** argument to this function.
32142**
32143** Such a file descriptor may exist if a database connection was closed
32144** but the associated file descriptor could not be closed because some
32145** other file descriptor open on the same file is holding a file-lock.
32146** Refer to comments in the unixClose() function and the lengthy comment
32147** describing "Posix Advisory Locking" at the start of this file for
32148** further details. Also, ticket #4018.
32149**
32150** If a suitable file descriptor is found, then it is returned. If no
32151** such file descriptor is located, -1 is returned.
32152*/
32153static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
32154  UnixUnusedFd *pUnused = 0;
32155
32156  /* Do not search for an unused file descriptor on vxworks. Not because
32157  ** vxworks would not benefit from the change (it might, we're not sure),
32158  ** but because no way to test it is currently available. It is better
32159  ** not to risk breaking vxworks support for the sake of such an obscure
32160  ** feature.  */
32161#if !OS_VXWORKS
32162  struct stat sStat;                   /* Results of stat() call */
32163
32164  /* A stat() call may fail for various reasons. If this happens, it is
32165  ** almost certain that an open() call on the same path will also fail.
32166  ** For this reason, if an error occurs in the stat() call here, it is
32167  ** ignored and -1 is returned. The caller will try to open a new file
32168  ** descriptor on the same path, fail, and return an error to SQLite.
32169  **
32170  ** Even if a subsequent open() call does succeed, the consequences of
32171  ** not searching for a reusable file descriptor are not dire.  */
32172  if( 0==osStat(zPath, &sStat) ){
32173    unixInodeInfo *pInode;
32174
32175    unixEnterMutex();
32176    pInode = inodeList;
32177    while( pInode && (pInode->fileId.dev!=sStat.st_dev
32178                     || pInode->fileId.ino!=sStat.st_ino) ){
32179       pInode = pInode->pNext;
32180    }
32181    if( pInode ){
32182      UnixUnusedFd **pp;
32183      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
32184      pUnused = *pp;
32185      if( pUnused ){
32186        *pp = pUnused->pNext;
32187      }
32188    }
32189    unixLeaveMutex();
32190  }
32191#endif    /* if !OS_VXWORKS */
32192  return pUnused;
32193}
32194
32195/*
32196** This function is called by unixOpen() to determine the unix permissions
32197** to create new files with. If no error occurs, then SQLITE_OK is returned
32198** and a value suitable for passing as the third argument to open(2) is
32199** written to *pMode. If an IO error occurs, an SQLite error code is
32200** returned and the value of *pMode is not modified.
32201**
32202** In most cases, this routine sets *pMode to 0, which will become
32203** an indication to robust_open() to create the file using
32204** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
32205** But if the file being opened is a WAL or regular journal file, then
32206** this function queries the file-system for the permissions on the
32207** corresponding database file and sets *pMode to this value. Whenever
32208** possible, WAL and journal files are created using the same permissions
32209** as the associated database file.
32210**
32211** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
32212** original filename is unavailable.  But 8_3_NAMES is only used for
32213** FAT filesystems and permissions do not matter there, so just use
32214** the default permissions.
32215*/
32216static int findCreateFileMode(
32217  const char *zPath,              /* Path of file (possibly) being created */
32218  int flags,                      /* Flags passed as 4th argument to xOpen() */
32219  mode_t *pMode,                  /* OUT: Permissions to open file with */
32220  uid_t *pUid,                    /* OUT: uid to set on the file */
32221  gid_t *pGid                     /* OUT: gid to set on the file */
32222){
32223  int rc = SQLITE_OK;             /* Return Code */
32224  *pMode = 0;
32225  *pUid = 0;
32226  *pGid = 0;
32227  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
32228    char zDb[MAX_PATHNAME+1];     /* Database file path */
32229    int nDb;                      /* Number of valid bytes in zDb */
32230    struct stat sStat;            /* Output of stat() on database file */
32231
32232    /* zPath is a path to a WAL or journal file. The following block derives
32233    ** the path to the associated database file from zPath. This block handles
32234    ** the following naming conventions:
32235    **
32236    **   "<path to db>-journal"
32237    **   "<path to db>-wal"
32238    **   "<path to db>-journalNN"
32239    **   "<path to db>-walNN"
32240    **
32241    ** where NN is a decimal number. The NN naming schemes are
32242    ** used by the test_multiplex.c module.
32243    */
32244    nDb = sqlite3Strlen30(zPath) - 1;
32245#ifdef SQLITE_ENABLE_8_3_NAMES
32246    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
32247    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
32248#else
32249    while( zPath[nDb]!='-' ){
32250      assert( nDb>0 );
32251      assert( zPath[nDb]!='\n' );
32252      nDb--;
32253    }
32254#endif
32255    memcpy(zDb, zPath, nDb);
32256    zDb[nDb] = '\0';
32257
32258    if( 0==osStat(zDb, &sStat) ){
32259      *pMode = sStat.st_mode & 0777;
32260      *pUid = sStat.st_uid;
32261      *pGid = sStat.st_gid;
32262    }else{
32263      rc = SQLITE_IOERR_FSTAT;
32264    }
32265  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
32266    *pMode = 0600;
32267  }
32268  return rc;
32269}
32270
32271/*
32272** Open the file zPath.
32273**
32274** Previously, the SQLite OS layer used three functions in place of this
32275** one:
32276**
32277**     sqlite3OsOpenReadWrite();
32278**     sqlite3OsOpenReadOnly();
32279**     sqlite3OsOpenExclusive();
32280**
32281** These calls correspond to the following combinations of flags:
32282**
32283**     ReadWrite() ->     (READWRITE | CREATE)
32284**     ReadOnly()  ->     (READONLY)
32285**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
32286**
32287** The old OpenExclusive() accepted a boolean argument - "delFlag". If
32288** true, the file was configured to be automatically deleted when the
32289** file handle closed. To achieve the same effect using this new
32290** interface, add the DELETEONCLOSE flag to those specified above for
32291** OpenExclusive().
32292*/
32293static int unixOpen(
32294  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
32295  const char *zPath,           /* Pathname of file to be opened */
32296  sqlite3_file *pFile,         /* The file descriptor to be filled in */
32297  int flags,                   /* Input flags to control the opening */
32298  int *pOutFlags               /* Output flags returned to SQLite core */
32299){
32300  unixFile *p = (unixFile *)pFile;
32301  int fd = -1;                   /* File descriptor returned by open() */
32302  int openFlags = 0;             /* Flags to pass to open() */
32303  int eType = flags&0xFFFFFF00;  /* Type of file to open */
32304  int noLock;                    /* True to omit locking primitives */
32305  int rc = SQLITE_OK;            /* Function Return Code */
32306  int ctrlFlags = 0;             /* UNIXFILE_* flags */
32307
32308  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
32309  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
32310  int isCreate     = (flags & SQLITE_OPEN_CREATE);
32311  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
32312  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
32313#if SQLITE_ENABLE_LOCKING_STYLE
32314  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
32315#endif
32316#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
32317  struct statfs fsInfo;
32318#endif
32319
32320  /* If creating a master or main-file journal, this function will open
32321  ** a file-descriptor on the directory too. The first time unixSync()
32322  ** is called the directory file descriptor will be fsync()ed and close()d.
32323  */
32324  int syncDir = (isCreate && (
32325        eType==SQLITE_OPEN_MASTER_JOURNAL
32326     || eType==SQLITE_OPEN_MAIN_JOURNAL
32327     || eType==SQLITE_OPEN_WAL
32328  ));
32329
32330  /* If argument zPath is a NULL pointer, this function is required to open
32331  ** a temporary file. Use this buffer to store the file name in.
32332  */
32333  char zTmpname[MAX_PATHNAME+2];
32334  const char *zName = zPath;
32335
32336  /* Check the following statements are true:
32337  **
32338  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
32339  **   (b) if CREATE is set, then READWRITE must also be set, and
32340  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
32341  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
32342  */
32343  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
32344  assert(isCreate==0 || isReadWrite);
32345  assert(isExclusive==0 || isCreate);
32346  assert(isDelete==0 || isCreate);
32347
32348  /* The main DB, main journal, WAL file and master journal are never
32349  ** automatically deleted. Nor are they ever temporary files.  */
32350  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
32351  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
32352  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
32353  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
32354
32355  /* Assert that the upper layer has set one of the "file-type" flags. */
32356  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
32357       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
32358       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
32359       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
32360  );
32361
32362  /* Detect a pid change and reset the PRNG.  There is a race condition
32363  ** here such that two or more threads all trying to open databases at
32364  ** the same instant might all reset the PRNG.  But multiple resets
32365  ** are harmless.
32366  */
32367  if( randomnessPid!=osGetpid(0) ){
32368    randomnessPid = osGetpid(0);
32369    sqlite3_randomness(0,0);
32370  }
32371
32372  memset(p, 0, sizeof(unixFile));
32373
32374  if( eType==SQLITE_OPEN_MAIN_DB ){
32375    UnixUnusedFd *pUnused;
32376    pUnused = findReusableFd(zName, flags);
32377    if( pUnused ){
32378      fd = pUnused->fd;
32379    }else{
32380      pUnused = sqlite3_malloc64(sizeof(*pUnused));
32381      if( !pUnused ){
32382        return SQLITE_NOMEM;
32383      }
32384    }
32385    p->pUnused = pUnused;
32386
32387    /* Database filenames are double-zero terminated if they are not
32388    ** URIs with parameters.  Hence, they can always be passed into
32389    ** sqlite3_uri_parameter(). */
32390    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
32391
32392  }else if( !zName ){
32393    /* If zName is NULL, the upper layer is requesting a temp file. */
32394    assert(isDelete && !syncDir);
32395    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
32396    if( rc!=SQLITE_OK ){
32397      return rc;
32398    }
32399    zName = zTmpname;
32400
32401    /* Generated temporary filenames are always double-zero terminated
32402    ** for use by sqlite3_uri_parameter(). */
32403    assert( zName[strlen(zName)+1]==0 );
32404  }
32405
32406  /* Determine the value of the flags parameter passed to POSIX function
32407  ** open(). These must be calculated even if open() is not called, as
32408  ** they may be stored as part of the file handle and used by the
32409  ** 'conch file' locking functions later on.  */
32410  if( isReadonly )  openFlags |= O_RDONLY;
32411  if( isReadWrite ) openFlags |= O_RDWR;
32412  if( isCreate )    openFlags |= O_CREAT;
32413  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
32414  openFlags |= (O_LARGEFILE|O_BINARY);
32415
32416  if( fd<0 ){
32417    mode_t openMode;              /* Permissions to create file with */
32418    uid_t uid;                    /* Userid for the file */
32419    gid_t gid;                    /* Groupid for the file */
32420    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
32421    if( rc!=SQLITE_OK ){
32422      assert( !p->pUnused );
32423      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
32424      return rc;
32425    }
32426    fd = robust_open(zName, openFlags, openMode);
32427    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
32428    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
32429      /* Failed to open the file for read/write access. Try read-only. */
32430      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
32431      openFlags &= ~(O_RDWR|O_CREAT);
32432      flags |= SQLITE_OPEN_READONLY;
32433      openFlags |= O_RDONLY;
32434      isReadonly = 1;
32435      fd = robust_open(zName, openFlags, openMode);
32436    }
32437    if( fd<0 ){
32438      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
32439      goto open_finished;
32440    }
32441
32442    /* If this process is running as root and if creating a new rollback
32443    ** journal or WAL file, set the ownership of the journal or WAL to be
32444    ** the same as the original database.
32445    */
32446    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
32447      osFchown(fd, uid, gid);
32448    }
32449  }
32450  assert( fd>=0 );
32451  if( pOutFlags ){
32452    *pOutFlags = flags;
32453  }
32454
32455  if( p->pUnused ){
32456    p->pUnused->fd = fd;
32457    p->pUnused->flags = flags;
32458  }
32459
32460  if( isDelete ){
32461#if OS_VXWORKS
32462    zPath = zName;
32463#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
32464    zPath = sqlite3_mprintf("%s", zName);
32465    if( zPath==0 ){
32466      robust_close(p, fd, __LINE__);
32467      return SQLITE_NOMEM;
32468    }
32469#else
32470    osUnlink(zName);
32471#endif
32472  }
32473#if SQLITE_ENABLE_LOCKING_STYLE
32474  else{
32475    p->openFlags = openFlags;
32476  }
32477#endif
32478
32479  noLock = eType!=SQLITE_OPEN_MAIN_DB;
32480
32481
32482#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
32483  if( fstatfs(fd, &fsInfo) == -1 ){
32484    storeLastErrno(p, errno);
32485    robust_close(p, fd, __LINE__);
32486    return SQLITE_IOERR_ACCESS;
32487  }
32488  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
32489    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
32490  }
32491  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
32492    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
32493  }
32494#endif
32495
32496  /* Set up appropriate ctrlFlags */
32497  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
32498  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
32499  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
32500  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
32501  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
32502
32503#if SQLITE_ENABLE_LOCKING_STYLE
32504#if SQLITE_PREFER_PROXY_LOCKING
32505  isAutoProxy = 1;
32506#endif
32507  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
32508    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
32509    int useProxy = 0;
32510
32511    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
32512    ** never use proxy, NULL means use proxy for non-local files only.  */
32513    if( envforce!=NULL ){
32514      useProxy = atoi(envforce)>0;
32515    }else{
32516      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
32517    }
32518    if( useProxy ){
32519      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
32520      if( rc==SQLITE_OK ){
32521        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
32522        if( rc!=SQLITE_OK ){
32523          /* Use unixClose to clean up the resources added in fillInUnixFile
32524          ** and clear all the structure's references.  Specifically,
32525          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
32526          */
32527          unixClose(pFile);
32528          return rc;
32529        }
32530      }
32531      goto open_finished;
32532    }
32533  }
32534#endif
32535
32536  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
32537
32538open_finished:
32539  if( rc!=SQLITE_OK ){
32540    sqlite3_free(p->pUnused);
32541  }
32542  return rc;
32543}
32544
32545
32546/*
32547** Delete the file at zPath. If the dirSync argument is true, fsync()
32548** the directory after deleting the file.
32549*/
32550static int unixDelete(
32551  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
32552  const char *zPath,        /* Name of file to be deleted */
32553  int dirSync               /* If true, fsync() directory after deleting file */
32554){
32555  int rc = SQLITE_OK;
32556  UNUSED_PARAMETER(NotUsed);
32557  SimulateIOError(return SQLITE_IOERR_DELETE);
32558  if( osUnlink(zPath)==(-1) ){
32559    if( errno==ENOENT
32560#if OS_VXWORKS
32561        || osAccess(zPath,0)!=0
32562#endif
32563    ){
32564      rc = SQLITE_IOERR_DELETE_NOENT;
32565    }else{
32566      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
32567    }
32568    return rc;
32569  }
32570#ifndef SQLITE_DISABLE_DIRSYNC
32571  if( (dirSync & 1)!=0 ){
32572    int fd;
32573    rc = osOpenDirectory(zPath, &fd);
32574    if( rc==SQLITE_OK ){
32575#if OS_VXWORKS
32576      if( fsync(fd)==-1 )
32577#else
32578      if( fsync(fd) )
32579#endif
32580      {
32581        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
32582      }
32583      robust_close(0, fd, __LINE__);
32584    }else if( rc==SQLITE_CANTOPEN ){
32585      rc = SQLITE_OK;
32586    }
32587  }
32588#endif
32589  return rc;
32590}
32591
32592/*
32593** Test the existence of or access permissions of file zPath. The
32594** test performed depends on the value of flags:
32595**
32596**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
32597**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
32598**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
32599**
32600** Otherwise return 0.
32601*/
32602static int unixAccess(
32603  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
32604  const char *zPath,      /* Path of the file to examine */
32605  int flags,              /* What do we want to learn about the zPath file? */
32606  int *pResOut            /* Write result boolean here */
32607){
32608  int amode = 0;
32609  UNUSED_PARAMETER(NotUsed);
32610  SimulateIOError( return SQLITE_IOERR_ACCESS; );
32611  switch( flags ){
32612    case SQLITE_ACCESS_EXISTS:
32613      amode = F_OK;
32614      break;
32615    case SQLITE_ACCESS_READWRITE:
32616      amode = W_OK|R_OK;
32617      break;
32618    case SQLITE_ACCESS_READ:
32619      amode = R_OK;
32620      break;
32621
32622    default:
32623      assert(!"Invalid flags argument");
32624  }
32625  *pResOut = (osAccess(zPath, amode)==0);
32626  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
32627    struct stat buf;
32628    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
32629      *pResOut = 0;
32630    }
32631  }
32632  return SQLITE_OK;
32633}
32634
32635
32636/*
32637** Turn a relative pathname into a full pathname. The relative path
32638** is stored as a nul-terminated string in the buffer pointed to by
32639** zPath.
32640**
32641** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
32642** (in this case, MAX_PATHNAME bytes). The full-path is written to
32643** this buffer before returning.
32644*/
32645static int unixFullPathname(
32646  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
32647  const char *zPath,            /* Possibly relative input path */
32648  int nOut,                     /* Size of output buffer in bytes */
32649  char *zOut                    /* Output buffer */
32650){
32651
32652  /* It's odd to simulate an io-error here, but really this is just
32653  ** using the io-error infrastructure to test that SQLite handles this
32654  ** function failing. This function could fail if, for example, the
32655  ** current working directory has been unlinked.
32656  */
32657  SimulateIOError( return SQLITE_ERROR );
32658
32659  assert( pVfs->mxPathname==MAX_PATHNAME );
32660  UNUSED_PARAMETER(pVfs);
32661
32662  zOut[nOut-1] = '\0';
32663  if( zPath[0]=='/' ){
32664    sqlite3_snprintf(nOut, zOut, "%s", zPath);
32665  }else{
32666    int nCwd;
32667    if( osGetcwd(zOut, nOut-1)==0 ){
32668      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
32669    }
32670    nCwd = (int)strlen(zOut);
32671    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
32672  }
32673  return SQLITE_OK;
32674}
32675
32676
32677#ifndef SQLITE_OMIT_LOAD_EXTENSION
32678/*
32679** Interfaces for opening a shared library, finding entry points
32680** within the shared library, and closing the shared library.
32681*/
32682#include <dlfcn.h>
32683static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
32684  UNUSED_PARAMETER(NotUsed);
32685  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
32686}
32687
32688/*
32689** SQLite calls this function immediately after a call to unixDlSym() or
32690** unixDlOpen() fails (returns a null pointer). If a more detailed error
32691** message is available, it is written to zBufOut. If no error message
32692** is available, zBufOut is left unmodified and SQLite uses a default
32693** error message.
32694*/
32695static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
32696  const char *zErr;
32697  UNUSED_PARAMETER(NotUsed);
32698  unixEnterMutex();
32699  zErr = dlerror();
32700  if( zErr ){
32701    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
32702  }
32703  unixLeaveMutex();
32704}
32705static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
32706  /*
32707  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
32708  ** cast into a pointer to a function.  And yet the library dlsym() routine
32709  ** returns a void* which is really a pointer to a function.  So how do we
32710  ** use dlsym() with -pedantic-errors?
32711  **
32712  ** Variable x below is defined to be a pointer to a function taking
32713  ** parameters void* and const char* and returning a pointer to a function.
32714  ** We initialize x by assigning it a pointer to the dlsym() function.
32715  ** (That assignment requires a cast.)  Then we call the function that
32716  ** x points to.
32717  **
32718  ** This work-around is unlikely to work correctly on any system where
32719  ** you really cannot cast a function pointer into void*.  But then, on the
32720  ** other hand, dlsym() will not work on such a system either, so we have
32721  ** not really lost anything.
32722  */
32723  void (*(*x)(void*,const char*))(void);
32724  UNUSED_PARAMETER(NotUsed);
32725  x = (void(*(*)(void*,const char*))(void))dlsym;
32726  return (*x)(p, zSym);
32727}
32728static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
32729  UNUSED_PARAMETER(NotUsed);
32730  dlclose(pHandle);
32731}
32732#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
32733  #define unixDlOpen  0
32734  #define unixDlError 0
32735  #define unixDlSym   0
32736  #define unixDlClose 0
32737#endif
32738
32739/*
32740** Write nBuf bytes of random data to the supplied buffer zBuf.
32741*/
32742static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
32743  UNUSED_PARAMETER(NotUsed);
32744  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
32745
32746  /* We have to initialize zBuf to prevent valgrind from reporting
32747  ** errors.  The reports issued by valgrind are incorrect - we would
32748  ** prefer that the randomness be increased by making use of the
32749  ** uninitialized space in zBuf - but valgrind errors tend to worry
32750  ** some users.  Rather than argue, it seems easier just to initialize
32751  ** the whole array and silence valgrind, even if that means less randomness
32752  ** in the random seed.
32753  **
32754  ** When testing, initializing zBuf[] to zero is all we do.  That means
32755  ** that we always use the same random number sequence.  This makes the
32756  ** tests repeatable.
32757  */
32758  memset(zBuf, 0, nBuf);
32759  randomnessPid = osGetpid(0);
32760#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
32761  {
32762    int fd, got;
32763    fd = robust_open("/dev/urandom", O_RDONLY, 0);
32764    if( fd<0 ){
32765      time_t t;
32766      time(&t);
32767      memcpy(zBuf, &t, sizeof(t));
32768      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
32769      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
32770      nBuf = sizeof(t) + sizeof(randomnessPid);
32771    }else{
32772      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
32773      robust_close(0, fd, __LINE__);
32774    }
32775  }
32776#endif
32777  return nBuf;
32778}
32779
32780
32781/*
32782** Sleep for a little while.  Return the amount of time slept.
32783** The argument is the number of microseconds we want to sleep.
32784** The return value is the number of microseconds of sleep actually
32785** requested from the underlying operating system, a number which
32786** might be greater than or equal to the argument, but not less
32787** than the argument.
32788*/
32789static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
32790#if OS_VXWORKS
32791  struct timespec sp;
32792
32793  sp.tv_sec = microseconds / 1000000;
32794  sp.tv_nsec = (microseconds % 1000000) * 1000;
32795  nanosleep(&sp, NULL);
32796  UNUSED_PARAMETER(NotUsed);
32797  return microseconds;
32798#elif defined(HAVE_USLEEP) && HAVE_USLEEP
32799  usleep(microseconds);
32800  UNUSED_PARAMETER(NotUsed);
32801  return microseconds;
32802#else
32803  int seconds = (microseconds+999999)/1000000;
32804  sleep(seconds);
32805  UNUSED_PARAMETER(NotUsed);
32806  return seconds*1000000;
32807#endif
32808}
32809
32810/*
32811** The following variable, if set to a non-zero value, is interpreted as
32812** the number of seconds since 1970 and is used to set the result of
32813** sqlite3OsCurrentTime() during testing.
32814*/
32815#ifdef SQLITE_TEST
32816SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
32817#endif
32818
32819/*
32820** Find the current time (in Universal Coordinated Time).  Write into *piNow
32821** the current time and date as a Julian Day number times 86_400_000.  In
32822** other words, write into *piNow the number of milliseconds since the Julian
32823** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32824** proleptic Gregorian calendar.
32825**
32826** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
32827** cannot be found.
32828*/
32829static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
32830  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
32831  int rc = SQLITE_OK;
32832#if defined(NO_GETTOD)
32833  time_t t;
32834  time(&t);
32835  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
32836#elif OS_VXWORKS
32837  struct timespec sNow;
32838  clock_gettime(CLOCK_REALTIME, &sNow);
32839  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
32840#else
32841  struct timeval sNow;
32842  if( gettimeofday(&sNow, 0)==0 ){
32843    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
32844  }else{
32845    rc = SQLITE_ERROR;
32846  }
32847#endif
32848
32849#ifdef SQLITE_TEST
32850  if( sqlite3_current_time ){
32851    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
32852  }
32853#endif
32854  UNUSED_PARAMETER(NotUsed);
32855  return rc;
32856}
32857
32858/*
32859** Find the current time (in Universal Coordinated Time).  Write the
32860** current time and date as a Julian Day number into *prNow and
32861** return 0.  Return 1 if the time and date cannot be found.
32862*/
32863static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
32864  sqlite3_int64 i = 0;
32865  int rc;
32866  UNUSED_PARAMETER(NotUsed);
32867  rc = unixCurrentTimeInt64(0, &i);
32868  *prNow = i/86400000.0;
32869  return rc;
32870}
32871
32872/*
32873** We added the xGetLastError() method with the intention of providing
32874** better low-level error messages when operating-system problems come up
32875** during SQLite operation.  But so far, none of that has been implemented
32876** in the core.  So this routine is never called.  For now, it is merely
32877** a place-holder.
32878*/
32879static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
32880  UNUSED_PARAMETER(NotUsed);
32881  UNUSED_PARAMETER(NotUsed2);
32882  UNUSED_PARAMETER(NotUsed3);
32883  return 0;
32884}
32885
32886
32887/*
32888************************ End of sqlite3_vfs methods ***************************
32889******************************************************************************/
32890
32891/******************************************************************************
32892************************** Begin Proxy Locking ********************************
32893**
32894** Proxy locking is a "uber-locking-method" in this sense:  It uses the
32895** other locking methods on secondary lock files.  Proxy locking is a
32896** meta-layer over top of the primitive locking implemented above.  For
32897** this reason, the division that implements of proxy locking is deferred
32898** until late in the file (here) after all of the other I/O methods have
32899** been defined - so that the primitive locking methods are available
32900** as services to help with the implementation of proxy locking.
32901**
32902****
32903**
32904** The default locking schemes in SQLite use byte-range locks on the
32905** database file to coordinate safe, concurrent access by multiple readers
32906** and writers [http://sqlite.org/lockingv3.html].  The five file locking
32907** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
32908** as POSIX read & write locks over fixed set of locations (via fsctl),
32909** on AFP and SMB only exclusive byte-range locks are available via fsctl
32910** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
32911** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
32912** address in the shared range is taken for a SHARED lock, the entire
32913** shared range is taken for an EXCLUSIVE lock):
32914**
32915**      PENDING_BYTE        0x40000000
32916**      RESERVED_BYTE       0x40000001
32917**      SHARED_RANGE        0x40000002 -> 0x40000200
32918**
32919** This works well on the local file system, but shows a nearly 100x
32920** slowdown in read performance on AFP because the AFP client disables
32921** the read cache when byte-range locks are present.  Enabling the read
32922** cache exposes a cache coherency problem that is present on all OS X
32923** supported network file systems.  NFS and AFP both observe the
32924** close-to-open semantics for ensuring cache coherency
32925** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
32926** address the requirements for concurrent database access by multiple
32927** readers and writers
32928** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
32929**
32930** To address the performance and cache coherency issues, proxy file locking
32931** changes the way database access is controlled by limiting access to a
32932** single host at a time and moving file locks off of the database file
32933** and onto a proxy file on the local file system.
32934**
32935**
32936** Using proxy locks
32937** -----------------
32938**
32939** C APIs
32940**
32941**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
32942**                       <proxy_path> | ":auto:");
32943**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
32944**                       &<proxy_path>);
32945**
32946**
32947** SQL pragmas
32948**
32949**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
32950**  PRAGMA [database.]lock_proxy_file
32951**
32952** Specifying ":auto:" means that if there is a conch file with a matching
32953** host ID in it, the proxy path in the conch file will be used, otherwise
32954** a proxy path based on the user's temp dir
32955** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
32956** actual proxy file name is generated from the name and path of the
32957** database file.  For example:
32958**
32959**       For database path "/Users/me/foo.db"
32960**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
32961**
32962** Once a lock proxy is configured for a database connection, it can not
32963** be removed, however it may be switched to a different proxy path via
32964** the above APIs (assuming the conch file is not being held by another
32965** connection or process).
32966**
32967**
32968** How proxy locking works
32969** -----------------------
32970**
32971** Proxy file locking relies primarily on two new supporting files:
32972**
32973**   *  conch file to limit access to the database file to a single host
32974**      at a time
32975**
32976**   *  proxy file to act as a proxy for the advisory locks normally
32977**      taken on the database
32978**
32979** The conch file - to use a proxy file, sqlite must first "hold the conch"
32980** by taking an sqlite-style shared lock on the conch file, reading the
32981** contents and comparing the host's unique host ID (see below) and lock
32982** proxy path against the values stored in the conch.  The conch file is
32983** stored in the same directory as the database file and the file name
32984** is patterned after the database file name as ".<databasename>-conch".
32985** If the conch file does not exist, or its contents do not match the
32986** host ID and/or proxy path, then the lock is escalated to an exclusive
32987** lock and the conch file contents is updated with the host ID and proxy
32988** path and the lock is downgraded to a shared lock again.  If the conch
32989** is held by another process (with a shared lock), the exclusive lock
32990** will fail and SQLITE_BUSY is returned.
32991**
32992** The proxy file - a single-byte file used for all advisory file locks
32993** normally taken on the database file.   This allows for safe sharing
32994** of the database file for multiple readers and writers on the same
32995** host (the conch ensures that they all use the same local lock file).
32996**
32997** Requesting the lock proxy does not immediately take the conch, it is
32998** only taken when the first request to lock database file is made.
32999** This matches the semantics of the traditional locking behavior, where
33000** opening a connection to a database file does not take a lock on it.
33001** The shared lock and an open file descriptor are maintained until
33002** the connection to the database is closed.
33003**
33004** The proxy file and the lock file are never deleted so they only need
33005** to be created the first time they are used.
33006**
33007** Configuration options
33008** ---------------------
33009**
33010**  SQLITE_PREFER_PROXY_LOCKING
33011**
33012**       Database files accessed on non-local file systems are
33013**       automatically configured for proxy locking, lock files are
33014**       named automatically using the same logic as
33015**       PRAGMA lock_proxy_file=":auto:"
33016**
33017**  SQLITE_PROXY_DEBUG
33018**
33019**       Enables the logging of error messages during host id file
33020**       retrieval and creation
33021**
33022**  LOCKPROXYDIR
33023**
33024**       Overrides the default directory used for lock proxy files that
33025**       are named automatically via the ":auto:" setting
33026**
33027**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
33028**
33029**       Permissions to use when creating a directory for storing the
33030**       lock proxy files, only used when LOCKPROXYDIR is not set.
33031**
33032**
33033** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
33034** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
33035** force proxy locking to be used for every database file opened, and 0
33036** will force automatic proxy locking to be disabled for all database
33037** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
33038** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
33039*/
33040
33041/*
33042** Proxy locking is only available on MacOSX
33043*/
33044#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33045
33046/*
33047** The proxyLockingContext has the path and file structures for the remote
33048** and local proxy files in it
33049*/
33050typedef struct proxyLockingContext proxyLockingContext;
33051struct proxyLockingContext {
33052  unixFile *conchFile;         /* Open conch file */
33053  char *conchFilePath;         /* Name of the conch file */
33054  unixFile *lockProxy;         /* Open proxy lock file */
33055  char *lockProxyPath;         /* Name of the proxy lock file */
33056  char *dbPath;                /* Name of the open file */
33057  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
33058  int nFails;                  /* Number of conch taking failures */
33059  void *oldLockingContext;     /* Original lockingcontext to restore on close */
33060  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
33061};
33062
33063/*
33064** The proxy lock file path for the database at dbPath is written into lPath,
33065** which must point to valid, writable memory large enough for a maxLen length
33066** file path.
33067*/
33068static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
33069  int len;
33070  int dbLen;
33071  int i;
33072
33073#ifdef LOCKPROXYDIR
33074  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
33075#else
33076# ifdef _CS_DARWIN_USER_TEMP_DIR
33077  {
33078    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
33079      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
33080               lPath, errno, osGetpid(0)));
33081      return SQLITE_IOERR_LOCK;
33082    }
33083    len = strlcat(lPath, "sqliteplocks", maxLen);
33084  }
33085# else
33086  len = strlcpy(lPath, "/tmp/", maxLen);
33087# endif
33088#endif
33089
33090  if( lPath[len-1]!='/' ){
33091    len = strlcat(lPath, "/", maxLen);
33092  }
33093
33094  /* transform the db path to a unique cache name */
33095  dbLen = (int)strlen(dbPath);
33096  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
33097    char c = dbPath[i];
33098    lPath[i+len] = (c=='/')?'_':c;
33099  }
33100  lPath[i+len]='\0';
33101  strlcat(lPath, ":auto:", maxLen);
33102  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
33103  return SQLITE_OK;
33104}
33105
33106/*
33107 ** Creates the lock file and any missing directories in lockPath
33108 */
33109static int proxyCreateLockPath(const char *lockPath){
33110  int i, len;
33111  char buf[MAXPATHLEN];
33112  int start = 0;
33113
33114  assert(lockPath!=NULL);
33115  /* try to create all the intermediate directories */
33116  len = (int)strlen(lockPath);
33117  buf[0] = lockPath[0];
33118  for( i=1; i<len; i++ ){
33119    if( lockPath[i] == '/' && (i - start > 0) ){
33120      /* only mkdir if leaf dir != "." or "/" or ".." */
33121      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
33122         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
33123        buf[i]='\0';
33124        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
33125          int err=errno;
33126          if( err!=EEXIST ) {
33127            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
33128                     "'%s' proxy lock path=%s pid=%d\n",
33129                     buf, strerror(err), lockPath, osGetpid(0)));
33130            return err;
33131          }
33132        }
33133      }
33134      start=i+1;
33135    }
33136    buf[i] = lockPath[i];
33137  }
33138  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
33139  return 0;
33140}
33141
33142/*
33143** Create a new VFS file descriptor (stored in memory obtained from
33144** sqlite3_malloc) and open the file named "path" in the file descriptor.
33145**
33146** The caller is responsible not only for closing the file descriptor
33147** but also for freeing the memory associated with the file descriptor.
33148*/
33149static int proxyCreateUnixFile(
33150    const char *path,        /* path for the new unixFile */
33151    unixFile **ppFile,       /* unixFile created and returned by ref */
33152    int islockfile           /* if non zero missing dirs will be created */
33153) {
33154  int fd = -1;
33155  unixFile *pNew;
33156  int rc = SQLITE_OK;
33157  int openFlags = O_RDWR | O_CREAT;
33158  sqlite3_vfs dummyVfs;
33159  int terrno = 0;
33160  UnixUnusedFd *pUnused = NULL;
33161
33162  /* 1. first try to open/create the file
33163  ** 2. if that fails, and this is a lock file (not-conch), try creating
33164  ** the parent directories and then try again.
33165  ** 3. if that fails, try to open the file read-only
33166  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
33167  */
33168  pUnused = findReusableFd(path, openFlags);
33169  if( pUnused ){
33170    fd = pUnused->fd;
33171  }else{
33172    pUnused = sqlite3_malloc64(sizeof(*pUnused));
33173    if( !pUnused ){
33174      return SQLITE_NOMEM;
33175    }
33176  }
33177  if( fd<0 ){
33178    fd = robust_open(path, openFlags, 0);
33179    terrno = errno;
33180    if( fd<0 && errno==ENOENT && islockfile ){
33181      if( proxyCreateLockPath(path) == SQLITE_OK ){
33182        fd = robust_open(path, openFlags, 0);
33183      }
33184    }
33185  }
33186  if( fd<0 ){
33187    openFlags = O_RDONLY;
33188    fd = robust_open(path, openFlags, 0);
33189    terrno = errno;
33190  }
33191  if( fd<0 ){
33192    if( islockfile ){
33193      return SQLITE_BUSY;
33194    }
33195    switch (terrno) {
33196      case EACCES:
33197        return SQLITE_PERM;
33198      case EIO:
33199        return SQLITE_IOERR_LOCK; /* even though it is the conch */
33200      default:
33201        return SQLITE_CANTOPEN_BKPT;
33202    }
33203  }
33204
33205  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
33206  if( pNew==NULL ){
33207    rc = SQLITE_NOMEM;
33208    goto end_create_proxy;
33209  }
33210  memset(pNew, 0, sizeof(unixFile));
33211  pNew->openFlags = openFlags;
33212  memset(&dummyVfs, 0, sizeof(dummyVfs));
33213  dummyVfs.pAppData = (void*)&autolockIoFinder;
33214  dummyVfs.zName = "dummy";
33215  pUnused->fd = fd;
33216  pUnused->flags = openFlags;
33217  pNew->pUnused = pUnused;
33218
33219  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
33220  if( rc==SQLITE_OK ){
33221    *ppFile = pNew;
33222    return SQLITE_OK;
33223  }
33224end_create_proxy:
33225  robust_close(pNew, fd, __LINE__);
33226  sqlite3_free(pNew);
33227  sqlite3_free(pUnused);
33228  return rc;
33229}
33230
33231#ifdef SQLITE_TEST
33232/* simulate multiple hosts by creating unique hostid file paths */
33233SQLITE_API int sqlite3_hostid_num = 0;
33234#endif
33235
33236#define PROXY_HOSTIDLEN    16  /* conch file host id length */
33237
33238#ifdef HAVE_GETHOSTUUID
33239/* Not always defined in the headers as it ought to be */
33240extern int gethostuuid(uuid_t id, const struct timespec *wait);
33241#endif
33242
33243/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
33244** bytes of writable memory.
33245*/
33246static int proxyGetHostID(unsigned char *pHostID, int *pError){
33247  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
33248  memset(pHostID, 0, PROXY_HOSTIDLEN);
33249#ifdef HAVE_GETHOSTUUID
33250  {
33251    struct timespec timeout = {1, 0}; /* 1 sec timeout */
33252    if( gethostuuid(pHostID, &timeout) ){
33253      int err = errno;
33254      if( pError ){
33255        *pError = err;
33256      }
33257      return SQLITE_IOERR;
33258    }
33259  }
33260#else
33261  UNUSED_PARAMETER(pError);
33262#endif
33263#ifdef SQLITE_TEST
33264  /* simulate multiple hosts by creating unique hostid file paths */
33265  if( sqlite3_hostid_num != 0){
33266    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
33267  }
33268#endif
33269
33270  return SQLITE_OK;
33271}
33272
33273/* The conch file contains the header, host id and lock file path
33274 */
33275#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
33276#define PROXY_HEADERLEN    1   /* conch file header length */
33277#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
33278#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
33279
33280/*
33281** Takes an open conch file, copies the contents to a new path and then moves
33282** it back.  The newly created file's file descriptor is assigned to the
33283** conch file structure and finally the original conch file descriptor is
33284** closed.  Returns zero if successful.
33285*/
33286static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
33287  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33288  unixFile *conchFile = pCtx->conchFile;
33289  char tPath[MAXPATHLEN];
33290  char buf[PROXY_MAXCONCHLEN];
33291  char *cPath = pCtx->conchFilePath;
33292  size_t readLen = 0;
33293  size_t pathLen = 0;
33294  char errmsg[64] = "";
33295  int fd = -1;
33296  int rc = -1;
33297  UNUSED_PARAMETER(myHostID);
33298
33299  /* create a new path by replace the trailing '-conch' with '-break' */
33300  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
33301  if( pathLen>MAXPATHLEN || pathLen<6 ||
33302     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
33303    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
33304    goto end_breaklock;
33305  }
33306  /* read the conch content */
33307  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
33308  if( readLen<PROXY_PATHINDEX ){
33309    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
33310    goto end_breaklock;
33311  }
33312  /* write it out to the temporary break file */
33313  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
33314  if( fd<0 ){
33315    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
33316    goto end_breaklock;
33317  }
33318  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
33319    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
33320    goto end_breaklock;
33321  }
33322  if( rename(tPath, cPath) ){
33323    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
33324    goto end_breaklock;
33325  }
33326  rc = 0;
33327  fprintf(stderr, "broke stale lock on %s\n", cPath);
33328  robust_close(pFile, conchFile->h, __LINE__);
33329  conchFile->h = fd;
33330  conchFile->openFlags = O_RDWR | O_CREAT;
33331
33332end_breaklock:
33333  if( rc ){
33334    if( fd>=0 ){
33335      osUnlink(tPath);
33336      robust_close(pFile, fd, __LINE__);
33337    }
33338    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
33339  }
33340  return rc;
33341}
33342
33343/* Take the requested lock on the conch file and break a stale lock if the
33344** host id matches.
33345*/
33346static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
33347  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33348  unixFile *conchFile = pCtx->conchFile;
33349  int rc = SQLITE_OK;
33350  int nTries = 0;
33351  struct timespec conchModTime;
33352
33353  memset(&conchModTime, 0, sizeof(conchModTime));
33354  do {
33355    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
33356    nTries ++;
33357    if( rc==SQLITE_BUSY ){
33358      /* If the lock failed (busy):
33359       * 1st try: get the mod time of the conch, wait 0.5s and try again.
33360       * 2nd try: fail if the mod time changed or host id is different, wait
33361       *           10 sec and try again
33362       * 3rd try: break the lock unless the mod time has changed.
33363       */
33364      struct stat buf;
33365      if( osFstat(conchFile->h, &buf) ){
33366        storeLastErrno(pFile, errno);
33367        return SQLITE_IOERR_LOCK;
33368      }
33369
33370      if( nTries==1 ){
33371        conchModTime = buf.st_mtimespec;
33372        usleep(500000); /* wait 0.5 sec and try the lock again*/
33373        continue;
33374      }
33375
33376      assert( nTries>1 );
33377      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
33378         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
33379        return SQLITE_BUSY;
33380      }
33381
33382      if( nTries==2 ){
33383        char tBuf[PROXY_MAXCONCHLEN];
33384        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
33385        if( len<0 ){
33386          storeLastErrno(pFile, errno);
33387          return SQLITE_IOERR_LOCK;
33388        }
33389        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
33390          /* don't break the lock if the host id doesn't match */
33391          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
33392            return SQLITE_BUSY;
33393          }
33394        }else{
33395          /* don't break the lock on short read or a version mismatch */
33396          return SQLITE_BUSY;
33397        }
33398        usleep(10000000); /* wait 10 sec and try the lock again */
33399        continue;
33400      }
33401
33402      assert( nTries==3 );
33403      if( 0==proxyBreakConchLock(pFile, myHostID) ){
33404        rc = SQLITE_OK;
33405        if( lockType==EXCLUSIVE_LOCK ){
33406          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
33407        }
33408        if( !rc ){
33409          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
33410        }
33411      }
33412    }
33413  } while( rc==SQLITE_BUSY && nTries<3 );
33414
33415  return rc;
33416}
33417
33418/* Takes the conch by taking a shared lock and read the contents conch, if
33419** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
33420** lockPath means that the lockPath in the conch file will be used if the
33421** host IDs match, or a new lock path will be generated automatically
33422** and written to the conch file.
33423*/
33424static int proxyTakeConch(unixFile *pFile){
33425  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33426
33427  if( pCtx->conchHeld!=0 ){
33428    return SQLITE_OK;
33429  }else{
33430    unixFile *conchFile = pCtx->conchFile;
33431    uuid_t myHostID;
33432    int pError = 0;
33433    char readBuf[PROXY_MAXCONCHLEN];
33434    char lockPath[MAXPATHLEN];
33435    char *tempLockPath = NULL;
33436    int rc = SQLITE_OK;
33437    int createConch = 0;
33438    int hostIdMatch = 0;
33439    int readLen = 0;
33440    int tryOldLockPath = 0;
33441    int forceNewLockPath = 0;
33442
33443    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
33444             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
33445             osGetpid(0)));
33446
33447    rc = proxyGetHostID(myHostID, &pError);
33448    if( (rc&0xff)==SQLITE_IOERR ){
33449      storeLastErrno(pFile, pError);
33450      goto end_takeconch;
33451    }
33452    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
33453    if( rc!=SQLITE_OK ){
33454      goto end_takeconch;
33455    }
33456    /* read the existing conch file */
33457    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
33458    if( readLen<0 ){
33459      /* I/O error: lastErrno set by seekAndRead */
33460      storeLastErrno(pFile, conchFile->lastErrno);
33461      rc = SQLITE_IOERR_READ;
33462      goto end_takeconch;
33463    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
33464             readBuf[0]!=(char)PROXY_CONCHVERSION ){
33465      /* a short read or version format mismatch means we need to create a new
33466      ** conch file.
33467      */
33468      createConch = 1;
33469    }
33470    /* if the host id matches and the lock path already exists in the conch
33471    ** we'll try to use the path there, if we can't open that path, we'll
33472    ** retry with a new auto-generated path
33473    */
33474    do { /* in case we need to try again for an :auto: named lock file */
33475
33476      if( !createConch && !forceNewLockPath ){
33477        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
33478                                  PROXY_HOSTIDLEN);
33479        /* if the conch has data compare the contents */
33480        if( !pCtx->lockProxyPath ){
33481          /* for auto-named local lock file, just check the host ID and we'll
33482           ** use the local lock file path that's already in there
33483           */
33484          if( hostIdMatch ){
33485            size_t pathLen = (readLen - PROXY_PATHINDEX);
33486
33487            if( pathLen>=MAXPATHLEN ){
33488              pathLen=MAXPATHLEN-1;
33489            }
33490            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
33491            lockPath[pathLen] = 0;
33492            tempLockPath = lockPath;
33493            tryOldLockPath = 1;
33494            /* create a copy of the lock path if the conch is taken */
33495            goto end_takeconch;
33496          }
33497        }else if( hostIdMatch
33498               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
33499                           readLen-PROXY_PATHINDEX)
33500        ){
33501          /* conch host and lock path match */
33502          goto end_takeconch;
33503        }
33504      }
33505
33506      /* if the conch isn't writable and doesn't match, we can't take it */
33507      if( (conchFile->openFlags&O_RDWR) == 0 ){
33508        rc = SQLITE_BUSY;
33509        goto end_takeconch;
33510      }
33511
33512      /* either the conch didn't match or we need to create a new one */
33513      if( !pCtx->lockProxyPath ){
33514        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
33515        tempLockPath = lockPath;
33516        /* create a copy of the lock path _only_ if the conch is taken */
33517      }
33518
33519      /* update conch with host and path (this will fail if other process
33520      ** has a shared lock already), if the host id matches, use the big
33521      ** stick.
33522      */
33523      futimes(conchFile->h, NULL);
33524      if( hostIdMatch && !createConch ){
33525        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
33526          /* We are trying for an exclusive lock but another thread in this
33527           ** same process is still holding a shared lock. */
33528          rc = SQLITE_BUSY;
33529        } else {
33530          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
33531        }
33532      }else{
33533        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
33534      }
33535      if( rc==SQLITE_OK ){
33536        char writeBuffer[PROXY_MAXCONCHLEN];
33537        int writeSize = 0;
33538
33539        writeBuffer[0] = (char)PROXY_CONCHVERSION;
33540        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
33541        if( pCtx->lockProxyPath!=NULL ){
33542          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
33543                  MAXPATHLEN);
33544        }else{
33545          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
33546        }
33547        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
33548        robust_ftruncate(conchFile->h, writeSize);
33549        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
33550        fsync(conchFile->h);
33551        /* If we created a new conch file (not just updated the contents of a
33552         ** valid conch file), try to match the permissions of the database
33553         */
33554        if( rc==SQLITE_OK && createConch ){
33555          struct stat buf;
33556          int err = osFstat(pFile->h, &buf);
33557          if( err==0 ){
33558            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
33559                                        S_IROTH|S_IWOTH);
33560            /* try to match the database file R/W permissions, ignore failure */
33561#ifndef SQLITE_PROXY_DEBUG
33562            osFchmod(conchFile->h, cmode);
33563#else
33564            do{
33565              rc = osFchmod(conchFile->h, cmode);
33566            }while( rc==(-1) && errno==EINTR );
33567            if( rc!=0 ){
33568              int code = errno;
33569              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
33570                      cmode, code, strerror(code));
33571            } else {
33572              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
33573            }
33574          }else{
33575            int code = errno;
33576            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
33577                    err, code, strerror(code));
33578#endif
33579          }
33580        }
33581      }
33582      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
33583
33584    end_takeconch:
33585      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
33586      if( rc==SQLITE_OK && pFile->openFlags ){
33587        int fd;
33588        if( pFile->h>=0 ){
33589          robust_close(pFile, pFile->h, __LINE__);
33590        }
33591        pFile->h = -1;
33592        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
33593        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
33594        if( fd>=0 ){
33595          pFile->h = fd;
33596        }else{
33597          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
33598           during locking */
33599        }
33600      }
33601      if( rc==SQLITE_OK && !pCtx->lockProxy ){
33602        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
33603        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
33604        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
33605          /* we couldn't create the proxy lock file with the old lock file path
33606           ** so try again via auto-naming
33607           */
33608          forceNewLockPath = 1;
33609          tryOldLockPath = 0;
33610          continue; /* go back to the do {} while start point, try again */
33611        }
33612      }
33613      if( rc==SQLITE_OK ){
33614        /* Need to make a copy of path if we extracted the value
33615         ** from the conch file or the path was allocated on the stack
33616         */
33617        if( tempLockPath ){
33618          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
33619          if( !pCtx->lockProxyPath ){
33620            rc = SQLITE_NOMEM;
33621          }
33622        }
33623      }
33624      if( rc==SQLITE_OK ){
33625        pCtx->conchHeld = 1;
33626
33627        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
33628          afpLockingContext *afpCtx;
33629          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
33630          afpCtx->dbPath = pCtx->lockProxyPath;
33631        }
33632      } else {
33633        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
33634      }
33635      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
33636               rc==SQLITE_OK?"ok":"failed"));
33637      return rc;
33638    } while (1); /* in case we need to retry the :auto: lock file -
33639                 ** we should never get here except via the 'continue' call. */
33640  }
33641}
33642
33643/*
33644** If pFile holds a lock on a conch file, then release that lock.
33645*/
33646static int proxyReleaseConch(unixFile *pFile){
33647  int rc = SQLITE_OK;         /* Subroutine return code */
33648  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
33649  unixFile *conchFile;        /* Name of the conch file */
33650
33651  pCtx = (proxyLockingContext *)pFile->lockingContext;
33652  conchFile = pCtx->conchFile;
33653  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
33654           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
33655           osGetpid(0)));
33656  if( pCtx->conchHeld>0 ){
33657    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
33658  }
33659  pCtx->conchHeld = 0;
33660  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
33661           (rc==SQLITE_OK ? "ok" : "failed")));
33662  return rc;
33663}
33664
33665/*
33666** Given the name of a database file, compute the name of its conch file.
33667** Store the conch filename in memory obtained from sqlite3_malloc64().
33668** Make *pConchPath point to the new name.  Return SQLITE_OK on success
33669** or SQLITE_NOMEM if unable to obtain memory.
33670**
33671** The caller is responsible for ensuring that the allocated memory
33672** space is eventually freed.
33673**
33674** *pConchPath is set to NULL if a memory allocation error occurs.
33675*/
33676static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
33677  int i;                        /* Loop counter */
33678  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
33679  char *conchPath;              /* buffer in which to construct conch name */
33680
33681  /* Allocate space for the conch filename and initialize the name to
33682  ** the name of the original database file. */
33683  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
33684  if( conchPath==0 ){
33685    return SQLITE_NOMEM;
33686  }
33687  memcpy(conchPath, dbPath, len+1);
33688
33689  /* now insert a "." before the last / character */
33690  for( i=(len-1); i>=0; i-- ){
33691    if( conchPath[i]=='/' ){
33692      i++;
33693      break;
33694    }
33695  }
33696  conchPath[i]='.';
33697  while ( i<len ){
33698    conchPath[i+1]=dbPath[i];
33699    i++;
33700  }
33701
33702  /* append the "-conch" suffix to the file */
33703  memcpy(&conchPath[i+1], "-conch", 7);
33704  assert( (int)strlen(conchPath) == len+7 );
33705
33706  return SQLITE_OK;
33707}
33708
33709
33710/* Takes a fully configured proxy locking-style unix file and switches
33711** the local lock file path
33712*/
33713static int switchLockProxyPath(unixFile *pFile, const char *path) {
33714  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33715  char *oldPath = pCtx->lockProxyPath;
33716  int rc = SQLITE_OK;
33717
33718  if( pFile->eFileLock!=NO_LOCK ){
33719    return SQLITE_BUSY;
33720  }
33721
33722  /* nothing to do if the path is NULL, :auto: or matches the existing path */
33723  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
33724    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
33725    return SQLITE_OK;
33726  }else{
33727    unixFile *lockProxy = pCtx->lockProxy;
33728    pCtx->lockProxy=NULL;
33729    pCtx->conchHeld = 0;
33730    if( lockProxy!=NULL ){
33731      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
33732      if( rc ) return rc;
33733      sqlite3_free(lockProxy);
33734    }
33735    sqlite3_free(oldPath);
33736    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
33737  }
33738
33739  return rc;
33740}
33741
33742/*
33743** pFile is a file that has been opened by a prior xOpen call.  dbPath
33744** is a string buffer at least MAXPATHLEN+1 characters in size.
33745**
33746** This routine find the filename associated with pFile and writes it
33747** int dbPath.
33748*/
33749static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
33750#if defined(__APPLE__)
33751  if( pFile->pMethod == &afpIoMethods ){
33752    /* afp style keeps a reference to the db path in the filePath field
33753    ** of the struct */
33754    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33755    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
33756            MAXPATHLEN);
33757  } else
33758#endif
33759  if( pFile->pMethod == &dotlockIoMethods ){
33760    /* dot lock style uses the locking context to store the dot lock
33761    ** file path */
33762    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
33763    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
33764  }else{
33765    /* all other styles use the locking context to store the db file path */
33766    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33767    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
33768  }
33769  return SQLITE_OK;
33770}
33771
33772/*
33773** Takes an already filled in unix file and alters it so all file locking
33774** will be performed on the local proxy lock file.  The following fields
33775** are preserved in the locking context so that they can be restored and
33776** the unix structure properly cleaned up at close time:
33777**  ->lockingContext
33778**  ->pMethod
33779*/
33780static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
33781  proxyLockingContext *pCtx;
33782  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
33783  char *lockPath=NULL;
33784  int rc = SQLITE_OK;
33785
33786  if( pFile->eFileLock!=NO_LOCK ){
33787    return SQLITE_BUSY;
33788  }
33789  proxyGetDbPathForUnixFile(pFile, dbPath);
33790  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
33791    lockPath=NULL;
33792  }else{
33793    lockPath=(char *)path;
33794  }
33795
33796  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
33797           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
33798
33799  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
33800  if( pCtx==0 ){
33801    return SQLITE_NOMEM;
33802  }
33803  memset(pCtx, 0, sizeof(*pCtx));
33804
33805  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
33806  if( rc==SQLITE_OK ){
33807    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
33808    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
33809      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
33810      ** (c) the file system is read-only, then enable no-locking access.
33811      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
33812      ** that openFlags will have only one of O_RDONLY or O_RDWR.
33813      */
33814      struct statfs fsInfo;
33815      struct stat conchInfo;
33816      int goLockless = 0;
33817
33818      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
33819        int err = errno;
33820        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
33821          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
33822        }
33823      }
33824      if( goLockless ){
33825        pCtx->conchHeld = -1; /* read only FS/ lockless */
33826        rc = SQLITE_OK;
33827      }
33828    }
33829  }
33830  if( rc==SQLITE_OK && lockPath ){
33831    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
33832  }
33833
33834  if( rc==SQLITE_OK ){
33835    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
33836    if( pCtx->dbPath==NULL ){
33837      rc = SQLITE_NOMEM;
33838    }
33839  }
33840  if( rc==SQLITE_OK ){
33841    /* all memory is allocated, proxys are created and assigned,
33842    ** switch the locking context and pMethod then return.
33843    */
33844    pCtx->oldLockingContext = pFile->lockingContext;
33845    pFile->lockingContext = pCtx;
33846    pCtx->pOldMethod = pFile->pMethod;
33847    pFile->pMethod = &proxyIoMethods;
33848  }else{
33849    if( pCtx->conchFile ){
33850      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
33851      sqlite3_free(pCtx->conchFile);
33852    }
33853    sqlite3DbFree(0, pCtx->lockProxyPath);
33854    sqlite3_free(pCtx->conchFilePath);
33855    sqlite3_free(pCtx);
33856  }
33857  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
33858           (rc==SQLITE_OK ? "ok" : "failed")));
33859  return rc;
33860}
33861
33862
33863/*
33864** This routine handles sqlite3_file_control() calls that are specific
33865** to proxy locking.
33866*/
33867static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
33868  switch( op ){
33869    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33870      unixFile *pFile = (unixFile*)id;
33871      if( pFile->pMethod == &proxyIoMethods ){
33872        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33873        proxyTakeConch(pFile);
33874        if( pCtx->lockProxyPath ){
33875          *(const char **)pArg = pCtx->lockProxyPath;
33876        }else{
33877          *(const char **)pArg = ":auto: (not held)";
33878        }
33879      } else {
33880        *(const char **)pArg = NULL;
33881      }
33882      return SQLITE_OK;
33883    }
33884    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
33885      unixFile *pFile = (unixFile*)id;
33886      int rc = SQLITE_OK;
33887      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
33888      if( pArg==NULL || (const char *)pArg==0 ){
33889        if( isProxyStyle ){
33890          /* turn off proxy locking - not supported.  If support is added for
33891          ** switching proxy locking mode off then it will need to fail if
33892          ** the journal mode is WAL mode.
33893          */
33894          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
33895        }else{
33896          /* turn off proxy locking - already off - NOOP */
33897          rc = SQLITE_OK;
33898        }
33899      }else{
33900        const char *proxyPath = (const char *)pArg;
33901        if( isProxyStyle ){
33902          proxyLockingContext *pCtx =
33903            (proxyLockingContext*)pFile->lockingContext;
33904          if( !strcmp(pArg, ":auto:")
33905           || (pCtx->lockProxyPath &&
33906               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
33907          ){
33908            rc = SQLITE_OK;
33909          }else{
33910            rc = switchLockProxyPath(pFile, proxyPath);
33911          }
33912        }else{
33913          /* turn on proxy file locking */
33914          rc = proxyTransformUnixFile(pFile, proxyPath);
33915        }
33916      }
33917      return rc;
33918    }
33919    default: {
33920      assert( 0 );  /* The call assures that only valid opcodes are sent */
33921    }
33922  }
33923  /*NOTREACHED*/
33924  return SQLITE_ERROR;
33925}
33926
33927/*
33928** Within this division (the proxying locking implementation) the procedures
33929** above this point are all utilities.  The lock-related methods of the
33930** proxy-locking sqlite3_io_method object follow.
33931*/
33932
33933
33934/*
33935** This routine checks if there is a RESERVED lock held on the specified
33936** file by this or any other process. If such a lock is held, set *pResOut
33937** to a non-zero value otherwise *pResOut is set to zero.  The return value
33938** is set to SQLITE_OK unless an I/O error occurs during lock checking.
33939*/
33940static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
33941  unixFile *pFile = (unixFile*)id;
33942  int rc = proxyTakeConch(pFile);
33943  if( rc==SQLITE_OK ){
33944    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33945    if( pCtx->conchHeld>0 ){
33946      unixFile *proxy = pCtx->lockProxy;
33947      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
33948    }else{ /* conchHeld < 0 is lockless */
33949      pResOut=0;
33950    }
33951  }
33952  return rc;
33953}
33954
33955/*
33956** Lock the file with the lock specified by parameter eFileLock - one
33957** of the following:
33958**
33959**     (1) SHARED_LOCK
33960**     (2) RESERVED_LOCK
33961**     (3) PENDING_LOCK
33962**     (4) EXCLUSIVE_LOCK
33963**
33964** Sometimes when requesting one lock state, additional lock states
33965** are inserted in between.  The locking might fail on one of the later
33966** transitions leaving the lock state different from what it started but
33967** still short of its goal.  The following chart shows the allowed
33968** transitions and the inserted intermediate states:
33969**
33970**    UNLOCKED -> SHARED
33971**    SHARED -> RESERVED
33972**    SHARED -> (PENDING) -> EXCLUSIVE
33973**    RESERVED -> (PENDING) -> EXCLUSIVE
33974**    PENDING -> EXCLUSIVE
33975**
33976** This routine will only increase a lock.  Use the sqlite3OsUnlock()
33977** routine to lower a locking level.
33978*/
33979static int proxyLock(sqlite3_file *id, int eFileLock) {
33980  unixFile *pFile = (unixFile*)id;
33981  int rc = proxyTakeConch(pFile);
33982  if( rc==SQLITE_OK ){
33983    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33984    if( pCtx->conchHeld>0 ){
33985      unixFile *proxy = pCtx->lockProxy;
33986      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
33987      pFile->eFileLock = proxy->eFileLock;
33988    }else{
33989      /* conchHeld < 0 is lockless */
33990    }
33991  }
33992  return rc;
33993}
33994
33995
33996/*
33997** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
33998** must be either NO_LOCK or SHARED_LOCK.
33999**
34000** If the locking level of the file descriptor is already at or below
34001** the requested locking level, this routine is a no-op.
34002*/
34003static int proxyUnlock(sqlite3_file *id, int eFileLock) {
34004  unixFile *pFile = (unixFile*)id;
34005  int rc = proxyTakeConch(pFile);
34006  if( rc==SQLITE_OK ){
34007    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
34008    if( pCtx->conchHeld>0 ){
34009      unixFile *proxy = pCtx->lockProxy;
34010      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
34011      pFile->eFileLock = proxy->eFileLock;
34012    }else{
34013      /* conchHeld < 0 is lockless */
34014    }
34015  }
34016  return rc;
34017}
34018
34019/*
34020** Close a file that uses proxy locks.
34021*/
34022static int proxyClose(sqlite3_file *id) {
34023  if( id ){
34024    unixFile *pFile = (unixFile*)id;
34025    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
34026    unixFile *lockProxy = pCtx->lockProxy;
34027    unixFile *conchFile = pCtx->conchFile;
34028    int rc = SQLITE_OK;
34029
34030    if( lockProxy ){
34031      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
34032      if( rc ) return rc;
34033      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
34034      if( rc ) return rc;
34035      sqlite3_free(lockProxy);
34036      pCtx->lockProxy = 0;
34037    }
34038    if( conchFile ){
34039      if( pCtx->conchHeld ){
34040        rc = proxyReleaseConch(pFile);
34041        if( rc ) return rc;
34042      }
34043      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
34044      if( rc ) return rc;
34045      sqlite3_free(conchFile);
34046    }
34047    sqlite3DbFree(0, pCtx->lockProxyPath);
34048    sqlite3_free(pCtx->conchFilePath);
34049    sqlite3DbFree(0, pCtx->dbPath);
34050    /* restore the original locking context and pMethod then close it */
34051    pFile->lockingContext = pCtx->oldLockingContext;
34052    pFile->pMethod = pCtx->pOldMethod;
34053    sqlite3_free(pCtx);
34054    return pFile->pMethod->xClose(id);
34055  }
34056  return SQLITE_OK;
34057}
34058
34059
34060
34061#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34062/*
34063** The proxy locking style is intended for use with AFP filesystems.
34064** And since AFP is only supported on MacOSX, the proxy locking is also
34065** restricted to MacOSX.
34066**
34067**
34068******************* End of the proxy lock implementation **********************
34069******************************************************************************/
34070
34071/*
34072** Initialize the operating system interface.
34073**
34074** This routine registers all VFS implementations for unix-like operating
34075** systems.  This routine, and the sqlite3_os_end() routine that follows,
34076** should be the only routines in this file that are visible from other
34077** files.
34078**
34079** This routine is called once during SQLite initialization and by a
34080** single thread.  The memory allocation and mutex subsystems have not
34081** necessarily been initialized when this routine is called, and so they
34082** should not be used.
34083*/
34084SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
34085  /*
34086  ** The following macro defines an initializer for an sqlite3_vfs object.
34087  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
34088  ** to the "finder" function.  (pAppData is a pointer to a pointer because
34089  ** silly C90 rules prohibit a void* from being cast to a function pointer
34090  ** and so we have to go through the intermediate pointer to avoid problems
34091  ** when compiling with -pedantic-errors on GCC.)
34092  **
34093  ** The FINDER parameter to this macro is the name of the pointer to the
34094  ** finder-function.  The finder-function returns a pointer to the
34095  ** sqlite_io_methods object that implements the desired locking
34096  ** behaviors.  See the division above that contains the IOMETHODS
34097  ** macro for addition information on finder-functions.
34098  **
34099  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
34100  ** object.  But the "autolockIoFinder" available on MacOSX does a little
34101  ** more than that; it looks at the filesystem type that hosts the
34102  ** database file and tries to choose an locking method appropriate for
34103  ** that filesystem time.
34104  */
34105  #define UNIXVFS(VFSNAME, FINDER) {                        \
34106    3,                    /* iVersion */                    \
34107    sizeof(unixFile),     /* szOsFile */                    \
34108    MAX_PATHNAME,         /* mxPathname */                  \
34109    0,                    /* pNext */                       \
34110    VFSNAME,              /* zName */                       \
34111    (void*)&FINDER,       /* pAppData */                    \
34112    unixOpen,             /* xOpen */                       \
34113    unixDelete,           /* xDelete */                     \
34114    unixAccess,           /* xAccess */                     \
34115    unixFullPathname,     /* xFullPathname */               \
34116    unixDlOpen,           /* xDlOpen */                     \
34117    unixDlError,          /* xDlError */                    \
34118    unixDlSym,            /* xDlSym */                      \
34119    unixDlClose,          /* xDlClose */                    \
34120    unixRandomness,       /* xRandomness */                 \
34121    unixSleep,            /* xSleep */                      \
34122    unixCurrentTime,      /* xCurrentTime */                \
34123    unixGetLastError,     /* xGetLastError */               \
34124    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
34125    unixSetSystemCall,    /* xSetSystemCall */              \
34126    unixGetSystemCall,    /* xGetSystemCall */              \
34127    unixNextSystemCall,   /* xNextSystemCall */             \
34128  }
34129
34130  /*
34131  ** All default VFSes for unix are contained in the following array.
34132  **
34133  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
34134  ** by the SQLite core when the VFS is registered.  So the following
34135  ** array cannot be const.
34136  */
34137  static sqlite3_vfs aVfs[] = {
34138#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34139    UNIXVFS("unix",          autolockIoFinder ),
34140#elif OS_VXWORKS
34141    UNIXVFS("unix",          vxworksIoFinder ),
34142#else
34143    UNIXVFS("unix",          posixIoFinder ),
34144#endif
34145    UNIXVFS("unix-none",     nolockIoFinder ),
34146    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
34147    UNIXVFS("unix-excl",     posixIoFinder ),
34148#if OS_VXWORKS
34149    UNIXVFS("unix-namedsem", semIoFinder ),
34150#endif
34151#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
34152    UNIXVFS("unix-posix",    posixIoFinder ),
34153#endif
34154#if SQLITE_ENABLE_LOCKING_STYLE
34155    UNIXVFS("unix-flock",    flockIoFinder ),
34156#endif
34157#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34158    UNIXVFS("unix-afp",      afpIoFinder ),
34159    UNIXVFS("unix-nfs",      nfsIoFinder ),
34160    UNIXVFS("unix-proxy",    proxyIoFinder ),
34161#endif
34162  };
34163  unsigned int i;          /* Loop counter */
34164
34165  /* Double-check that the aSyscall[] array has been constructed
34166  ** correctly.  See ticket [bb3a86e890c8e96ab] */
34167  assert( ArraySize(aSyscall)==25 );
34168
34169  /* Register all VFSes defined in the aVfs[] array */
34170  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
34171    sqlite3_vfs_register(&aVfs[i], i==0);
34172  }
34173  return SQLITE_OK;
34174}
34175
34176/*
34177** Shutdown the operating system interface.
34178**
34179** Some operating systems might need to do some cleanup in this routine,
34180** to release dynamically allocated objects.  But not on unix.
34181** This routine is a no-op for unix.
34182*/
34183SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
34184  return SQLITE_OK;
34185}
34186
34187#endif /* SQLITE_OS_UNIX */
34188
34189/************** End of os_unix.c *********************************************/
34190/************** Begin file os_win.c ******************************************/
34191/*
34192** 2004 May 22
34193**
34194** The author disclaims copyright to this source code.  In place of
34195** a legal notice, here is a blessing:
34196**
34197**    May you do good and not evil.
34198**    May you find forgiveness for yourself and forgive others.
34199**    May you share freely, never taking more than you give.
34200**
34201******************************************************************************
34202**
34203** This file contains code that is specific to Windows.
34204*/
34205/* #include "sqliteInt.h" */
34206#if SQLITE_OS_WIN               /* This file is used for Windows only */
34207
34208/*
34209** Include code that is common to all os_*.c files
34210*/
34211/************** Include os_common.h in the middle of os_win.c ****************/
34212/************** Begin file os_common.h ***************************************/
34213/*
34214** 2004 May 22
34215**
34216** The author disclaims copyright to this source code.  In place of
34217** a legal notice, here is a blessing:
34218**
34219**    May you do good and not evil.
34220**    May you find forgiveness for yourself and forgive others.
34221**    May you share freely, never taking more than you give.
34222**
34223******************************************************************************
34224**
34225** This file contains macros and a little bit of code that is common to
34226** all of the platform-specific files (os_*.c) and is #included into those
34227** files.
34228**
34229** This file should be #included by the os_*.c files only.  It is not a
34230** general purpose header file.
34231*/
34232#ifndef _OS_COMMON_H_
34233#define _OS_COMMON_H_
34234
34235/*
34236** At least two bugs have slipped in because we changed the MEMORY_DEBUG
34237** macro to SQLITE_DEBUG and some older makefiles have not yet made the
34238** switch.  The following code should catch this problem at compile-time.
34239*/
34240#ifdef MEMORY_DEBUG
34241# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
34242#endif
34243
34244/*
34245** Macros for performance tracing.  Normally turned off.  Only works
34246** on i486 hardware.
34247*/
34248#ifdef SQLITE_PERFORMANCE_TRACE
34249
34250/*
34251** hwtime.h contains inline assembler code for implementing
34252** high-performance timing routines.
34253*/
34254/************** Include hwtime.h in the middle of os_common.h ****************/
34255/************** Begin file hwtime.h ******************************************/
34256/*
34257** 2008 May 27
34258**
34259** The author disclaims copyright to this source code.  In place of
34260** a legal notice, here is a blessing:
34261**
34262**    May you do good and not evil.
34263**    May you find forgiveness for yourself and forgive others.
34264**    May you share freely, never taking more than you give.
34265**
34266******************************************************************************
34267**
34268** This file contains inline asm code for retrieving "high-performance"
34269** counters for x86 class CPUs.
34270*/
34271#ifndef _HWTIME_H_
34272#define _HWTIME_H_
34273
34274/*
34275** The following routine only works on pentium-class (or newer) processors.
34276** It uses the RDTSC opcode to read the cycle count value out of the
34277** processor and returns that value.  This can be used for high-res
34278** profiling.
34279*/
34280#if (defined(__GNUC__) || defined(_MSC_VER)) && \
34281      (defined(i386) || defined(__i386__) || defined(_M_IX86))
34282
34283  #if defined(__GNUC__)
34284
34285  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34286     unsigned int lo, hi;
34287     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
34288     return (sqlite_uint64)hi << 32 | lo;
34289  }
34290
34291  #elif defined(_MSC_VER)
34292
34293  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
34294     __asm {
34295        rdtsc
34296        ret       ; return value at EDX:EAX
34297     }
34298  }
34299
34300  #endif
34301
34302#elif (defined(__GNUC__) && defined(__x86_64__))
34303
34304  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34305      unsigned long val;
34306      __asm__ __volatile__ ("rdtsc" : "=A" (val));
34307      return val;
34308  }
34309
34310#elif (defined(__GNUC__) && defined(__ppc__))
34311
34312  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34313      unsigned long long retval;
34314      unsigned long junk;
34315      __asm__ __volatile__ ("\n\
34316          1:      mftbu   %1\n\
34317                  mftb    %L0\n\
34318                  mftbu   %0\n\
34319                  cmpw    %0,%1\n\
34320                  bne     1b"
34321                  : "=r" (retval), "=r" (junk));
34322      return retval;
34323  }
34324
34325#else
34326
34327  #error Need implementation of sqlite3Hwtime() for your platform.
34328
34329  /*
34330  ** To compile without implementing sqlite3Hwtime() for your platform,
34331  ** you can remove the above #error and use the following
34332  ** stub function.  You will lose timing support for many
34333  ** of the debugging and testing utilities, but it should at
34334  ** least compile and run.
34335  */
34336SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
34337
34338#endif
34339
34340#endif /* !defined(_HWTIME_H_) */
34341
34342/************** End of hwtime.h **********************************************/
34343/************** Continuing where we left off in os_common.h ******************/
34344
34345static sqlite_uint64 g_start;
34346static sqlite_uint64 g_elapsed;
34347#define TIMER_START       g_start=sqlite3Hwtime()
34348#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
34349#define TIMER_ELAPSED     g_elapsed
34350#else
34351#define TIMER_START
34352#define TIMER_END
34353#define TIMER_ELAPSED     ((sqlite_uint64)0)
34354#endif
34355
34356/*
34357** If we compile with the SQLITE_TEST macro set, then the following block
34358** of code will give us the ability to simulate a disk I/O error.  This
34359** is used for testing the I/O recovery logic.
34360*/
34361#ifdef SQLITE_TEST
34362SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
34363SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
34364SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
34365SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
34366SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
34367SQLITE_API int sqlite3_diskfull_pending = 0;
34368SQLITE_API int sqlite3_diskfull = 0;
34369#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
34370#define SimulateIOError(CODE)  \
34371  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
34372       || sqlite3_io_error_pending-- == 1 )  \
34373              { local_ioerr(); CODE; }
34374static void local_ioerr(){
34375  IOTRACE(("IOERR\n"));
34376  sqlite3_io_error_hit++;
34377  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
34378}
34379#define SimulateDiskfullError(CODE) \
34380   if( sqlite3_diskfull_pending ){ \
34381     if( sqlite3_diskfull_pending == 1 ){ \
34382       local_ioerr(); \
34383       sqlite3_diskfull = 1; \
34384       sqlite3_io_error_hit = 1; \
34385       CODE; \
34386     }else{ \
34387       sqlite3_diskfull_pending--; \
34388     } \
34389   }
34390#else
34391#define SimulateIOErrorBenign(X)
34392#define SimulateIOError(A)
34393#define SimulateDiskfullError(A)
34394#endif
34395
34396/*
34397** When testing, keep a count of the number of open files.
34398*/
34399#ifdef SQLITE_TEST
34400SQLITE_API int sqlite3_open_file_count = 0;
34401#define OpenCounter(X)  sqlite3_open_file_count+=(X)
34402#else
34403#define OpenCounter(X)
34404#endif
34405
34406#endif /* !defined(_OS_COMMON_H_) */
34407
34408/************** End of os_common.h *******************************************/
34409/************** Continuing where we left off in os_win.c *********************/
34410
34411/*
34412** Include the header file for the Windows VFS.
34413*/
34414/* #include "os_win.h" */
34415
34416/*
34417** Compiling and using WAL mode requires several APIs that are only
34418** available in Windows platforms based on the NT kernel.
34419*/
34420#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
34421#  error "WAL mode requires support from the Windows NT kernel, compile\
34422 with SQLITE_OMIT_WAL."
34423#endif
34424
34425#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
34426#  error "Memory mapped files require support from the Windows NT kernel,\
34427 compile with SQLITE_MAX_MMAP_SIZE=0."
34428#endif
34429
34430/*
34431** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
34432** based on the sub-platform)?
34433*/
34434#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
34435#  define SQLITE_WIN32_HAS_ANSI
34436#endif
34437
34438/*
34439** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
34440** based on the sub-platform)?
34441*/
34442#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
34443    !defined(SQLITE_WIN32_NO_WIDE)
34444#  define SQLITE_WIN32_HAS_WIDE
34445#endif
34446
34447/*
34448** Make sure at least one set of Win32 APIs is available.
34449*/
34450#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
34451#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
34452 must be defined."
34453#endif
34454
34455/*
34456** Define the required Windows SDK version constants if they are not
34457** already available.
34458*/
34459#ifndef NTDDI_WIN8
34460#  define NTDDI_WIN8                        0x06020000
34461#endif
34462
34463#ifndef NTDDI_WINBLUE
34464#  define NTDDI_WINBLUE                     0x06030000
34465#endif
34466
34467/*
34468** Check to see if the GetVersionEx[AW] functions are deprecated on the
34469** target system.  GetVersionEx was first deprecated in Win8.1.
34470*/
34471#ifndef SQLITE_WIN32_GETVERSIONEX
34472#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
34473#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
34474#  else
34475#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
34476#  endif
34477#endif
34478
34479/*
34480** This constant should already be defined (in the "WinDef.h" SDK file).
34481*/
34482#ifndef MAX_PATH
34483#  define MAX_PATH                      (260)
34484#endif
34485
34486/*
34487** Maximum pathname length (in chars) for Win32.  This should normally be
34488** MAX_PATH.
34489*/
34490#ifndef SQLITE_WIN32_MAX_PATH_CHARS
34491#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
34492#endif
34493
34494/*
34495** This constant should already be defined (in the "WinNT.h" SDK file).
34496*/
34497#ifndef UNICODE_STRING_MAX_CHARS
34498#  define UNICODE_STRING_MAX_CHARS      (32767)
34499#endif
34500
34501/*
34502** Maximum pathname length (in chars) for WinNT.  This should normally be
34503** UNICODE_STRING_MAX_CHARS.
34504*/
34505#ifndef SQLITE_WINNT_MAX_PATH_CHARS
34506#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
34507#endif
34508
34509/*
34510** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
34511** characters, so we allocate 4 bytes per character assuming worst-case of
34512** 4-bytes-per-character for UTF8.
34513*/
34514#ifndef SQLITE_WIN32_MAX_PATH_BYTES
34515#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
34516#endif
34517
34518/*
34519** Maximum pathname length (in bytes) for WinNT.  This should normally be
34520** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
34521*/
34522#ifndef SQLITE_WINNT_MAX_PATH_BYTES
34523#  define SQLITE_WINNT_MAX_PATH_BYTES   \
34524                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
34525#endif
34526
34527/*
34528** Maximum error message length (in chars) for WinRT.
34529*/
34530#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
34531#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
34532#endif
34533
34534/*
34535** Returns non-zero if the character should be treated as a directory
34536** separator.
34537*/
34538#ifndef winIsDirSep
34539#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
34540#endif
34541
34542/*
34543** This macro is used when a local variable is set to a value that is
34544** [sometimes] not used by the code (e.g. via conditional compilation).
34545*/
34546#ifndef UNUSED_VARIABLE_VALUE
34547#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
34548#endif
34549
34550/*
34551** Returns the character that should be used as the directory separator.
34552*/
34553#ifndef winGetDirSep
34554#  define winGetDirSep()                '\\'
34555#endif
34556
34557/*
34558** Do we need to manually define the Win32 file mapping APIs for use with WAL
34559** mode or memory mapped files (e.g. these APIs are available in the Windows
34560** CE SDK; however, they are not present in the header file)?
34561*/
34562#if SQLITE_WIN32_FILEMAPPING_API && \
34563        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34564/*
34565** Two of the file mapping APIs are different under WinRT.  Figure out which
34566** set we need.
34567*/
34568#if SQLITE_OS_WINRT
34569WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
34570        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
34571
34572WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
34573#else
34574#if defined(SQLITE_WIN32_HAS_ANSI)
34575WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
34576        DWORD, DWORD, DWORD, LPCSTR);
34577#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
34578
34579#if defined(SQLITE_WIN32_HAS_WIDE)
34580WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
34581        DWORD, DWORD, DWORD, LPCWSTR);
34582#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
34583
34584WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
34585#endif /* SQLITE_OS_WINRT */
34586
34587/*
34588** These file mapping APIs are common to both Win32 and WinRT.
34589*/
34590
34591WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
34592WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
34593#endif /* SQLITE_WIN32_FILEMAPPING_API */
34594
34595/*
34596** Some Microsoft compilers lack this definition.
34597*/
34598#ifndef INVALID_FILE_ATTRIBUTES
34599# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
34600#endif
34601
34602#ifndef FILE_FLAG_MASK
34603# define FILE_FLAG_MASK          (0xFF3C0000)
34604#endif
34605
34606#ifndef FILE_ATTRIBUTE_MASK
34607# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
34608#endif
34609
34610#ifndef SQLITE_OMIT_WAL
34611/* Forward references to structures used for WAL */
34612typedef struct winShm winShm;           /* A connection to shared-memory */
34613typedef struct winShmNode winShmNode;   /* A region of shared-memory */
34614#endif
34615
34616/*
34617** WinCE lacks native support for file locking so we have to fake it
34618** with some code of our own.
34619*/
34620#if SQLITE_OS_WINCE
34621typedef struct winceLock {
34622  int nReaders;       /* Number of reader locks obtained */
34623  BOOL bPending;      /* Indicates a pending lock has been obtained */
34624  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
34625  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
34626} winceLock;
34627#endif
34628
34629/*
34630** The winFile structure is a subclass of sqlite3_file* specific to the win32
34631** portability layer.
34632*/
34633typedef struct winFile winFile;
34634struct winFile {
34635  const sqlite3_io_methods *pMethod; /*** Must be first ***/
34636  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
34637  HANDLE h;               /* Handle for accessing the file */
34638  u8 locktype;            /* Type of lock currently held on this file */
34639  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
34640  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
34641  DWORD lastErrno;        /* The Windows errno from the last I/O error */
34642#ifndef SQLITE_OMIT_WAL
34643  winShm *pShm;           /* Instance of shared memory on this file */
34644#endif
34645  const char *zPath;      /* Full pathname of this file */
34646  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
34647#if SQLITE_OS_WINCE
34648  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
34649  HANDLE hMutex;          /* Mutex used to control access to shared lock */
34650  HANDLE hShared;         /* Shared memory segment used for locking */
34651  winceLock local;        /* Locks obtained by this instance of winFile */
34652  winceLock *shared;      /* Global shared lock memory for the file  */
34653#endif
34654#if SQLITE_MAX_MMAP_SIZE>0
34655  int nFetchOut;                /* Number of outstanding xFetch references */
34656  HANDLE hMap;                  /* Handle for accessing memory mapping */
34657  void *pMapRegion;             /* Area memory mapped */
34658  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
34659  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
34660  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
34661#endif
34662};
34663
34664/*
34665** Allowed values for winFile.ctrlFlags
34666*/
34667#define WINFILE_RDONLY          0x02   /* Connection is read only */
34668#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
34669#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
34670
34671/*
34672 * The size of the buffer used by sqlite3_win32_write_debug().
34673 */
34674#ifndef SQLITE_WIN32_DBG_BUF_SIZE
34675#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
34676#endif
34677
34678/*
34679 * The value used with sqlite3_win32_set_directory() to specify that
34680 * the data directory should be changed.
34681 */
34682#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
34683#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
34684#endif
34685
34686/*
34687 * The value used with sqlite3_win32_set_directory() to specify that
34688 * the temporary directory should be changed.
34689 */
34690#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34691#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
34692#endif
34693
34694/*
34695 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
34696 * various Win32 API heap functions instead of our own.
34697 */
34698#ifdef SQLITE_WIN32_MALLOC
34699
34700/*
34701 * If this is non-zero, an isolated heap will be created by the native Win32
34702 * allocator subsystem; otherwise, the default process heap will be used.  This
34703 * setting has no effect when compiling for WinRT.  By default, this is enabled
34704 * and an isolated heap will be created to store all allocated data.
34705 *
34706 ******************************************************************************
34707 * WARNING: It is important to note that when this setting is non-zero and the
34708 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
34709 *          function), all data that was allocated using the isolated heap will
34710 *          be freed immediately and any attempt to access any of that freed
34711 *          data will almost certainly result in an immediate access violation.
34712 ******************************************************************************
34713 */
34714#ifndef SQLITE_WIN32_HEAP_CREATE
34715#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
34716#endif
34717
34718/*
34719 * The initial size of the Win32-specific heap.  This value may be zero.
34720 */
34721#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
34722#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
34723                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
34724#endif
34725
34726/*
34727 * The maximum size of the Win32-specific heap.  This value may be zero.
34728 */
34729#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
34730#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
34731#endif
34732
34733/*
34734 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
34735 * zero for the default behavior.
34736 */
34737#ifndef SQLITE_WIN32_HEAP_FLAGS
34738#  define SQLITE_WIN32_HEAP_FLAGS     (0)
34739#endif
34740
34741
34742/*
34743** The winMemData structure stores information required by the Win32-specific
34744** sqlite3_mem_methods implementation.
34745*/
34746typedef struct winMemData winMemData;
34747struct winMemData {
34748#ifndef NDEBUG
34749  u32 magic1;   /* Magic number to detect structure corruption. */
34750#endif
34751  HANDLE hHeap; /* The handle to our heap. */
34752  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
34753#ifndef NDEBUG
34754  u32 magic2;   /* Magic number to detect structure corruption. */
34755#endif
34756};
34757
34758#ifndef NDEBUG
34759#define WINMEM_MAGIC1     0x42b2830b
34760#define WINMEM_MAGIC2     0xbd4d7cf4
34761#endif
34762
34763static struct winMemData win_mem_data = {
34764#ifndef NDEBUG
34765  WINMEM_MAGIC1,
34766#endif
34767  NULL, FALSE
34768#ifndef NDEBUG
34769  ,WINMEM_MAGIC2
34770#endif
34771};
34772
34773#ifndef NDEBUG
34774#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
34775#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
34776#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
34777#else
34778#define winMemAssertMagic()
34779#endif
34780
34781#define winMemGetDataPtr()  &win_mem_data
34782#define winMemGetHeap()     win_mem_data.hHeap
34783#define winMemGetOwned()    win_mem_data.bOwned
34784
34785static void *winMemMalloc(int nBytes);
34786static void winMemFree(void *pPrior);
34787static void *winMemRealloc(void *pPrior, int nBytes);
34788static int winMemSize(void *p);
34789static int winMemRoundup(int n);
34790static int winMemInit(void *pAppData);
34791static void winMemShutdown(void *pAppData);
34792
34793SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
34794#endif /* SQLITE_WIN32_MALLOC */
34795
34796/*
34797** The following variable is (normally) set once and never changes
34798** thereafter.  It records whether the operating system is Win9x
34799** or WinNT.
34800**
34801** 0:   Operating system unknown.
34802** 1:   Operating system is Win9x.
34803** 2:   Operating system is WinNT.
34804**
34805** In order to facilitate testing on a WinNT system, the test fixture
34806** can manually set this value to 1 to emulate Win98 behavior.
34807*/
34808#ifdef SQLITE_TEST
34809SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
34810#else
34811static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
34812#endif
34813
34814#ifndef SYSCALL
34815#  define SYSCALL sqlite3_syscall_ptr
34816#endif
34817
34818/*
34819** This function is not available on Windows CE or WinRT.
34820 */
34821
34822#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
34823#  define osAreFileApisANSI()       1
34824#endif
34825
34826/*
34827** Many system calls are accessed through pointer-to-functions so that
34828** they may be overridden at runtime to facilitate fault injection during
34829** testing and sandboxing.  The following array holds the names and pointers
34830** to all overrideable system calls.
34831*/
34832static struct win_syscall {
34833  const char *zName;            /* Name of the system call */
34834  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
34835  sqlite3_syscall_ptr pDefault; /* Default value */
34836} aSyscall[] = {
34837#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34838  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
34839#else
34840  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
34841#endif
34842
34843#ifndef osAreFileApisANSI
34844#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
34845#endif
34846
34847#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
34848  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
34849#else
34850  { "CharLowerW",              (SYSCALL)0,                       0 },
34851#endif
34852
34853#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
34854
34855#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
34856  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
34857#else
34858  { "CharUpperW",              (SYSCALL)0,                       0 },
34859#endif
34860
34861#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
34862
34863  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
34864
34865#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
34866
34867#if defined(SQLITE_WIN32_HAS_ANSI)
34868  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
34869#else
34870  { "CreateFileA",             (SYSCALL)0,                       0 },
34871#endif
34872
34873#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
34874        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
34875
34876#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
34877  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
34878#else
34879  { "CreateFileW",             (SYSCALL)0,                       0 },
34880#endif
34881
34882#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
34883        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
34884
34885#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
34886        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
34887  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
34888#else
34889  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
34890#endif
34891
34892#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
34893        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
34894
34895#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
34896        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
34897  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
34898#else
34899  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
34900#endif
34901
34902#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
34903        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
34904
34905#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
34906  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
34907#else
34908  { "CreateMutexW",            (SYSCALL)0,                       0 },
34909#endif
34910
34911#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
34912        LPCWSTR))aSyscall[8].pCurrent)
34913
34914#if defined(SQLITE_WIN32_HAS_ANSI)
34915  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
34916#else
34917  { "DeleteFileA",             (SYSCALL)0,                       0 },
34918#endif
34919
34920#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
34921
34922#if defined(SQLITE_WIN32_HAS_WIDE)
34923  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
34924#else
34925  { "DeleteFileW",             (SYSCALL)0,                       0 },
34926#endif
34927
34928#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
34929
34930#if SQLITE_OS_WINCE
34931  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
34932#else
34933  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
34934#endif
34935
34936#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
34937        LPFILETIME))aSyscall[11].pCurrent)
34938
34939#if SQLITE_OS_WINCE
34940  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
34941#else
34942  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
34943#endif
34944
34945#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
34946        LPSYSTEMTIME))aSyscall[12].pCurrent)
34947
34948  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
34949
34950#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
34951
34952#if defined(SQLITE_WIN32_HAS_ANSI)
34953  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
34954#else
34955  { "FormatMessageA",          (SYSCALL)0,                       0 },
34956#endif
34957
34958#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
34959        DWORD,va_list*))aSyscall[14].pCurrent)
34960
34961#if defined(SQLITE_WIN32_HAS_WIDE)
34962  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
34963#else
34964  { "FormatMessageW",          (SYSCALL)0,                       0 },
34965#endif
34966
34967#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
34968        DWORD,va_list*))aSyscall[15].pCurrent)
34969
34970#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
34971  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
34972#else
34973  { "FreeLibrary",             (SYSCALL)0,                       0 },
34974#endif
34975
34976#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
34977
34978  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
34979
34980#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
34981
34982#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
34983  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
34984#else
34985  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
34986#endif
34987
34988#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
34989        LPDWORD))aSyscall[18].pCurrent)
34990
34991#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
34992  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
34993#else
34994  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
34995#endif
34996
34997#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
34998        LPDWORD))aSyscall[19].pCurrent)
34999
35000#if defined(SQLITE_WIN32_HAS_ANSI)
35001  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
35002#else
35003  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
35004#endif
35005
35006#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
35007
35008#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35009  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
35010#else
35011  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
35012#endif
35013
35014#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
35015
35016#if defined(SQLITE_WIN32_HAS_WIDE)
35017  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
35018#else
35019  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
35020#endif
35021
35022#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
35023        LPVOID))aSyscall[22].pCurrent)
35024
35025#if !SQLITE_OS_WINRT
35026  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
35027#else
35028  { "GetFileSize",             (SYSCALL)0,                       0 },
35029#endif
35030
35031#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
35032
35033#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
35034  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
35035#else
35036  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
35037#endif
35038
35039#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
35040        LPSTR*))aSyscall[24].pCurrent)
35041
35042#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35043  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
35044#else
35045  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
35046#endif
35047
35048#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
35049        LPWSTR*))aSyscall[25].pCurrent)
35050
35051  { "GetLastError",            (SYSCALL)GetLastError,            0 },
35052
35053#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
35054
35055#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
35056#if SQLITE_OS_WINCE
35057  /* The GetProcAddressA() routine is only available on Windows CE. */
35058  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
35059#else
35060  /* All other Windows platforms expect GetProcAddress() to take
35061  ** an ANSI string regardless of the _UNICODE setting */
35062  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
35063#endif
35064#else
35065  { "GetProcAddressA",         (SYSCALL)0,                       0 },
35066#endif
35067
35068#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
35069        LPCSTR))aSyscall[27].pCurrent)
35070
35071#if !SQLITE_OS_WINRT
35072  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
35073#else
35074  { "GetSystemInfo",           (SYSCALL)0,                       0 },
35075#endif
35076
35077#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
35078
35079  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
35080
35081#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
35082
35083#if !SQLITE_OS_WINCE
35084  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
35085#else
35086  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
35087#endif
35088
35089#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
35090        LPFILETIME))aSyscall[30].pCurrent)
35091
35092#if defined(SQLITE_WIN32_HAS_ANSI)
35093  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
35094#else
35095  { "GetTempPathA",            (SYSCALL)0,                       0 },
35096#endif
35097
35098#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
35099
35100#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35101  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
35102#else
35103  { "GetTempPathW",            (SYSCALL)0,                       0 },
35104#endif
35105
35106#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
35107
35108#if !SQLITE_OS_WINRT
35109  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
35110#else
35111  { "GetTickCount",            (SYSCALL)0,                       0 },
35112#endif
35113
35114#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
35115
35116#if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
35117        SQLITE_WIN32_GETVERSIONEX
35118  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
35119#else
35120  { "GetVersionExA",           (SYSCALL)0,                       0 },
35121#endif
35122
35123#define osGetVersionExA ((BOOL(WINAPI*)( \
35124        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
35125
35126#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
35127        defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
35128  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
35129#else
35130  { "GetVersionExW",           (SYSCALL)0,                       0 },
35131#endif
35132
35133#define osGetVersionExW ((BOOL(WINAPI*)( \
35134        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
35135
35136  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
35137
35138#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
35139        SIZE_T))aSyscall[36].pCurrent)
35140
35141#if !SQLITE_OS_WINRT
35142  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
35143#else
35144  { "HeapCreate",              (SYSCALL)0,                       0 },
35145#endif
35146
35147#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
35148        SIZE_T))aSyscall[37].pCurrent)
35149
35150#if !SQLITE_OS_WINRT
35151  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
35152#else
35153  { "HeapDestroy",             (SYSCALL)0,                       0 },
35154#endif
35155
35156#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
35157
35158  { "HeapFree",                (SYSCALL)HeapFree,                0 },
35159
35160#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
35161
35162  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
35163
35164#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
35165        SIZE_T))aSyscall[40].pCurrent)
35166
35167  { "HeapSize",                (SYSCALL)HeapSize,                0 },
35168
35169#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
35170        LPCVOID))aSyscall[41].pCurrent)
35171
35172#if !SQLITE_OS_WINRT
35173  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
35174#else
35175  { "HeapValidate",            (SYSCALL)0,                       0 },
35176#endif
35177
35178#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
35179        LPCVOID))aSyscall[42].pCurrent)
35180
35181#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35182  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
35183#else
35184  { "HeapCompact",             (SYSCALL)0,                       0 },
35185#endif
35186
35187#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
35188
35189#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
35190  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
35191#else
35192  { "LoadLibraryA",            (SYSCALL)0,                       0 },
35193#endif
35194
35195#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
35196
35197#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
35198        !defined(SQLITE_OMIT_LOAD_EXTENSION)
35199  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
35200#else
35201  { "LoadLibraryW",            (SYSCALL)0,                       0 },
35202#endif
35203
35204#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
35205
35206#if !SQLITE_OS_WINRT
35207  { "LocalFree",               (SYSCALL)LocalFree,               0 },
35208#else
35209  { "LocalFree",               (SYSCALL)0,                       0 },
35210#endif
35211
35212#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
35213
35214#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35215  { "LockFile",                (SYSCALL)LockFile,                0 },
35216#else
35217  { "LockFile",                (SYSCALL)0,                       0 },
35218#endif
35219
35220#ifndef osLockFile
35221#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35222        DWORD))aSyscall[47].pCurrent)
35223#endif
35224
35225#if !SQLITE_OS_WINCE
35226  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
35227#else
35228  { "LockFileEx",              (SYSCALL)0,                       0 },
35229#endif
35230
35231#ifndef osLockFileEx
35232#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
35233        LPOVERLAPPED))aSyscall[48].pCurrent)
35234#endif
35235
35236#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
35237        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
35238  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
35239#else
35240  { "MapViewOfFile",           (SYSCALL)0,                       0 },
35241#endif
35242
35243#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35244        SIZE_T))aSyscall[49].pCurrent)
35245
35246  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
35247
35248#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
35249        int))aSyscall[50].pCurrent)
35250
35251  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
35252
35253#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
35254        LARGE_INTEGER*))aSyscall[51].pCurrent)
35255
35256  { "ReadFile",                (SYSCALL)ReadFile,                0 },
35257
35258#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
35259        LPOVERLAPPED))aSyscall[52].pCurrent)
35260
35261  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
35262
35263#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
35264
35265#if !SQLITE_OS_WINRT
35266  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
35267#else
35268  { "SetFilePointer",          (SYSCALL)0,                       0 },
35269#endif
35270
35271#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
35272        DWORD))aSyscall[54].pCurrent)
35273
35274#if !SQLITE_OS_WINRT
35275  { "Sleep",                   (SYSCALL)Sleep,                   0 },
35276#else
35277  { "Sleep",                   (SYSCALL)0,                       0 },
35278#endif
35279
35280#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
35281
35282  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
35283
35284#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
35285        LPFILETIME))aSyscall[56].pCurrent)
35286
35287#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35288  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
35289#else
35290  { "UnlockFile",              (SYSCALL)0,                       0 },
35291#endif
35292
35293#ifndef osUnlockFile
35294#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35295        DWORD))aSyscall[57].pCurrent)
35296#endif
35297
35298#if !SQLITE_OS_WINCE
35299  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
35300#else
35301  { "UnlockFileEx",            (SYSCALL)0,                       0 },
35302#endif
35303
35304#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35305        LPOVERLAPPED))aSyscall[58].pCurrent)
35306
35307#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
35308  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
35309#else
35310  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
35311#endif
35312
35313#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
35314
35315  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
35316
35317#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
35318        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
35319
35320  { "WriteFile",               (SYSCALL)WriteFile,               0 },
35321
35322#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
35323        LPOVERLAPPED))aSyscall[61].pCurrent)
35324
35325#if SQLITE_OS_WINRT
35326  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
35327#else
35328  { "CreateEventExW",          (SYSCALL)0,                       0 },
35329#endif
35330
35331#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
35332        DWORD,DWORD))aSyscall[62].pCurrent)
35333
35334#if !SQLITE_OS_WINRT
35335  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
35336#else
35337  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
35338#endif
35339
35340#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
35341        DWORD))aSyscall[63].pCurrent)
35342
35343#if !SQLITE_OS_WINCE
35344  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
35345#else
35346  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
35347#endif
35348
35349#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
35350        BOOL))aSyscall[64].pCurrent)
35351
35352#if SQLITE_OS_WINRT
35353  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
35354#else
35355  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
35356#endif
35357
35358#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
35359        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
35360
35361#if SQLITE_OS_WINRT
35362  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
35363#else
35364  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
35365#endif
35366
35367#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
35368        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
35369
35370#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
35371  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
35372#else
35373  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
35374#endif
35375
35376#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
35377        SIZE_T))aSyscall[67].pCurrent)
35378
35379#if SQLITE_OS_WINRT
35380  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
35381#else
35382  { "CreateFile2",             (SYSCALL)0,                       0 },
35383#endif
35384
35385#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
35386        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
35387
35388#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
35389  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
35390#else
35391  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
35392#endif
35393
35394#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
35395        DWORD))aSyscall[69].pCurrent)
35396
35397#if SQLITE_OS_WINRT
35398  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
35399#else
35400  { "GetTickCount64",          (SYSCALL)0,                       0 },
35401#endif
35402
35403#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
35404
35405#if SQLITE_OS_WINRT
35406  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
35407#else
35408  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
35409#endif
35410
35411#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
35412        LPSYSTEM_INFO))aSyscall[71].pCurrent)
35413
35414#if defined(SQLITE_WIN32_HAS_ANSI)
35415  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
35416#else
35417  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
35418#endif
35419
35420#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
35421
35422#if defined(SQLITE_WIN32_HAS_WIDE)
35423  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
35424#else
35425  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
35426#endif
35427
35428#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
35429
35430  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
35431
35432#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
35433
35434#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
35435  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
35436#else
35437  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
35438#endif
35439
35440#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
35441        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
35442
35443/*
35444** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
35445**       is really just a macro that uses a compiler intrinsic (e.g. x64).
35446**       So do not try to make this is into a redefinable interface.
35447*/
35448#if defined(InterlockedCompareExchange)
35449  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
35450
35451#define osInterlockedCompareExchange InterlockedCompareExchange
35452#else
35453  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
35454
35455#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
35456        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
35457#endif /* defined(InterlockedCompareExchange) */
35458
35459#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
35460  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
35461#else
35462  { "UuidCreate",               (SYSCALL)0,                      0 },
35463#endif
35464
35465#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
35466
35467#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
35468  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
35469#else
35470  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
35471#endif
35472
35473#define osUuidCreateSequential \
35474        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
35475
35476#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
35477  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
35478#else
35479  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
35480#endif
35481
35482#define osFlushViewOfFile \
35483        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
35484
35485}; /* End of the overrideable system calls */
35486
35487/*
35488** This is the xSetSystemCall() method of sqlite3_vfs for all of the
35489** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
35490** system call pointer, or SQLITE_NOTFOUND if there is no configurable
35491** system call named zName.
35492*/
35493static int winSetSystemCall(
35494  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
35495  const char *zName,            /* Name of system call to override */
35496  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
35497){
35498  unsigned int i;
35499  int rc = SQLITE_NOTFOUND;
35500
35501  UNUSED_PARAMETER(pNotUsed);
35502  if( zName==0 ){
35503    /* If no zName is given, restore all system calls to their default
35504    ** settings and return NULL
35505    */
35506    rc = SQLITE_OK;
35507    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35508      if( aSyscall[i].pDefault ){
35509        aSyscall[i].pCurrent = aSyscall[i].pDefault;
35510      }
35511    }
35512  }else{
35513    /* If zName is specified, operate on only the one system call
35514    ** specified.
35515    */
35516    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35517      if( strcmp(zName, aSyscall[i].zName)==0 ){
35518        if( aSyscall[i].pDefault==0 ){
35519          aSyscall[i].pDefault = aSyscall[i].pCurrent;
35520        }
35521        rc = SQLITE_OK;
35522        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
35523        aSyscall[i].pCurrent = pNewFunc;
35524        break;
35525      }
35526    }
35527  }
35528  return rc;
35529}
35530
35531/*
35532** Return the value of a system call.  Return NULL if zName is not a
35533** recognized system call name.  NULL is also returned if the system call
35534** is currently undefined.
35535*/
35536static sqlite3_syscall_ptr winGetSystemCall(
35537  sqlite3_vfs *pNotUsed,
35538  const char *zName
35539){
35540  unsigned int i;
35541
35542  UNUSED_PARAMETER(pNotUsed);
35543  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35544    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
35545  }
35546  return 0;
35547}
35548
35549/*
35550** Return the name of the first system call after zName.  If zName==NULL
35551** then return the name of the first system call.  Return NULL if zName
35552** is the last system call or if zName is not the name of a valid
35553** system call.
35554*/
35555static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
35556  int i = -1;
35557
35558  UNUSED_PARAMETER(p);
35559  if( zName ){
35560    for(i=0; i<ArraySize(aSyscall)-1; i++){
35561      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
35562    }
35563  }
35564  for(i++; i<ArraySize(aSyscall); i++){
35565    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
35566  }
35567  return 0;
35568}
35569
35570#ifdef SQLITE_WIN32_MALLOC
35571/*
35572** If a Win32 native heap has been configured, this function will attempt to
35573** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
35574** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
35575** "pnLargest" argument, if non-zero, will be used to return the size of the
35576** largest committed free block in the heap, in bytes.
35577*/
35578SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
35579  int rc = SQLITE_OK;
35580  UINT nLargest = 0;
35581  HANDLE hHeap;
35582
35583  winMemAssertMagic();
35584  hHeap = winMemGetHeap();
35585  assert( hHeap!=0 );
35586  assert( hHeap!=INVALID_HANDLE_VALUE );
35587#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35588  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35589#endif
35590#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35591  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
35592    DWORD lastErrno = osGetLastError();
35593    if( lastErrno==NO_ERROR ){
35594      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
35595                  (void*)hHeap);
35596      rc = SQLITE_NOMEM;
35597    }else{
35598      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
35599                  osGetLastError(), (void*)hHeap);
35600      rc = SQLITE_ERROR;
35601    }
35602  }
35603#else
35604  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
35605              (void*)hHeap);
35606  rc = SQLITE_NOTFOUND;
35607#endif
35608  if( pnLargest ) *pnLargest = nLargest;
35609  return rc;
35610}
35611
35612/*
35613** If a Win32 native heap has been configured, this function will attempt to
35614** destroy and recreate it.  If the Win32 native heap is not isolated and/or
35615** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
35616** be returned and no changes will be made to the Win32 native heap.
35617*/
35618SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
35619  int rc;
35620  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
35621  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
35622  MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
35623  MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
35624  sqlite3_mutex_enter(pMaster);
35625  sqlite3_mutex_enter(pMem);
35626  winMemAssertMagic();
35627  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
35628    /*
35629    ** At this point, there should be no outstanding memory allocations on
35630    ** the heap.  Also, since both the master and memsys locks are currently
35631    ** being held by us, no other function (i.e. from another thread) should
35632    ** be able to even access the heap.  Attempt to destroy and recreate our
35633    ** isolated Win32 native heap now.
35634    */
35635    assert( winMemGetHeap()!=NULL );
35636    assert( winMemGetOwned() );
35637    assert( sqlite3_memory_used()==0 );
35638    winMemShutdown(winMemGetDataPtr());
35639    assert( winMemGetHeap()==NULL );
35640    assert( !winMemGetOwned() );
35641    assert( sqlite3_memory_used()==0 );
35642    rc = winMemInit(winMemGetDataPtr());
35643    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
35644    assert( rc!=SQLITE_OK || winMemGetOwned() );
35645    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
35646  }else{
35647    /*
35648    ** The Win32 native heap cannot be modified because it may be in use.
35649    */
35650    rc = SQLITE_BUSY;
35651  }
35652  sqlite3_mutex_leave(pMem);
35653  sqlite3_mutex_leave(pMaster);
35654  return rc;
35655}
35656#endif /* SQLITE_WIN32_MALLOC */
35657
35658/*
35659** This function outputs the specified (ANSI) string to the Win32 debugger
35660** (if available).
35661*/
35662
35663SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
35664  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
35665  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
35666  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
35667  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
35668#if defined(SQLITE_WIN32_HAS_ANSI)
35669  if( nMin>0 ){
35670    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35671    memcpy(zDbgBuf, zBuf, nMin);
35672    osOutputDebugStringA(zDbgBuf);
35673  }else{
35674    osOutputDebugStringA(zBuf);
35675  }
35676#elif defined(SQLITE_WIN32_HAS_WIDE)
35677  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35678  if ( osMultiByteToWideChar(
35679          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
35680          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
35681    return;
35682  }
35683  osOutputDebugStringW((LPCWSTR)zDbgBuf);
35684#else
35685  if( nMin>0 ){
35686    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35687    memcpy(zDbgBuf, zBuf, nMin);
35688    fprintf(stderr, "%s", zDbgBuf);
35689  }else{
35690    fprintf(stderr, "%s", zBuf);
35691  }
35692#endif
35693}
35694
35695/*
35696** The following routine suspends the current thread for at least ms
35697** milliseconds.  This is equivalent to the Win32 Sleep() interface.
35698*/
35699#if SQLITE_OS_WINRT
35700static HANDLE sleepObj = NULL;
35701#endif
35702
35703SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
35704#if SQLITE_OS_WINRT
35705  if ( sleepObj==NULL ){
35706    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
35707                                SYNCHRONIZE);
35708  }
35709  assert( sleepObj!=NULL );
35710  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
35711#else
35712  osSleep(milliseconds);
35713#endif
35714}
35715
35716#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
35717        SQLITE_THREADSAFE>0
35718SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
35719  DWORD rc;
35720  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
35721                                       TRUE))==WAIT_IO_COMPLETION ){}
35722  return rc;
35723}
35724#endif
35725
35726/*
35727** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
35728** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
35729**
35730** Here is an interesting observation:  Win95, Win98, and WinME lack
35731** the LockFileEx() API.  But we can still statically link against that
35732** API as long as we don't call it when running Win95/98/ME.  A call to
35733** this routine is used to determine if the host is Win95/98/ME or
35734** WinNT/2K/XP so that we will know whether or not we can safely call
35735** the LockFileEx() API.
35736*/
35737
35738#if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
35739# define osIsNT()  (1)
35740#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
35741# define osIsNT()  (1)
35742#elif !defined(SQLITE_WIN32_HAS_WIDE)
35743# define osIsNT()  (0)
35744#else
35745# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
35746#endif
35747
35748/*
35749** This function determines if the machine is running a version of Windows
35750** based on the NT kernel.
35751*/
35752SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
35753#if SQLITE_OS_WINRT
35754  /*
35755  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
35756  **       kernel.
35757  */
35758  return 1;
35759#elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
35760  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
35761#if defined(SQLITE_WIN32_HAS_ANSI)
35762    OSVERSIONINFOA sInfo;
35763    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
35764    osGetVersionExA(&sInfo);
35765    osInterlockedCompareExchange(&sqlite3_os_type,
35766        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
35767#elif defined(SQLITE_WIN32_HAS_WIDE)
35768    OSVERSIONINFOW sInfo;
35769    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
35770    osGetVersionExW(&sInfo);
35771    osInterlockedCompareExchange(&sqlite3_os_type,
35772        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
35773#endif
35774  }
35775  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
35776#elif SQLITE_TEST
35777  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
35778#else
35779  /*
35780  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
35781  **       deprecated are always assumed to be based on the NT kernel.
35782  */
35783  return 1;
35784#endif
35785}
35786
35787#ifdef SQLITE_WIN32_MALLOC
35788/*
35789** Allocate nBytes of memory.
35790*/
35791static void *winMemMalloc(int nBytes){
35792  HANDLE hHeap;
35793  void *p;
35794
35795  winMemAssertMagic();
35796  hHeap = winMemGetHeap();
35797  assert( hHeap!=0 );
35798  assert( hHeap!=INVALID_HANDLE_VALUE );
35799#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35800  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35801#endif
35802  assert( nBytes>=0 );
35803  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
35804  if( !p ){
35805    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
35806                nBytes, osGetLastError(), (void*)hHeap);
35807  }
35808  return p;
35809}
35810
35811/*
35812** Free memory.
35813*/
35814static void winMemFree(void *pPrior){
35815  HANDLE hHeap;
35816
35817  winMemAssertMagic();
35818  hHeap = winMemGetHeap();
35819  assert( hHeap!=0 );
35820  assert( hHeap!=INVALID_HANDLE_VALUE );
35821#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35822  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
35823#endif
35824  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
35825  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
35826    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
35827                pPrior, osGetLastError(), (void*)hHeap);
35828  }
35829}
35830
35831/*
35832** Change the size of an existing memory allocation
35833*/
35834static void *winMemRealloc(void *pPrior, int nBytes){
35835  HANDLE hHeap;
35836  void *p;
35837
35838  winMemAssertMagic();
35839  hHeap = winMemGetHeap();
35840  assert( hHeap!=0 );
35841  assert( hHeap!=INVALID_HANDLE_VALUE );
35842#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35843  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
35844#endif
35845  assert( nBytes>=0 );
35846  if( !pPrior ){
35847    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
35848  }else{
35849    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
35850  }
35851  if( !p ){
35852    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
35853                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
35854                (void*)hHeap);
35855  }
35856  return p;
35857}
35858
35859/*
35860** Return the size of an outstanding allocation, in bytes.
35861*/
35862static int winMemSize(void *p){
35863  HANDLE hHeap;
35864  SIZE_T n;
35865
35866  winMemAssertMagic();
35867  hHeap = winMemGetHeap();
35868  assert( hHeap!=0 );
35869  assert( hHeap!=INVALID_HANDLE_VALUE );
35870#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35871  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
35872#endif
35873  if( !p ) return 0;
35874  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
35875  if( n==(SIZE_T)-1 ){
35876    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
35877                p, osGetLastError(), (void*)hHeap);
35878    return 0;
35879  }
35880  return (int)n;
35881}
35882
35883/*
35884** Round up a request size to the next valid allocation size.
35885*/
35886static int winMemRoundup(int n){
35887  return n;
35888}
35889
35890/*
35891** Initialize this module.
35892*/
35893static int winMemInit(void *pAppData){
35894  winMemData *pWinMemData = (winMemData *)pAppData;
35895
35896  if( !pWinMemData ) return SQLITE_ERROR;
35897  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
35898  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
35899
35900#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
35901  if( !pWinMemData->hHeap ){
35902    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
35903    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
35904    if( dwMaximumSize==0 ){
35905      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
35906    }else if( dwInitialSize>dwMaximumSize ){
35907      dwInitialSize = dwMaximumSize;
35908    }
35909    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
35910                                      dwInitialSize, dwMaximumSize);
35911    if( !pWinMemData->hHeap ){
35912      sqlite3_log(SQLITE_NOMEM,
35913          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
35914          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
35915          dwMaximumSize);
35916      return SQLITE_NOMEM;
35917    }
35918    pWinMemData->bOwned = TRUE;
35919    assert( pWinMemData->bOwned );
35920  }
35921#else
35922  pWinMemData->hHeap = osGetProcessHeap();
35923  if( !pWinMemData->hHeap ){
35924    sqlite3_log(SQLITE_NOMEM,
35925        "failed to GetProcessHeap (%lu)", osGetLastError());
35926    return SQLITE_NOMEM;
35927  }
35928  pWinMemData->bOwned = FALSE;
35929  assert( !pWinMemData->bOwned );
35930#endif
35931  assert( pWinMemData->hHeap!=0 );
35932  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
35933#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35934  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35935#endif
35936  return SQLITE_OK;
35937}
35938
35939/*
35940** Deinitialize this module.
35941*/
35942static void winMemShutdown(void *pAppData){
35943  winMemData *pWinMemData = (winMemData *)pAppData;
35944
35945  if( !pWinMemData ) return;
35946  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
35947  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
35948
35949  if( pWinMemData->hHeap ){
35950    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
35951#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35952    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35953#endif
35954    if( pWinMemData->bOwned ){
35955      if( !osHeapDestroy(pWinMemData->hHeap) ){
35956        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
35957                    osGetLastError(), (void*)pWinMemData->hHeap);
35958      }
35959      pWinMemData->bOwned = FALSE;
35960    }
35961    pWinMemData->hHeap = NULL;
35962  }
35963}
35964
35965/*
35966** Populate the low-level memory allocation function pointers in
35967** sqlite3GlobalConfig.m with pointers to the routines in this file. The
35968** arguments specify the block of memory to manage.
35969**
35970** This routine is only called by sqlite3_config(), and therefore
35971** is not required to be threadsafe (it is not).
35972*/
35973SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
35974  static const sqlite3_mem_methods winMemMethods = {
35975    winMemMalloc,
35976    winMemFree,
35977    winMemRealloc,
35978    winMemSize,
35979    winMemRoundup,
35980    winMemInit,
35981    winMemShutdown,
35982    &win_mem_data
35983  };
35984  return &winMemMethods;
35985}
35986
35987SQLITE_PRIVATE void sqlite3MemSetDefault(void){
35988  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
35989}
35990#endif /* SQLITE_WIN32_MALLOC */
35991
35992/*
35993** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
35994**
35995** Space to hold the returned string is obtained from malloc.
35996*/
35997static LPWSTR winUtf8ToUnicode(const char *zFilename){
35998  int nChar;
35999  LPWSTR zWideFilename;
36000
36001  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
36002  if( nChar==0 ){
36003    return 0;
36004  }
36005  zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
36006  if( zWideFilename==0 ){
36007    return 0;
36008  }
36009  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
36010                                nChar);
36011  if( nChar==0 ){
36012    sqlite3_free(zWideFilename);
36013    zWideFilename = 0;
36014  }
36015  return zWideFilename;
36016}
36017
36018/*
36019** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
36020** obtained from sqlite3_malloc().
36021*/
36022static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
36023  int nByte;
36024  char *zFilename;
36025
36026  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
36027  if( nByte == 0 ){
36028    return 0;
36029  }
36030  zFilename = sqlite3MallocZero( nByte );
36031  if( zFilename==0 ){
36032    return 0;
36033  }
36034  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
36035                                0, 0);
36036  if( nByte == 0 ){
36037    sqlite3_free(zFilename);
36038    zFilename = 0;
36039  }
36040  return zFilename;
36041}
36042
36043/*
36044** Convert an ANSI string to Microsoft Unicode, based on the
36045** current codepage settings for file apis.
36046**
36047** Space to hold the returned string is obtained
36048** from sqlite3_malloc.
36049*/
36050static LPWSTR winMbcsToUnicode(const char *zFilename){
36051  int nByte;
36052  LPWSTR zMbcsFilename;
36053  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
36054
36055  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
36056                                0)*sizeof(WCHAR);
36057  if( nByte==0 ){
36058    return 0;
36059  }
36060  zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
36061  if( zMbcsFilename==0 ){
36062    return 0;
36063  }
36064  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
36065                                nByte);
36066  if( nByte==0 ){
36067    sqlite3_free(zMbcsFilename);
36068    zMbcsFilename = 0;
36069  }
36070  return zMbcsFilename;
36071}
36072
36073/*
36074** Convert Microsoft Unicode to multi-byte character string, based on the
36075** user's ANSI codepage.
36076**
36077** Space to hold the returned string is obtained from
36078** sqlite3_malloc().
36079*/
36080static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
36081  int nByte;
36082  char *zFilename;
36083  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
36084
36085  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
36086  if( nByte == 0 ){
36087    return 0;
36088  }
36089  zFilename = sqlite3MallocZero( nByte );
36090  if( zFilename==0 ){
36091    return 0;
36092  }
36093  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
36094                                nByte, 0, 0);
36095  if( nByte == 0 ){
36096    sqlite3_free(zFilename);
36097    zFilename = 0;
36098  }
36099  return zFilename;
36100}
36101
36102/*
36103** Convert multibyte character string to UTF-8.  Space to hold the
36104** returned string is obtained from sqlite3_malloc().
36105*/
36106SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
36107  char *zFilenameUtf8;
36108  LPWSTR zTmpWide;
36109
36110  zTmpWide = winMbcsToUnicode(zFilename);
36111  if( zTmpWide==0 ){
36112    return 0;
36113  }
36114  zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
36115  sqlite3_free(zTmpWide);
36116  return zFilenameUtf8;
36117}
36118
36119/*
36120** Convert UTF-8 to multibyte character string.  Space to hold the
36121** returned string is obtained from sqlite3_malloc().
36122*/
36123SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
36124  char *zFilenameMbcs;
36125  LPWSTR zTmpWide;
36126
36127  zTmpWide = winUtf8ToUnicode(zFilename);
36128  if( zTmpWide==0 ){
36129    return 0;
36130  }
36131  zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
36132  sqlite3_free(zTmpWide);
36133  return zFilenameMbcs;
36134}
36135
36136/*
36137** This function sets the data directory or the temporary directory based on
36138** the provided arguments.  The type argument must be 1 in order to set the
36139** data directory or 2 in order to set the temporary directory.  The zValue
36140** argument is the name of the directory to use.  The return value will be
36141** SQLITE_OK if successful.
36142*/
36143SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
36144  char **ppDirectory = 0;
36145#ifndef SQLITE_OMIT_AUTOINIT
36146  int rc = sqlite3_initialize();
36147  if( rc ) return rc;
36148#endif
36149  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
36150    ppDirectory = &sqlite3_data_directory;
36151  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
36152    ppDirectory = &sqlite3_temp_directory;
36153  }
36154  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
36155          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
36156  );
36157  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
36158  if( ppDirectory ){
36159    char *zValueUtf8 = 0;
36160    if( zValue && zValue[0] ){
36161      zValueUtf8 = winUnicodeToUtf8(zValue);
36162      if ( zValueUtf8==0 ){
36163        return SQLITE_NOMEM;
36164      }
36165    }
36166    sqlite3_free(*ppDirectory);
36167    *ppDirectory = zValueUtf8;
36168    return SQLITE_OK;
36169  }
36170  return SQLITE_ERROR;
36171}
36172
36173/*
36174** The return value of winGetLastErrorMsg
36175** is zero if the error message fits in the buffer, or non-zero
36176** otherwise (if the message was truncated).
36177*/
36178static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
36179  /* FormatMessage returns 0 on failure.  Otherwise it
36180  ** returns the number of TCHARs written to the output
36181  ** buffer, excluding the terminating null char.
36182  */
36183  DWORD dwLen = 0;
36184  char *zOut = 0;
36185
36186  if( osIsNT() ){
36187#if SQLITE_OS_WINRT
36188    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
36189    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
36190                             FORMAT_MESSAGE_IGNORE_INSERTS,
36191                             NULL,
36192                             lastErrno,
36193                             0,
36194                             zTempWide,
36195                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
36196                             0);
36197#else
36198    LPWSTR zTempWide = NULL;
36199    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
36200                             FORMAT_MESSAGE_FROM_SYSTEM |
36201                             FORMAT_MESSAGE_IGNORE_INSERTS,
36202                             NULL,
36203                             lastErrno,
36204                             0,
36205                             (LPWSTR) &zTempWide,
36206                             0,
36207                             0);
36208#endif
36209    if( dwLen > 0 ){
36210      /* allocate a buffer and convert to UTF8 */
36211      sqlite3BeginBenignMalloc();
36212      zOut = winUnicodeToUtf8(zTempWide);
36213      sqlite3EndBenignMalloc();
36214#if !SQLITE_OS_WINRT
36215      /* free the system buffer allocated by FormatMessage */
36216      osLocalFree(zTempWide);
36217#endif
36218    }
36219  }
36220#ifdef SQLITE_WIN32_HAS_ANSI
36221  else{
36222    char *zTemp = NULL;
36223    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
36224                             FORMAT_MESSAGE_FROM_SYSTEM |
36225                             FORMAT_MESSAGE_IGNORE_INSERTS,
36226                             NULL,
36227                             lastErrno,
36228                             0,
36229                             (LPSTR) &zTemp,
36230                             0,
36231                             0);
36232    if( dwLen > 0 ){
36233      /* allocate a buffer and convert to UTF8 */
36234      sqlite3BeginBenignMalloc();
36235      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36236      sqlite3EndBenignMalloc();
36237      /* free the system buffer allocated by FormatMessage */
36238      osLocalFree(zTemp);
36239    }
36240  }
36241#endif
36242  if( 0 == dwLen ){
36243    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
36244  }else{
36245    /* copy a maximum of nBuf chars to output buffer */
36246    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
36247    /* free the UTF8 buffer */
36248    sqlite3_free(zOut);
36249  }
36250  return 0;
36251}
36252
36253/*
36254**
36255** This function - winLogErrorAtLine() - is only ever called via the macro
36256** winLogError().
36257**
36258** This routine is invoked after an error occurs in an OS function.
36259** It logs a message using sqlite3_log() containing the current value of
36260** error code and, if possible, the human-readable equivalent from
36261** FormatMessage.
36262**
36263** The first argument passed to the macro should be the error code that
36264** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
36265** The two subsequent arguments should be the name of the OS function that
36266** failed and the associated file-system path, if any.
36267*/
36268#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
36269static int winLogErrorAtLine(
36270  int errcode,                    /* SQLite error code */
36271  DWORD lastErrno,                /* Win32 last error */
36272  const char *zFunc,              /* Name of OS function that failed */
36273  const char *zPath,              /* File path associated with error */
36274  int iLine                       /* Source line number where error occurred */
36275){
36276  char zMsg[500];                 /* Human readable error text */
36277  int i;                          /* Loop counter */
36278
36279  zMsg[0] = 0;
36280  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
36281  assert( errcode!=SQLITE_OK );
36282  if( zPath==0 ) zPath = "";
36283  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
36284  zMsg[i] = 0;
36285  sqlite3_log(errcode,
36286      "os_win.c:%d: (%lu) %s(%s) - %s",
36287      iLine, lastErrno, zFunc, zPath, zMsg
36288  );
36289
36290  return errcode;
36291}
36292
36293/*
36294** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
36295** will be retried following a locking error - probably caused by
36296** antivirus software.  Also the initial delay before the first retry.
36297** The delay increases linearly with each retry.
36298*/
36299#ifndef SQLITE_WIN32_IOERR_RETRY
36300# define SQLITE_WIN32_IOERR_RETRY 10
36301#endif
36302#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
36303# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
36304#endif
36305static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
36306static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
36307
36308/*
36309** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
36310** error code obtained via GetLastError() is eligible to be retried.  It
36311** must accept the error code DWORD as its only argument and should return
36312** non-zero if the error code is transient in nature and the operation
36313** responsible for generating the original error might succeed upon being
36314** retried.  The argument to this macro should be a variable.
36315**
36316** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
36317** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
36318** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
36319** may be used to include additional error codes in the set that should
36320** result in the failing I/O operation being retried by the caller.  If
36321** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
36322** identical to those of the "winIoerrCanRetry1" macro.
36323*/
36324#if !defined(winIoerrCanRetry1)
36325#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
36326                              ((a)==ERROR_SHARING_VIOLATION)    || \
36327                              ((a)==ERROR_LOCK_VIOLATION)       || \
36328                              ((a)==ERROR_DEV_NOT_EXIST)        || \
36329                              ((a)==ERROR_NETNAME_DELETED)      || \
36330                              ((a)==ERROR_SEM_TIMEOUT)          || \
36331                              ((a)==ERROR_NETWORK_UNREACHABLE))
36332#endif
36333
36334/*
36335** If a ReadFile() or WriteFile() error occurs, invoke this routine
36336** to see if it should be retried.  Return TRUE to retry.  Return FALSE
36337** to give up with an error.
36338*/
36339static int winRetryIoerr(int *pnRetry, DWORD *pError){
36340  DWORD e = osGetLastError();
36341  if( *pnRetry>=winIoerrRetry ){
36342    if( pError ){
36343      *pError = e;
36344    }
36345    return 0;
36346  }
36347  if( winIoerrCanRetry1(e) ){
36348    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
36349    ++*pnRetry;
36350    return 1;
36351  }
36352#if defined(winIoerrCanRetry2)
36353  else if( winIoerrCanRetry2(e) ){
36354    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
36355    ++*pnRetry;
36356    return 1;
36357  }
36358#endif
36359  if( pError ){
36360    *pError = e;
36361  }
36362  return 0;
36363}
36364
36365/*
36366** Log a I/O error retry episode.
36367*/
36368static void winLogIoerr(int nRetry, int lineno){
36369  if( nRetry ){
36370    sqlite3_log(SQLITE_NOTICE,
36371      "delayed %dms for lock/sharing conflict at line %d",
36372      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
36373    );
36374  }
36375}
36376
36377#if SQLITE_OS_WINCE
36378/*************************************************************************
36379** This section contains code for WinCE only.
36380*/
36381#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
36382/*
36383** The MSVC CRT on Windows CE may not have a localtime() function.  So
36384** create a substitute.
36385*/
36386/* #include <time.h> */
36387struct tm *__cdecl localtime(const time_t *t)
36388{
36389  static struct tm y;
36390  FILETIME uTm, lTm;
36391  SYSTEMTIME pTm;
36392  sqlite3_int64 t64;
36393  t64 = *t;
36394  t64 = (t64 + 11644473600)*10000000;
36395  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
36396  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
36397  osFileTimeToLocalFileTime(&uTm,&lTm);
36398  osFileTimeToSystemTime(&lTm,&pTm);
36399  y.tm_year = pTm.wYear - 1900;
36400  y.tm_mon = pTm.wMonth - 1;
36401  y.tm_wday = pTm.wDayOfWeek;
36402  y.tm_mday = pTm.wDay;
36403  y.tm_hour = pTm.wHour;
36404  y.tm_min = pTm.wMinute;
36405  y.tm_sec = pTm.wSecond;
36406  return &y;
36407}
36408#endif
36409
36410#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
36411
36412/*
36413** Acquire a lock on the handle h
36414*/
36415static void winceMutexAcquire(HANDLE h){
36416   DWORD dwErr;
36417   do {
36418     dwErr = osWaitForSingleObject(h, INFINITE);
36419   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
36420}
36421/*
36422** Release a lock acquired by winceMutexAcquire()
36423*/
36424#define winceMutexRelease(h) ReleaseMutex(h)
36425
36426/*
36427** Create the mutex and shared memory used for locking in the file
36428** descriptor pFile
36429*/
36430static int winceCreateLock(const char *zFilename, winFile *pFile){
36431  LPWSTR zTok;
36432  LPWSTR zName;
36433  DWORD lastErrno;
36434  BOOL bLogged = FALSE;
36435  BOOL bInit = TRUE;
36436
36437  zName = winUtf8ToUnicode(zFilename);
36438  if( zName==0 ){
36439    /* out of memory */
36440    return SQLITE_IOERR_NOMEM;
36441  }
36442
36443  /* Initialize the local lockdata */
36444  memset(&pFile->local, 0, sizeof(pFile->local));
36445
36446  /* Replace the backslashes from the filename and lowercase it
36447  ** to derive a mutex name. */
36448  zTok = osCharLowerW(zName);
36449  for (;*zTok;zTok++){
36450    if (*zTok == '\\') *zTok = '_';
36451  }
36452
36453  /* Create/open the named mutex */
36454  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
36455  if (!pFile->hMutex){
36456    pFile->lastErrno = osGetLastError();
36457    sqlite3_free(zName);
36458    return winLogError(SQLITE_IOERR, pFile->lastErrno,
36459                       "winceCreateLock1", zFilename);
36460  }
36461
36462  /* Acquire the mutex before continuing */
36463  winceMutexAcquire(pFile->hMutex);
36464
36465  /* Since the names of named mutexes, semaphores, file mappings etc are
36466  ** case-sensitive, take advantage of that by uppercasing the mutex name
36467  ** and using that as the shared filemapping name.
36468  */
36469  osCharUpperW(zName);
36470  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
36471                                        PAGE_READWRITE, 0, sizeof(winceLock),
36472                                        zName);
36473
36474  /* Set a flag that indicates we're the first to create the memory so it
36475  ** must be zero-initialized */
36476  lastErrno = osGetLastError();
36477  if (lastErrno == ERROR_ALREADY_EXISTS){
36478    bInit = FALSE;
36479  }
36480
36481  sqlite3_free(zName);
36482
36483  /* If we succeeded in making the shared memory handle, map it. */
36484  if( pFile->hShared ){
36485    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
36486             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
36487    /* If mapping failed, close the shared memory handle and erase it */
36488    if( !pFile->shared ){
36489      pFile->lastErrno = osGetLastError();
36490      winLogError(SQLITE_IOERR, pFile->lastErrno,
36491                  "winceCreateLock2", zFilename);
36492      bLogged = TRUE;
36493      osCloseHandle(pFile->hShared);
36494      pFile->hShared = NULL;
36495    }
36496  }
36497
36498  /* If shared memory could not be created, then close the mutex and fail */
36499  if( pFile->hShared==NULL ){
36500    if( !bLogged ){
36501      pFile->lastErrno = lastErrno;
36502      winLogError(SQLITE_IOERR, pFile->lastErrno,
36503                  "winceCreateLock3", zFilename);
36504      bLogged = TRUE;
36505    }
36506    winceMutexRelease(pFile->hMutex);
36507    osCloseHandle(pFile->hMutex);
36508    pFile->hMutex = NULL;
36509    return SQLITE_IOERR;
36510  }
36511
36512  /* Initialize the shared memory if we're supposed to */
36513  if( bInit ){
36514    memset(pFile->shared, 0, sizeof(winceLock));
36515  }
36516
36517  winceMutexRelease(pFile->hMutex);
36518  return SQLITE_OK;
36519}
36520
36521/*
36522** Destroy the part of winFile that deals with wince locks
36523*/
36524static void winceDestroyLock(winFile *pFile){
36525  if (pFile->hMutex){
36526    /* Acquire the mutex */
36527    winceMutexAcquire(pFile->hMutex);
36528
36529    /* The following blocks should probably assert in debug mode, but they
36530       are to cleanup in case any locks remained open */
36531    if (pFile->local.nReaders){
36532      pFile->shared->nReaders --;
36533    }
36534    if (pFile->local.bReserved){
36535      pFile->shared->bReserved = FALSE;
36536    }
36537    if (pFile->local.bPending){
36538      pFile->shared->bPending = FALSE;
36539    }
36540    if (pFile->local.bExclusive){
36541      pFile->shared->bExclusive = FALSE;
36542    }
36543
36544    /* De-reference and close our copy of the shared memory handle */
36545    osUnmapViewOfFile(pFile->shared);
36546    osCloseHandle(pFile->hShared);
36547
36548    /* Done with the mutex */
36549    winceMutexRelease(pFile->hMutex);
36550    osCloseHandle(pFile->hMutex);
36551    pFile->hMutex = NULL;
36552  }
36553}
36554
36555/*
36556** An implementation of the LockFile() API of Windows for CE
36557*/
36558static BOOL winceLockFile(
36559  LPHANDLE phFile,
36560  DWORD dwFileOffsetLow,
36561  DWORD dwFileOffsetHigh,
36562  DWORD nNumberOfBytesToLockLow,
36563  DWORD nNumberOfBytesToLockHigh
36564){
36565  winFile *pFile = HANDLE_TO_WINFILE(phFile);
36566  BOOL bReturn = FALSE;
36567
36568  UNUSED_PARAMETER(dwFileOffsetHigh);
36569  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
36570
36571  if (!pFile->hMutex) return TRUE;
36572  winceMutexAcquire(pFile->hMutex);
36573
36574  /* Wanting an exclusive lock? */
36575  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
36576       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
36577    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
36578       pFile->shared->bExclusive = TRUE;
36579       pFile->local.bExclusive = TRUE;
36580       bReturn = TRUE;
36581    }
36582  }
36583
36584  /* Want a read-only lock? */
36585  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
36586           nNumberOfBytesToLockLow == 1){
36587    if (pFile->shared->bExclusive == 0){
36588      pFile->local.nReaders ++;
36589      if (pFile->local.nReaders == 1){
36590        pFile->shared->nReaders ++;
36591      }
36592      bReturn = TRUE;
36593    }
36594  }
36595
36596  /* Want a pending lock? */
36597  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
36598           && nNumberOfBytesToLockLow == 1){
36599    /* If no pending lock has been acquired, then acquire it */
36600    if (pFile->shared->bPending == 0) {
36601      pFile->shared->bPending = TRUE;
36602      pFile->local.bPending = TRUE;
36603      bReturn = TRUE;
36604    }
36605  }
36606
36607  /* Want a reserved lock? */
36608  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
36609           && nNumberOfBytesToLockLow == 1){
36610    if (pFile->shared->bReserved == 0) {
36611      pFile->shared->bReserved = TRUE;
36612      pFile->local.bReserved = TRUE;
36613      bReturn = TRUE;
36614    }
36615  }
36616
36617  winceMutexRelease(pFile->hMutex);
36618  return bReturn;
36619}
36620
36621/*
36622** An implementation of the UnlockFile API of Windows for CE
36623*/
36624static BOOL winceUnlockFile(
36625  LPHANDLE phFile,
36626  DWORD dwFileOffsetLow,
36627  DWORD dwFileOffsetHigh,
36628  DWORD nNumberOfBytesToUnlockLow,
36629  DWORD nNumberOfBytesToUnlockHigh
36630){
36631  winFile *pFile = HANDLE_TO_WINFILE(phFile);
36632  BOOL bReturn = FALSE;
36633
36634  UNUSED_PARAMETER(dwFileOffsetHigh);
36635  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
36636
36637  if (!pFile->hMutex) return TRUE;
36638  winceMutexAcquire(pFile->hMutex);
36639
36640  /* Releasing a reader lock or an exclusive lock */
36641  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
36642    /* Did we have an exclusive lock? */
36643    if (pFile->local.bExclusive){
36644      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
36645      pFile->local.bExclusive = FALSE;
36646      pFile->shared->bExclusive = FALSE;
36647      bReturn = TRUE;
36648    }
36649
36650    /* Did we just have a reader lock? */
36651    else if (pFile->local.nReaders){
36652      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
36653             || nNumberOfBytesToUnlockLow == 1);
36654      pFile->local.nReaders --;
36655      if (pFile->local.nReaders == 0)
36656      {
36657        pFile->shared->nReaders --;
36658      }
36659      bReturn = TRUE;
36660    }
36661  }
36662
36663  /* Releasing a pending lock */
36664  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
36665           && nNumberOfBytesToUnlockLow == 1){
36666    if (pFile->local.bPending){
36667      pFile->local.bPending = FALSE;
36668      pFile->shared->bPending = FALSE;
36669      bReturn = TRUE;
36670    }
36671  }
36672  /* Releasing a reserved lock */
36673  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
36674           && nNumberOfBytesToUnlockLow == 1){
36675    if (pFile->local.bReserved) {
36676      pFile->local.bReserved = FALSE;
36677      pFile->shared->bReserved = FALSE;
36678      bReturn = TRUE;
36679    }
36680  }
36681
36682  winceMutexRelease(pFile->hMutex);
36683  return bReturn;
36684}
36685/*
36686** End of the special code for wince
36687*****************************************************************************/
36688#endif /* SQLITE_OS_WINCE */
36689
36690/*
36691** Lock a file region.
36692*/
36693static BOOL winLockFile(
36694  LPHANDLE phFile,
36695  DWORD flags,
36696  DWORD offsetLow,
36697  DWORD offsetHigh,
36698  DWORD numBytesLow,
36699  DWORD numBytesHigh
36700){
36701#if SQLITE_OS_WINCE
36702  /*
36703  ** NOTE: Windows CE is handled differently here due its lack of the Win32
36704  **       API LockFile.
36705  */
36706  return winceLockFile(phFile, offsetLow, offsetHigh,
36707                       numBytesLow, numBytesHigh);
36708#else
36709  if( osIsNT() ){
36710    OVERLAPPED ovlp;
36711    memset(&ovlp, 0, sizeof(OVERLAPPED));
36712    ovlp.Offset = offsetLow;
36713    ovlp.OffsetHigh = offsetHigh;
36714    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
36715  }else{
36716    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
36717                      numBytesHigh);
36718  }
36719#endif
36720}
36721
36722/*
36723** Unlock a file region.
36724 */
36725static BOOL winUnlockFile(
36726  LPHANDLE phFile,
36727  DWORD offsetLow,
36728  DWORD offsetHigh,
36729  DWORD numBytesLow,
36730  DWORD numBytesHigh
36731){
36732#if SQLITE_OS_WINCE
36733  /*
36734  ** NOTE: Windows CE is handled differently here due its lack of the Win32
36735  **       API UnlockFile.
36736  */
36737  return winceUnlockFile(phFile, offsetLow, offsetHigh,
36738                         numBytesLow, numBytesHigh);
36739#else
36740  if( osIsNT() ){
36741    OVERLAPPED ovlp;
36742    memset(&ovlp, 0, sizeof(OVERLAPPED));
36743    ovlp.Offset = offsetLow;
36744    ovlp.OffsetHigh = offsetHigh;
36745    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
36746  }else{
36747    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
36748                        numBytesHigh);
36749  }
36750#endif
36751}
36752
36753/*****************************************************************************
36754** The next group of routines implement the I/O methods specified
36755** by the sqlite3_io_methods object.
36756******************************************************************************/
36757
36758/*
36759** Some Microsoft compilers lack this definition.
36760*/
36761#ifndef INVALID_SET_FILE_POINTER
36762# define INVALID_SET_FILE_POINTER ((DWORD)-1)
36763#endif
36764
36765/*
36766** Move the current position of the file handle passed as the first
36767** argument to offset iOffset within the file. If successful, return 0.
36768** Otherwise, set pFile->lastErrno and return non-zero.
36769*/
36770static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
36771#if !SQLITE_OS_WINRT
36772  LONG upperBits;                 /* Most sig. 32 bits of new offset */
36773  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
36774  DWORD dwRet;                    /* Value returned by SetFilePointer() */
36775  DWORD lastErrno;                /* Value returned by GetLastError() */
36776
36777  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
36778
36779  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
36780  lowerBits = (LONG)(iOffset & 0xffffffff);
36781
36782  /* API oddity: If successful, SetFilePointer() returns a dword
36783  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
36784  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
36785  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
36786  ** whether an error has actually occurred, it is also necessary to call
36787  ** GetLastError().
36788  */
36789  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
36790
36791  if( (dwRet==INVALID_SET_FILE_POINTER
36792      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
36793    pFile->lastErrno = lastErrno;
36794    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
36795                "winSeekFile", pFile->zPath);
36796    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
36797    return 1;
36798  }
36799
36800  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
36801  return 0;
36802#else
36803  /*
36804  ** Same as above, except that this implementation works for WinRT.
36805  */
36806
36807  LARGE_INTEGER x;                /* The new offset */
36808  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
36809
36810  x.QuadPart = iOffset;
36811  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
36812
36813  if(!bRet){
36814    pFile->lastErrno = osGetLastError();
36815    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
36816                "winSeekFile", pFile->zPath);
36817    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
36818    return 1;
36819  }
36820
36821  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
36822  return 0;
36823#endif
36824}
36825
36826#if SQLITE_MAX_MMAP_SIZE>0
36827/* Forward references to VFS helper methods used for memory mapped files */
36828static int winMapfile(winFile*, sqlite3_int64);
36829static int winUnmapfile(winFile*);
36830#endif
36831
36832/*
36833** Close a file.
36834**
36835** It is reported that an attempt to close a handle might sometimes
36836** fail.  This is a very unreasonable result, but Windows is notorious
36837** for being unreasonable so I do not doubt that it might happen.  If
36838** the close fails, we pause for 100 milliseconds and try again.  As
36839** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
36840** giving up and returning an error.
36841*/
36842#define MX_CLOSE_ATTEMPT 3
36843static int winClose(sqlite3_file *id){
36844  int rc, cnt = 0;
36845  winFile *pFile = (winFile*)id;
36846
36847  assert( id!=0 );
36848#ifndef SQLITE_OMIT_WAL
36849  assert( pFile->pShm==0 );
36850#endif
36851  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
36852  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
36853           osGetCurrentProcessId(), pFile, pFile->h));
36854
36855#if SQLITE_MAX_MMAP_SIZE>0
36856  winUnmapfile(pFile);
36857#endif
36858
36859  do{
36860    rc = osCloseHandle(pFile->h);
36861    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
36862  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
36863#if SQLITE_OS_WINCE
36864#define WINCE_DELETION_ATTEMPTS 3
36865  winceDestroyLock(pFile);
36866  if( pFile->zDeleteOnClose ){
36867    int cnt = 0;
36868    while(
36869           osDeleteFileW(pFile->zDeleteOnClose)==0
36870        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
36871        && cnt++ < WINCE_DELETION_ATTEMPTS
36872    ){
36873       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
36874    }
36875    sqlite3_free(pFile->zDeleteOnClose);
36876  }
36877#endif
36878  if( rc ){
36879    pFile->h = NULL;
36880  }
36881  OpenCounter(-1);
36882  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
36883           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
36884  return rc ? SQLITE_OK
36885            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
36886                          "winClose", pFile->zPath);
36887}
36888
36889/*
36890** Read data from a file into a buffer.  Return SQLITE_OK if all
36891** bytes were read successfully and SQLITE_IOERR if anything goes
36892** wrong.
36893*/
36894static int winRead(
36895  sqlite3_file *id,          /* File to read from */
36896  void *pBuf,                /* Write content into this buffer */
36897  int amt,                   /* Number of bytes to read */
36898  sqlite3_int64 offset       /* Begin reading at this offset */
36899){
36900#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
36901  OVERLAPPED overlapped;          /* The offset for ReadFile. */
36902#endif
36903  winFile *pFile = (winFile*)id;  /* file handle */
36904  DWORD nRead;                    /* Number of bytes actually read from file */
36905  int nRetry = 0;                 /* Number of retrys */
36906
36907  assert( id!=0 );
36908  assert( amt>0 );
36909  assert( offset>=0 );
36910  SimulateIOError(return SQLITE_IOERR_READ);
36911  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
36912           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
36913           pFile->h, pBuf, amt, offset, pFile->locktype));
36914
36915#if SQLITE_MAX_MMAP_SIZE>0
36916  /* Deal with as much of this read request as possible by transfering
36917  ** data from the memory mapping using memcpy().  */
36918  if( offset<pFile->mmapSize ){
36919    if( offset+amt <= pFile->mmapSize ){
36920      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
36921      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36922               osGetCurrentProcessId(), pFile, pFile->h));
36923      return SQLITE_OK;
36924    }else{
36925      int nCopy = (int)(pFile->mmapSize - offset);
36926      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
36927      pBuf = &((u8 *)pBuf)[nCopy];
36928      amt -= nCopy;
36929      offset += nCopy;
36930    }
36931  }
36932#endif
36933
36934#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
36935  if( winSeekFile(pFile, offset) ){
36936    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
36937             osGetCurrentProcessId(), pFile, pFile->h));
36938    return SQLITE_FULL;
36939  }
36940  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
36941#else
36942  memset(&overlapped, 0, sizeof(OVERLAPPED));
36943  overlapped.Offset = (LONG)(offset & 0xffffffff);
36944  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
36945  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
36946         osGetLastError()!=ERROR_HANDLE_EOF ){
36947#endif
36948    DWORD lastErrno;
36949    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
36950    pFile->lastErrno = lastErrno;
36951    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
36952             osGetCurrentProcessId(), pFile, pFile->h));
36953    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
36954                       "winRead", pFile->zPath);
36955  }
36956  winLogIoerr(nRetry, __LINE__);
36957  if( nRead<(DWORD)amt ){
36958    /* Unread parts of the buffer must be zero-filled */
36959    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
36960    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
36961             osGetCurrentProcessId(), pFile, pFile->h));
36962    return SQLITE_IOERR_SHORT_READ;
36963  }
36964
36965  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36966           osGetCurrentProcessId(), pFile, pFile->h));
36967  return SQLITE_OK;
36968}
36969
36970/*
36971** Write data from a buffer into a file.  Return SQLITE_OK on success
36972** or some other error code on failure.
36973*/
36974static int winWrite(
36975  sqlite3_file *id,               /* File to write into */
36976  const void *pBuf,               /* The bytes to be written */
36977  int amt,                        /* Number of bytes to write */
36978  sqlite3_int64 offset            /* Offset into the file to begin writing at */
36979){
36980  int rc = 0;                     /* True if error has occurred, else false */
36981  winFile *pFile = (winFile*)id;  /* File handle */
36982  int nRetry = 0;                 /* Number of retries */
36983
36984  assert( amt>0 );
36985  assert( pFile );
36986  SimulateIOError(return SQLITE_IOERR_WRITE);
36987  SimulateDiskfullError(return SQLITE_FULL);
36988
36989  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
36990           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
36991           pFile->h, pBuf, amt, offset, pFile->locktype));
36992
36993#if SQLITE_MAX_MMAP_SIZE>0
36994  /* Deal with as much of this write request as possible by transfering
36995  ** data from the memory mapping using memcpy().  */
36996  if( offset<pFile->mmapSize ){
36997    if( offset+amt <= pFile->mmapSize ){
36998      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
36999      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37000               osGetCurrentProcessId(), pFile, pFile->h));
37001      return SQLITE_OK;
37002    }else{
37003      int nCopy = (int)(pFile->mmapSize - offset);
37004      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
37005      pBuf = &((u8 *)pBuf)[nCopy];
37006      amt -= nCopy;
37007      offset += nCopy;
37008    }
37009  }
37010#endif
37011
37012#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
37013  rc = winSeekFile(pFile, offset);
37014  if( rc==0 ){
37015#else
37016  {
37017#endif
37018#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37019    OVERLAPPED overlapped;        /* The offset for WriteFile. */
37020#endif
37021    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
37022    int nRem = amt;               /* Number of bytes yet to be written */
37023    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
37024    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
37025
37026#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37027    memset(&overlapped, 0, sizeof(OVERLAPPED));
37028    overlapped.Offset = (LONG)(offset & 0xffffffff);
37029    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
37030#endif
37031
37032    while( nRem>0 ){
37033#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
37034      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
37035#else
37036      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
37037#endif
37038        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
37039        break;
37040      }
37041      assert( nWrite==0 || nWrite<=(DWORD)nRem );
37042      if( nWrite==0 || nWrite>(DWORD)nRem ){
37043        lastErrno = osGetLastError();
37044        break;
37045      }
37046#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37047      offset += nWrite;
37048      overlapped.Offset = (LONG)(offset & 0xffffffff);
37049      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
37050#endif
37051      aRem += nWrite;
37052      nRem -= nWrite;
37053    }
37054    if( nRem>0 ){
37055      pFile->lastErrno = lastErrno;
37056      rc = 1;
37057    }
37058  }
37059
37060  if( rc ){
37061    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
37062       || ( pFile->lastErrno==ERROR_DISK_FULL )){
37063      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
37064               osGetCurrentProcessId(), pFile, pFile->h));
37065      return winLogError(SQLITE_FULL, pFile->lastErrno,
37066                         "winWrite1", pFile->zPath);
37067    }
37068    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
37069             osGetCurrentProcessId(), pFile, pFile->h));
37070    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
37071                       "winWrite2", pFile->zPath);
37072  }else{
37073    winLogIoerr(nRetry, __LINE__);
37074  }
37075  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37076           osGetCurrentProcessId(), pFile, pFile->h));
37077  return SQLITE_OK;
37078}
37079
37080/*
37081** Truncate an open file to a specified size
37082*/
37083static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
37084  winFile *pFile = (winFile*)id;  /* File handle object */
37085  int rc = SQLITE_OK;             /* Return code for this function */
37086  DWORD lastErrno;
37087
37088  assert( pFile );
37089  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
37090  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
37091           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
37092
37093  /* If the user has configured a chunk-size for this file, truncate the
37094  ** file so that it consists of an integer number of chunks (i.e. the
37095  ** actual file size after the operation may be larger than the requested
37096  ** size).
37097  */
37098  if( pFile->szChunk>0 ){
37099    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
37100  }
37101
37102  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
37103  if( winSeekFile(pFile, nByte) ){
37104    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
37105                     "winTruncate1", pFile->zPath);
37106  }else if( 0==osSetEndOfFile(pFile->h) &&
37107            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
37108    pFile->lastErrno = lastErrno;
37109    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
37110                     "winTruncate2", pFile->zPath);
37111  }
37112
37113#if SQLITE_MAX_MMAP_SIZE>0
37114  /* If the file was truncated to a size smaller than the currently
37115  ** mapped region, reduce the effective mapping size as well. SQLite will
37116  ** use read() and write() to access data beyond this point from now on.
37117  */
37118  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
37119    pFile->mmapSize = nByte;
37120  }
37121#endif
37122
37123  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
37124           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
37125  return rc;
37126}
37127
37128#ifdef SQLITE_TEST
37129/*
37130** Count the number of fullsyncs and normal syncs.  This is used to test
37131** that syncs and fullsyncs are occuring at the right times.
37132*/
37133SQLITE_API int sqlite3_sync_count = 0;
37134SQLITE_API int sqlite3_fullsync_count = 0;
37135#endif
37136
37137/*
37138** Make sure all writes to a particular file are committed to disk.
37139*/
37140static int winSync(sqlite3_file *id, int flags){
37141#ifndef SQLITE_NO_SYNC
37142  /*
37143  ** Used only when SQLITE_NO_SYNC is not defined.
37144   */
37145  BOOL rc;
37146#endif
37147#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
37148    defined(SQLITE_HAVE_OS_TRACE)
37149  /*
37150  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
37151  ** OSTRACE() macros.
37152   */
37153  winFile *pFile = (winFile*)id;
37154#else
37155  UNUSED_PARAMETER(id);
37156#endif
37157
37158  assert( pFile );
37159  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
37160  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
37161      || (flags&0x0F)==SQLITE_SYNC_FULL
37162  );
37163
37164  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
37165  ** line is to test that doing so does not cause any problems.
37166  */
37167  SimulateDiskfullError( return SQLITE_FULL );
37168
37169  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
37170           osGetCurrentProcessId(), pFile, pFile->h, flags,
37171           pFile->locktype));
37172
37173#ifndef SQLITE_TEST
37174  UNUSED_PARAMETER(flags);
37175#else
37176  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
37177    sqlite3_fullsync_count++;
37178  }
37179  sqlite3_sync_count++;
37180#endif
37181
37182  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
37183  ** no-op
37184  */
37185#ifdef SQLITE_NO_SYNC
37186  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37187           osGetCurrentProcessId(), pFile, pFile->h));
37188  return SQLITE_OK;
37189#else
37190#if SQLITE_MAX_MMAP_SIZE>0
37191  if( pFile->pMapRegion ){
37192    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
37193      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
37194               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
37195               pFile, pFile->pMapRegion));
37196    }else{
37197      pFile->lastErrno = osGetLastError();
37198      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
37199               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
37200               pFile, pFile->pMapRegion));
37201      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37202                         "winSync1", pFile->zPath);
37203    }
37204  }
37205#endif
37206  rc = osFlushFileBuffers(pFile->h);
37207  SimulateIOError( rc=FALSE );
37208  if( rc ){
37209    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37210             osGetCurrentProcessId(), pFile, pFile->h));
37211    return SQLITE_OK;
37212  }else{
37213    pFile->lastErrno = osGetLastError();
37214    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
37215             osGetCurrentProcessId(), pFile, pFile->h));
37216    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
37217                       "winSync2", pFile->zPath);
37218  }
37219#endif
37220}
37221
37222/*
37223** Determine the current size of a file in bytes
37224*/
37225static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
37226  winFile *pFile = (winFile*)id;
37227  int rc = SQLITE_OK;
37228
37229  assert( id!=0 );
37230  assert( pSize!=0 );
37231  SimulateIOError(return SQLITE_IOERR_FSTAT);
37232  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
37233
37234#if SQLITE_OS_WINRT
37235  {
37236    FILE_STANDARD_INFO info;
37237    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
37238                                     &info, sizeof(info)) ){
37239      *pSize = info.EndOfFile.QuadPart;
37240    }else{
37241      pFile->lastErrno = osGetLastError();
37242      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
37243                       "winFileSize", pFile->zPath);
37244    }
37245  }
37246#else
37247  {
37248    DWORD upperBits;
37249    DWORD lowerBits;
37250    DWORD lastErrno;
37251
37252    lowerBits = osGetFileSize(pFile->h, &upperBits);
37253    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
37254    if(   (lowerBits == INVALID_FILE_SIZE)
37255       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
37256      pFile->lastErrno = lastErrno;
37257      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
37258                       "winFileSize", pFile->zPath);
37259    }
37260  }
37261#endif
37262  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
37263           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
37264  return rc;
37265}
37266
37267/*
37268** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
37269*/
37270#ifndef LOCKFILE_FAIL_IMMEDIATELY
37271# define LOCKFILE_FAIL_IMMEDIATELY 1
37272#endif
37273
37274#ifndef LOCKFILE_EXCLUSIVE_LOCK
37275# define LOCKFILE_EXCLUSIVE_LOCK 2
37276#endif
37277
37278/*
37279** Historically, SQLite has used both the LockFile and LockFileEx functions.
37280** When the LockFile function was used, it was always expected to fail
37281** immediately if the lock could not be obtained.  Also, it always expected to
37282** obtain an exclusive lock.  These flags are used with the LockFileEx function
37283** and reflect those expectations; therefore, they should not be changed.
37284*/
37285#ifndef SQLITE_LOCKFILE_FLAGS
37286# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
37287                                  LOCKFILE_EXCLUSIVE_LOCK)
37288#endif
37289
37290/*
37291** Currently, SQLite never calls the LockFileEx function without wanting the
37292** call to fail immediately if the lock cannot be obtained.
37293*/
37294#ifndef SQLITE_LOCKFILEEX_FLAGS
37295# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
37296#endif
37297
37298/*
37299** Acquire a reader lock.
37300** Different API routines are called depending on whether or not this
37301** is Win9x or WinNT.
37302*/
37303static int winGetReadLock(winFile *pFile){
37304  int res;
37305  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
37306  if( osIsNT() ){
37307#if SQLITE_OS_WINCE
37308    /*
37309    ** NOTE: Windows CE is handled differently here due its lack of the Win32
37310    **       API LockFileEx.
37311    */
37312    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
37313#else
37314    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
37315                      SHARED_SIZE, 0);
37316#endif
37317  }
37318#ifdef SQLITE_WIN32_HAS_ANSI
37319  else{
37320    int lk;
37321    sqlite3_randomness(sizeof(lk), &lk);
37322    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
37323    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
37324                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
37325  }
37326#endif
37327  if( res == 0 ){
37328    pFile->lastErrno = osGetLastError();
37329    /* No need to log a failure to lock */
37330  }
37331  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
37332  return res;
37333}
37334
37335/*
37336** Undo a readlock
37337*/
37338static int winUnlockReadLock(winFile *pFile){
37339  int res;
37340  DWORD lastErrno;
37341  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
37342  if( osIsNT() ){
37343    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
37344  }
37345#ifdef SQLITE_WIN32_HAS_ANSI
37346  else{
37347    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
37348  }
37349#endif
37350  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
37351    pFile->lastErrno = lastErrno;
37352    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
37353                "winUnlockReadLock", pFile->zPath);
37354  }
37355  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
37356  return res;
37357}
37358
37359/*
37360** Lock the file with the lock specified by parameter locktype - one
37361** of the following:
37362**
37363**     (1) SHARED_LOCK
37364**     (2) RESERVED_LOCK
37365**     (3) PENDING_LOCK
37366**     (4) EXCLUSIVE_LOCK
37367**
37368** Sometimes when requesting one lock state, additional lock states
37369** are inserted in between.  The locking might fail on one of the later
37370** transitions leaving the lock state different from what it started but
37371** still short of its goal.  The following chart shows the allowed
37372** transitions and the inserted intermediate states:
37373**
37374**    UNLOCKED -> SHARED
37375**    SHARED -> RESERVED
37376**    SHARED -> (PENDING) -> EXCLUSIVE
37377**    RESERVED -> (PENDING) -> EXCLUSIVE
37378**    PENDING -> EXCLUSIVE
37379**
37380** This routine will only increase a lock.  The winUnlock() routine
37381** erases all locks at once and returns us immediately to locking level 0.
37382** It is not possible to lower the locking level one step at a time.  You
37383** must go straight to locking level 0.
37384*/
37385static int winLock(sqlite3_file *id, int locktype){
37386  int rc = SQLITE_OK;    /* Return code from subroutines */
37387  int res = 1;           /* Result of a Windows lock call */
37388  int newLocktype;       /* Set pFile->locktype to this value before exiting */
37389  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
37390  winFile *pFile = (winFile*)id;
37391  DWORD lastErrno = NO_ERROR;
37392
37393  assert( id!=0 );
37394  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
37395           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
37396
37397  /* If there is already a lock of this type or more restrictive on the
37398  ** OsFile, do nothing. Don't use the end_lock: exit path, as
37399  ** sqlite3OsEnterMutex() hasn't been called yet.
37400  */
37401  if( pFile->locktype>=locktype ){
37402    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
37403    return SQLITE_OK;
37404  }
37405
37406  /* Do not allow any kind of write-lock on a read-only database
37407  */
37408  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
37409    return SQLITE_IOERR_LOCK;
37410  }
37411
37412  /* Make sure the locking sequence is correct
37413  */
37414  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
37415  assert( locktype!=PENDING_LOCK );
37416  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
37417
37418  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
37419  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
37420  ** the PENDING_LOCK byte is temporary.
37421  */
37422  newLocktype = pFile->locktype;
37423  if(   (pFile->locktype==NO_LOCK)
37424     || (   (locktype==EXCLUSIVE_LOCK)
37425         && (pFile->locktype==RESERVED_LOCK))
37426  ){
37427    int cnt = 3;
37428    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
37429                                         PENDING_BYTE, 0, 1, 0))==0 ){
37430      /* Try 3 times to get the pending lock.  This is needed to work
37431      ** around problems caused by indexing and/or anti-virus software on
37432      ** Windows systems.
37433      ** If you are using this code as a model for alternative VFSes, do not
37434      ** copy this retry logic.  It is a hack intended for Windows only.
37435      */
37436      lastErrno = osGetLastError();
37437      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
37438               pFile->h, cnt, res));
37439      if( lastErrno==ERROR_INVALID_HANDLE ){
37440        pFile->lastErrno = lastErrno;
37441        rc = SQLITE_IOERR_LOCK;
37442        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
37443                 pFile->h, cnt, sqlite3ErrName(rc)));
37444        return rc;
37445      }
37446      if( cnt ) sqlite3_win32_sleep(1);
37447    }
37448    gotPendingLock = res;
37449    if( !res ){
37450      lastErrno = osGetLastError();
37451    }
37452  }
37453
37454  /* Acquire a shared lock
37455  */
37456  if( locktype==SHARED_LOCK && res ){
37457    assert( pFile->locktype==NO_LOCK );
37458    res = winGetReadLock(pFile);
37459    if( res ){
37460      newLocktype = SHARED_LOCK;
37461    }else{
37462      lastErrno = osGetLastError();
37463    }
37464  }
37465
37466  /* Acquire a RESERVED lock
37467  */
37468  if( locktype==RESERVED_LOCK && res ){
37469    assert( pFile->locktype==SHARED_LOCK );
37470    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
37471    if( res ){
37472      newLocktype = RESERVED_LOCK;
37473    }else{
37474      lastErrno = osGetLastError();
37475    }
37476  }
37477
37478  /* Acquire a PENDING lock
37479  */
37480  if( locktype==EXCLUSIVE_LOCK && res ){
37481    newLocktype = PENDING_LOCK;
37482    gotPendingLock = 0;
37483  }
37484
37485  /* Acquire an EXCLUSIVE lock
37486  */
37487  if( locktype==EXCLUSIVE_LOCK && res ){
37488    assert( pFile->locktype>=SHARED_LOCK );
37489    res = winUnlockReadLock(pFile);
37490    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
37491                      SHARED_SIZE, 0);
37492    if( res ){
37493      newLocktype = EXCLUSIVE_LOCK;
37494    }else{
37495      lastErrno = osGetLastError();
37496      winGetReadLock(pFile);
37497    }
37498  }
37499
37500  /* If we are holding a PENDING lock that ought to be released, then
37501  ** release it now.
37502  */
37503  if( gotPendingLock && locktype==SHARED_LOCK ){
37504    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
37505  }
37506
37507  /* Update the state of the lock has held in the file descriptor then
37508  ** return the appropriate result code.
37509  */
37510  if( res ){
37511    rc = SQLITE_OK;
37512  }else{
37513    pFile->lastErrno = lastErrno;
37514    rc = SQLITE_BUSY;
37515    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
37516             pFile->h, locktype, newLocktype));
37517  }
37518  pFile->locktype = (u8)newLocktype;
37519  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
37520           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
37521  return rc;
37522}
37523
37524/*
37525** This routine checks if there is a RESERVED lock held on the specified
37526** file by this or any other process. If such a lock is held, return
37527** non-zero, otherwise zero.
37528*/
37529static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
37530  int res;
37531  winFile *pFile = (winFile*)id;
37532
37533  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
37534  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
37535
37536  assert( id!=0 );
37537  if( pFile->locktype>=RESERVED_LOCK ){
37538    res = 1;
37539    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
37540  }else{
37541    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
37542    if( res ){
37543      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
37544    }
37545    res = !res;
37546    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
37547  }
37548  *pResOut = res;
37549  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
37550           pFile->h, pResOut, *pResOut));
37551  return SQLITE_OK;
37552}
37553
37554/*
37555** Lower the locking level on file descriptor id to locktype.  locktype
37556** must be either NO_LOCK or SHARED_LOCK.
37557**
37558** If the locking level of the file descriptor is already at or below
37559** the requested locking level, this routine is a no-op.
37560**
37561** It is not possible for this routine to fail if the second argument
37562** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
37563** might return SQLITE_IOERR;
37564*/
37565static int winUnlock(sqlite3_file *id, int locktype){
37566  int type;
37567  winFile *pFile = (winFile*)id;
37568  int rc = SQLITE_OK;
37569  assert( pFile!=0 );
37570  assert( locktype<=SHARED_LOCK );
37571  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
37572           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
37573  type = pFile->locktype;
37574  if( type>=EXCLUSIVE_LOCK ){
37575    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
37576    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
37577      /* This should never happen.  We should always be able to
37578      ** reacquire the read lock */
37579      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
37580                       "winUnlock", pFile->zPath);
37581    }
37582  }
37583  if( type>=RESERVED_LOCK ){
37584    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
37585  }
37586  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
37587    winUnlockReadLock(pFile);
37588  }
37589  if( type>=PENDING_LOCK ){
37590    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
37591  }
37592  pFile->locktype = (u8)locktype;
37593  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
37594           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
37595  return rc;
37596}
37597
37598/*
37599** If *pArg is initially negative then this is a query.  Set *pArg to
37600** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
37601**
37602** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
37603*/
37604static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
37605  if( *pArg<0 ){
37606    *pArg = (pFile->ctrlFlags & mask)!=0;
37607  }else if( (*pArg)==0 ){
37608    pFile->ctrlFlags &= ~mask;
37609  }else{
37610    pFile->ctrlFlags |= mask;
37611  }
37612}
37613
37614/* Forward references to VFS helper methods used for temporary files */
37615static int winGetTempname(sqlite3_vfs *, char **);
37616static int winIsDir(const void *);
37617static BOOL winIsDriveLetterAndColon(const char *);
37618
37619/*
37620** Control and query of the open file handle.
37621*/
37622static int winFileControl(sqlite3_file *id, int op, void *pArg){
37623  winFile *pFile = (winFile*)id;
37624  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
37625  switch( op ){
37626    case SQLITE_FCNTL_LOCKSTATE: {
37627      *(int*)pArg = pFile->locktype;
37628      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37629      return SQLITE_OK;
37630    }
37631    case SQLITE_LAST_ERRNO: {
37632      *(int*)pArg = (int)pFile->lastErrno;
37633      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37634      return SQLITE_OK;
37635    }
37636    case SQLITE_FCNTL_CHUNK_SIZE: {
37637      pFile->szChunk = *(int *)pArg;
37638      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37639      return SQLITE_OK;
37640    }
37641    case SQLITE_FCNTL_SIZE_HINT: {
37642      if( pFile->szChunk>0 ){
37643        sqlite3_int64 oldSz;
37644        int rc = winFileSize(id, &oldSz);
37645        if( rc==SQLITE_OK ){
37646          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
37647          if( newSz>oldSz ){
37648            SimulateIOErrorBenign(1);
37649            rc = winTruncate(id, newSz);
37650            SimulateIOErrorBenign(0);
37651          }
37652        }
37653        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37654        return rc;
37655      }
37656      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37657      return SQLITE_OK;
37658    }
37659    case SQLITE_FCNTL_PERSIST_WAL: {
37660      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
37661      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37662      return SQLITE_OK;
37663    }
37664    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
37665      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
37666      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37667      return SQLITE_OK;
37668    }
37669    case SQLITE_FCNTL_VFSNAME: {
37670      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
37671      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37672      return SQLITE_OK;
37673    }
37674    case SQLITE_FCNTL_WIN32_AV_RETRY: {
37675      int *a = (int*)pArg;
37676      if( a[0]>0 ){
37677        winIoerrRetry = a[0];
37678      }else{
37679        a[0] = winIoerrRetry;
37680      }
37681      if( a[1]>0 ){
37682        winIoerrRetryDelay = a[1];
37683      }else{
37684        a[1] = winIoerrRetryDelay;
37685      }
37686      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37687      return SQLITE_OK;
37688    }
37689#ifdef SQLITE_TEST
37690    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
37691      LPHANDLE phFile = (LPHANDLE)pArg;
37692      HANDLE hOldFile = pFile->h;
37693      pFile->h = *phFile;
37694      *phFile = hOldFile;
37695      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
37696               hOldFile, pFile->h));
37697      return SQLITE_OK;
37698    }
37699#endif
37700    case SQLITE_FCNTL_TEMPFILENAME: {
37701      char *zTFile = 0;
37702      int rc = winGetTempname(pFile->pVfs, &zTFile);
37703      if( rc==SQLITE_OK ){
37704        *(char**)pArg = zTFile;
37705      }
37706      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37707      return rc;
37708    }
37709#if SQLITE_MAX_MMAP_SIZE>0
37710    case SQLITE_FCNTL_MMAP_SIZE: {
37711      i64 newLimit = *(i64*)pArg;
37712      int rc = SQLITE_OK;
37713      if( newLimit>sqlite3GlobalConfig.mxMmap ){
37714        newLimit = sqlite3GlobalConfig.mxMmap;
37715      }
37716      *(i64*)pArg = pFile->mmapSizeMax;
37717      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
37718        pFile->mmapSizeMax = newLimit;
37719        if( pFile->mmapSize>0 ){
37720          winUnmapfile(pFile);
37721          rc = winMapfile(pFile, -1);
37722        }
37723      }
37724      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37725      return rc;
37726    }
37727#endif
37728  }
37729  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
37730  return SQLITE_NOTFOUND;
37731}
37732
37733/*
37734** Return the sector size in bytes of the underlying block device for
37735** the specified file. This is almost always 512 bytes, but may be
37736** larger for some devices.
37737**
37738** SQLite code assumes this function cannot fail. It also assumes that
37739** if two files are created in the same file-system directory (i.e.
37740** a database and its journal file) that the sector size will be the
37741** same for both.
37742*/
37743static int winSectorSize(sqlite3_file *id){
37744  (void)id;
37745  return SQLITE_DEFAULT_SECTOR_SIZE;
37746}
37747
37748/*
37749** Return a vector of device characteristics.
37750*/
37751static int winDeviceCharacteristics(sqlite3_file *id){
37752  winFile *p = (winFile*)id;
37753  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
37754         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
37755}
37756
37757/*
37758** Windows will only let you create file view mappings
37759** on allocation size granularity boundaries.
37760** During sqlite3_os_init() we do a GetSystemInfo()
37761** to get the granularity size.
37762*/
37763static SYSTEM_INFO winSysInfo;
37764
37765#ifndef SQLITE_OMIT_WAL
37766
37767/*
37768** Helper functions to obtain and relinquish the global mutex. The
37769** global mutex is used to protect the winLockInfo objects used by
37770** this file, all of which may be shared by multiple threads.
37771**
37772** Function winShmMutexHeld() is used to assert() that the global mutex
37773** is held when required. This function is only used as part of assert()
37774** statements. e.g.
37775**
37776**   winShmEnterMutex()
37777**     assert( winShmMutexHeld() );
37778**   winShmLeaveMutex()
37779*/
37780static void winShmEnterMutex(void){
37781  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37782}
37783static void winShmLeaveMutex(void){
37784  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37785}
37786#ifndef NDEBUG
37787static int winShmMutexHeld(void) {
37788  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37789}
37790#endif
37791
37792/*
37793** Object used to represent a single file opened and mmapped to provide
37794** shared memory.  When multiple threads all reference the same
37795** log-summary, each thread has its own winFile object, but they all
37796** point to a single instance of this object.  In other words, each
37797** log-summary is opened only once per process.
37798**
37799** winShmMutexHeld() must be true when creating or destroying
37800** this object or while reading or writing the following fields:
37801**
37802**      nRef
37803**      pNext
37804**
37805** The following fields are read-only after the object is created:
37806**
37807**      fid
37808**      zFilename
37809**
37810** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
37811** winShmMutexHeld() is true when reading or writing any other field
37812** in this structure.
37813**
37814*/
37815struct winShmNode {
37816  sqlite3_mutex *mutex;      /* Mutex to access this object */
37817  char *zFilename;           /* Name of the file */
37818  winFile hFile;             /* File handle from winOpen */
37819
37820  int szRegion;              /* Size of shared-memory regions */
37821  int nRegion;               /* Size of array apRegion */
37822  struct ShmRegion {
37823    HANDLE hMap;             /* File handle from CreateFileMapping */
37824    void *pMap;
37825  } *aRegion;
37826  DWORD lastErrno;           /* The Windows errno from the last I/O error */
37827
37828  int nRef;                  /* Number of winShm objects pointing to this */
37829  winShm *pFirst;            /* All winShm objects pointing to this */
37830  winShmNode *pNext;         /* Next in list of all winShmNode objects */
37831#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
37832  u8 nextShmId;              /* Next available winShm.id value */
37833#endif
37834};
37835
37836/*
37837** A global array of all winShmNode objects.
37838**
37839** The winShmMutexHeld() must be true while reading or writing this list.
37840*/
37841static winShmNode *winShmNodeList = 0;
37842
37843/*
37844** Structure used internally by this VFS to record the state of an
37845** open shared memory connection.
37846**
37847** The following fields are initialized when this object is created and
37848** are read-only thereafter:
37849**
37850**    winShm.pShmNode
37851**    winShm.id
37852**
37853** All other fields are read/write.  The winShm.pShmNode->mutex must be held
37854** while accessing any read/write fields.
37855*/
37856struct winShm {
37857  winShmNode *pShmNode;      /* The underlying winShmNode object */
37858  winShm *pNext;             /* Next winShm with the same winShmNode */
37859  u8 hasMutex;               /* True if holding the winShmNode mutex */
37860  u16 sharedMask;            /* Mask of shared locks held */
37861  u16 exclMask;              /* Mask of exclusive locks held */
37862#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
37863  u8 id;                     /* Id of this connection with its winShmNode */
37864#endif
37865};
37866
37867/*
37868** Constants used for locking
37869*/
37870#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
37871#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
37872
37873/*
37874** Apply advisory locks for all n bytes beginning at ofst.
37875*/
37876#define _SHM_UNLCK  1
37877#define _SHM_RDLCK  2
37878#define _SHM_WRLCK  3
37879static int winShmSystemLock(
37880  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
37881  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
37882  int ofst,             /* Offset to first byte to be locked/unlocked */
37883  int nByte             /* Number of bytes to lock or unlock */
37884){
37885  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
37886
37887  /* Access to the winShmNode object is serialized by the caller */
37888  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
37889
37890  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
37891           pFile->hFile.h, lockType, ofst, nByte));
37892
37893  /* Release/Acquire the system-level lock */
37894  if( lockType==_SHM_UNLCK ){
37895    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
37896  }else{
37897    /* Initialize the locking parameters */
37898    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
37899    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
37900    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
37901  }
37902
37903  if( rc!= 0 ){
37904    rc = SQLITE_OK;
37905  }else{
37906    pFile->lastErrno =  osGetLastError();
37907    rc = SQLITE_BUSY;
37908  }
37909
37910  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
37911           pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
37912           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
37913
37914  return rc;
37915}
37916
37917/* Forward references to VFS methods */
37918static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
37919static int winDelete(sqlite3_vfs *,const char*,int);
37920
37921/*
37922** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
37923**
37924** This is not a VFS shared-memory method; it is a utility function called
37925** by VFS shared-memory methods.
37926*/
37927static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
37928  winShmNode **pp;
37929  winShmNode *p;
37930  assert( winShmMutexHeld() );
37931  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
37932           osGetCurrentProcessId(), deleteFlag));
37933  pp = &winShmNodeList;
37934  while( (p = *pp)!=0 ){
37935    if( p->nRef==0 ){
37936      int i;
37937      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
37938      for(i=0; i<p->nRegion; i++){
37939        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
37940        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
37941                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
37942        UNUSED_VARIABLE_VALUE(bRc);
37943        bRc = osCloseHandle(p->aRegion[i].hMap);
37944        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
37945                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
37946        UNUSED_VARIABLE_VALUE(bRc);
37947      }
37948      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
37949        SimulateIOErrorBenign(1);
37950        winClose((sqlite3_file *)&p->hFile);
37951        SimulateIOErrorBenign(0);
37952      }
37953      if( deleteFlag ){
37954        SimulateIOErrorBenign(1);
37955        sqlite3BeginBenignMalloc();
37956        winDelete(pVfs, p->zFilename, 0);
37957        sqlite3EndBenignMalloc();
37958        SimulateIOErrorBenign(0);
37959      }
37960      *pp = p->pNext;
37961      sqlite3_free(p->aRegion);
37962      sqlite3_free(p);
37963    }else{
37964      pp = &p->pNext;
37965    }
37966  }
37967}
37968
37969/*
37970** Open the shared-memory area associated with database file pDbFd.
37971**
37972** When opening a new shared-memory file, if no other instances of that
37973** file are currently open, in this process or in other processes, then
37974** the file must be truncated to zero length or have its header cleared.
37975*/
37976static int winOpenSharedMemory(winFile *pDbFd){
37977  struct winShm *p;                  /* The connection to be opened */
37978  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
37979  int rc;                            /* Result code */
37980  struct winShmNode *pNew;           /* Newly allocated winShmNode */
37981  int nName;                         /* Size of zName in bytes */
37982
37983  assert( pDbFd->pShm==0 );    /* Not previously opened */
37984
37985  /* Allocate space for the new sqlite3_shm object.  Also speculatively
37986  ** allocate space for a new winShmNode and filename.
37987  */
37988  p = sqlite3MallocZero( sizeof(*p) );
37989  if( p==0 ) return SQLITE_IOERR_NOMEM;
37990  nName = sqlite3Strlen30(pDbFd->zPath);
37991  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
37992  if( pNew==0 ){
37993    sqlite3_free(p);
37994    return SQLITE_IOERR_NOMEM;
37995  }
37996  pNew->zFilename = (char*)&pNew[1];
37997  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
37998  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
37999
38000  /* Look to see if there is an existing winShmNode that can be used.
38001  ** If no matching winShmNode currently exists, create a new one.
38002  */
38003  winShmEnterMutex();
38004  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
38005    /* TBD need to come up with better match here.  Perhaps
38006    ** use FILE_ID_BOTH_DIR_INFO Structure.
38007    */
38008    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
38009  }
38010  if( pShmNode ){
38011    sqlite3_free(pNew);
38012  }else{
38013    pShmNode = pNew;
38014    pNew = 0;
38015    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
38016    pShmNode->pNext = winShmNodeList;
38017    winShmNodeList = pShmNode;
38018
38019    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
38020    if( pShmNode->mutex==0 ){
38021      rc = SQLITE_IOERR_NOMEM;
38022      goto shm_open_err;
38023    }
38024
38025    rc = winOpen(pDbFd->pVfs,
38026                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
38027                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
38028                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
38029                 0);
38030    if( SQLITE_OK!=rc ){
38031      goto shm_open_err;
38032    }
38033
38034    /* Check to see if another process is holding the dead-man switch.
38035    ** If not, truncate the file to zero length.
38036    */
38037    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
38038      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
38039      if( rc!=SQLITE_OK ){
38040        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
38041                         "winOpenShm", pDbFd->zPath);
38042      }
38043    }
38044    if( rc==SQLITE_OK ){
38045      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
38046      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
38047    }
38048    if( rc ) goto shm_open_err;
38049  }
38050
38051  /* Make the new connection a child of the winShmNode */
38052  p->pShmNode = pShmNode;
38053#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
38054  p->id = pShmNode->nextShmId++;
38055#endif
38056  pShmNode->nRef++;
38057  pDbFd->pShm = p;
38058  winShmLeaveMutex();
38059
38060  /* The reference count on pShmNode has already been incremented under
38061  ** the cover of the winShmEnterMutex() mutex and the pointer from the
38062  ** new (struct winShm) object to the pShmNode has been set. All that is
38063  ** left to do is to link the new object into the linked list starting
38064  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
38065  ** mutex.
38066  */
38067  sqlite3_mutex_enter(pShmNode->mutex);
38068  p->pNext = pShmNode->pFirst;
38069  pShmNode->pFirst = p;
38070  sqlite3_mutex_leave(pShmNode->mutex);
38071  return SQLITE_OK;
38072
38073  /* Jump here on any error */
38074shm_open_err:
38075  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
38076  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
38077  sqlite3_free(p);
38078  sqlite3_free(pNew);
38079  winShmLeaveMutex();
38080  return rc;
38081}
38082
38083/*
38084** Close a connection to shared-memory.  Delete the underlying
38085** storage if deleteFlag is true.
38086*/
38087static int winShmUnmap(
38088  sqlite3_file *fd,          /* Database holding shared memory */
38089  int deleteFlag             /* Delete after closing if true */
38090){
38091  winFile *pDbFd;       /* Database holding shared-memory */
38092  winShm *p;            /* The connection to be closed */
38093  winShmNode *pShmNode; /* The underlying shared-memory file */
38094  winShm **pp;          /* For looping over sibling connections */
38095
38096  pDbFd = (winFile*)fd;
38097  p = pDbFd->pShm;
38098  if( p==0 ) return SQLITE_OK;
38099  pShmNode = p->pShmNode;
38100
38101  /* Remove connection p from the set of connections associated
38102  ** with pShmNode */
38103  sqlite3_mutex_enter(pShmNode->mutex);
38104  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
38105  *pp = p->pNext;
38106
38107  /* Free the connection p */
38108  sqlite3_free(p);
38109  pDbFd->pShm = 0;
38110  sqlite3_mutex_leave(pShmNode->mutex);
38111
38112  /* If pShmNode->nRef has reached 0, then close the underlying
38113  ** shared-memory file, too */
38114  winShmEnterMutex();
38115  assert( pShmNode->nRef>0 );
38116  pShmNode->nRef--;
38117  if( pShmNode->nRef==0 ){
38118    winShmPurge(pDbFd->pVfs, deleteFlag);
38119  }
38120  winShmLeaveMutex();
38121
38122  return SQLITE_OK;
38123}
38124
38125/*
38126** Change the lock state for a shared-memory segment.
38127*/
38128static int winShmLock(
38129  sqlite3_file *fd,          /* Database file holding the shared memory */
38130  int ofst,                  /* First lock to acquire or release */
38131  int n,                     /* Number of locks to acquire or release */
38132  int flags                  /* What to do with the lock */
38133){
38134  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
38135  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
38136  winShm *pX;                           /* For looping over all siblings */
38137  winShmNode *pShmNode = p->pShmNode;
38138  int rc = SQLITE_OK;                   /* Result code */
38139  u16 mask;                             /* Mask of locks to take or release */
38140
38141  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
38142  assert( n>=1 );
38143  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
38144       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
38145       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
38146       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
38147  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
38148
38149  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
38150  assert( n>1 || mask==(1<<ofst) );
38151  sqlite3_mutex_enter(pShmNode->mutex);
38152  if( flags & SQLITE_SHM_UNLOCK ){
38153    u16 allMask = 0; /* Mask of locks held by siblings */
38154
38155    /* See if any siblings hold this same lock */
38156    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38157      if( pX==p ) continue;
38158      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
38159      allMask |= pX->sharedMask;
38160    }
38161
38162    /* Unlock the system-level locks */
38163    if( (mask & allMask)==0 ){
38164      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
38165    }else{
38166      rc = SQLITE_OK;
38167    }
38168
38169    /* Undo the local locks */
38170    if( rc==SQLITE_OK ){
38171      p->exclMask &= ~mask;
38172      p->sharedMask &= ~mask;
38173    }
38174  }else if( flags & SQLITE_SHM_SHARED ){
38175    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
38176
38177    /* Find out which shared locks are already held by sibling connections.
38178    ** If any sibling already holds an exclusive lock, go ahead and return
38179    ** SQLITE_BUSY.
38180    */
38181    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38182      if( (pX->exclMask & mask)!=0 ){
38183        rc = SQLITE_BUSY;
38184        break;
38185      }
38186      allShared |= pX->sharedMask;
38187    }
38188
38189    /* Get shared locks at the system level, if necessary */
38190    if( rc==SQLITE_OK ){
38191      if( (allShared & mask)==0 ){
38192        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
38193      }else{
38194        rc = SQLITE_OK;
38195      }
38196    }
38197
38198    /* Get the local shared locks */
38199    if( rc==SQLITE_OK ){
38200      p->sharedMask |= mask;
38201    }
38202  }else{
38203    /* Make sure no sibling connections hold locks that will block this
38204    ** lock.  If any do, return SQLITE_BUSY right away.
38205    */
38206    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38207      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
38208        rc = SQLITE_BUSY;
38209        break;
38210      }
38211    }
38212
38213    /* Get the exclusive locks at the system level.  Then if successful
38214    ** also mark the local connection as being locked.
38215    */
38216    if( rc==SQLITE_OK ){
38217      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
38218      if( rc==SQLITE_OK ){
38219        assert( (p->sharedMask & mask)==0 );
38220        p->exclMask |= mask;
38221      }
38222    }
38223  }
38224  sqlite3_mutex_leave(pShmNode->mutex);
38225  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
38226           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
38227           sqlite3ErrName(rc)));
38228  return rc;
38229}
38230
38231/*
38232** Implement a memory barrier or memory fence on shared memory.
38233**
38234** All loads and stores begun before the barrier must complete before
38235** any load or store begun after the barrier.
38236*/
38237static void winShmBarrier(
38238  sqlite3_file *fd          /* Database holding the shared memory */
38239){
38240  UNUSED_PARAMETER(fd);
38241  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
38242  winShmEnterMutex();       /* Also mutex, for redundancy */
38243  winShmLeaveMutex();
38244}
38245
38246/*
38247** This function is called to obtain a pointer to region iRegion of the
38248** shared-memory associated with the database file fd. Shared-memory regions
38249** are numbered starting from zero. Each shared-memory region is szRegion
38250** bytes in size.
38251**
38252** If an error occurs, an error code is returned and *pp is set to NULL.
38253**
38254** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
38255** region has not been allocated (by any client, including one running in a
38256** separate process), then *pp is set to NULL and SQLITE_OK returned. If
38257** isWrite is non-zero and the requested shared-memory region has not yet
38258** been allocated, it is allocated by this function.
38259**
38260** If the shared-memory region has already been allocated or is allocated by
38261** this call as described above, then it is mapped into this processes
38262** address space (if it is not already), *pp is set to point to the mapped
38263** memory and SQLITE_OK returned.
38264*/
38265static int winShmMap(
38266  sqlite3_file *fd,               /* Handle open on database file */
38267  int iRegion,                    /* Region to retrieve */
38268  int szRegion,                   /* Size of regions */
38269  int isWrite,                    /* True to extend file if necessary */
38270  void volatile **pp              /* OUT: Mapped memory */
38271){
38272  winFile *pDbFd = (winFile*)fd;
38273  winShm *pShm = pDbFd->pShm;
38274  winShmNode *pShmNode;
38275  int rc = SQLITE_OK;
38276
38277  if( !pShm ){
38278    rc = winOpenSharedMemory(pDbFd);
38279    if( rc!=SQLITE_OK ) return rc;
38280    pShm = pDbFd->pShm;
38281  }
38282  pShmNode = pShm->pShmNode;
38283
38284  sqlite3_mutex_enter(pShmNode->mutex);
38285  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
38286
38287  if( pShmNode->nRegion<=iRegion ){
38288    struct ShmRegion *apNew;           /* New aRegion[] array */
38289    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
38290    sqlite3_int64 sz;                  /* Current size of wal-index file */
38291
38292    pShmNode->szRegion = szRegion;
38293
38294    /* The requested region is not mapped into this processes address space.
38295    ** Check to see if it has been allocated (i.e. if the wal-index file is
38296    ** large enough to contain the requested region).
38297    */
38298    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
38299    if( rc!=SQLITE_OK ){
38300      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
38301                       "winShmMap1", pDbFd->zPath);
38302      goto shmpage_out;
38303    }
38304
38305    if( sz<nByte ){
38306      /* The requested memory region does not exist. If isWrite is set to
38307      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
38308      **
38309      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
38310      ** the requested memory region.
38311      */
38312      if( !isWrite ) goto shmpage_out;
38313      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
38314      if( rc!=SQLITE_OK ){
38315        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
38316                         "winShmMap2", pDbFd->zPath);
38317        goto shmpage_out;
38318      }
38319    }
38320
38321    /* Map the requested memory region into this processes address space. */
38322    apNew = (struct ShmRegion *)sqlite3_realloc64(
38323        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
38324    );
38325    if( !apNew ){
38326      rc = SQLITE_IOERR_NOMEM;
38327      goto shmpage_out;
38328    }
38329    pShmNode->aRegion = apNew;
38330
38331    while( pShmNode->nRegion<=iRegion ){
38332      HANDLE hMap = NULL;         /* file-mapping handle */
38333      void *pMap = 0;             /* Mapped memory region */
38334
38335#if SQLITE_OS_WINRT
38336      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
38337          NULL, PAGE_READWRITE, nByte, NULL
38338      );
38339#elif defined(SQLITE_WIN32_HAS_WIDE)
38340      hMap = osCreateFileMappingW(pShmNode->hFile.h,
38341          NULL, PAGE_READWRITE, 0, nByte, NULL
38342      );
38343#elif defined(SQLITE_WIN32_HAS_ANSI)
38344      hMap = osCreateFileMappingA(pShmNode->hFile.h,
38345          NULL, PAGE_READWRITE, 0, nByte, NULL
38346      );
38347#endif
38348      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
38349               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
38350               hMap ? "ok" : "failed"));
38351      if( hMap ){
38352        int iOffset = pShmNode->nRegion*szRegion;
38353        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
38354#if SQLITE_OS_WINRT
38355        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
38356            iOffset - iOffsetShift, szRegion + iOffsetShift
38357        );
38358#else
38359        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
38360            0, iOffset - iOffsetShift, szRegion + iOffsetShift
38361        );
38362#endif
38363        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
38364                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
38365                 szRegion, pMap ? "ok" : "failed"));
38366      }
38367      if( !pMap ){
38368        pShmNode->lastErrno = osGetLastError();
38369        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
38370                         "winShmMap3", pDbFd->zPath);
38371        if( hMap ) osCloseHandle(hMap);
38372        goto shmpage_out;
38373      }
38374
38375      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
38376      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
38377      pShmNode->nRegion++;
38378    }
38379  }
38380
38381shmpage_out:
38382  if( pShmNode->nRegion>iRegion ){
38383    int iOffset = iRegion*szRegion;
38384    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
38385    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
38386    *pp = (void *)&p[iOffsetShift];
38387  }else{
38388    *pp = 0;
38389  }
38390  sqlite3_mutex_leave(pShmNode->mutex);
38391  return rc;
38392}
38393
38394#else
38395# define winShmMap     0
38396# define winShmLock    0
38397# define winShmBarrier 0
38398# define winShmUnmap   0
38399#endif /* #ifndef SQLITE_OMIT_WAL */
38400
38401/*
38402** Cleans up the mapped region of the specified file, if any.
38403*/
38404#if SQLITE_MAX_MMAP_SIZE>0
38405static int winUnmapfile(winFile *pFile){
38406  assert( pFile!=0 );
38407  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
38408           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
38409           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
38410           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
38411  if( pFile->pMapRegion ){
38412    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
38413      pFile->lastErrno = osGetLastError();
38414      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
38415               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
38416               pFile->pMapRegion));
38417      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
38418                         "winUnmapfile1", pFile->zPath);
38419    }
38420    pFile->pMapRegion = 0;
38421    pFile->mmapSize = 0;
38422    pFile->mmapSizeActual = 0;
38423  }
38424  if( pFile->hMap!=NULL ){
38425    if( !osCloseHandle(pFile->hMap) ){
38426      pFile->lastErrno = osGetLastError();
38427      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
38428               osGetCurrentProcessId(), pFile, pFile->hMap));
38429      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
38430                         "winUnmapfile2", pFile->zPath);
38431    }
38432    pFile->hMap = NULL;
38433  }
38434  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38435           osGetCurrentProcessId(), pFile));
38436  return SQLITE_OK;
38437}
38438
38439/*
38440** Memory map or remap the file opened by file-descriptor pFd (if the file
38441** is already mapped, the existing mapping is replaced by the new). Or, if
38442** there already exists a mapping for this file, and there are still
38443** outstanding xFetch() references to it, this function is a no-op.
38444**
38445** If parameter nByte is non-negative, then it is the requested size of
38446** the mapping to create. Otherwise, if nByte is less than zero, then the
38447** requested size is the size of the file on disk. The actual size of the
38448** created mapping is either the requested size or the value configured
38449** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
38450**
38451** SQLITE_OK is returned if no error occurs (even if the mapping is not
38452** recreated as a result of outstanding references) or an SQLite error
38453** code otherwise.
38454*/
38455static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
38456  sqlite3_int64 nMap = nByte;
38457  int rc;
38458
38459  assert( nMap>=0 || pFd->nFetchOut==0 );
38460  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
38461           osGetCurrentProcessId(), pFd, nByte));
38462
38463  if( pFd->nFetchOut>0 ) return SQLITE_OK;
38464
38465  if( nMap<0 ){
38466    rc = winFileSize((sqlite3_file*)pFd, &nMap);
38467    if( rc ){
38468      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
38469               osGetCurrentProcessId(), pFd));
38470      return SQLITE_IOERR_FSTAT;
38471    }
38472  }
38473  if( nMap>pFd->mmapSizeMax ){
38474    nMap = pFd->mmapSizeMax;
38475  }
38476  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
38477
38478  if( nMap==0 && pFd->mmapSize>0 ){
38479    winUnmapfile(pFd);
38480  }
38481  if( nMap!=pFd->mmapSize ){
38482    void *pNew = 0;
38483    DWORD protect = PAGE_READONLY;
38484    DWORD flags = FILE_MAP_READ;
38485
38486    winUnmapfile(pFd);
38487    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
38488      protect = PAGE_READWRITE;
38489      flags |= FILE_MAP_WRITE;
38490    }
38491#if SQLITE_OS_WINRT
38492    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
38493#elif defined(SQLITE_WIN32_HAS_WIDE)
38494    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
38495                                (DWORD)((nMap>>32) & 0xffffffff),
38496                                (DWORD)(nMap & 0xffffffff), NULL);
38497#elif defined(SQLITE_WIN32_HAS_ANSI)
38498    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
38499                                (DWORD)((nMap>>32) & 0xffffffff),
38500                                (DWORD)(nMap & 0xffffffff), NULL);
38501#endif
38502    if( pFd->hMap==NULL ){
38503      pFd->lastErrno = osGetLastError();
38504      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
38505                       "winMapfile1", pFd->zPath);
38506      /* Log the error, but continue normal operation using xRead/xWrite */
38507      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
38508               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38509      return SQLITE_OK;
38510    }
38511    assert( (nMap % winSysInfo.dwPageSize)==0 );
38512    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
38513#if SQLITE_OS_WINRT
38514    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
38515#else
38516    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
38517#endif
38518    if( pNew==NULL ){
38519      osCloseHandle(pFd->hMap);
38520      pFd->hMap = NULL;
38521      pFd->lastErrno = osGetLastError();
38522      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
38523                       "winMapfile2", pFd->zPath);
38524      /* Log the error, but continue normal operation using xRead/xWrite */
38525      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
38526               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38527      return SQLITE_OK;
38528    }
38529    pFd->pMapRegion = pNew;
38530    pFd->mmapSize = nMap;
38531    pFd->mmapSizeActual = nMap;
38532  }
38533
38534  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38535           osGetCurrentProcessId(), pFd));
38536  return SQLITE_OK;
38537}
38538#endif /* SQLITE_MAX_MMAP_SIZE>0 */
38539
38540/*
38541** If possible, return a pointer to a mapping of file fd starting at offset
38542** iOff. The mapping must be valid for at least nAmt bytes.
38543**
38544** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
38545** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
38546** Finally, if an error does occur, return an SQLite error code. The final
38547** value of *pp is undefined in this case.
38548**
38549** If this function does return a pointer, the caller must eventually
38550** release the reference by calling winUnfetch().
38551*/
38552static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
38553#if SQLITE_MAX_MMAP_SIZE>0
38554  winFile *pFd = (winFile*)fd;   /* The underlying database file */
38555#endif
38556  *pp = 0;
38557
38558  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
38559           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
38560
38561#if SQLITE_MAX_MMAP_SIZE>0
38562  if( pFd->mmapSizeMax>0 ){
38563    if( pFd->pMapRegion==0 ){
38564      int rc = winMapfile(pFd, -1);
38565      if( rc!=SQLITE_OK ){
38566        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
38567                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38568        return rc;
38569      }
38570    }
38571    if( pFd->mmapSize >= iOff+nAmt ){
38572      *pp = &((u8 *)pFd->pMapRegion)[iOff];
38573      pFd->nFetchOut++;
38574    }
38575  }
38576#endif
38577
38578  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
38579           osGetCurrentProcessId(), fd, pp, *pp));
38580  return SQLITE_OK;
38581}
38582
38583/*
38584** If the third argument is non-NULL, then this function releases a
38585** reference obtained by an earlier call to winFetch(). The second
38586** argument passed to this function must be the same as the corresponding
38587** argument that was passed to the winFetch() invocation.
38588**
38589** Or, if the third argument is NULL, then this function is being called
38590** to inform the VFS layer that, according to POSIX, any existing mapping
38591** may now be invalid and should be unmapped.
38592*/
38593static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
38594#if SQLITE_MAX_MMAP_SIZE>0
38595  winFile *pFd = (winFile*)fd;   /* The underlying database file */
38596
38597  /* If p==0 (unmap the entire file) then there must be no outstanding
38598  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
38599  ** then there must be at least one outstanding.  */
38600  assert( (p==0)==(pFd->nFetchOut==0) );
38601
38602  /* If p!=0, it must match the iOff value. */
38603  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
38604
38605  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
38606           osGetCurrentProcessId(), pFd, iOff, p));
38607
38608  if( p ){
38609    pFd->nFetchOut--;
38610  }else{
38611    /* FIXME:  If Windows truly always prevents truncating or deleting a
38612    ** file while a mapping is held, then the following winUnmapfile() call
38613    ** is unnecessary can be omitted - potentially improving
38614    ** performance.  */
38615    winUnmapfile(pFd);
38616  }
38617
38618  assert( pFd->nFetchOut>=0 );
38619#endif
38620
38621  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38622           osGetCurrentProcessId(), fd));
38623  return SQLITE_OK;
38624}
38625
38626/*
38627** Here ends the implementation of all sqlite3_file methods.
38628**
38629********************** End sqlite3_file Methods *******************************
38630******************************************************************************/
38631
38632/*
38633** This vector defines all the methods that can operate on an
38634** sqlite3_file for win32.
38635*/
38636static const sqlite3_io_methods winIoMethod = {
38637  3,                              /* iVersion */
38638  winClose,                       /* xClose */
38639  winRead,                        /* xRead */
38640  winWrite,                       /* xWrite */
38641  winTruncate,                    /* xTruncate */
38642  winSync,                        /* xSync */
38643  winFileSize,                    /* xFileSize */
38644  winLock,                        /* xLock */
38645  winUnlock,                      /* xUnlock */
38646  winCheckReservedLock,           /* xCheckReservedLock */
38647  winFileControl,                 /* xFileControl */
38648  winSectorSize,                  /* xSectorSize */
38649  winDeviceCharacteristics,       /* xDeviceCharacteristics */
38650  winShmMap,                      /* xShmMap */
38651  winShmLock,                     /* xShmLock */
38652  winShmBarrier,                  /* xShmBarrier */
38653  winShmUnmap,                    /* xShmUnmap */
38654  winFetch,                       /* xFetch */
38655  winUnfetch                      /* xUnfetch */
38656};
38657
38658/****************************************************************************
38659**************************** sqlite3_vfs methods ****************************
38660**
38661** This division contains the implementation of methods on the
38662** sqlite3_vfs object.
38663*/
38664
38665#if defined(__CYGWIN__)
38666/*
38667** Convert a filename from whatever the underlying operating system
38668** supports for filenames into UTF-8.  Space to hold the result is
38669** obtained from malloc and must be freed by the calling function.
38670*/
38671static char *winConvertToUtf8Filename(const void *zFilename){
38672  char *zConverted = 0;
38673  if( osIsNT() ){
38674    zConverted = winUnicodeToUtf8(zFilename);
38675  }
38676#ifdef SQLITE_WIN32_HAS_ANSI
38677  else{
38678    zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
38679  }
38680#endif
38681  /* caller will handle out of memory */
38682  return zConverted;
38683}
38684#endif
38685
38686/*
38687** Convert a UTF-8 filename into whatever form the underlying
38688** operating system wants filenames in.  Space to hold the result
38689** is obtained from malloc and must be freed by the calling
38690** function.
38691*/
38692static void *winConvertFromUtf8Filename(const char *zFilename){
38693  void *zConverted = 0;
38694  if( osIsNT() ){
38695    zConverted = winUtf8ToUnicode(zFilename);
38696  }
38697#ifdef SQLITE_WIN32_HAS_ANSI
38698  else{
38699    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
38700  }
38701#endif
38702  /* caller will handle out of memory */
38703  return zConverted;
38704}
38705
38706/*
38707** This function returns non-zero if the specified UTF-8 string buffer
38708** ends with a directory separator character or one was successfully
38709** added to it.
38710*/
38711static int winMakeEndInDirSep(int nBuf, char *zBuf){
38712  if( zBuf ){
38713    int nLen = sqlite3Strlen30(zBuf);
38714    if( nLen>0 ){
38715      if( winIsDirSep(zBuf[nLen-1]) ){
38716        return 1;
38717      }else if( nLen+1<nBuf ){
38718        zBuf[nLen] = winGetDirSep();
38719        zBuf[nLen+1] = '\0';
38720        return 1;
38721      }
38722    }
38723  }
38724  return 0;
38725}
38726
38727/*
38728** Create a temporary file name and store the resulting pointer into pzBuf.
38729** The pointer returned in pzBuf must be freed via sqlite3_free().
38730*/
38731static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
38732  static char zChars[] =
38733    "abcdefghijklmnopqrstuvwxyz"
38734    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
38735    "0123456789";
38736  size_t i, j;
38737  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
38738  int nMax, nBuf, nDir, nLen;
38739  char *zBuf;
38740
38741  /* It's odd to simulate an io-error here, but really this is just
38742  ** using the io-error infrastructure to test that SQLite handles this
38743  ** function failing.
38744  */
38745  SimulateIOError( return SQLITE_IOERR );
38746
38747  /* Allocate a temporary buffer to store the fully qualified file
38748  ** name for the temporary file.  If this fails, we cannot continue.
38749  */
38750  nMax = pVfs->mxPathname; nBuf = nMax + 2;
38751  zBuf = sqlite3MallocZero( nBuf );
38752  if( !zBuf ){
38753    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38754    return SQLITE_IOERR_NOMEM;
38755  }
38756
38757  /* Figure out the effective temporary directory.  First, check if one
38758  ** has been explicitly set by the application; otherwise, use the one
38759  ** configured by the operating system.
38760  */
38761  nDir = nMax - (nPre + 15);
38762  assert( nDir>0 );
38763  if( sqlite3_temp_directory ){
38764    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
38765    if( nDirLen>0 ){
38766      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
38767        nDirLen++;
38768      }
38769      if( nDirLen>nDir ){
38770        sqlite3_free(zBuf);
38771        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38772        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
38773      }
38774      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
38775    }
38776  }
38777#if defined(__CYGWIN__)
38778  else{
38779    static const char *azDirs[] = {
38780       0, /* getenv("SQLITE_TMPDIR") */
38781       0, /* getenv("TMPDIR") */
38782       0, /* getenv("TMP") */
38783       0, /* getenv("TEMP") */
38784       0, /* getenv("USERPROFILE") */
38785       "/var/tmp",
38786       "/usr/tmp",
38787       "/tmp",
38788       ".",
38789       0        /* List terminator */
38790    };
38791    unsigned int i;
38792    const char *zDir = 0;
38793
38794    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
38795    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
38796    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
38797    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
38798    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
38799    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
38800      void *zConverted;
38801      if( zDir==0 ) continue;
38802      /* If the path starts with a drive letter followed by the colon
38803      ** character, assume it is already a native Win32 path; otherwise,
38804      ** it must be converted to a native Win32 path via the Cygwin API
38805      ** prior to using it.
38806      */
38807      if( winIsDriveLetterAndColon(zDir) ){
38808        zConverted = winConvertFromUtf8Filename(zDir);
38809        if( !zConverted ){
38810          sqlite3_free(zBuf);
38811          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38812          return SQLITE_IOERR_NOMEM;
38813        }
38814        if( winIsDir(zConverted) ){
38815          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
38816          sqlite3_free(zConverted);
38817          break;
38818        }
38819        sqlite3_free(zConverted);
38820      }else{
38821        zConverted = sqlite3MallocZero( nMax+1 );
38822        if( !zConverted ){
38823          sqlite3_free(zBuf);
38824          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38825          return SQLITE_IOERR_NOMEM;
38826        }
38827        if( cygwin_conv_path(
38828                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
38829                zConverted, nMax+1)<0 ){
38830          sqlite3_free(zConverted);
38831          sqlite3_free(zBuf);
38832          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
38833          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
38834                             "winGetTempname2", zDir);
38835        }
38836        if( winIsDir(zConverted) ){
38837          /* At this point, we know the candidate directory exists and should
38838          ** be used.  However, we may need to convert the string containing
38839          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
38840          */
38841          char *zUtf8 = winConvertToUtf8Filename(zConverted);
38842          if( !zUtf8 ){
38843            sqlite3_free(zConverted);
38844            sqlite3_free(zBuf);
38845            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38846            return SQLITE_IOERR_NOMEM;
38847          }
38848          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
38849          sqlite3_free(zUtf8);
38850          sqlite3_free(zConverted);
38851          break;
38852        }
38853        sqlite3_free(zConverted);
38854      }
38855    }
38856  }
38857#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
38858  else if( osIsNT() ){
38859    char *zMulti;
38860    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
38861    if( !zWidePath ){
38862      sqlite3_free(zBuf);
38863      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38864      return SQLITE_IOERR_NOMEM;
38865    }
38866    if( osGetTempPathW(nMax, zWidePath)==0 ){
38867      sqlite3_free(zWidePath);
38868      sqlite3_free(zBuf);
38869      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
38870      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
38871                         "winGetTempname2", 0);
38872    }
38873    zMulti = winUnicodeToUtf8(zWidePath);
38874    if( zMulti ){
38875      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
38876      sqlite3_free(zMulti);
38877      sqlite3_free(zWidePath);
38878    }else{
38879      sqlite3_free(zWidePath);
38880      sqlite3_free(zBuf);
38881      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38882      return SQLITE_IOERR_NOMEM;
38883    }
38884  }
38885#ifdef SQLITE_WIN32_HAS_ANSI
38886  else{
38887    char *zUtf8;
38888    char *zMbcsPath = sqlite3MallocZero( nMax );
38889    if( !zMbcsPath ){
38890      sqlite3_free(zBuf);
38891      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38892      return SQLITE_IOERR_NOMEM;
38893    }
38894    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
38895      sqlite3_free(zBuf);
38896      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
38897      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
38898                         "winGetTempname3", 0);
38899    }
38900    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
38901    if( zUtf8 ){
38902      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
38903      sqlite3_free(zUtf8);
38904    }else{
38905      sqlite3_free(zBuf);
38906      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38907      return SQLITE_IOERR_NOMEM;
38908    }
38909  }
38910#endif /* SQLITE_WIN32_HAS_ANSI */
38911#endif /* !SQLITE_OS_WINRT */
38912
38913  /*
38914  ** Check to make sure the temporary directory ends with an appropriate
38915  ** separator.  If it does not and there is not enough space left to add
38916  ** one, fail.
38917  */
38918  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
38919    sqlite3_free(zBuf);
38920    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38921    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
38922  }
38923
38924  /*
38925  ** Check that the output buffer is large enough for the temporary file
38926  ** name in the following format:
38927  **
38928  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
38929  **
38930  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
38931  ** account for the space used by the 15 character random suffix and the
38932  ** two trailing NUL characters.  The final directory separator character
38933  ** has already added if it was not already present.
38934  */
38935  nLen = sqlite3Strlen30(zBuf);
38936  if( (nLen + nPre + 17) > nBuf ){
38937    sqlite3_free(zBuf);
38938    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38939    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
38940  }
38941
38942  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
38943
38944  j = sqlite3Strlen30(zBuf);
38945  sqlite3_randomness(15, &zBuf[j]);
38946  for(i=0; i<15; i++, j++){
38947    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
38948  }
38949  zBuf[j] = 0;
38950  zBuf[j+1] = 0;
38951  *pzBuf = zBuf;
38952
38953  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
38954  return SQLITE_OK;
38955}
38956
38957/*
38958** Return TRUE if the named file is really a directory.  Return false if
38959** it is something other than a directory, or if there is any kind of memory
38960** allocation failure.
38961*/
38962static int winIsDir(const void *zConverted){
38963  DWORD attr;
38964  int rc = 0;
38965  DWORD lastErrno;
38966
38967  if( osIsNT() ){
38968    int cnt = 0;
38969    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38970    memset(&sAttrData, 0, sizeof(sAttrData));
38971    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
38972                             GetFileExInfoStandard,
38973                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
38974    if( !rc ){
38975      return 0; /* Invalid name? */
38976    }
38977    attr = sAttrData.dwFileAttributes;
38978#if SQLITE_OS_WINCE==0
38979  }else{
38980    attr = osGetFileAttributesA((char*)zConverted);
38981#endif
38982  }
38983  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
38984}
38985
38986/*
38987** Open a file.
38988*/
38989static int winOpen(
38990  sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
38991  const char *zName,        /* Name of the file (UTF-8) */
38992  sqlite3_file *id,         /* Write the SQLite file handle here */
38993  int flags,                /* Open mode flags */
38994  int *pOutFlags            /* Status return flags */
38995){
38996  HANDLE h;
38997  DWORD lastErrno = 0;
38998  DWORD dwDesiredAccess;
38999  DWORD dwShareMode;
39000  DWORD dwCreationDisposition;
39001  DWORD dwFlagsAndAttributes = 0;
39002#if SQLITE_OS_WINCE
39003  int isTemp = 0;
39004#endif
39005  winFile *pFile = (winFile*)id;
39006  void *zConverted;              /* Filename in OS encoding */
39007  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
39008  int cnt = 0;
39009
39010  /* If argument zPath is a NULL pointer, this function is required to open
39011  ** a temporary file. Use this buffer to store the file name in.
39012  */
39013  char *zTmpname = 0; /* For temporary filename, if necessary. */
39014
39015  int rc = SQLITE_OK;            /* Function Return Code */
39016#if !defined(NDEBUG) || SQLITE_OS_WINCE
39017  int eType = flags&0xFFFFFF00;  /* Type of file to open */
39018#endif
39019
39020  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
39021  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
39022  int isCreate     = (flags & SQLITE_OPEN_CREATE);
39023  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
39024  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
39025
39026#ifndef NDEBUG
39027  int isOpenJournal = (isCreate && (
39028        eType==SQLITE_OPEN_MASTER_JOURNAL
39029     || eType==SQLITE_OPEN_MAIN_JOURNAL
39030     || eType==SQLITE_OPEN_WAL
39031  ));
39032#endif
39033
39034  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
39035           zUtf8Name, id, flags, pOutFlags));
39036
39037  /* Check the following statements are true:
39038  **
39039  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
39040  **   (b) if CREATE is set, then READWRITE must also be set, and
39041  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
39042  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
39043  */
39044  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
39045  assert(isCreate==0 || isReadWrite);
39046  assert(isExclusive==0 || isCreate);
39047  assert(isDelete==0 || isCreate);
39048
39049  /* The main DB, main journal, WAL file and master journal are never
39050  ** automatically deleted. Nor are they ever temporary files.  */
39051  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
39052  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
39053  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
39054  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
39055
39056  /* Assert that the upper layer has set one of the "file-type" flags. */
39057  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
39058       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
39059       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
39060       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
39061  );
39062
39063  assert( pFile!=0 );
39064  memset(pFile, 0, sizeof(winFile));
39065  pFile->h = INVALID_HANDLE_VALUE;
39066
39067#if SQLITE_OS_WINRT
39068  if( !zUtf8Name && !sqlite3_temp_directory ){
39069    sqlite3_log(SQLITE_ERROR,
39070        "sqlite3_temp_directory variable should be set for WinRT");
39071  }
39072#endif
39073
39074  /* If the second argument to this function is NULL, generate a
39075  ** temporary file name to use
39076  */
39077  if( !zUtf8Name ){
39078    assert( isDelete && !isOpenJournal );
39079    rc = winGetTempname(pVfs, &zTmpname);
39080    if( rc!=SQLITE_OK ){
39081      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
39082      return rc;
39083    }
39084    zUtf8Name = zTmpname;
39085  }
39086
39087  /* Database filenames are double-zero terminated if they are not
39088  ** URIs with parameters.  Hence, they can always be passed into
39089  ** sqlite3_uri_parameter().
39090  */
39091  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
39092       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
39093
39094  /* Convert the filename to the system encoding. */
39095  zConverted = winConvertFromUtf8Filename(zUtf8Name);
39096  if( zConverted==0 ){
39097    sqlite3_free(zTmpname);
39098    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
39099    return SQLITE_IOERR_NOMEM;
39100  }
39101
39102  if( winIsDir(zConverted) ){
39103    sqlite3_free(zConverted);
39104    sqlite3_free(zTmpname);
39105    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
39106    return SQLITE_CANTOPEN_ISDIR;
39107  }
39108
39109  if( isReadWrite ){
39110    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
39111  }else{
39112    dwDesiredAccess = GENERIC_READ;
39113  }
39114
39115  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
39116  ** created. SQLite doesn't use it to indicate "exclusive access"
39117  ** as it is usually understood.
39118  */
39119  if( isExclusive ){
39120    /* Creates a new file, only if it does not already exist. */
39121    /* If the file exists, it fails. */
39122    dwCreationDisposition = CREATE_NEW;
39123  }else if( isCreate ){
39124    /* Open existing file, or create if it doesn't exist */
39125    dwCreationDisposition = OPEN_ALWAYS;
39126  }else{
39127    /* Opens a file, only if it exists. */
39128    dwCreationDisposition = OPEN_EXISTING;
39129  }
39130
39131  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
39132
39133  if( isDelete ){
39134#if SQLITE_OS_WINCE
39135    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
39136    isTemp = 1;
39137#else
39138    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
39139                               | FILE_ATTRIBUTE_HIDDEN
39140                               | FILE_FLAG_DELETE_ON_CLOSE;
39141#endif
39142  }else{
39143    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
39144  }
39145  /* Reports from the internet are that performance is always
39146  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
39147#if SQLITE_OS_WINCE
39148  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
39149#endif
39150
39151  if( osIsNT() ){
39152#if SQLITE_OS_WINRT
39153    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
39154    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
39155    extendedParameters.dwFileAttributes =
39156            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
39157    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
39158    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
39159    extendedParameters.lpSecurityAttributes = NULL;
39160    extendedParameters.hTemplateFile = NULL;
39161    while( (h = osCreateFile2((LPCWSTR)zConverted,
39162                              dwDesiredAccess,
39163                              dwShareMode,
39164                              dwCreationDisposition,
39165                              &extendedParameters))==INVALID_HANDLE_VALUE &&
39166                              winRetryIoerr(&cnt, &lastErrno) ){
39167               /* Noop */
39168    }
39169#else
39170    while( (h = osCreateFileW((LPCWSTR)zConverted,
39171                              dwDesiredAccess,
39172                              dwShareMode, NULL,
39173                              dwCreationDisposition,
39174                              dwFlagsAndAttributes,
39175                              NULL))==INVALID_HANDLE_VALUE &&
39176                              winRetryIoerr(&cnt, &lastErrno) ){
39177               /* Noop */
39178    }
39179#endif
39180  }
39181#ifdef SQLITE_WIN32_HAS_ANSI
39182  else{
39183    while( (h = osCreateFileA((LPCSTR)zConverted,
39184                              dwDesiredAccess,
39185                              dwShareMode, NULL,
39186                              dwCreationDisposition,
39187                              dwFlagsAndAttributes,
39188                              NULL))==INVALID_HANDLE_VALUE &&
39189                              winRetryIoerr(&cnt, &lastErrno) ){
39190               /* Noop */
39191    }
39192  }
39193#endif
39194  winLogIoerr(cnt, __LINE__);
39195
39196  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
39197           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
39198
39199  if( h==INVALID_HANDLE_VALUE ){
39200    pFile->lastErrno = lastErrno;
39201    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
39202    sqlite3_free(zConverted);
39203    sqlite3_free(zTmpname);
39204    if( isReadWrite && !isExclusive ){
39205      return winOpen(pVfs, zName, id,
39206         ((flags|SQLITE_OPEN_READONLY) &
39207                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
39208         pOutFlags);
39209    }else{
39210      return SQLITE_CANTOPEN_BKPT;
39211    }
39212  }
39213
39214  if( pOutFlags ){
39215    if( isReadWrite ){
39216      *pOutFlags = SQLITE_OPEN_READWRITE;
39217    }else{
39218      *pOutFlags = SQLITE_OPEN_READONLY;
39219    }
39220  }
39221
39222  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
39223           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
39224           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
39225
39226#if SQLITE_OS_WINCE
39227  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
39228       && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
39229  ){
39230    osCloseHandle(h);
39231    sqlite3_free(zConverted);
39232    sqlite3_free(zTmpname);
39233    OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
39234    return rc;
39235  }
39236  if( isTemp ){
39237    pFile->zDeleteOnClose = zConverted;
39238  }else
39239#endif
39240  {
39241    sqlite3_free(zConverted);
39242  }
39243
39244  sqlite3_free(zTmpname);
39245  pFile->pMethod = &winIoMethod;
39246  pFile->pVfs = pVfs;
39247  pFile->h = h;
39248  if( isReadonly ){
39249    pFile->ctrlFlags |= WINFILE_RDONLY;
39250  }
39251  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
39252    pFile->ctrlFlags |= WINFILE_PSOW;
39253  }
39254  pFile->lastErrno = NO_ERROR;
39255  pFile->zPath = zName;
39256#if SQLITE_MAX_MMAP_SIZE>0
39257  pFile->hMap = NULL;
39258  pFile->pMapRegion = 0;
39259  pFile->mmapSize = 0;
39260  pFile->mmapSizeActual = 0;
39261  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
39262#endif
39263
39264  OpenCounter(+1);
39265  return rc;
39266}
39267
39268/*
39269** Delete the named file.
39270**
39271** Note that Windows does not allow a file to be deleted if some other
39272** process has it open.  Sometimes a virus scanner or indexing program
39273** will open a journal file shortly after it is created in order to do
39274** whatever it does.  While this other process is holding the
39275** file open, we will be unable to delete it.  To work around this
39276** problem, we delay 100 milliseconds and try to delete again.  Up
39277** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
39278** up and returning an error.
39279*/
39280static int winDelete(
39281  sqlite3_vfs *pVfs,          /* Not used on win32 */
39282  const char *zFilename,      /* Name of file to delete */
39283  int syncDir                 /* Not used on win32 */
39284){
39285  int cnt = 0;
39286  int rc;
39287  DWORD attr;
39288  DWORD lastErrno = 0;
39289  void *zConverted;
39290  UNUSED_PARAMETER(pVfs);
39291  UNUSED_PARAMETER(syncDir);
39292
39293  SimulateIOError(return SQLITE_IOERR_DELETE);
39294  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
39295
39296  zConverted = winConvertFromUtf8Filename(zFilename);
39297  if( zConverted==0 ){
39298    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
39299    return SQLITE_IOERR_NOMEM;
39300  }
39301  if( osIsNT() ){
39302    do {
39303#if SQLITE_OS_WINRT
39304      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
39305      memset(&sAttrData, 0, sizeof(sAttrData));
39306      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
39307                                  &sAttrData) ){
39308        attr = sAttrData.dwFileAttributes;
39309      }else{
39310        lastErrno = osGetLastError();
39311        if( lastErrno==ERROR_FILE_NOT_FOUND
39312         || lastErrno==ERROR_PATH_NOT_FOUND ){
39313          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39314        }else{
39315          rc = SQLITE_ERROR;
39316        }
39317        break;
39318      }
39319#else
39320      attr = osGetFileAttributesW(zConverted);
39321#endif
39322      if ( attr==INVALID_FILE_ATTRIBUTES ){
39323        lastErrno = osGetLastError();
39324        if( lastErrno==ERROR_FILE_NOT_FOUND
39325         || lastErrno==ERROR_PATH_NOT_FOUND ){
39326          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39327        }else{
39328          rc = SQLITE_ERROR;
39329        }
39330        break;
39331      }
39332      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
39333        rc = SQLITE_ERROR; /* Files only. */
39334        break;
39335      }
39336      if ( osDeleteFileW(zConverted) ){
39337        rc = SQLITE_OK; /* Deleted OK. */
39338        break;
39339      }
39340      if ( !winRetryIoerr(&cnt, &lastErrno) ){
39341        rc = SQLITE_ERROR; /* No more retries. */
39342        break;
39343      }
39344    } while(1);
39345  }
39346#ifdef SQLITE_WIN32_HAS_ANSI
39347  else{
39348    do {
39349      attr = osGetFileAttributesA(zConverted);
39350      if ( attr==INVALID_FILE_ATTRIBUTES ){
39351        lastErrno = osGetLastError();
39352        if( lastErrno==ERROR_FILE_NOT_FOUND
39353         || lastErrno==ERROR_PATH_NOT_FOUND ){
39354          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39355        }else{
39356          rc = SQLITE_ERROR;
39357        }
39358        break;
39359      }
39360      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
39361        rc = SQLITE_ERROR; /* Files only. */
39362        break;
39363      }
39364      if ( osDeleteFileA(zConverted) ){
39365        rc = SQLITE_OK; /* Deleted OK. */
39366        break;
39367      }
39368      if ( !winRetryIoerr(&cnt, &lastErrno) ){
39369        rc = SQLITE_ERROR; /* No more retries. */
39370        break;
39371      }
39372    } while(1);
39373  }
39374#endif
39375  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
39376    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
39377  }else{
39378    winLogIoerr(cnt, __LINE__);
39379  }
39380  sqlite3_free(zConverted);
39381  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
39382  return rc;
39383}
39384
39385/*
39386** Check the existence and status of a file.
39387*/
39388static int winAccess(
39389  sqlite3_vfs *pVfs,         /* Not used on win32 */
39390  const char *zFilename,     /* Name of file to check */
39391  int flags,                 /* Type of test to make on this file */
39392  int *pResOut               /* OUT: Result */
39393){
39394  DWORD attr;
39395  int rc = 0;
39396  DWORD lastErrno = 0;
39397  void *zConverted;
39398  UNUSED_PARAMETER(pVfs);
39399
39400  SimulateIOError( return SQLITE_IOERR_ACCESS; );
39401  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
39402           zFilename, flags, pResOut));
39403
39404  zConverted = winConvertFromUtf8Filename(zFilename);
39405  if( zConverted==0 ){
39406    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
39407    return SQLITE_IOERR_NOMEM;
39408  }
39409  if( osIsNT() ){
39410    int cnt = 0;
39411    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
39412    memset(&sAttrData, 0, sizeof(sAttrData));
39413    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
39414                             GetFileExInfoStandard,
39415                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
39416    if( rc ){
39417      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
39418      ** as if it does not exist.
39419      */
39420      if(    flags==SQLITE_ACCESS_EXISTS
39421          && sAttrData.nFileSizeHigh==0
39422          && sAttrData.nFileSizeLow==0 ){
39423        attr = INVALID_FILE_ATTRIBUTES;
39424      }else{
39425        attr = sAttrData.dwFileAttributes;
39426      }
39427    }else{
39428      winLogIoerr(cnt, __LINE__);
39429      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
39430        sqlite3_free(zConverted);
39431        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
39432                           zFilename);
39433      }else{
39434        attr = INVALID_FILE_ATTRIBUTES;
39435      }
39436    }
39437  }
39438#ifdef SQLITE_WIN32_HAS_ANSI
39439  else{
39440    attr = osGetFileAttributesA((char*)zConverted);
39441  }
39442#endif
39443  sqlite3_free(zConverted);
39444  switch( flags ){
39445    case SQLITE_ACCESS_READ:
39446    case SQLITE_ACCESS_EXISTS:
39447      rc = attr!=INVALID_FILE_ATTRIBUTES;
39448      break;
39449    case SQLITE_ACCESS_READWRITE:
39450      rc = attr!=INVALID_FILE_ATTRIBUTES &&
39451             (attr & FILE_ATTRIBUTE_READONLY)==0;
39452      break;
39453    default:
39454      assert(!"Invalid flags argument");
39455  }
39456  *pResOut = rc;
39457  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
39458           zFilename, pResOut, *pResOut));
39459  return SQLITE_OK;
39460}
39461
39462/*
39463** Returns non-zero if the specified path name starts with a drive letter
39464** followed by a colon character.
39465*/
39466static BOOL winIsDriveLetterAndColon(
39467  const char *zPathname
39468){
39469  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
39470}
39471
39472/*
39473** Returns non-zero if the specified path name should be used verbatim.  If
39474** non-zero is returned from this function, the calling function must simply
39475** use the provided path name verbatim -OR- resolve it into a full path name
39476** using the GetFullPathName Win32 API function (if available).
39477*/
39478static BOOL winIsVerbatimPathname(
39479  const char *zPathname
39480){
39481  /*
39482  ** If the path name starts with a forward slash or a backslash, it is either
39483  ** a legal UNC name, a volume relative path, or an absolute path name in the
39484  ** "Unix" format on Windows.  There is no easy way to differentiate between
39485  ** the final two cases; therefore, we return the safer return value of TRUE
39486  ** so that callers of this function will simply use it verbatim.
39487  */
39488  if ( winIsDirSep(zPathname[0]) ){
39489    return TRUE;
39490  }
39491
39492  /*
39493  ** If the path name starts with a letter and a colon it is either a volume
39494  ** relative path or an absolute path.  Callers of this function must not
39495  ** attempt to treat it as a relative path name (i.e. they should simply use
39496  ** it verbatim).
39497  */
39498  if ( winIsDriveLetterAndColon(zPathname) ){
39499    return TRUE;
39500  }
39501
39502  /*
39503  ** If we get to this point, the path name should almost certainly be a purely
39504  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
39505  */
39506  return FALSE;
39507}
39508
39509/*
39510** Turn a relative pathname into a full pathname.  Write the full
39511** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
39512** bytes in size.
39513*/
39514static int winFullPathname(
39515  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
39516  const char *zRelative,        /* Possibly relative input path */
39517  int nFull,                    /* Size of output buffer in bytes */
39518  char *zFull                   /* Output buffer */
39519){
39520
39521#if defined(__CYGWIN__)
39522  SimulateIOError( return SQLITE_ERROR );
39523  UNUSED_PARAMETER(nFull);
39524  assert( nFull>=pVfs->mxPathname );
39525  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39526    /*
39527    ** NOTE: We are dealing with a relative path name and the data
39528    **       directory has been set.  Therefore, use it as the basis
39529    **       for converting the relative path name to an absolute
39530    **       one by prepending the data directory and a slash.
39531    */
39532    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
39533    if( !zOut ){
39534      return SQLITE_IOERR_NOMEM;
39535    }
39536    if( cygwin_conv_path(
39537            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
39538            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
39539      sqlite3_free(zOut);
39540      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
39541                         "winFullPathname1", zRelative);
39542    }else{
39543      char *zUtf8 = winConvertToUtf8Filename(zOut);
39544      if( !zUtf8 ){
39545        sqlite3_free(zOut);
39546        return SQLITE_IOERR_NOMEM;
39547      }
39548      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39549                       sqlite3_data_directory, winGetDirSep(), zUtf8);
39550      sqlite3_free(zUtf8);
39551      sqlite3_free(zOut);
39552    }
39553  }else{
39554    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
39555    if( !zOut ){
39556      return SQLITE_IOERR_NOMEM;
39557    }
39558    if( cygwin_conv_path(
39559            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
39560            zRelative, zOut, pVfs->mxPathname+1)<0 ){
39561      sqlite3_free(zOut);
39562      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
39563                         "winFullPathname2", zRelative);
39564    }else{
39565      char *zUtf8 = winConvertToUtf8Filename(zOut);
39566      if( !zUtf8 ){
39567        sqlite3_free(zOut);
39568        return SQLITE_IOERR_NOMEM;
39569      }
39570      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
39571      sqlite3_free(zUtf8);
39572      sqlite3_free(zOut);
39573    }
39574  }
39575  return SQLITE_OK;
39576#endif
39577
39578#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
39579  SimulateIOError( return SQLITE_ERROR );
39580  /* WinCE has no concept of a relative pathname, or so I am told. */
39581  /* WinRT has no way to convert a relative path to an absolute one. */
39582  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39583    /*
39584    ** NOTE: We are dealing with a relative path name and the data
39585    **       directory has been set.  Therefore, use it as the basis
39586    **       for converting the relative path name to an absolute
39587    **       one by prepending the data directory and a backslash.
39588    */
39589    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39590                     sqlite3_data_directory, winGetDirSep(), zRelative);
39591  }else{
39592    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
39593  }
39594  return SQLITE_OK;
39595#endif
39596
39597#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
39598  DWORD nByte;
39599  void *zConverted;
39600  char *zOut;
39601
39602  /* If this path name begins with "/X:", where "X" is any alphabetic
39603  ** character, discard the initial "/" from the pathname.
39604  */
39605  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
39606    zRelative++;
39607  }
39608
39609  /* It's odd to simulate an io-error here, but really this is just
39610  ** using the io-error infrastructure to test that SQLite handles this
39611  ** function failing. This function could fail if, for example, the
39612  ** current working directory has been unlinked.
39613  */
39614  SimulateIOError( return SQLITE_ERROR );
39615  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39616    /*
39617    ** NOTE: We are dealing with a relative path name and the data
39618    **       directory has been set.  Therefore, use it as the basis
39619    **       for converting the relative path name to an absolute
39620    **       one by prepending the data directory and a backslash.
39621    */
39622    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39623                     sqlite3_data_directory, winGetDirSep(), zRelative);
39624    return SQLITE_OK;
39625  }
39626  zConverted = winConvertFromUtf8Filename(zRelative);
39627  if( zConverted==0 ){
39628    return SQLITE_IOERR_NOMEM;
39629  }
39630  if( osIsNT() ){
39631    LPWSTR zTemp;
39632    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
39633    if( nByte==0 ){
39634      sqlite3_free(zConverted);
39635      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39636                         "winFullPathname1", zRelative);
39637    }
39638    nByte += 3;
39639    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
39640    if( zTemp==0 ){
39641      sqlite3_free(zConverted);
39642      return SQLITE_IOERR_NOMEM;
39643    }
39644    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
39645    if( nByte==0 ){
39646      sqlite3_free(zConverted);
39647      sqlite3_free(zTemp);
39648      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39649                         "winFullPathname2", zRelative);
39650    }
39651    sqlite3_free(zConverted);
39652    zOut = winUnicodeToUtf8(zTemp);
39653    sqlite3_free(zTemp);
39654  }
39655#ifdef SQLITE_WIN32_HAS_ANSI
39656  else{
39657    char *zTemp;
39658    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
39659    if( nByte==0 ){
39660      sqlite3_free(zConverted);
39661      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39662                         "winFullPathname3", zRelative);
39663    }
39664    nByte += 3;
39665    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
39666    if( zTemp==0 ){
39667      sqlite3_free(zConverted);
39668      return SQLITE_IOERR_NOMEM;
39669    }
39670    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
39671    if( nByte==0 ){
39672      sqlite3_free(zConverted);
39673      sqlite3_free(zTemp);
39674      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39675                         "winFullPathname4", zRelative);
39676    }
39677    sqlite3_free(zConverted);
39678    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
39679    sqlite3_free(zTemp);
39680  }
39681#endif
39682  if( zOut ){
39683    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
39684    sqlite3_free(zOut);
39685    return SQLITE_OK;
39686  }else{
39687    return SQLITE_IOERR_NOMEM;
39688  }
39689#endif
39690}
39691
39692#ifndef SQLITE_OMIT_LOAD_EXTENSION
39693/*
39694** Interfaces for opening a shared library, finding entry points
39695** within the shared library, and closing the shared library.
39696*/
39697static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
39698  HANDLE h;
39699#if defined(__CYGWIN__)
39700  int nFull = pVfs->mxPathname+1;
39701  char *zFull = sqlite3MallocZero( nFull );
39702  void *zConverted = 0;
39703  if( zFull==0 ){
39704    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39705    return 0;
39706  }
39707  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
39708    sqlite3_free(zFull);
39709    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39710    return 0;
39711  }
39712  zConverted = winConvertFromUtf8Filename(zFull);
39713  sqlite3_free(zFull);
39714#else
39715  void *zConverted = winConvertFromUtf8Filename(zFilename);
39716  UNUSED_PARAMETER(pVfs);
39717#endif
39718  if( zConverted==0 ){
39719    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39720    return 0;
39721  }
39722  if( osIsNT() ){
39723#if SQLITE_OS_WINRT
39724    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
39725#else
39726    h = osLoadLibraryW((LPCWSTR)zConverted);
39727#endif
39728  }
39729#ifdef SQLITE_WIN32_HAS_ANSI
39730  else{
39731    h = osLoadLibraryA((char*)zConverted);
39732  }
39733#endif
39734  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
39735  sqlite3_free(zConverted);
39736  return (void*)h;
39737}
39738static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
39739  UNUSED_PARAMETER(pVfs);
39740  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
39741}
39742static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
39743  FARPROC proc;
39744  UNUSED_PARAMETER(pVfs);
39745  proc = osGetProcAddressA((HANDLE)pH, zSym);
39746  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
39747           (void*)pH, zSym, (void*)proc));
39748  return (void(*)(void))proc;
39749}
39750static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
39751  UNUSED_PARAMETER(pVfs);
39752  osFreeLibrary((HANDLE)pHandle);
39753  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
39754}
39755#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
39756  #define winDlOpen  0
39757  #define winDlError 0
39758  #define winDlSym   0
39759  #define winDlClose 0
39760#endif
39761
39762
39763/*
39764** Write up to nBuf bytes of randomness into zBuf.
39765*/
39766static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39767  int n = 0;
39768  UNUSED_PARAMETER(pVfs);
39769#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
39770  n = nBuf;
39771  memset(zBuf, 0, nBuf);
39772#else
39773  if( sizeof(SYSTEMTIME)<=nBuf-n ){
39774    SYSTEMTIME x;
39775    osGetSystemTime(&x);
39776    memcpy(&zBuf[n], &x, sizeof(x));
39777    n += sizeof(x);
39778  }
39779  if( sizeof(DWORD)<=nBuf-n ){
39780    DWORD pid = osGetCurrentProcessId();
39781    memcpy(&zBuf[n], &pid, sizeof(pid));
39782    n += sizeof(pid);
39783  }
39784#if SQLITE_OS_WINRT
39785  if( sizeof(ULONGLONG)<=nBuf-n ){
39786    ULONGLONG cnt = osGetTickCount64();
39787    memcpy(&zBuf[n], &cnt, sizeof(cnt));
39788    n += sizeof(cnt);
39789  }
39790#else
39791  if( sizeof(DWORD)<=nBuf-n ){
39792    DWORD cnt = osGetTickCount();
39793    memcpy(&zBuf[n], &cnt, sizeof(cnt));
39794    n += sizeof(cnt);
39795  }
39796#endif
39797  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
39798    LARGE_INTEGER i;
39799    osQueryPerformanceCounter(&i);
39800    memcpy(&zBuf[n], &i, sizeof(i));
39801    n += sizeof(i);
39802  }
39803#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39804  if( sizeof(UUID)<=nBuf-n ){
39805    UUID id;
39806    memset(&id, 0, sizeof(UUID));
39807    osUuidCreate(&id);
39808    memcpy(&zBuf[n], &id, sizeof(UUID));
39809    n += sizeof(UUID);
39810  }
39811  if( sizeof(UUID)<=nBuf-n ){
39812    UUID id;
39813    memset(&id, 0, sizeof(UUID));
39814    osUuidCreateSequential(&id);
39815    memcpy(&zBuf[n], &id, sizeof(UUID));
39816    n += sizeof(UUID);
39817  }
39818#endif
39819#endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
39820  return n;
39821}
39822
39823
39824/*
39825** Sleep for a little while.  Return the amount of time slept.
39826*/
39827static int winSleep(sqlite3_vfs *pVfs, int microsec){
39828  sqlite3_win32_sleep((microsec+999)/1000);
39829  UNUSED_PARAMETER(pVfs);
39830  return ((microsec+999)/1000)*1000;
39831}
39832
39833/*
39834** The following variable, if set to a non-zero value, is interpreted as
39835** the number of seconds since 1970 and is used to set the result of
39836** sqlite3OsCurrentTime() during testing.
39837*/
39838#ifdef SQLITE_TEST
39839SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
39840#endif
39841
39842/*
39843** Find the current time (in Universal Coordinated Time).  Write into *piNow
39844** the current time and date as a Julian Day number times 86_400_000.  In
39845** other words, write into *piNow the number of milliseconds since the Julian
39846** epoch of noon in Greenwich on November 24, 4714 B.C according to the
39847** proleptic Gregorian calendar.
39848**
39849** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
39850** cannot be found.
39851*/
39852static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
39853  /* FILETIME structure is a 64-bit value representing the number of
39854     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
39855  */
39856  FILETIME ft;
39857  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
39858#ifdef SQLITE_TEST
39859  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
39860#endif
39861  /* 2^32 - to avoid use of LL and warnings in gcc */
39862  static const sqlite3_int64 max32BitValue =
39863      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
39864      (sqlite3_int64)294967296;
39865
39866#if SQLITE_OS_WINCE
39867  SYSTEMTIME time;
39868  osGetSystemTime(&time);
39869  /* if SystemTimeToFileTime() fails, it returns zero. */
39870  if (!osSystemTimeToFileTime(&time,&ft)){
39871    return SQLITE_ERROR;
39872  }
39873#else
39874  osGetSystemTimeAsFileTime( &ft );
39875#endif
39876
39877  *piNow = winFiletimeEpoch +
39878            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
39879               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
39880
39881#ifdef SQLITE_TEST
39882  if( sqlite3_current_time ){
39883    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
39884  }
39885#endif
39886  UNUSED_PARAMETER(pVfs);
39887  return SQLITE_OK;
39888}
39889
39890/*
39891** Find the current time (in Universal Coordinated Time).  Write the
39892** current time and date as a Julian Day number into *prNow and
39893** return 0.  Return 1 if the time and date cannot be found.
39894*/
39895static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
39896  int rc;
39897  sqlite3_int64 i;
39898  rc = winCurrentTimeInt64(pVfs, &i);
39899  if( !rc ){
39900    *prNow = i/86400000.0;
39901  }
39902  return rc;
39903}
39904
39905/*
39906** The idea is that this function works like a combination of
39907** GetLastError() and FormatMessage() on Windows (or errno and
39908** strerror_r() on Unix). After an error is returned by an OS
39909** function, SQLite calls this function with zBuf pointing to
39910** a buffer of nBuf bytes. The OS layer should populate the
39911** buffer with a nul-terminated UTF-8 encoded error message
39912** describing the last IO error to have occurred within the calling
39913** thread.
39914**
39915** If the error message is too large for the supplied buffer,
39916** it should be truncated. The return value of xGetLastError
39917** is zero if the error message fits in the buffer, or non-zero
39918** otherwise (if the message was truncated). If non-zero is returned,
39919** then it is not necessary to include the nul-terminator character
39920** in the output buffer.
39921**
39922** Not supplying an error message will have no adverse effect
39923** on SQLite. It is fine to have an implementation that never
39924** returns an error message:
39925**
39926**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39927**     assert(zBuf[0]=='\0');
39928**     return 0;
39929**   }
39930**
39931** However if an error message is supplied, it will be incorporated
39932** by sqlite into the error message available to the user using
39933** sqlite3_errmsg(), possibly making IO errors easier to debug.
39934*/
39935static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39936  UNUSED_PARAMETER(pVfs);
39937  return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
39938}
39939
39940/*
39941** Initialize and deinitialize the operating system interface.
39942*/
39943SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
39944  static sqlite3_vfs winVfs = {
39945    3,                   /* iVersion */
39946    sizeof(winFile),     /* szOsFile */
39947    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
39948    0,                   /* pNext */
39949    "win32",             /* zName */
39950    0,                   /* pAppData */
39951    winOpen,             /* xOpen */
39952    winDelete,           /* xDelete */
39953    winAccess,           /* xAccess */
39954    winFullPathname,     /* xFullPathname */
39955    winDlOpen,           /* xDlOpen */
39956    winDlError,          /* xDlError */
39957    winDlSym,            /* xDlSym */
39958    winDlClose,          /* xDlClose */
39959    winRandomness,       /* xRandomness */
39960    winSleep,            /* xSleep */
39961    winCurrentTime,      /* xCurrentTime */
39962    winGetLastError,     /* xGetLastError */
39963    winCurrentTimeInt64, /* xCurrentTimeInt64 */
39964    winSetSystemCall,    /* xSetSystemCall */
39965    winGetSystemCall,    /* xGetSystemCall */
39966    winNextSystemCall,   /* xNextSystemCall */
39967  };
39968#if defined(SQLITE_WIN32_HAS_WIDE)
39969  static sqlite3_vfs winLongPathVfs = {
39970    3,                   /* iVersion */
39971    sizeof(winFile),     /* szOsFile */
39972    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
39973    0,                   /* pNext */
39974    "win32-longpath",    /* zName */
39975    0,                   /* pAppData */
39976    winOpen,             /* xOpen */
39977    winDelete,           /* xDelete */
39978    winAccess,           /* xAccess */
39979    winFullPathname,     /* xFullPathname */
39980    winDlOpen,           /* xDlOpen */
39981    winDlError,          /* xDlError */
39982    winDlSym,            /* xDlSym */
39983    winDlClose,          /* xDlClose */
39984    winRandomness,       /* xRandomness */
39985    winSleep,            /* xSleep */
39986    winCurrentTime,      /* xCurrentTime */
39987    winGetLastError,     /* xGetLastError */
39988    winCurrentTimeInt64, /* xCurrentTimeInt64 */
39989    winSetSystemCall,    /* xSetSystemCall */
39990    winGetSystemCall,    /* xGetSystemCall */
39991    winNextSystemCall,   /* xNextSystemCall */
39992  };
39993#endif
39994
39995  /* Double-check that the aSyscall[] array has been constructed
39996  ** correctly.  See ticket [bb3a86e890c8e96ab] */
39997  assert( ArraySize(aSyscall)==80 );
39998
39999  /* get memory map allocation granularity */
40000  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
40001#if SQLITE_OS_WINRT
40002  osGetNativeSystemInfo(&winSysInfo);
40003#else
40004  osGetSystemInfo(&winSysInfo);
40005#endif
40006  assert( winSysInfo.dwAllocationGranularity>0 );
40007  assert( winSysInfo.dwPageSize>0 );
40008
40009  sqlite3_vfs_register(&winVfs, 1);
40010
40011#if defined(SQLITE_WIN32_HAS_WIDE)
40012  sqlite3_vfs_register(&winLongPathVfs, 0);
40013#endif
40014
40015  return SQLITE_OK;
40016}
40017
40018SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
40019#if SQLITE_OS_WINRT
40020  if( sleepObj!=NULL ){
40021    osCloseHandle(sleepObj);
40022    sleepObj = NULL;
40023  }
40024#endif
40025  return SQLITE_OK;
40026}
40027
40028#endif /* SQLITE_OS_WIN */
40029
40030/************** End of os_win.c **********************************************/
40031/************** Begin file bitvec.c ******************************************/
40032/*
40033** 2008 February 16
40034**
40035** The author disclaims copyright to this source code.  In place of
40036** a legal notice, here is a blessing:
40037**
40038**    May you do good and not evil.
40039**    May you find forgiveness for yourself and forgive others.
40040**    May you share freely, never taking more than you give.
40041**
40042*************************************************************************
40043** This file implements an object that represents a fixed-length
40044** bitmap.  Bits are numbered starting with 1.
40045**
40046** A bitmap is used to record which pages of a database file have been
40047** journalled during a transaction, or which pages have the "dont-write"
40048** property.  Usually only a few pages are meet either condition.
40049** So the bitmap is usually sparse and has low cardinality.
40050** But sometimes (for example when during a DROP of a large table) most
40051** or all of the pages in a database can get journalled.  In those cases,
40052** the bitmap becomes dense with high cardinality.  The algorithm needs
40053** to handle both cases well.
40054**
40055** The size of the bitmap is fixed when the object is created.
40056**
40057** All bits are clear when the bitmap is created.  Individual bits
40058** may be set or cleared one at a time.
40059**
40060** Test operations are about 100 times more common that set operations.
40061** Clear operations are exceedingly rare.  There are usually between
40062** 5 and 500 set operations per Bitvec object, though the number of sets can
40063** sometimes grow into tens of thousands or larger.  The size of the
40064** Bitvec object is the number of pages in the database file at the
40065** start of a transaction, and is thus usually less than a few thousand,
40066** but can be as large as 2 billion for a really big database.
40067*/
40068/* #include "sqliteInt.h" */
40069
40070/* Size of the Bitvec structure in bytes. */
40071#define BITVEC_SZ        512
40072
40073/* Round the union size down to the nearest pointer boundary, since that's how
40074** it will be aligned within the Bitvec struct. */
40075#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
40076
40077/* Type of the array "element" for the bitmap representation.
40078** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
40079** Setting this to the "natural word" size of your CPU may improve
40080** performance. */
40081#define BITVEC_TELEM     u8
40082/* Size, in bits, of the bitmap element. */
40083#define BITVEC_SZELEM    8
40084/* Number of elements in a bitmap array. */
40085#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
40086/* Number of bits in the bitmap array. */
40087#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
40088
40089/* Number of u32 values in hash table. */
40090#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
40091/* Maximum number of entries in hash table before
40092** sub-dividing and re-hashing. */
40093#define BITVEC_MXHASH    (BITVEC_NINT/2)
40094/* Hashing function for the aHash representation.
40095** Empirical testing showed that the *37 multiplier
40096** (an arbitrary prime)in the hash function provided
40097** no fewer collisions than the no-op *1. */
40098#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
40099
40100#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
40101
40102
40103/*
40104** A bitmap is an instance of the following structure.
40105**
40106** This bitmap records the existence of zero or more bits
40107** with values between 1 and iSize, inclusive.
40108**
40109** There are three possible representations of the bitmap.
40110** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
40111** bitmap.  The least significant bit is bit 1.
40112**
40113** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
40114** a hash table that will hold up to BITVEC_MXHASH distinct values.
40115**
40116** Otherwise, the value i is redirected into one of BITVEC_NPTR
40117** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
40118** handles up to iDivisor separate values of i.  apSub[0] holds
40119** values between 1 and iDivisor.  apSub[1] holds values between
40120** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
40121** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
40122** to hold deal with values between 1 and iDivisor.
40123*/
40124struct Bitvec {
40125  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
40126  u32 nSet;       /* Number of bits that are set - only valid for aHash
40127                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
40128                  ** this would be 125. */
40129  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
40130                  /* Should >=0 for apSub element. */
40131                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
40132                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
40133  union {
40134    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
40135    u32 aHash[BITVEC_NINT];      /* Hash table representation */
40136    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
40137  } u;
40138};
40139
40140/*
40141** Create a new bitmap object able to handle bits between 0 and iSize,
40142** inclusive.  Return a pointer to the new object.  Return NULL if
40143** malloc fails.
40144*/
40145SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
40146  Bitvec *p;
40147  assert( sizeof(*p)==BITVEC_SZ );
40148  p = sqlite3MallocZero( sizeof(*p) );
40149  if( p ){
40150    p->iSize = iSize;
40151  }
40152  return p;
40153}
40154
40155/*
40156** Check to see if the i-th bit is set.  Return true or false.
40157** If p is NULL (if the bitmap has not been created) or if
40158** i is out of range, then return false.
40159*/
40160SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
40161  assert( p!=0 );
40162  i--;
40163  if( i>=p->iSize ) return 0;
40164  while( p->iDivisor ){
40165    u32 bin = i/p->iDivisor;
40166    i = i%p->iDivisor;
40167    p = p->u.apSub[bin];
40168    if (!p) {
40169      return 0;
40170    }
40171  }
40172  if( p->iSize<=BITVEC_NBIT ){
40173    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
40174  } else{
40175    u32 h = BITVEC_HASH(i++);
40176    while( p->u.aHash[h] ){
40177      if( p->u.aHash[h]==i ) return 1;
40178      h = (h+1) % BITVEC_NINT;
40179    }
40180    return 0;
40181  }
40182}
40183SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
40184  return p!=0 && sqlite3BitvecTestNotNull(p,i);
40185}
40186
40187/*
40188** Set the i-th bit.  Return 0 on success and an error code if
40189** anything goes wrong.
40190**
40191** This routine might cause sub-bitmaps to be allocated.  Failing
40192** to get the memory needed to hold the sub-bitmap is the only
40193** that can go wrong with an insert, assuming p and i are valid.
40194**
40195** The calling function must ensure that p is a valid Bitvec object
40196** and that the value for "i" is within range of the Bitvec object.
40197** Otherwise the behavior is undefined.
40198*/
40199SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
40200  u32 h;
40201  if( p==0 ) return SQLITE_OK;
40202  assert( i>0 );
40203  assert( i<=p->iSize );
40204  i--;
40205  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
40206    u32 bin = i/p->iDivisor;
40207    i = i%p->iDivisor;
40208    if( p->u.apSub[bin]==0 ){
40209      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
40210      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
40211    }
40212    p = p->u.apSub[bin];
40213  }
40214  if( p->iSize<=BITVEC_NBIT ){
40215    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
40216    return SQLITE_OK;
40217  }
40218  h = BITVEC_HASH(i++);
40219  /* if there wasn't a hash collision, and this doesn't */
40220  /* completely fill the hash, then just add it without */
40221  /* worring about sub-dividing and re-hashing. */
40222  if( !p->u.aHash[h] ){
40223    if (p->nSet<(BITVEC_NINT-1)) {
40224      goto bitvec_set_end;
40225    } else {
40226      goto bitvec_set_rehash;
40227    }
40228  }
40229  /* there was a collision, check to see if it's already */
40230  /* in hash, if not, try to find a spot for it */
40231  do {
40232    if( p->u.aHash[h]==i ) return SQLITE_OK;
40233    h++;
40234    if( h>=BITVEC_NINT ) h = 0;
40235  } while( p->u.aHash[h] );
40236  /* we didn't find it in the hash.  h points to the first */
40237  /* available free spot. check to see if this is going to */
40238  /* make our hash too "full".  */
40239bitvec_set_rehash:
40240  if( p->nSet>=BITVEC_MXHASH ){
40241    unsigned int j;
40242    int rc;
40243    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
40244    if( aiValues==0 ){
40245      return SQLITE_NOMEM;
40246    }else{
40247      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
40248      memset(p->u.apSub, 0, sizeof(p->u.apSub));
40249      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
40250      rc = sqlite3BitvecSet(p, i);
40251      for(j=0; j<BITVEC_NINT; j++){
40252        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
40253      }
40254      sqlite3StackFree(0, aiValues);
40255      return rc;
40256    }
40257  }
40258bitvec_set_end:
40259  p->nSet++;
40260  p->u.aHash[h] = i;
40261  return SQLITE_OK;
40262}
40263
40264/*
40265** Clear the i-th bit.
40266**
40267** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
40268** that BitvecClear can use to rebuilt its hash table.
40269*/
40270SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
40271  if( p==0 ) return;
40272  assert( i>0 );
40273  i--;
40274  while( p->iDivisor ){
40275    u32 bin = i/p->iDivisor;
40276    i = i%p->iDivisor;
40277    p = p->u.apSub[bin];
40278    if (!p) {
40279      return;
40280    }
40281  }
40282  if( p->iSize<=BITVEC_NBIT ){
40283    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
40284  }else{
40285    unsigned int j;
40286    u32 *aiValues = pBuf;
40287    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
40288    memset(p->u.aHash, 0, sizeof(p->u.aHash));
40289    p->nSet = 0;
40290    for(j=0; j<BITVEC_NINT; j++){
40291      if( aiValues[j] && aiValues[j]!=(i+1) ){
40292        u32 h = BITVEC_HASH(aiValues[j]-1);
40293        p->nSet++;
40294        while( p->u.aHash[h] ){
40295          h++;
40296          if( h>=BITVEC_NINT ) h = 0;
40297        }
40298        p->u.aHash[h] = aiValues[j];
40299      }
40300    }
40301  }
40302}
40303
40304/*
40305** Destroy a bitmap object.  Reclaim all memory used.
40306*/
40307SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
40308  if( p==0 ) return;
40309  if( p->iDivisor ){
40310    unsigned int i;
40311    for(i=0; i<BITVEC_NPTR; i++){
40312      sqlite3BitvecDestroy(p->u.apSub[i]);
40313    }
40314  }
40315  sqlite3_free(p);
40316}
40317
40318/*
40319** Return the value of the iSize parameter specified when Bitvec *p
40320** was created.
40321*/
40322SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
40323  return p->iSize;
40324}
40325
40326#ifndef SQLITE_OMIT_BUILTIN_TEST
40327/*
40328** Let V[] be an array of unsigned characters sufficient to hold
40329** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
40330** Then the following macros can be used to set, clear, or test
40331** individual bits within V.
40332*/
40333#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
40334#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
40335#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
40336
40337/*
40338** This routine runs an extensive test of the Bitvec code.
40339**
40340** The input is an array of integers that acts as a program
40341** to test the Bitvec.  The integers are opcodes followed
40342** by 0, 1, or 3 operands, depending on the opcode.  Another
40343** opcode follows immediately after the last operand.
40344**
40345** There are 6 opcodes numbered from 0 through 5.  0 is the
40346** "halt" opcode and causes the test to end.
40347**
40348**    0          Halt and return the number of errors
40349**    1 N S X    Set N bits beginning with S and incrementing by X
40350**    2 N S X    Clear N bits beginning with S and incrementing by X
40351**    3 N        Set N randomly chosen bits
40352**    4 N        Clear N randomly chosen bits
40353**    5 N S X    Set N bits from S increment X in array only, not in bitvec
40354**
40355** The opcodes 1 through 4 perform set and clear operations are performed
40356** on both a Bitvec object and on a linear array of bits obtained from malloc.
40357** Opcode 5 works on the linear array only, not on the Bitvec.
40358** Opcode 5 is used to deliberately induce a fault in order to
40359** confirm that error detection works.
40360**
40361** At the conclusion of the test the linear array is compared
40362** against the Bitvec object.  If there are any differences,
40363** an error is returned.  If they are the same, zero is returned.
40364**
40365** If a memory allocation error occurs, return -1.
40366*/
40367SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
40368  Bitvec *pBitvec = 0;
40369  unsigned char *pV = 0;
40370  int rc = -1;
40371  int i, nx, pc, op;
40372  void *pTmpSpace;
40373
40374  /* Allocate the Bitvec to be tested and a linear array of
40375  ** bits to act as the reference */
40376  pBitvec = sqlite3BitvecCreate( sz );
40377  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
40378  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
40379  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
40380
40381  /* NULL pBitvec tests */
40382  sqlite3BitvecSet(0, 1);
40383  sqlite3BitvecClear(0, 1, pTmpSpace);
40384
40385  /* Run the program */
40386  pc = 0;
40387  while( (op = aOp[pc])!=0 ){
40388    switch( op ){
40389      case 1:
40390      case 2:
40391      case 5: {
40392        nx = 4;
40393        i = aOp[pc+2] - 1;
40394        aOp[pc+2] += aOp[pc+3];
40395        break;
40396      }
40397      case 3:
40398      case 4:
40399      default: {
40400        nx = 2;
40401        sqlite3_randomness(sizeof(i), &i);
40402        break;
40403      }
40404    }
40405    if( (--aOp[pc+1]) > 0 ) nx = 0;
40406    pc += nx;
40407    i = (i & 0x7fffffff)%sz;
40408    if( (op & 1)!=0 ){
40409      SETBIT(pV, (i+1));
40410      if( op!=5 ){
40411        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
40412      }
40413    }else{
40414      CLEARBIT(pV, (i+1));
40415      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
40416    }
40417  }
40418
40419  /* Test to make sure the linear array exactly matches the
40420  ** Bitvec object.  Start with the assumption that they do
40421  ** match (rc==0).  Change rc to non-zero if a discrepancy
40422  ** is found.
40423  */
40424  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
40425          + sqlite3BitvecTest(pBitvec, 0)
40426          + (sqlite3BitvecSize(pBitvec) - sz);
40427  for(i=1; i<=sz; i++){
40428    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
40429      rc = i;
40430      break;
40431    }
40432  }
40433
40434  /* Free allocated structure */
40435bitvec_end:
40436  sqlite3_free(pTmpSpace);
40437  sqlite3_free(pV);
40438  sqlite3BitvecDestroy(pBitvec);
40439  return rc;
40440}
40441#endif /* SQLITE_OMIT_BUILTIN_TEST */
40442
40443/************** End of bitvec.c **********************************************/
40444/************** Begin file pcache.c ******************************************/
40445/*
40446** 2008 August 05
40447**
40448** The author disclaims copyright to this source code.  In place of
40449** a legal notice, here is a blessing:
40450**
40451**    May you do good and not evil.
40452**    May you find forgiveness for yourself and forgive others.
40453**    May you share freely, never taking more than you give.
40454**
40455*************************************************************************
40456** This file implements that page cache.
40457*/
40458/* #include "sqliteInt.h" */
40459
40460/*
40461** A complete page cache is an instance of this structure.
40462*/
40463struct PCache {
40464  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
40465  PgHdr *pSynced;                     /* Last synced page in dirty page list */
40466  int nRefSum;                        /* Sum of ref counts over all pages */
40467  int szCache;                        /* Configured cache size */
40468  int szPage;                         /* Size of every page in this cache */
40469  int szExtra;                        /* Size of extra space for each page */
40470  u8 bPurgeable;                      /* True if pages are on backing store */
40471  u8 eCreate;                         /* eCreate value for for xFetch() */
40472  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
40473  void *pStress;                      /* Argument to xStress */
40474  sqlite3_pcache *pCache;             /* Pluggable cache module */
40475};
40476
40477/********************************** Linked List Management ********************/
40478
40479/* Allowed values for second argument to pcacheManageDirtyList() */
40480#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
40481#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
40482#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
40483
40484/*
40485** Manage pPage's participation on the dirty list.  Bits of the addRemove
40486** argument determines what operation to do.  The 0x01 bit means first
40487** remove pPage from the dirty list.  The 0x02 means add pPage back to
40488** the dirty list.  Doing both moves pPage to the front of the dirty list.
40489*/
40490static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
40491  PCache *p = pPage->pCache;
40492
40493  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
40494    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
40495    assert( pPage->pDirtyPrev || pPage==p->pDirty );
40496
40497    /* Update the PCache1.pSynced variable if necessary. */
40498    if( p->pSynced==pPage ){
40499      PgHdr *pSynced = pPage->pDirtyPrev;
40500      while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
40501        pSynced = pSynced->pDirtyPrev;
40502      }
40503      p->pSynced = pSynced;
40504    }
40505
40506    if( pPage->pDirtyNext ){
40507      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
40508    }else{
40509      assert( pPage==p->pDirtyTail );
40510      p->pDirtyTail = pPage->pDirtyPrev;
40511    }
40512    if( pPage->pDirtyPrev ){
40513      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
40514    }else{
40515      assert( pPage==p->pDirty );
40516      p->pDirty = pPage->pDirtyNext;
40517      if( p->pDirty==0 && p->bPurgeable ){
40518        assert( p->eCreate==1 );
40519        p->eCreate = 2;
40520      }
40521    }
40522    pPage->pDirtyNext = 0;
40523    pPage->pDirtyPrev = 0;
40524  }
40525  if( addRemove & PCACHE_DIRTYLIST_ADD ){
40526    assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
40527
40528    pPage->pDirtyNext = p->pDirty;
40529    if( pPage->pDirtyNext ){
40530      assert( pPage->pDirtyNext->pDirtyPrev==0 );
40531      pPage->pDirtyNext->pDirtyPrev = pPage;
40532    }else{
40533      p->pDirtyTail = pPage;
40534      if( p->bPurgeable ){
40535        assert( p->eCreate==2 );
40536        p->eCreate = 1;
40537      }
40538    }
40539    p->pDirty = pPage;
40540    if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
40541      p->pSynced = pPage;
40542    }
40543  }
40544}
40545
40546/*
40547** Wrapper around the pluggable caches xUnpin method. If the cache is
40548** being used for an in-memory database, this function is a no-op.
40549*/
40550static void pcacheUnpin(PgHdr *p){
40551  if( p->pCache->bPurgeable ){
40552    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
40553  }
40554}
40555
40556/*
40557** Compute the number of pages of cache requested.  p->szCache is the
40558** cache size requested by the "PRAGMA cache_size" statement.
40559**
40560**
40561*/
40562static int numberOfCachePages(PCache *p){
40563  if( p->szCache>=0 ){
40564    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
40565    ** suggested cache size is set to N. */
40566    return p->szCache;
40567  }else{
40568    /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
40569    ** the number of cache pages is adjusted to use approximately abs(N*1024)
40570    ** bytes of memory. */
40571    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
40572  }
40573}
40574
40575/*************************************************** General Interfaces ******
40576**
40577** Initialize and shutdown the page cache subsystem. Neither of these
40578** functions are threadsafe.
40579*/
40580SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
40581  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
40582    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
40583    ** built-in default page cache is used instead of the application defined
40584    ** page cache. */
40585    sqlite3PCacheSetDefault();
40586  }
40587  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
40588}
40589SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
40590  if( sqlite3GlobalConfig.pcache2.xShutdown ){
40591    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
40592    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
40593  }
40594}
40595
40596/*
40597** Return the size in bytes of a PCache object.
40598*/
40599SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
40600
40601/*
40602** Create a new PCache object. Storage space to hold the object
40603** has already been allocated and is passed in as the p pointer.
40604** The caller discovers how much space needs to be allocated by
40605** calling sqlite3PcacheSize().
40606*/
40607SQLITE_PRIVATE int sqlite3PcacheOpen(
40608  int szPage,                  /* Size of every page */
40609  int szExtra,                 /* Extra space associated with each page */
40610  int bPurgeable,              /* True if pages are on backing store */
40611  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
40612  void *pStress,               /* Argument to xStress */
40613  PCache *p                    /* Preallocated space for the PCache */
40614){
40615  memset(p, 0, sizeof(PCache));
40616  p->szPage = 1;
40617  p->szExtra = szExtra;
40618  p->bPurgeable = bPurgeable;
40619  p->eCreate = 2;
40620  p->xStress = xStress;
40621  p->pStress = pStress;
40622  p->szCache = 100;
40623  return sqlite3PcacheSetPageSize(p, szPage);
40624}
40625
40626/*
40627** Change the page size for PCache object. The caller must ensure that there
40628** are no outstanding page references when this function is called.
40629*/
40630SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
40631  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
40632  if( pCache->szPage ){
40633    sqlite3_pcache *pNew;
40634    pNew = sqlite3GlobalConfig.pcache2.xCreate(
40635                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
40636                pCache->bPurgeable
40637    );
40638    if( pNew==0 ) return SQLITE_NOMEM;
40639    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
40640    if( pCache->pCache ){
40641      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
40642    }
40643    pCache->pCache = pNew;
40644    pCache->szPage = szPage;
40645  }
40646  return SQLITE_OK;
40647}
40648
40649/*
40650** Try to obtain a page from the cache.
40651**
40652** This routine returns a pointer to an sqlite3_pcache_page object if
40653** such an object is already in cache, or if a new one is created.
40654** This routine returns a NULL pointer if the object was not in cache
40655** and could not be created.
40656**
40657** The createFlags should be 0 to check for existing pages and should
40658** be 3 (not 1, but 3) to try to create a new page.
40659**
40660** If the createFlag is 0, then NULL is always returned if the page
40661** is not already in the cache.  If createFlag is 1, then a new page
40662** is created only if that can be done without spilling dirty pages
40663** and without exceeding the cache size limit.
40664**
40665** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
40666** initialize the sqlite3_pcache_page object and convert it into a
40667** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
40668** routines are split this way for performance reasons. When separated
40669** they can both (usually) operate without having to push values to
40670** the stack on entry and pop them back off on exit, which saves a
40671** lot of pushing and popping.
40672*/
40673SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
40674  PCache *pCache,       /* Obtain the page from this cache */
40675  Pgno pgno,            /* Page number to obtain */
40676  int createFlag        /* If true, create page if it does not exist already */
40677){
40678  int eCreate;
40679
40680  assert( pCache!=0 );
40681  assert( pCache->pCache!=0 );
40682  assert( createFlag==3 || createFlag==0 );
40683  assert( pgno>0 );
40684
40685  /* eCreate defines what to do if the page does not exist.
40686  **    0     Do not allocate a new page.  (createFlag==0)
40687  **    1     Allocate a new page if doing so is inexpensive.
40688  **          (createFlag==1 AND bPurgeable AND pDirty)
40689  **    2     Allocate a new page even it doing so is difficult.
40690  **          (createFlag==1 AND !(bPurgeable AND pDirty)
40691  */
40692  eCreate = createFlag & pCache->eCreate;
40693  assert( eCreate==0 || eCreate==1 || eCreate==2 );
40694  assert( createFlag==0 || pCache->eCreate==eCreate );
40695  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
40696  return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
40697}
40698
40699/*
40700** If the sqlite3PcacheFetch() routine is unable to allocate a new
40701** page because new clean pages are available for reuse and the cache
40702** size limit has been reached, then this routine can be invoked to
40703** try harder to allocate a page.  This routine might invoke the stress
40704** callback to spill dirty pages to the journal.  It will then try to
40705** allocate the new page and will only fail to allocate a new page on
40706** an OOM error.
40707**
40708** This routine should be invoked only after sqlite3PcacheFetch() fails.
40709*/
40710SQLITE_PRIVATE int sqlite3PcacheFetchStress(
40711  PCache *pCache,                 /* Obtain the page from this cache */
40712  Pgno pgno,                      /* Page number to obtain */
40713  sqlite3_pcache_page **ppPage    /* Write result here */
40714){
40715  PgHdr *pPg;
40716  if( pCache->eCreate==2 ) return 0;
40717
40718
40719  /* Find a dirty page to write-out and recycle. First try to find a
40720  ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
40721  ** cleared), but if that is not possible settle for any other
40722  ** unreferenced dirty page.
40723  */
40724  for(pPg=pCache->pSynced;
40725      pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
40726      pPg=pPg->pDirtyPrev
40727  );
40728  pCache->pSynced = pPg;
40729  if( !pPg ){
40730    for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
40731  }
40732  if( pPg ){
40733    int rc;
40734#ifdef SQLITE_LOG_CACHE_SPILL
40735    sqlite3_log(SQLITE_FULL,
40736                "spill page %d making room for %d - cache used: %d/%d",
40737                pPg->pgno, pgno,
40738                sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
40739                numberOfCachePages(pCache));
40740#endif
40741    rc = pCache->xStress(pCache->pStress, pPg);
40742    if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
40743      return rc;
40744    }
40745  }
40746  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
40747  return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
40748}
40749
40750/*
40751** This is a helper routine for sqlite3PcacheFetchFinish()
40752**
40753** In the uncommon case where the page being fetched has not been
40754** initialized, this routine is invoked to do the initialization.
40755** This routine is broken out into a separate function since it
40756** requires extra stack manipulation that can be avoided in the common
40757** case.
40758*/
40759static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
40760  PCache *pCache,             /* Obtain the page from this cache */
40761  Pgno pgno,                  /* Page number obtained */
40762  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
40763){
40764  PgHdr *pPgHdr;
40765  assert( pPage!=0 );
40766  pPgHdr = (PgHdr*)pPage->pExtra;
40767  assert( pPgHdr->pPage==0 );
40768  memset(pPgHdr, 0, sizeof(PgHdr));
40769  pPgHdr->pPage = pPage;
40770  pPgHdr->pData = pPage->pBuf;
40771  pPgHdr->pExtra = (void *)&pPgHdr[1];
40772  memset(pPgHdr->pExtra, 0, pCache->szExtra);
40773  pPgHdr->pCache = pCache;
40774  pPgHdr->pgno = pgno;
40775  pPgHdr->flags = PGHDR_CLEAN;
40776  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
40777}
40778
40779/*
40780** This routine converts the sqlite3_pcache_page object returned by
40781** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
40782** must be called after sqlite3PcacheFetch() in order to get a usable
40783** result.
40784*/
40785SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
40786  PCache *pCache,             /* Obtain the page from this cache */
40787  Pgno pgno,                  /* Page number obtained */
40788  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
40789){
40790  PgHdr *pPgHdr;
40791
40792  assert( pPage!=0 );
40793  pPgHdr = (PgHdr *)pPage->pExtra;
40794
40795  if( !pPgHdr->pPage ){
40796    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
40797  }
40798  pCache->nRefSum++;
40799  pPgHdr->nRef++;
40800  return pPgHdr;
40801}
40802
40803/*
40804** Decrement the reference count on a page. If the page is clean and the
40805** reference count drops to 0, then it is made eligible for recycling.
40806*/
40807SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
40808  assert( p->nRef>0 );
40809  p->pCache->nRefSum--;
40810  if( (--p->nRef)==0 ){
40811    if( p->flags&PGHDR_CLEAN ){
40812      pcacheUnpin(p);
40813    }else if( p->pDirtyPrev!=0 ){
40814      /* Move the page to the head of the dirty list. */
40815      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
40816    }
40817  }
40818}
40819
40820/*
40821** Increase the reference count of a supplied page by 1.
40822*/
40823SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
40824  assert(p->nRef>0);
40825  p->nRef++;
40826  p->pCache->nRefSum++;
40827}
40828
40829/*
40830** Drop a page from the cache. There must be exactly one reference to the
40831** page. This function deletes that reference, so after it returns the
40832** page pointed to by p is invalid.
40833*/
40834SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
40835  assert( p->nRef==1 );
40836  if( p->flags&PGHDR_DIRTY ){
40837    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
40838  }
40839  p->pCache->nRefSum--;
40840  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
40841}
40842
40843/*
40844** Make sure the page is marked as dirty. If it isn't dirty already,
40845** make it so.
40846*/
40847SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
40848  assert( p->nRef>0 );
40849  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
40850    p->flags &= ~PGHDR_DONT_WRITE;
40851    if( p->flags & PGHDR_CLEAN ){
40852      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
40853      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
40854      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
40855    }
40856  }
40857}
40858
40859/*
40860** Make sure the page is marked as clean. If it isn't clean already,
40861** make it so.
40862*/
40863SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
40864  if( (p->flags & PGHDR_DIRTY) ){
40865    assert( (p->flags & PGHDR_CLEAN)==0 );
40866    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
40867    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
40868    p->flags |= PGHDR_CLEAN;
40869    if( p->nRef==0 ){
40870      pcacheUnpin(p);
40871    }
40872  }
40873}
40874
40875/*
40876** Make every page in the cache clean.
40877*/
40878SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
40879  PgHdr *p;
40880  while( (p = pCache->pDirty)!=0 ){
40881    sqlite3PcacheMakeClean(p);
40882  }
40883}
40884
40885/*
40886** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
40887*/
40888SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
40889  PgHdr *p;
40890  for(p=pCache->pDirty; p; p=p->pDirtyNext){
40891    p->flags &= ~PGHDR_NEED_SYNC;
40892  }
40893  pCache->pSynced = pCache->pDirtyTail;
40894}
40895
40896/*
40897** Change the page number of page p to newPgno.
40898*/
40899SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
40900  PCache *pCache = p->pCache;
40901  assert( p->nRef>0 );
40902  assert( newPgno>0 );
40903  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
40904  p->pgno = newPgno;
40905  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
40906    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
40907  }
40908}
40909
40910/*
40911** Drop every cache entry whose page number is greater than "pgno". The
40912** caller must ensure that there are no outstanding references to any pages
40913** other than page 1 with a page number greater than pgno.
40914**
40915** If there is a reference to page 1 and the pgno parameter passed to this
40916** function is 0, then the data area associated with page 1 is zeroed, but
40917** the page object is not dropped.
40918*/
40919SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
40920  if( pCache->pCache ){
40921    PgHdr *p;
40922    PgHdr *pNext;
40923    for(p=pCache->pDirty; p; p=pNext){
40924      pNext = p->pDirtyNext;
40925      /* This routine never gets call with a positive pgno except right
40926      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
40927      ** it must be that pgno==0.
40928      */
40929      assert( p->pgno>0 );
40930      if( ALWAYS(p->pgno>pgno) ){
40931        assert( p->flags&PGHDR_DIRTY );
40932        sqlite3PcacheMakeClean(p);
40933      }
40934    }
40935    if( pgno==0 && pCache->nRefSum ){
40936      sqlite3_pcache_page *pPage1;
40937      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
40938      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
40939                             ** pCache->nRefSum>0 */
40940        memset(pPage1->pBuf, 0, pCache->szPage);
40941        pgno = 1;
40942      }
40943    }
40944    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
40945  }
40946}
40947
40948/*
40949** Close a cache.
40950*/
40951SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
40952  assert( pCache->pCache!=0 );
40953  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
40954}
40955
40956/*
40957** Discard the contents of the cache.
40958*/
40959SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
40960  sqlite3PcacheTruncate(pCache, 0);
40961}
40962
40963/*
40964** Merge two lists of pages connected by pDirty and in pgno order.
40965** Do not both fixing the pDirtyPrev pointers.
40966*/
40967static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
40968  PgHdr result, *pTail;
40969  pTail = &result;
40970  while( pA && pB ){
40971    if( pA->pgno<pB->pgno ){
40972      pTail->pDirty = pA;
40973      pTail = pA;
40974      pA = pA->pDirty;
40975    }else{
40976      pTail->pDirty = pB;
40977      pTail = pB;
40978      pB = pB->pDirty;
40979    }
40980  }
40981  if( pA ){
40982    pTail->pDirty = pA;
40983  }else if( pB ){
40984    pTail->pDirty = pB;
40985  }else{
40986    pTail->pDirty = 0;
40987  }
40988  return result.pDirty;
40989}
40990
40991/*
40992** Sort the list of pages in accending order by pgno.  Pages are
40993** connected by pDirty pointers.  The pDirtyPrev pointers are
40994** corrupted by this sort.
40995**
40996** Since there cannot be more than 2^31 distinct pages in a database,
40997** there cannot be more than 31 buckets required by the merge sorter.
40998** One extra bucket is added to catch overflow in case something
40999** ever changes to make the previous sentence incorrect.
41000*/
41001#define N_SORT_BUCKET  32
41002static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
41003  PgHdr *a[N_SORT_BUCKET], *p;
41004  int i;
41005  memset(a, 0, sizeof(a));
41006  while( pIn ){
41007    p = pIn;
41008    pIn = p->pDirty;
41009    p->pDirty = 0;
41010    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
41011      if( a[i]==0 ){
41012        a[i] = p;
41013        break;
41014      }else{
41015        p = pcacheMergeDirtyList(a[i], p);
41016        a[i] = 0;
41017      }
41018    }
41019    if( NEVER(i==N_SORT_BUCKET-1) ){
41020      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
41021      ** the input list.  But that is impossible.
41022      */
41023      a[i] = pcacheMergeDirtyList(a[i], p);
41024    }
41025  }
41026  p = a[0];
41027  for(i=1; i<N_SORT_BUCKET; i++){
41028    p = pcacheMergeDirtyList(p, a[i]);
41029  }
41030  return p;
41031}
41032
41033/*
41034** Return a list of all dirty pages in the cache, sorted by page number.
41035*/
41036SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
41037  PgHdr *p;
41038  for(p=pCache->pDirty; p; p=p->pDirtyNext){
41039    p->pDirty = p->pDirtyNext;
41040  }
41041  return pcacheSortDirtyList(pCache->pDirty);
41042}
41043
41044/*
41045** Return the total number of references to all pages held by the cache.
41046**
41047** This is not the total number of pages referenced, but the sum of the
41048** reference count for all pages.
41049*/
41050SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
41051  return pCache->nRefSum;
41052}
41053
41054/*
41055** Return the number of references to the page supplied as an argument.
41056*/
41057SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
41058  return p->nRef;
41059}
41060
41061/*
41062** Return the total number of pages in the cache.
41063*/
41064SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
41065  assert( pCache->pCache!=0 );
41066  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
41067}
41068
41069#ifdef SQLITE_TEST
41070/*
41071** Get the suggested cache-size value.
41072*/
41073SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
41074  return numberOfCachePages(pCache);
41075}
41076#endif
41077
41078/*
41079** Set the suggested cache-size value.
41080*/
41081SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
41082  assert( pCache->pCache!=0 );
41083  pCache->szCache = mxPage;
41084  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
41085                                         numberOfCachePages(pCache));
41086}
41087
41088/*
41089** Free up as much memory as possible from the page cache.
41090*/
41091SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
41092  assert( pCache->pCache!=0 );
41093  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
41094}
41095
41096/*
41097** Return the size of the header added by this middleware layer
41098** in the page-cache hierarchy.
41099*/
41100SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
41101
41102
41103#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
41104/*
41105** For all dirty pages currently in the cache, invoke the specified
41106** callback. This is only used if the SQLITE_CHECK_PAGES macro is
41107** defined.
41108*/
41109SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
41110  PgHdr *pDirty;
41111  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
41112    xIter(pDirty);
41113  }
41114}
41115#endif
41116
41117/************** End of pcache.c **********************************************/
41118/************** Begin file pcache1.c *****************************************/
41119/*
41120** 2008 November 05
41121**
41122** The author disclaims copyright to this source code.  In place of
41123** a legal notice, here is a blessing:
41124**
41125**    May you do good and not evil.
41126**    May you find forgiveness for yourself and forgive others.
41127**    May you share freely, never taking more than you give.
41128**
41129*************************************************************************
41130**
41131** This file implements the default page cache implementation (the
41132** sqlite3_pcache interface). It also contains part of the implementation
41133** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
41134** If the default page cache implementation is overridden, then neither of
41135** these two features are available.
41136**
41137** A Page cache line looks like this:
41138**
41139**  -------------------------------------------------------------
41140**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
41141**  -------------------------------------------------------------
41142**
41143** The database page content is up front (so that buffer overreads tend to
41144** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
41145** is the extension added by the btree.c module containing information such
41146** as the database page number and how that database page is used.  PgHdr
41147** is added by the pcache.c layer and contains information used to keep track
41148** of which pages are "dirty".  PgHdr1 is an extension added by this
41149** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
41150** PgHdr1 contains information needed to look up a page by its page number.
41151** The superclass sqlite3_pcache_page.pBuf points to the start of the
41152** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
41153**
41154** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
41155** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
41156** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
41157** size can vary according to architecture, compile-time options, and
41158** SQLite library version number.
41159**
41160** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
41161** using a separate memory allocation from the database page content.  This
41162** seeks to overcome the "clownshoe" problem (also called "internal
41163** fragmentation" in academic literature) of allocating a few bytes more
41164** than a power of two with the memory allocator rounding up to the next
41165** power of two, and leaving the rounded-up space unused.
41166**
41167** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
41168** with this module.  Information is passed back and forth as PgHdr1 pointers.
41169**
41170** The pcache.c and pager.c modules deal pointers to PgHdr objects.
41171** The btree.c module deals with pointers to MemPage objects.
41172**
41173** SOURCE OF PAGE CACHE MEMORY:
41174**
41175** Memory for a page might come from any of three sources:
41176**
41177**    (1)  The general-purpose memory allocator - sqlite3Malloc()
41178**    (2)  Global page-cache memory provided using sqlite3_config() with
41179**         SQLITE_CONFIG_PAGECACHE.
41180**    (3)  PCache-local bulk allocation.
41181**
41182** The third case is a chunk of heap memory (defaulting to 100 pages worth)
41183** that is allocated when the page cache is created.  The size of the local
41184** bulk allocation can be adjusted using
41185**
41186**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, 0, 0, N).
41187**
41188** If N is positive, then N pages worth of memory are allocated using a single
41189** sqlite3Malloc() call and that memory is used for the first N pages allocated.
41190** Or if N is negative, then -1024*N bytes of memory are allocated and used
41191** for as many pages as can be accomodated.
41192**
41193** Only one of (2) or (3) can be used.  Once the memory available to (2) or
41194** (3) is exhausted, subsequent allocations fail over to the general-purpose
41195** memory allocator (1).
41196**
41197** Earlier versions of SQLite used only methods (1) and (2).  But experiments
41198** show that method (3) with N==100 provides about a 5% performance boost for
41199** common workloads.
41200*/
41201/* #include "sqliteInt.h" */
41202
41203typedef struct PCache1 PCache1;
41204typedef struct PgHdr1 PgHdr1;
41205typedef struct PgFreeslot PgFreeslot;
41206typedef struct PGroup PGroup;
41207
41208/*
41209** Each cache entry is represented by an instance of the following
41210** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
41211** PgHdr1.pCache->szPage bytes is allocated directly before this structure
41212** in memory.
41213*/
41214struct PgHdr1 {
41215  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
41216  unsigned int iKey;             /* Key value (page number) */
41217  u8 isPinned;                   /* Page in use, not on the LRU list */
41218  u8 isBulkLocal;                /* This page from bulk local storage */
41219  u8 isAnchor;                   /* This is the PGroup.lru element */
41220  PgHdr1 *pNext;                 /* Next in hash table chain */
41221  PCache1 *pCache;               /* Cache that currently owns this page */
41222  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
41223  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
41224};
41225
41226/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
41227** of one or more PCaches that are able to recycle each other's unpinned
41228** pages when they are under memory pressure.  A PGroup is an instance of
41229** the following object.
41230**
41231** This page cache implementation works in one of two modes:
41232**
41233**   (1)  Every PCache is the sole member of its own PGroup.  There is
41234**        one PGroup per PCache.
41235**
41236**   (2)  There is a single global PGroup that all PCaches are a member
41237**        of.
41238**
41239** Mode 1 uses more memory (since PCache instances are not able to rob
41240** unused pages from other PCaches) but it also operates without a mutex,
41241** and is therefore often faster.  Mode 2 requires a mutex in order to be
41242** threadsafe, but recycles pages more efficiently.
41243**
41244** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
41245** PGroup which is the pcache1.grp global variable and its mutex is
41246** SQLITE_MUTEX_STATIC_LRU.
41247*/
41248struct PGroup {
41249  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
41250  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
41251  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
41252  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
41253  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
41254  PgHdr1 lru;                    /* The beginning and end of the LRU list */
41255};
41256
41257/* Each page cache is an instance of the following object.  Every
41258** open database file (including each in-memory database and each
41259** temporary or transient database) has a single page cache which
41260** is an instance of this object.
41261**
41262** Pointers to structures of this type are cast and returned as
41263** opaque sqlite3_pcache* handles.
41264*/
41265struct PCache1 {
41266  /* Cache configuration parameters. Page size (szPage) and the purgeable
41267  ** flag (bPurgeable) are set when the cache is created. nMax may be
41268  ** modified at any time by a call to the pcache1Cachesize() method.
41269  ** The PGroup mutex must be held when accessing nMax.
41270  */
41271  PGroup *pGroup;                     /* PGroup this cache belongs to */
41272  int szPage;                         /* Size of database content section */
41273  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
41274  int szAlloc;                        /* Total size of one pcache line */
41275  int bPurgeable;                     /* True if cache is purgeable */
41276  unsigned int nMin;                  /* Minimum number of pages reserved */
41277  unsigned int nMax;                  /* Configured "cache_size" value */
41278  unsigned int n90pct;                /* nMax*9/10 */
41279  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
41280
41281  /* Hash table of all pages. The following variables may only be accessed
41282  ** when the accessor is holding the PGroup mutex.
41283  */
41284  unsigned int nRecyclable;           /* Number of pages in the LRU list */
41285  unsigned int nPage;                 /* Total number of pages in apHash */
41286  unsigned int nHash;                 /* Number of slots in apHash[] */
41287  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
41288  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
41289  void *pBulk;                        /* Bulk memory used by pcache-local */
41290};
41291
41292/*
41293** Free slots in the allocator used to divide up the global page cache
41294** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
41295*/
41296struct PgFreeslot {
41297  PgFreeslot *pNext;  /* Next free slot */
41298};
41299
41300/*
41301** Global data used by this cache.
41302*/
41303static SQLITE_WSD struct PCacheGlobal {
41304  PGroup grp;                    /* The global PGroup for mode (2) */
41305
41306  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
41307  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
41308  ** fixed at sqlite3_initialize() time and do not require mutex protection.
41309  ** The nFreeSlot and pFree values do require mutex protection.
41310  */
41311  int isInit;                    /* True if initialized */
41312  int separateCache;             /* Use a new PGroup for each PCache */
41313  int nInitPage;                 /* Initial bulk allocation size */
41314  int szSlot;                    /* Size of each free slot */
41315  int nSlot;                     /* The number of pcache slots */
41316  int nReserve;                  /* Try to keep nFreeSlot above this */
41317  void *pStart, *pEnd;           /* Bounds of global page cache memory */
41318  /* Above requires no mutex.  Use mutex below for variable that follow. */
41319  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
41320  PgFreeslot *pFree;             /* Free page blocks */
41321  int nFreeSlot;                 /* Number of unused pcache slots */
41322  /* The following value requires a mutex to change.  We skip the mutex on
41323  ** reading because (1) most platforms read a 32-bit integer atomically and
41324  ** (2) even if an incorrect value is read, no great harm is done since this
41325  ** is really just an optimization. */
41326  int bUnderPressure;            /* True if low on PAGECACHE memory */
41327} pcache1_g;
41328
41329/*
41330** All code in this file should access the global structure above via the
41331** alias "pcache1". This ensures that the WSD emulation is used when
41332** compiling for systems that do not support real WSD.
41333*/
41334#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
41335
41336/*
41337** Macros to enter and leave the PCache LRU mutex.
41338*/
41339#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
41340# define pcache1EnterMutex(X)  assert((X)->mutex==0)
41341# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
41342# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
41343#else
41344# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
41345# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
41346# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
41347#endif
41348
41349/******************************************************************************/
41350/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
41351
41352
41353/*
41354** This function is called during initialization if a static buffer is
41355** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
41356** verb to sqlite3_config(). Parameter pBuf points to an allocation large
41357** enough to contain 'n' buffers of 'sz' bytes each.
41358**
41359** This routine is called from sqlite3_initialize() and so it is guaranteed
41360** to be serialized already.  There is no need for further mutexing.
41361*/
41362SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
41363  if( pcache1.isInit ){
41364    PgFreeslot *p;
41365    if( pBuf==0 ) sz = n = 0;
41366    sz = ROUNDDOWN8(sz);
41367    pcache1.szSlot = sz;
41368    pcache1.nSlot = pcache1.nFreeSlot = n;
41369    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
41370    pcache1.pStart = pBuf;
41371    pcache1.pFree = 0;
41372    pcache1.bUnderPressure = 0;
41373    while( n-- ){
41374      p = (PgFreeslot*)pBuf;
41375      p->pNext = pcache1.pFree;
41376      pcache1.pFree = p;
41377      pBuf = (void*)&((char*)pBuf)[sz];
41378    }
41379    pcache1.pEnd = pBuf;
41380  }
41381}
41382
41383/*
41384** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
41385** true if pCache->pFree ends up containing one or more free pages.
41386*/
41387static int pcache1InitBulk(PCache1 *pCache){
41388  i64 szBulk;
41389  char *zBulk;
41390  if( pcache1.nInitPage==0 ) return 0;
41391  /* Do not bother with a bulk allocation if the cache size very small */
41392  if( pCache->nMax<3 ) return 0;
41393  sqlite3BeginBenignMalloc();
41394  if( pcache1.nInitPage>0 ){
41395    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
41396  }else{
41397    szBulk = -1024 * (i64)pcache1.nInitPage;
41398  }
41399  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
41400    szBulk = pCache->szAlloc*pCache->nMax;
41401  }
41402  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
41403  sqlite3EndBenignMalloc();
41404  if( zBulk ){
41405    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
41406    int i;
41407    for(i=0; i<nBulk; i++){
41408      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
41409      pX->page.pBuf = zBulk;
41410      pX->page.pExtra = &pX[1];
41411      pX->isBulkLocal = 1;
41412      pX->isAnchor = 0;
41413      pX->pNext = pCache->pFree;
41414      pCache->pFree = pX;
41415      zBulk += pCache->szAlloc;
41416    }
41417  }
41418  return pCache->pFree!=0;
41419}
41420
41421/*
41422** Malloc function used within this file to allocate space from the buffer
41423** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
41424** such buffer exists or there is no space left in it, this function falls
41425** back to sqlite3Malloc().
41426**
41427** Multiple threads can run this routine at the same time.  Global variables
41428** in pcache1 need to be protected via mutex.
41429*/
41430static void *pcache1Alloc(int nByte){
41431  void *p = 0;
41432  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
41433  if( nByte<=pcache1.szSlot ){
41434    sqlite3_mutex_enter(pcache1.mutex);
41435    p = (PgHdr1 *)pcache1.pFree;
41436    if( p ){
41437      pcache1.pFree = pcache1.pFree->pNext;
41438      pcache1.nFreeSlot--;
41439      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
41440      assert( pcache1.nFreeSlot>=0 );
41441      sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
41442      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
41443    }
41444    sqlite3_mutex_leave(pcache1.mutex);
41445  }
41446  if( p==0 ){
41447    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
41448    ** it from sqlite3Malloc instead.
41449    */
41450    p = sqlite3Malloc(nByte);
41451#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
41452    if( p ){
41453      int sz = sqlite3MallocSize(p);
41454      sqlite3_mutex_enter(pcache1.mutex);
41455      sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
41456      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
41457      sqlite3_mutex_leave(pcache1.mutex);
41458    }
41459#endif
41460    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
41461  }
41462  return p;
41463}
41464
41465/*
41466** Free an allocated buffer obtained from pcache1Alloc().
41467*/
41468static void pcache1Free(void *p){
41469  int nFreed = 0;
41470  if( p==0 ) return;
41471  if( p>=pcache1.pStart && p<pcache1.pEnd ){
41472    PgFreeslot *pSlot;
41473    sqlite3_mutex_enter(pcache1.mutex);
41474    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
41475    pSlot = (PgFreeslot*)p;
41476    pSlot->pNext = pcache1.pFree;
41477    pcache1.pFree = pSlot;
41478    pcache1.nFreeSlot++;
41479    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
41480    assert( pcache1.nFreeSlot<=pcache1.nSlot );
41481    sqlite3_mutex_leave(pcache1.mutex);
41482  }else{
41483    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
41484    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
41485#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
41486    nFreed = sqlite3MallocSize(p);
41487    sqlite3_mutex_enter(pcache1.mutex);
41488    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
41489    sqlite3_mutex_leave(pcache1.mutex);
41490#endif
41491    sqlite3_free(p);
41492  }
41493}
41494
41495#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41496/*
41497** Return the size of a pcache allocation
41498*/
41499static int pcache1MemSize(void *p){
41500  if( p>=pcache1.pStart && p<pcache1.pEnd ){
41501    return pcache1.szSlot;
41502  }else{
41503    int iSize;
41504    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
41505    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
41506    iSize = sqlite3MallocSize(p);
41507    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
41508    return iSize;
41509  }
41510}
41511#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
41512
41513/*
41514** Allocate a new page object initially associated with cache pCache.
41515*/
41516static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
41517  PgHdr1 *p = 0;
41518  void *pPg;
41519
41520  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41521  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
41522    p = pCache->pFree;
41523    pCache->pFree = p->pNext;
41524    p->pNext = 0;
41525  }else{
41526#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41527    /* The group mutex must be released before pcache1Alloc() is called. This
41528    ** is because it might call sqlite3_release_memory(), which assumes that
41529    ** this mutex is not held. */
41530    assert( pcache1.separateCache==0 );
41531    assert( pCache->pGroup==&pcache1.grp );
41532    pcache1LeaveMutex(pCache->pGroup);
41533#endif
41534    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
41535#ifdef SQLITE_PCACHE_SEPARATE_HEADER
41536    pPg = pcache1Alloc(pCache->szPage);
41537    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
41538    if( !pPg || !p ){
41539      pcache1Free(pPg);
41540      sqlite3_free(p);
41541      pPg = 0;
41542    }
41543#else
41544    pPg = pcache1Alloc(pCache->szAlloc);
41545    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
41546#endif
41547    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
41548#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41549    pcache1EnterMutex(pCache->pGroup);
41550#endif
41551    if( pPg==0 ) return 0;
41552    p->page.pBuf = pPg;
41553    p->page.pExtra = &p[1];
41554    p->isBulkLocal = 0;
41555    p->isAnchor = 0;
41556  }
41557  if( pCache->bPurgeable ){
41558    pCache->pGroup->nCurrentPage++;
41559  }
41560  return p;
41561}
41562
41563/*
41564** Free a page object allocated by pcache1AllocPage().
41565*/
41566static void pcache1FreePage(PgHdr1 *p){
41567  PCache1 *pCache;
41568  assert( p!=0 );
41569  pCache = p->pCache;
41570  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
41571  if( p->isBulkLocal ){
41572    p->pNext = pCache->pFree;
41573    pCache->pFree = p;
41574  }else{
41575    pcache1Free(p->page.pBuf);
41576#ifdef SQLITE_PCACHE_SEPARATE_HEADER
41577    sqlite3_free(p);
41578#endif
41579  }
41580  if( pCache->bPurgeable ){
41581    pCache->pGroup->nCurrentPage--;
41582  }
41583}
41584
41585/*
41586** Malloc function used by SQLite to obtain space from the buffer configured
41587** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
41588** exists, this function falls back to sqlite3Malloc().
41589*/
41590SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
41591  return pcache1Alloc(sz);
41592}
41593
41594/*
41595** Free an allocated buffer obtained from sqlite3PageMalloc().
41596*/
41597SQLITE_PRIVATE void sqlite3PageFree(void *p){
41598  pcache1Free(p);
41599}
41600
41601
41602/*
41603** Return true if it desirable to avoid allocating a new page cache
41604** entry.
41605**
41606** If memory was allocated specifically to the page cache using
41607** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
41608** it is desirable to avoid allocating a new page cache entry because
41609** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
41610** for all page cache needs and we should not need to spill the
41611** allocation onto the heap.
41612**
41613** Or, the heap is used for all page cache memory but the heap is
41614** under memory pressure, then again it is desirable to avoid
41615** allocating a new page cache entry in order to avoid stressing
41616** the heap even further.
41617*/
41618static int pcache1UnderMemoryPressure(PCache1 *pCache){
41619  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
41620    return pcache1.bUnderPressure;
41621  }else{
41622    return sqlite3HeapNearlyFull();
41623  }
41624}
41625
41626/******************************************************************************/
41627/******** General Implementation Functions ************************************/
41628
41629/*
41630** This function is used to resize the hash table used by the cache passed
41631** as the first argument.
41632**
41633** The PCache mutex must be held when this function is called.
41634*/
41635static void pcache1ResizeHash(PCache1 *p){
41636  PgHdr1 **apNew;
41637  unsigned int nNew;
41638  unsigned int i;
41639
41640  assert( sqlite3_mutex_held(p->pGroup->mutex) );
41641
41642  nNew = p->nHash*2;
41643  if( nNew<256 ){
41644    nNew = 256;
41645  }
41646
41647  pcache1LeaveMutex(p->pGroup);
41648  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
41649  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
41650  if( p->nHash ){ sqlite3EndBenignMalloc(); }
41651  pcache1EnterMutex(p->pGroup);
41652  if( apNew ){
41653    for(i=0; i<p->nHash; i++){
41654      PgHdr1 *pPage;
41655      PgHdr1 *pNext = p->apHash[i];
41656      while( (pPage = pNext)!=0 ){
41657        unsigned int h = pPage->iKey % nNew;
41658        pNext = pPage->pNext;
41659        pPage->pNext = apNew[h];
41660        apNew[h] = pPage;
41661      }
41662    }
41663    sqlite3_free(p->apHash);
41664    p->apHash = apNew;
41665    p->nHash = nNew;
41666  }
41667}
41668
41669/*
41670** This function is used internally to remove the page pPage from the
41671** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
41672** LRU list, then this function is a no-op.
41673**
41674** The PGroup mutex must be held when this function is called.
41675*/
41676static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
41677  PCache1 *pCache;
41678
41679  assert( pPage!=0 );
41680  assert( pPage->isPinned==0 );
41681  pCache = pPage->pCache;
41682  assert( pPage->pLruNext );
41683  assert( pPage->pLruPrev );
41684  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41685  pPage->pLruPrev->pLruNext = pPage->pLruNext;
41686  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
41687  pPage->pLruNext = 0;
41688  pPage->pLruPrev = 0;
41689  pPage->isPinned = 1;
41690  assert( pPage->isAnchor==0 );
41691  assert( pCache->pGroup->lru.isAnchor==1 );
41692  pCache->nRecyclable--;
41693  return pPage;
41694}
41695
41696
41697/*
41698** Remove the page supplied as an argument from the hash table
41699** (PCache1.apHash structure) that it is currently stored in.
41700** Also free the page if freePage is true.
41701**
41702** The PGroup mutex must be held when this function is called.
41703*/
41704static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
41705  unsigned int h;
41706  PCache1 *pCache = pPage->pCache;
41707  PgHdr1 **pp;
41708
41709  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41710  h = pPage->iKey % pCache->nHash;
41711  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
41712  *pp = (*pp)->pNext;
41713
41714  pCache->nPage--;
41715  if( freeFlag ) pcache1FreePage(pPage);
41716}
41717
41718/*
41719** If there are currently more than nMaxPage pages allocated, try
41720** to recycle pages to reduce the number allocated to nMaxPage.
41721*/
41722static void pcache1EnforceMaxPage(PCache1 *pCache){
41723  PGroup *pGroup = pCache->pGroup;
41724  PgHdr1 *p;
41725  assert( sqlite3_mutex_held(pGroup->mutex) );
41726  while( pGroup->nCurrentPage>pGroup->nMaxPage
41727      && (p=pGroup->lru.pLruPrev)->isAnchor==0
41728  ){
41729    assert( p->pCache->pGroup==pGroup );
41730    assert( p->isPinned==0 );
41731    pcache1PinPage(p);
41732    pcache1RemoveFromHash(p, 1);
41733  }
41734  if( pCache->nPage==0 && pCache->pBulk ){
41735    sqlite3_free(pCache->pBulk);
41736    pCache->pBulk = pCache->pFree = 0;
41737  }
41738}
41739
41740/*
41741** Discard all pages from cache pCache with a page number (key value)
41742** greater than or equal to iLimit. Any pinned pages that meet this
41743** criteria are unpinned before they are discarded.
41744**
41745** The PCache mutex must be held when this function is called.
41746*/
41747static void pcache1TruncateUnsafe(
41748  PCache1 *pCache,             /* The cache to truncate */
41749  unsigned int iLimit          /* Drop pages with this pgno or larger */
41750){
41751  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
41752  unsigned int h;
41753  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41754  for(h=0; h<pCache->nHash; h++){
41755    PgHdr1 **pp = &pCache->apHash[h];
41756    PgHdr1 *pPage;
41757    while( (pPage = *pp)!=0 ){
41758      if( pPage->iKey>=iLimit ){
41759        pCache->nPage--;
41760        *pp = pPage->pNext;
41761        if( !pPage->isPinned ) pcache1PinPage(pPage);
41762        pcache1FreePage(pPage);
41763      }else{
41764        pp = &pPage->pNext;
41765        TESTONLY( nPage++; )
41766      }
41767    }
41768  }
41769  assert( pCache->nPage==nPage );
41770}
41771
41772/******************************************************************************/
41773/******** sqlite3_pcache Methods **********************************************/
41774
41775/*
41776** Implementation of the sqlite3_pcache.xInit method.
41777*/
41778static int pcache1Init(void *NotUsed){
41779  UNUSED_PARAMETER(NotUsed);
41780  assert( pcache1.isInit==0 );
41781  memset(&pcache1, 0, sizeof(pcache1));
41782
41783
41784  /*
41785  ** The pcache1.separateCache variable is true if each PCache has its own
41786  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
41787  ** PGroup in pcache1.grp is used for all page caches (mode-2).
41788  **
41789  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
41790  **
41791  **   *  Use a unified cache in single-threaded applications that have
41792  **      configured a start-time buffer for use as page-cache memory using
41793  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
41794  **      pBuf argument.
41795  **
41796  **   *  Otherwise use separate caches (mode-1)
41797  */
41798#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
41799  pcache1.separateCache = 0;
41800#elif SQLITE_THREADSAFE
41801  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
41802                          || sqlite3GlobalConfig.bCoreMutex>0;
41803#else
41804  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
41805#endif
41806
41807#if SQLITE_THREADSAFE
41808  if( sqlite3GlobalConfig.bCoreMutex ){
41809    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
41810    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
41811  }
41812#endif
41813  if( pcache1.separateCache
41814   && sqlite3GlobalConfig.nPage!=0
41815   && sqlite3GlobalConfig.pPage==0
41816  ){
41817    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
41818  }else{
41819    pcache1.nInitPage = 0;
41820  }
41821  pcache1.grp.mxPinned = 10;
41822  pcache1.isInit = 1;
41823  return SQLITE_OK;
41824}
41825
41826/*
41827** Implementation of the sqlite3_pcache.xShutdown method.
41828** Note that the static mutex allocated in xInit does
41829** not need to be freed.
41830*/
41831static void pcache1Shutdown(void *NotUsed){
41832  UNUSED_PARAMETER(NotUsed);
41833  assert( pcache1.isInit!=0 );
41834  memset(&pcache1, 0, sizeof(pcache1));
41835}
41836
41837/* forward declaration */
41838static void pcache1Destroy(sqlite3_pcache *p);
41839
41840/*
41841** Implementation of the sqlite3_pcache.xCreate method.
41842**
41843** Allocate a new cache.
41844*/
41845static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
41846  PCache1 *pCache;      /* The newly created page cache */
41847  PGroup *pGroup;       /* The group the new page cache will belong to */
41848  int sz;               /* Bytes of memory required to allocate the new cache */
41849
41850  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
41851  assert( szExtra < 300 );
41852
41853  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
41854  pCache = (PCache1 *)sqlite3MallocZero(sz);
41855  if( pCache ){
41856    if( pcache1.separateCache ){
41857      pGroup = (PGroup*)&pCache[1];
41858      pGroup->mxPinned = 10;
41859    }else{
41860      pGroup = &pcache1.grp;
41861    }
41862    if( pGroup->lru.isAnchor==0 ){
41863      pGroup->lru.isAnchor = 1;
41864      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
41865    }
41866    pCache->pGroup = pGroup;
41867    pCache->szPage = szPage;
41868    pCache->szExtra = szExtra;
41869    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
41870    pCache->bPurgeable = (bPurgeable ? 1 : 0);
41871    pcache1EnterMutex(pGroup);
41872    pcache1ResizeHash(pCache);
41873    if( bPurgeable ){
41874      pCache->nMin = 10;
41875      pGroup->nMinPage += pCache->nMin;
41876      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
41877    }
41878    pcache1LeaveMutex(pGroup);
41879    if( pCache->nHash==0 ){
41880      pcache1Destroy((sqlite3_pcache*)pCache);
41881      pCache = 0;
41882    }
41883  }
41884  return (sqlite3_pcache *)pCache;
41885}
41886
41887/*
41888** Implementation of the sqlite3_pcache.xCachesize method.
41889**
41890** Configure the cache_size limit for a cache.
41891*/
41892static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
41893  PCache1 *pCache = (PCache1 *)p;
41894  if( pCache->bPurgeable ){
41895    PGroup *pGroup = pCache->pGroup;
41896    pcache1EnterMutex(pGroup);
41897    pGroup->nMaxPage += (nMax - pCache->nMax);
41898    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
41899    pCache->nMax = nMax;
41900    pCache->n90pct = pCache->nMax*9/10;
41901    pcache1EnforceMaxPage(pCache);
41902    pcache1LeaveMutex(pGroup);
41903  }
41904}
41905
41906/*
41907** Implementation of the sqlite3_pcache.xShrink method.
41908**
41909** Free up as much memory as possible.
41910*/
41911static void pcache1Shrink(sqlite3_pcache *p){
41912  PCache1 *pCache = (PCache1*)p;
41913  if( pCache->bPurgeable ){
41914    PGroup *pGroup = pCache->pGroup;
41915    int savedMaxPage;
41916    pcache1EnterMutex(pGroup);
41917    savedMaxPage = pGroup->nMaxPage;
41918    pGroup->nMaxPage = 0;
41919    pcache1EnforceMaxPage(pCache);
41920    pGroup->nMaxPage = savedMaxPage;
41921    pcache1LeaveMutex(pGroup);
41922  }
41923}
41924
41925/*
41926** Implementation of the sqlite3_pcache.xPagecount method.
41927*/
41928static int pcache1Pagecount(sqlite3_pcache *p){
41929  int n;
41930  PCache1 *pCache = (PCache1*)p;
41931  pcache1EnterMutex(pCache->pGroup);
41932  n = pCache->nPage;
41933  pcache1LeaveMutex(pCache->pGroup);
41934  return n;
41935}
41936
41937
41938/*
41939** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
41940** in the header of the pcache1Fetch() procedure.
41941**
41942** This steps are broken out into a separate procedure because they are
41943** usually not needed, and by avoiding the stack initialization required
41944** for these steps, the main pcache1Fetch() procedure can run faster.
41945*/
41946static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
41947  PCache1 *pCache,
41948  unsigned int iKey,
41949  int createFlag
41950){
41951  unsigned int nPinned;
41952  PGroup *pGroup = pCache->pGroup;
41953  PgHdr1 *pPage = 0;
41954
41955  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
41956  assert( pCache->nPage >= pCache->nRecyclable );
41957  nPinned = pCache->nPage - pCache->nRecyclable;
41958  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
41959  assert( pCache->n90pct == pCache->nMax*9/10 );
41960  if( createFlag==1 && (
41961        nPinned>=pGroup->mxPinned
41962     || nPinned>=pCache->n90pct
41963     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
41964  )){
41965    return 0;
41966  }
41967
41968  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
41969  assert( pCache->nHash>0 && pCache->apHash );
41970
41971  /* Step 4. Try to recycle a page. */
41972  if( pCache->bPurgeable
41973   && !pGroup->lru.pLruPrev->isAnchor
41974   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
41975  ){
41976    PCache1 *pOther;
41977    pPage = pGroup->lru.pLruPrev;
41978    assert( pPage->isPinned==0 );
41979    pcache1RemoveFromHash(pPage, 0);
41980    pcache1PinPage(pPage);
41981    pOther = pPage->pCache;
41982    if( pOther->szAlloc != pCache->szAlloc ){
41983      pcache1FreePage(pPage);
41984      pPage = 0;
41985    }else{
41986      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
41987    }
41988  }
41989
41990  /* Step 5. If a usable page buffer has still not been found,
41991  ** attempt to allocate a new one.
41992  */
41993  if( !pPage ){
41994    pPage = pcache1AllocPage(pCache, createFlag==1);
41995  }
41996
41997  if( pPage ){
41998    unsigned int h = iKey % pCache->nHash;
41999    pCache->nPage++;
42000    pPage->iKey = iKey;
42001    pPage->pNext = pCache->apHash[h];
42002    pPage->pCache = pCache;
42003    pPage->pLruPrev = 0;
42004    pPage->pLruNext = 0;
42005    pPage->isPinned = 1;
42006    *(void **)pPage->page.pExtra = 0;
42007    pCache->apHash[h] = pPage;
42008    if( iKey>pCache->iMaxKey ){
42009      pCache->iMaxKey = iKey;
42010    }
42011  }
42012  return pPage;
42013}
42014
42015/*
42016** Implementation of the sqlite3_pcache.xFetch method.
42017**
42018** Fetch a page by key value.
42019**
42020** Whether or not a new page may be allocated by this function depends on
42021** the value of the createFlag argument.  0 means do not allocate a new
42022** page.  1 means allocate a new page if space is easily available.  2
42023** means to try really hard to allocate a new page.
42024**
42025** For a non-purgeable cache (a cache used as the storage for an in-memory
42026** database) there is really no difference between createFlag 1 and 2.  So
42027** the calling function (pcache.c) will never have a createFlag of 1 on
42028** a non-purgeable cache.
42029**
42030** There are three different approaches to obtaining space for a page,
42031** depending on the value of parameter createFlag (which may be 0, 1 or 2).
42032**
42033**   1. Regardless of the value of createFlag, the cache is searched for a
42034**      copy of the requested page. If one is found, it is returned.
42035**
42036**   2. If createFlag==0 and the page is not already in the cache, NULL is
42037**      returned.
42038**
42039**   3. If createFlag is 1, and the page is not already in the cache, then
42040**      return NULL (do not allocate a new page) if any of the following
42041**      conditions are true:
42042**
42043**       (a) the number of pages pinned by the cache is greater than
42044**           PCache1.nMax, or
42045**
42046**       (b) the number of pages pinned by the cache is greater than
42047**           the sum of nMax for all purgeable caches, less the sum of
42048**           nMin for all other purgeable caches, or
42049**
42050**   4. If none of the first three conditions apply and the cache is marked
42051**      as purgeable, and if one of the following is true:
42052**
42053**       (a) The number of pages allocated for the cache is already
42054**           PCache1.nMax, or
42055**
42056**       (b) The number of pages allocated for all purgeable caches is
42057**           already equal to or greater than the sum of nMax for all
42058**           purgeable caches,
42059**
42060**       (c) The system is under memory pressure and wants to avoid
42061**           unnecessary pages cache entry allocations
42062**
42063**      then attempt to recycle a page from the LRU list. If it is the right
42064**      size, return the recycled buffer. Otherwise, free the buffer and
42065**      proceed to step 5.
42066**
42067**   5. Otherwise, allocate and return a new page buffer.
42068**
42069** There are two versions of this routine.  pcache1FetchWithMutex() is
42070** the general case.  pcache1FetchNoMutex() is a faster implementation for
42071** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
42072** invokes the appropriate routine.
42073*/
42074static PgHdr1 *pcache1FetchNoMutex(
42075  sqlite3_pcache *p,
42076  unsigned int iKey,
42077  int createFlag
42078){
42079  PCache1 *pCache = (PCache1 *)p;
42080  PgHdr1 *pPage = 0;
42081
42082  /* Step 1: Search the hash table for an existing entry. */
42083  pPage = pCache->apHash[iKey % pCache->nHash];
42084  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
42085
42086  /* Step 2: If the page was found in the hash table, then return it.
42087  ** If the page was not in the hash table and createFlag is 0, abort.
42088  ** Otherwise (page not in hash and createFlag!=0) continue with
42089  ** subsequent steps to try to create the page. */
42090  if( pPage ){
42091    if( !pPage->isPinned ){
42092      return pcache1PinPage(pPage);
42093    }else{
42094      return pPage;
42095    }
42096  }else if( createFlag ){
42097    /* Steps 3, 4, and 5 implemented by this subroutine */
42098    return pcache1FetchStage2(pCache, iKey, createFlag);
42099  }else{
42100    return 0;
42101  }
42102}
42103#if PCACHE1_MIGHT_USE_GROUP_MUTEX
42104static PgHdr1 *pcache1FetchWithMutex(
42105  sqlite3_pcache *p,
42106  unsigned int iKey,
42107  int createFlag
42108){
42109  PCache1 *pCache = (PCache1 *)p;
42110  PgHdr1 *pPage;
42111
42112  pcache1EnterMutex(pCache->pGroup);
42113  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
42114  assert( pPage==0 || pCache->iMaxKey>=iKey );
42115  pcache1LeaveMutex(pCache->pGroup);
42116  return pPage;
42117}
42118#endif
42119static sqlite3_pcache_page *pcache1Fetch(
42120  sqlite3_pcache *p,
42121  unsigned int iKey,
42122  int createFlag
42123){
42124#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
42125  PCache1 *pCache = (PCache1 *)p;
42126#endif
42127
42128  assert( offsetof(PgHdr1,page)==0 );
42129  assert( pCache->bPurgeable || createFlag!=1 );
42130  assert( pCache->bPurgeable || pCache->nMin==0 );
42131  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
42132  assert( pCache->nMin==0 || pCache->bPurgeable );
42133  assert( pCache->nHash>0 );
42134#if PCACHE1_MIGHT_USE_GROUP_MUTEX
42135  if( pCache->pGroup->mutex ){
42136    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
42137  }else
42138#endif
42139  {
42140    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
42141  }
42142}
42143
42144
42145/*
42146** Implementation of the sqlite3_pcache.xUnpin method.
42147**
42148** Mark a page as unpinned (eligible for asynchronous recycling).
42149*/
42150static void pcache1Unpin(
42151  sqlite3_pcache *p,
42152  sqlite3_pcache_page *pPg,
42153  int reuseUnlikely
42154){
42155  PCache1 *pCache = (PCache1 *)p;
42156  PgHdr1 *pPage = (PgHdr1 *)pPg;
42157  PGroup *pGroup = pCache->pGroup;
42158
42159  assert( pPage->pCache==pCache );
42160  pcache1EnterMutex(pGroup);
42161
42162  /* It is an error to call this function if the page is already
42163  ** part of the PGroup LRU list.
42164  */
42165  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
42166  assert( pPage->isPinned==1 );
42167
42168  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
42169    pcache1RemoveFromHash(pPage, 1);
42170  }else{
42171    /* Add the page to the PGroup LRU list. */
42172    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
42173    pPage->pLruPrev = &pGroup->lru;
42174    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
42175    *ppFirst = pPage;
42176    pCache->nRecyclable++;
42177    pPage->isPinned = 0;
42178  }
42179
42180  pcache1LeaveMutex(pCache->pGroup);
42181}
42182
42183/*
42184** Implementation of the sqlite3_pcache.xRekey method.
42185*/
42186static void pcache1Rekey(
42187  sqlite3_pcache *p,
42188  sqlite3_pcache_page *pPg,
42189  unsigned int iOld,
42190  unsigned int iNew
42191){
42192  PCache1 *pCache = (PCache1 *)p;
42193  PgHdr1 *pPage = (PgHdr1 *)pPg;
42194  PgHdr1 **pp;
42195  unsigned int h;
42196  assert( pPage->iKey==iOld );
42197  assert( pPage->pCache==pCache );
42198
42199  pcache1EnterMutex(pCache->pGroup);
42200
42201  h = iOld%pCache->nHash;
42202  pp = &pCache->apHash[h];
42203  while( (*pp)!=pPage ){
42204    pp = &(*pp)->pNext;
42205  }
42206  *pp = pPage->pNext;
42207
42208  h = iNew%pCache->nHash;
42209  pPage->iKey = iNew;
42210  pPage->pNext = pCache->apHash[h];
42211  pCache->apHash[h] = pPage;
42212  if( iNew>pCache->iMaxKey ){
42213    pCache->iMaxKey = iNew;
42214  }
42215
42216  pcache1LeaveMutex(pCache->pGroup);
42217}
42218
42219/*
42220** Implementation of the sqlite3_pcache.xTruncate method.
42221**
42222** Discard all unpinned pages in the cache with a page number equal to
42223** or greater than parameter iLimit. Any pinned pages with a page number
42224** equal to or greater than iLimit are implicitly unpinned.
42225*/
42226static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
42227  PCache1 *pCache = (PCache1 *)p;
42228  pcache1EnterMutex(pCache->pGroup);
42229  if( iLimit<=pCache->iMaxKey ){
42230    pcache1TruncateUnsafe(pCache, iLimit);
42231    pCache->iMaxKey = iLimit-1;
42232  }
42233  pcache1LeaveMutex(pCache->pGroup);
42234}
42235
42236/*
42237** Implementation of the sqlite3_pcache.xDestroy method.
42238**
42239** Destroy a cache allocated using pcache1Create().
42240*/
42241static void pcache1Destroy(sqlite3_pcache *p){
42242  PCache1 *pCache = (PCache1 *)p;
42243  PGroup *pGroup = pCache->pGroup;
42244  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
42245  pcache1EnterMutex(pGroup);
42246  pcache1TruncateUnsafe(pCache, 0);
42247  assert( pGroup->nMaxPage >= pCache->nMax );
42248  pGroup->nMaxPage -= pCache->nMax;
42249  assert( pGroup->nMinPage >= pCache->nMin );
42250  pGroup->nMinPage -= pCache->nMin;
42251  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
42252  pcache1EnforceMaxPage(pCache);
42253  pcache1LeaveMutex(pGroup);
42254  sqlite3_free(pCache->pBulk);
42255  sqlite3_free(pCache->apHash);
42256  sqlite3_free(pCache);
42257}
42258
42259/*
42260** This function is called during initialization (sqlite3_initialize()) to
42261** install the default pluggable cache module, assuming the user has not
42262** already provided an alternative.
42263*/
42264SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
42265  static const sqlite3_pcache_methods2 defaultMethods = {
42266    1,                       /* iVersion */
42267    0,                       /* pArg */
42268    pcache1Init,             /* xInit */
42269    pcache1Shutdown,         /* xShutdown */
42270    pcache1Create,           /* xCreate */
42271    pcache1Cachesize,        /* xCachesize */
42272    pcache1Pagecount,        /* xPagecount */
42273    pcache1Fetch,            /* xFetch */
42274    pcache1Unpin,            /* xUnpin */
42275    pcache1Rekey,            /* xRekey */
42276    pcache1Truncate,         /* xTruncate */
42277    pcache1Destroy,          /* xDestroy */
42278    pcache1Shrink            /* xShrink */
42279  };
42280  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
42281}
42282
42283/*
42284** Return the size of the header on each page of this PCACHE implementation.
42285*/
42286SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
42287
42288/*
42289** Return the global mutex used by this PCACHE implementation.  The
42290** sqlite3_status() routine needs access to this mutex.
42291*/
42292SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
42293  return pcache1.mutex;
42294}
42295
42296#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
42297/*
42298** This function is called to free superfluous dynamically allocated memory
42299** held by the pager system. Memory in use by any SQLite pager allocated
42300** by the current thread may be sqlite3_free()ed.
42301**
42302** nReq is the number of bytes of memory required. Once this much has
42303** been released, the function returns. The return value is the total number
42304** of bytes of memory released.
42305*/
42306SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
42307  int nFree = 0;
42308  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
42309  assert( sqlite3_mutex_notheld(pcache1.mutex) );
42310  if( sqlite3GlobalConfig.nPage==0 ){
42311    PgHdr1 *p;
42312    pcache1EnterMutex(&pcache1.grp);
42313    while( (nReq<0 || nFree<nReq)
42314       &&  (p=pcache1.grp.lru.pLruPrev)!=0
42315       &&  p->isAnchor==0
42316    ){
42317      nFree += pcache1MemSize(p->page.pBuf);
42318#ifdef SQLITE_PCACHE_SEPARATE_HEADER
42319      nFree += sqlite3MemSize(p);
42320#endif
42321      assert( p->isPinned==0 );
42322      pcache1PinPage(p);
42323      pcache1RemoveFromHash(p, 1);
42324    }
42325    pcache1LeaveMutex(&pcache1.grp);
42326  }
42327  return nFree;
42328}
42329#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
42330
42331#ifdef SQLITE_TEST
42332/*
42333** This function is used by test procedures to inspect the internal state
42334** of the global cache.
42335*/
42336SQLITE_PRIVATE void sqlite3PcacheStats(
42337  int *pnCurrent,      /* OUT: Total number of pages cached */
42338  int *pnMax,          /* OUT: Global maximum cache size */
42339  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
42340  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
42341){
42342  PgHdr1 *p;
42343  int nRecyclable = 0;
42344  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
42345    assert( p->isPinned==0 );
42346    nRecyclable++;
42347  }
42348  *pnCurrent = pcache1.grp.nCurrentPage;
42349  *pnMax = (int)pcache1.grp.nMaxPage;
42350  *pnMin = (int)pcache1.grp.nMinPage;
42351  *pnRecyclable = nRecyclable;
42352}
42353#endif
42354
42355/************** End of pcache1.c *********************************************/
42356/************** Begin file rowset.c ******************************************/
42357/*
42358** 2008 December 3
42359**
42360** The author disclaims copyright to this source code.  In place of
42361** a legal notice, here is a blessing:
42362**
42363**    May you do good and not evil.
42364**    May you find forgiveness for yourself and forgive others.
42365**    May you share freely, never taking more than you give.
42366**
42367*************************************************************************
42368**
42369** This module implements an object we call a "RowSet".
42370**
42371** The RowSet object is a collection of rowids.  Rowids
42372** are inserted into the RowSet in an arbitrary order.  Inserts
42373** can be intermixed with tests to see if a given rowid has been
42374** previously inserted into the RowSet.
42375**
42376** After all inserts are finished, it is possible to extract the
42377** elements of the RowSet in sorted order.  Once this extraction
42378** process has started, no new elements may be inserted.
42379**
42380** Hence, the primitive operations for a RowSet are:
42381**
42382**    CREATE
42383**    INSERT
42384**    TEST
42385**    SMALLEST
42386**    DESTROY
42387**
42388** The CREATE and DESTROY primitives are the constructor and destructor,
42389** obviously.  The INSERT primitive adds a new element to the RowSet.
42390** TEST checks to see if an element is already in the RowSet.  SMALLEST
42391** extracts the least value from the RowSet.
42392**
42393** The INSERT primitive might allocate additional memory.  Memory is
42394** allocated in chunks so most INSERTs do no allocation.  There is an
42395** upper bound on the size of allocated memory.  No memory is freed
42396** until DESTROY.
42397**
42398** The TEST primitive includes a "batch" number.  The TEST primitive
42399** will only see elements that were inserted before the last change
42400** in the batch number.  In other words, if an INSERT occurs between
42401** two TESTs where the TESTs have the same batch nubmer, then the
42402** value added by the INSERT will not be visible to the second TEST.
42403** The initial batch number is zero, so if the very first TEST contains
42404** a non-zero batch number, it will see all prior INSERTs.
42405**
42406** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
42407** that is attempted.
42408**
42409** The cost of an INSERT is roughly constant.  (Sometimes new memory
42410** has to be allocated on an INSERT.)  The cost of a TEST with a new
42411** batch number is O(NlogN) where N is the number of elements in the RowSet.
42412** The cost of a TEST using the same batch number is O(logN).  The cost
42413** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
42414** primitives are constant time.  The cost of DESTROY is O(N).
42415**
42416** There is an added cost of O(N) when switching between TEST and
42417** SMALLEST primitives.
42418*/
42419/* #include "sqliteInt.h" */
42420
42421
42422/*
42423** Target size for allocation chunks.
42424*/
42425#define ROWSET_ALLOCATION_SIZE 1024
42426
42427/*
42428** The number of rowset entries per allocation chunk.
42429*/
42430#define ROWSET_ENTRY_PER_CHUNK  \
42431                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
42432
42433/*
42434** Each entry in a RowSet is an instance of the following object.
42435**
42436** This same object is reused to store a linked list of trees of RowSetEntry
42437** objects.  In that alternative use, pRight points to the next entry
42438** in the list, pLeft points to the tree, and v is unused.  The
42439** RowSet.pForest value points to the head of this forest list.
42440*/
42441struct RowSetEntry {
42442  i64 v;                        /* ROWID value for this entry */
42443  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
42444  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
42445};
42446
42447/*
42448** RowSetEntry objects are allocated in large chunks (instances of the
42449** following structure) to reduce memory allocation overhead.  The
42450** chunks are kept on a linked list so that they can be deallocated
42451** when the RowSet is destroyed.
42452*/
42453struct RowSetChunk {
42454  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
42455  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
42456};
42457
42458/*
42459** A RowSet in an instance of the following structure.
42460**
42461** A typedef of this structure if found in sqliteInt.h.
42462*/
42463struct RowSet {
42464  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
42465  sqlite3 *db;                   /* The database connection */
42466  struct RowSetEntry *pEntry;    /* List of entries using pRight */
42467  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
42468  struct RowSetEntry *pFresh;    /* Source of new entry objects */
42469  struct RowSetEntry *pForest;   /* List of binary trees of entries */
42470  u16 nFresh;                    /* Number of objects on pFresh */
42471  u16 rsFlags;                   /* Various flags */
42472  int iBatch;                    /* Current insert batch */
42473};
42474
42475/*
42476** Allowed values for RowSet.rsFlags
42477*/
42478#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
42479#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
42480
42481/*
42482** Turn bulk memory into a RowSet object.  N bytes of memory
42483** are available at pSpace.  The db pointer is used as a memory context
42484** for any subsequent allocations that need to occur.
42485** Return a pointer to the new RowSet object.
42486**
42487** It must be the case that N is sufficient to make a Rowset.  If not
42488** an assertion fault occurs.
42489**
42490** If N is larger than the minimum, use the surplus as an initial
42491** allocation of entries available to be filled.
42492*/
42493SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
42494  RowSet *p;
42495  assert( N >= ROUND8(sizeof(*p)) );
42496  p = pSpace;
42497  p->pChunk = 0;
42498  p->db = db;
42499  p->pEntry = 0;
42500  p->pLast = 0;
42501  p->pForest = 0;
42502  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
42503  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
42504  p->rsFlags = ROWSET_SORTED;
42505  p->iBatch = 0;
42506  return p;
42507}
42508
42509/*
42510** Deallocate all chunks from a RowSet.  This frees all memory that
42511** the RowSet has allocated over its lifetime.  This routine is
42512** the destructor for the RowSet.
42513*/
42514SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
42515  struct RowSetChunk *pChunk, *pNextChunk;
42516  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
42517    pNextChunk = pChunk->pNextChunk;
42518    sqlite3DbFree(p->db, pChunk);
42519  }
42520  p->pChunk = 0;
42521  p->nFresh = 0;
42522  p->pEntry = 0;
42523  p->pLast = 0;
42524  p->pForest = 0;
42525  p->rsFlags = ROWSET_SORTED;
42526}
42527
42528/*
42529** Allocate a new RowSetEntry object that is associated with the
42530** given RowSet.  Return a pointer to the new and completely uninitialized
42531** objected.
42532**
42533** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
42534** routine returns NULL.
42535*/
42536static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
42537  assert( p!=0 );
42538  if( p->nFresh==0 ){
42539    struct RowSetChunk *pNew;
42540    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
42541    if( pNew==0 ){
42542      return 0;
42543    }
42544    pNew->pNextChunk = p->pChunk;
42545    p->pChunk = pNew;
42546    p->pFresh = pNew->aEntry;
42547    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
42548  }
42549  p->nFresh--;
42550  return p->pFresh++;
42551}
42552
42553/*
42554** Insert a new value into a RowSet.
42555**
42556** The mallocFailed flag of the database connection is set if a
42557** memory allocation fails.
42558*/
42559SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
42560  struct RowSetEntry *pEntry;  /* The new entry */
42561  struct RowSetEntry *pLast;   /* The last prior entry */
42562
42563  /* This routine is never called after sqlite3RowSetNext() */
42564  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
42565
42566  pEntry = rowSetEntryAlloc(p);
42567  if( pEntry==0 ) return;
42568  pEntry->v = rowid;
42569  pEntry->pRight = 0;
42570  pLast = p->pLast;
42571  if( pLast ){
42572    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
42573      p->rsFlags &= ~ROWSET_SORTED;
42574    }
42575    pLast->pRight = pEntry;
42576  }else{
42577    p->pEntry = pEntry;
42578  }
42579  p->pLast = pEntry;
42580}
42581
42582/*
42583** Merge two lists of RowSetEntry objects.  Remove duplicates.
42584**
42585** The input lists are connected via pRight pointers and are
42586** assumed to each already be in sorted order.
42587*/
42588static struct RowSetEntry *rowSetEntryMerge(
42589  struct RowSetEntry *pA,    /* First sorted list to be merged */
42590  struct RowSetEntry *pB     /* Second sorted list to be merged */
42591){
42592  struct RowSetEntry head;
42593  struct RowSetEntry *pTail;
42594
42595  pTail = &head;
42596  while( pA && pB ){
42597    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
42598    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
42599    if( pA->v<pB->v ){
42600      pTail->pRight = pA;
42601      pA = pA->pRight;
42602      pTail = pTail->pRight;
42603    }else if( pB->v<pA->v ){
42604      pTail->pRight = pB;
42605      pB = pB->pRight;
42606      pTail = pTail->pRight;
42607    }else{
42608      pA = pA->pRight;
42609    }
42610  }
42611  if( pA ){
42612    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
42613    pTail->pRight = pA;
42614  }else{
42615    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
42616    pTail->pRight = pB;
42617  }
42618  return head.pRight;
42619}
42620
42621/*
42622** Sort all elements on the list of RowSetEntry objects into order of
42623** increasing v.
42624*/
42625static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
42626  unsigned int i;
42627  struct RowSetEntry *pNext, *aBucket[40];
42628
42629  memset(aBucket, 0, sizeof(aBucket));
42630  while( pIn ){
42631    pNext = pIn->pRight;
42632    pIn->pRight = 0;
42633    for(i=0; aBucket[i]; i++){
42634      pIn = rowSetEntryMerge(aBucket[i], pIn);
42635      aBucket[i] = 0;
42636    }
42637    aBucket[i] = pIn;
42638    pIn = pNext;
42639  }
42640  pIn = 0;
42641  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
42642    pIn = rowSetEntryMerge(pIn, aBucket[i]);
42643  }
42644  return pIn;
42645}
42646
42647
42648/*
42649** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
42650** Convert this tree into a linked list connected by the pRight pointers
42651** and return pointers to the first and last elements of the new list.
42652*/
42653static void rowSetTreeToList(
42654  struct RowSetEntry *pIn,         /* Root of the input tree */
42655  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
42656  struct RowSetEntry **ppLast      /* Write tail of the output list here */
42657){
42658  assert( pIn!=0 );
42659  if( pIn->pLeft ){
42660    struct RowSetEntry *p;
42661    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
42662    p->pRight = pIn;
42663  }else{
42664    *ppFirst = pIn;
42665  }
42666  if( pIn->pRight ){
42667    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
42668  }else{
42669    *ppLast = pIn;
42670  }
42671  assert( (*ppLast)->pRight==0 );
42672}
42673
42674
42675/*
42676** Convert a sorted list of elements (connected by pRight) into a binary
42677** tree with depth of iDepth.  A depth of 1 means the tree contains a single
42678** node taken from the head of *ppList.  A depth of 2 means a tree with
42679** three nodes.  And so forth.
42680**
42681** Use as many entries from the input list as required and update the
42682** *ppList to point to the unused elements of the list.  If the input
42683** list contains too few elements, then construct an incomplete tree
42684** and leave *ppList set to NULL.
42685**
42686** Return a pointer to the root of the constructed binary tree.
42687*/
42688static struct RowSetEntry *rowSetNDeepTree(
42689  struct RowSetEntry **ppList,
42690  int iDepth
42691){
42692  struct RowSetEntry *p;         /* Root of the new tree */
42693  struct RowSetEntry *pLeft;     /* Left subtree */
42694  if( *ppList==0 ){
42695    return 0;
42696  }
42697  if( iDepth==1 ){
42698    p = *ppList;
42699    *ppList = p->pRight;
42700    p->pLeft = p->pRight = 0;
42701    return p;
42702  }
42703  pLeft = rowSetNDeepTree(ppList, iDepth-1);
42704  p = *ppList;
42705  if( p==0 ){
42706    return pLeft;
42707  }
42708  p->pLeft = pLeft;
42709  *ppList = p->pRight;
42710  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
42711  return p;
42712}
42713
42714/*
42715** Convert a sorted list of elements into a binary tree. Make the tree
42716** as deep as it needs to be in order to contain the entire list.
42717*/
42718static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
42719  int iDepth;           /* Depth of the tree so far */
42720  struct RowSetEntry *p;       /* Current tree root */
42721  struct RowSetEntry *pLeft;   /* Left subtree */
42722
42723  assert( pList!=0 );
42724  p = pList;
42725  pList = p->pRight;
42726  p->pLeft = p->pRight = 0;
42727  for(iDepth=1; pList; iDepth++){
42728    pLeft = p;
42729    p = pList;
42730    pList = p->pRight;
42731    p->pLeft = pLeft;
42732    p->pRight = rowSetNDeepTree(&pList, iDepth);
42733  }
42734  return p;
42735}
42736
42737/*
42738** Take all the entries on p->pEntry and on the trees in p->pForest and
42739** sort them all together into one big ordered list on p->pEntry.
42740**
42741** This routine should only be called once in the life of a RowSet.
42742*/
42743static void rowSetToList(RowSet *p){
42744
42745  /* This routine is called only once */
42746  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
42747
42748  if( (p->rsFlags & ROWSET_SORTED)==0 ){
42749    p->pEntry = rowSetEntrySort(p->pEntry);
42750  }
42751
42752  /* While this module could theoretically support it, sqlite3RowSetNext()
42753  ** is never called after sqlite3RowSetText() for the same RowSet.  So
42754  ** there is never a forest to deal with.  Should this change, simply
42755  ** remove the assert() and the #if 0. */
42756  assert( p->pForest==0 );
42757#if 0
42758  while( p->pForest ){
42759    struct RowSetEntry *pTree = p->pForest->pLeft;
42760    if( pTree ){
42761      struct RowSetEntry *pHead, *pTail;
42762      rowSetTreeToList(pTree, &pHead, &pTail);
42763      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
42764    }
42765    p->pForest = p->pForest->pRight;
42766  }
42767#endif
42768  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
42769}
42770
42771/*
42772** Extract the smallest element from the RowSet.
42773** Write the element into *pRowid.  Return 1 on success.  Return
42774** 0 if the RowSet is already empty.
42775**
42776** After this routine has been called, the sqlite3RowSetInsert()
42777** routine may not be called again.
42778*/
42779SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
42780  assert( p!=0 );
42781
42782  /* Merge the forest into a single sorted list on first call */
42783  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
42784
42785  /* Return the next entry on the list */
42786  if( p->pEntry ){
42787    *pRowid = p->pEntry->v;
42788    p->pEntry = p->pEntry->pRight;
42789    if( p->pEntry==0 ){
42790      sqlite3RowSetClear(p);
42791    }
42792    return 1;
42793  }else{
42794    return 0;
42795  }
42796}
42797
42798/*
42799** Check to see if element iRowid was inserted into the rowset as
42800** part of any insert batch prior to iBatch.  Return 1 or 0.
42801**
42802** If this is the first test of a new batch and if there exist entries
42803** on pRowSet->pEntry, then sort those entries into the forest at
42804** pRowSet->pForest so that they can be tested.
42805*/
42806SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
42807  struct RowSetEntry *p, *pTree;
42808
42809  /* This routine is never called after sqlite3RowSetNext() */
42810  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
42811
42812  /* Sort entries into the forest on the first test of a new batch
42813  */
42814  if( iBatch!=pRowSet->iBatch ){
42815    p = pRowSet->pEntry;
42816    if( p ){
42817      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
42818      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
42819        p = rowSetEntrySort(p);
42820      }
42821      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
42822        ppPrevTree = &pTree->pRight;
42823        if( pTree->pLeft==0 ){
42824          pTree->pLeft = rowSetListToTree(p);
42825          break;
42826        }else{
42827          struct RowSetEntry *pAux, *pTail;
42828          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
42829          pTree->pLeft = 0;
42830          p = rowSetEntryMerge(pAux, p);
42831        }
42832      }
42833      if( pTree==0 ){
42834        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
42835        if( pTree ){
42836          pTree->v = 0;
42837          pTree->pRight = 0;
42838          pTree->pLeft = rowSetListToTree(p);
42839        }
42840      }
42841      pRowSet->pEntry = 0;
42842      pRowSet->pLast = 0;
42843      pRowSet->rsFlags |= ROWSET_SORTED;
42844    }
42845    pRowSet->iBatch = iBatch;
42846  }
42847
42848  /* Test to see if the iRowid value appears anywhere in the forest.
42849  ** Return 1 if it does and 0 if not.
42850  */
42851  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
42852    p = pTree->pLeft;
42853    while( p ){
42854      if( p->v<iRowid ){
42855        p = p->pRight;
42856      }else if( p->v>iRowid ){
42857        p = p->pLeft;
42858      }else{
42859        return 1;
42860      }
42861    }
42862  }
42863  return 0;
42864}
42865
42866/************** End of rowset.c **********************************************/
42867/************** Begin file pager.c *******************************************/
42868/*
42869** 2001 September 15
42870**
42871** The author disclaims copyright to this source code.  In place of
42872** a legal notice, here is a blessing:
42873**
42874**    May you do good and not evil.
42875**    May you find forgiveness for yourself and forgive others.
42876**    May you share freely, never taking more than you give.
42877**
42878*************************************************************************
42879** This is the implementation of the page cache subsystem or "pager".
42880**
42881** The pager is used to access a database disk file.  It implements
42882** atomic commit and rollback through the use of a journal file that
42883** is separate from the database file.  The pager also implements file
42884** locking to prevent two processes from writing the same database
42885** file simultaneously, or one process from reading the database while
42886** another is writing.
42887*/
42888#ifndef SQLITE_OMIT_DISKIO
42889/* #include "sqliteInt.h" */
42890/************** Include wal.h in the middle of pager.c ***********************/
42891/************** Begin file wal.h *********************************************/
42892/*
42893** 2010 February 1
42894**
42895** The author disclaims copyright to this source code.  In place of
42896** a legal notice, here is a blessing:
42897**
42898**    May you do good and not evil.
42899**    May you find forgiveness for yourself and forgive others.
42900**    May you share freely, never taking more than you give.
42901**
42902*************************************************************************
42903** This header file defines the interface to the write-ahead logging
42904** system. Refer to the comments below and the header comment attached to
42905** the implementation of each function in log.c for further details.
42906*/
42907
42908#ifndef _WAL_H_
42909#define _WAL_H_
42910
42911/* #include "sqliteInt.h" */
42912
42913/* Additional values that can be added to the sync_flags argument of
42914** sqlite3WalFrames():
42915*/
42916#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
42917#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
42918
42919#ifdef SQLITE_OMIT_WAL
42920# define sqlite3WalOpen(x,y,z)                   0
42921# define sqlite3WalLimit(x,y)
42922# define sqlite3WalClose(w,x,y,z)                0
42923# define sqlite3WalBeginReadTransaction(y,z)     0
42924# define sqlite3WalEndReadTransaction(z)
42925# define sqlite3WalDbsize(y)                     0
42926# define sqlite3WalBeginWriteTransaction(y)      0
42927# define sqlite3WalEndWriteTransaction(x)        0
42928# define sqlite3WalUndo(x,y,z)                   0
42929# define sqlite3WalSavepoint(y,z)
42930# define sqlite3WalSavepointUndo(y,z)            0
42931# define sqlite3WalFrames(u,v,w,x,y,z)           0
42932# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
42933# define sqlite3WalCallback(z)                   0
42934# define sqlite3WalExclusiveMode(y,z)            0
42935# define sqlite3WalHeapMemory(z)                 0
42936# define sqlite3WalFramesize(z)                  0
42937# define sqlite3WalFindFrame(x,y,z)              0
42938#else
42939
42940#define WAL_SAVEPOINT_NDATA 4
42941
42942/* Connection to a write-ahead log (WAL) file.
42943** There is one object of this type for each pager.
42944*/
42945typedef struct Wal Wal;
42946
42947/* Open and close a connection to a write-ahead log. */
42948SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
42949SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
42950
42951/* Set the limiting size of a WAL file. */
42952SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
42953
42954/* Used by readers to open (lock) and close (unlock) a snapshot.  A
42955** snapshot is like a read-transaction.  It is the state of the database
42956** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
42957** preserves the current state even if the other threads or processes
42958** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
42959** transaction and releases the lock.
42960*/
42961SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
42962SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
42963
42964/* Read a page from the write-ahead log, if it is present. */
42965SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
42966SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
42967
42968/* If the WAL is not empty, return the size of the database. */
42969SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
42970
42971/* Obtain or release the WRITER lock. */
42972SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
42973SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
42974
42975/* Undo any frames written (but not committed) to the log */
42976SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
42977
42978/* Return an integer that records the current (uncommitted) write
42979** position in the WAL */
42980SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
42981
42982/* Move the write position of the WAL back to iFrame.  Called in
42983** response to a ROLLBACK TO command. */
42984SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
42985
42986/* Write a frame or frames to the log. */
42987SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
42988
42989/* Copy pages from the log to the database file */
42990SQLITE_PRIVATE int sqlite3WalCheckpoint(
42991  Wal *pWal,                      /* Write-ahead log connection */
42992  int eMode,                      /* One of PASSIVE, FULL and RESTART */
42993  int (*xBusy)(void*),            /* Function to call when busy */
42994  void *pBusyArg,                 /* Context argument for xBusyHandler */
42995  int sync_flags,                 /* Flags to sync db file with (or 0) */
42996  int nBuf,                       /* Size of buffer nBuf */
42997  u8 *zBuf,                       /* Temporary buffer to use */
42998  int *pnLog,                     /* OUT: Number of frames in WAL */
42999  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
43000);
43001
43002/* Return the value to pass to a sqlite3_wal_hook callback, the
43003** number of frames in the WAL at the point of the last commit since
43004** sqlite3WalCallback() was called.  If no commits have occurred since
43005** the last call, then return 0.
43006*/
43007SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
43008
43009/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
43010** by the pager layer on the database file.
43011*/
43012SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
43013
43014/* Return true if the argument is non-NULL and the WAL module is using
43015** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
43016** WAL module is using shared-memory, return false.
43017*/
43018SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
43019
43020#ifdef SQLITE_ENABLE_ZIPVFS
43021/* If the WAL file is not empty, return the number of bytes of content
43022** stored in each frame (i.e. the db page-size when the WAL was created).
43023*/
43024SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
43025#endif
43026
43027#endif /* ifndef SQLITE_OMIT_WAL */
43028#endif /* _WAL_H_ */
43029
43030/************** End of wal.h *************************************************/
43031/************** Continuing where we left off in pager.c **********************/
43032
43033
43034/******************* NOTES ON THE DESIGN OF THE PAGER ************************
43035**
43036** This comment block describes invariants that hold when using a rollback
43037** journal.  These invariants do not apply for journal_mode=WAL,
43038** journal_mode=MEMORY, or journal_mode=OFF.
43039**
43040** Within this comment block, a page is deemed to have been synced
43041** automatically as soon as it is written when PRAGMA synchronous=OFF.
43042** Otherwise, the page is not synced until the xSync method of the VFS
43043** is called successfully on the file containing the page.
43044**
43045** Definition:  A page of the database file is said to be "overwriteable" if
43046** one or more of the following are true about the page:
43047**
43048**     (a)  The original content of the page as it was at the beginning of
43049**          the transaction has been written into the rollback journal and
43050**          synced.
43051**
43052**     (b)  The page was a freelist leaf page at the start of the transaction.
43053**
43054**     (c)  The page number is greater than the largest page that existed in
43055**          the database file at the start of the transaction.
43056**
43057** (1) A page of the database file is never overwritten unless one of the
43058**     following are true:
43059**
43060**     (a) The page and all other pages on the same sector are overwriteable.
43061**
43062**     (b) The atomic page write optimization is enabled, and the entire
43063**         transaction other than the update of the transaction sequence
43064**         number consists of a single page change.
43065**
43066** (2) The content of a page written into the rollback journal exactly matches
43067**     both the content in the database when the rollback journal was written
43068**     and the content in the database at the beginning of the current
43069**     transaction.
43070**
43071** (3) Writes to the database file are an integer multiple of the page size
43072**     in length and are aligned on a page boundary.
43073**
43074** (4) Reads from the database file are either aligned on a page boundary and
43075**     an integer multiple of the page size in length or are taken from the
43076**     first 100 bytes of the database file.
43077**
43078** (5) All writes to the database file are synced prior to the rollback journal
43079**     being deleted, truncated, or zeroed.
43080**
43081** (6) If a master journal file is used, then all writes to the database file
43082**     are synced prior to the master journal being deleted.
43083**
43084** Definition: Two databases (or the same database at two points it time)
43085** are said to be "logically equivalent" if they give the same answer to
43086** all queries.  Note in particular the content of freelist leaf
43087** pages can be changed arbitrarily without affecting the logical equivalence
43088** of the database.
43089**
43090** (7) At any time, if any subset, including the empty set and the total set,
43091**     of the unsynced changes to a rollback journal are removed and the
43092**     journal is rolled back, the resulting database file will be logically
43093**     equivalent to the database file at the beginning of the transaction.
43094**
43095** (8) When a transaction is rolled back, the xTruncate method of the VFS
43096**     is called to restore the database file to the same size it was at
43097**     the beginning of the transaction.  (In some VFSes, the xTruncate
43098**     method is a no-op, but that does not change the fact the SQLite will
43099**     invoke it.)
43100**
43101** (9) Whenever the database file is modified, at least one bit in the range
43102**     of bytes from 24 through 39 inclusive will be changed prior to releasing
43103**     the EXCLUSIVE lock, thus signaling other connections on the same
43104**     database to flush their caches.
43105**
43106** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
43107**      than one billion transactions.
43108**
43109** (11) A database file is well-formed at the beginning and at the conclusion
43110**      of every transaction.
43111**
43112** (12) An EXCLUSIVE lock is held on the database file when writing to
43113**      the database file.
43114**
43115** (13) A SHARED lock is held on the database file while reading any
43116**      content out of the database file.
43117**
43118******************************************************************************/
43119
43120/*
43121** Macros for troubleshooting.  Normally turned off
43122*/
43123#if 0
43124int sqlite3PagerTrace=1;  /* True to enable tracing */
43125#define sqlite3DebugPrintf printf
43126#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
43127#else
43128#define PAGERTRACE(X)
43129#endif
43130
43131/*
43132** The following two macros are used within the PAGERTRACE() macros above
43133** to print out file-descriptors.
43134**
43135** PAGERID() takes a pointer to a Pager struct as its argument. The
43136** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
43137** struct as its argument.
43138*/
43139#define PAGERID(p) ((int)(p->fd))
43140#define FILEHANDLEID(fd) ((int)fd)
43141
43142/*
43143** The Pager.eState variable stores the current 'state' of a pager. A
43144** pager may be in any one of the seven states shown in the following
43145** state diagram.
43146**
43147**                            OPEN <------+------+
43148**                              |         |      |
43149**                              V         |      |
43150**               +---------> READER-------+      |
43151**               |              |                |
43152**               |              V                |
43153**               |<-------WRITER_LOCKED------> ERROR
43154**               |              |                ^
43155**               |              V                |
43156**               |<------WRITER_CACHEMOD-------->|
43157**               |              |                |
43158**               |              V                |
43159**               |<-------WRITER_DBMOD---------->|
43160**               |              |                |
43161**               |              V                |
43162**               +<------WRITER_FINISHED-------->+
43163**
43164**
43165** List of state transitions and the C [function] that performs each:
43166**
43167**   OPEN              -> READER              [sqlite3PagerSharedLock]
43168**   READER            -> OPEN                [pager_unlock]
43169**
43170**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
43171**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
43172**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
43173**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
43174**   WRITER_***        -> READER              [pager_end_transaction]
43175**
43176**   WRITER_***        -> ERROR               [pager_error]
43177**   ERROR             -> OPEN                [pager_unlock]
43178**
43179**
43180**  OPEN:
43181**
43182**    The pager starts up in this state. Nothing is guaranteed in this
43183**    state - the file may or may not be locked and the database size is
43184**    unknown. The database may not be read or written.
43185**
43186**    * No read or write transaction is active.
43187**    * Any lock, or no lock at all, may be held on the database file.
43188**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
43189**
43190**  READER:
43191**
43192**    In this state all the requirements for reading the database in
43193**    rollback (non-WAL) mode are met. Unless the pager is (or recently
43194**    was) in exclusive-locking mode, a user-level read transaction is
43195**    open. The database size is known in this state.
43196**
43197**    A connection running with locking_mode=normal enters this state when
43198**    it opens a read-transaction on the database and returns to state
43199**    OPEN after the read-transaction is completed. However a connection
43200**    running in locking_mode=exclusive (including temp databases) remains in
43201**    this state even after the read-transaction is closed. The only way
43202**    a locking_mode=exclusive connection can transition from READER to OPEN
43203**    is via the ERROR state (see below).
43204**
43205**    * A read transaction may be active (but a write-transaction cannot).
43206**    * A SHARED or greater lock is held on the database file.
43207**    * The dbSize variable may be trusted (even if a user-level read
43208**      transaction is not active). The dbOrigSize and dbFileSize variables
43209**      may not be trusted at this point.
43210**    * If the database is a WAL database, then the WAL connection is open.
43211**    * Even if a read-transaction is not open, it is guaranteed that
43212**      there is no hot-journal in the file-system.
43213**
43214**  WRITER_LOCKED:
43215**
43216**    The pager moves to this state from READER when a write-transaction
43217**    is first opened on the database. In WRITER_LOCKED state, all locks
43218**    required to start a write-transaction are held, but no actual
43219**    modifications to the cache or database have taken place.
43220**
43221**    In rollback mode, a RESERVED or (if the transaction was opened with
43222**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
43223**    moving to this state, but the journal file is not written to or opened
43224**    to in this state. If the transaction is committed or rolled back while
43225**    in WRITER_LOCKED state, all that is required is to unlock the database
43226**    file.
43227**
43228**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
43229**    If the connection is running with locking_mode=exclusive, an attempt
43230**    is made to obtain an EXCLUSIVE lock on the database file.
43231**
43232**    * A write transaction is active.
43233**    * If the connection is open in rollback-mode, a RESERVED or greater
43234**      lock is held on the database file.
43235**    * If the connection is open in WAL-mode, a WAL write transaction
43236**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
43237**      called).
43238**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
43239**    * The contents of the pager cache have not been modified.
43240**    * The journal file may or may not be open.
43241**    * Nothing (not even the first header) has been written to the journal.
43242**
43243**  WRITER_CACHEMOD:
43244**
43245**    A pager moves from WRITER_LOCKED state to this state when a page is
43246**    first modified by the upper layer. In rollback mode the journal file
43247**    is opened (if it is not already open) and a header written to the
43248**    start of it. The database file on disk has not been modified.
43249**
43250**    * A write transaction is active.
43251**    * A RESERVED or greater lock is held on the database file.
43252**    * The journal file is open and the first header has been written
43253**      to it, but the header has not been synced to disk.
43254**    * The contents of the page cache have been modified.
43255**
43256**  WRITER_DBMOD:
43257**
43258**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
43259**    when it modifies the contents of the database file. WAL connections
43260**    never enter this state (since they do not modify the database file,
43261**    just the log file).
43262**
43263**    * A write transaction is active.
43264**    * An EXCLUSIVE or greater lock is held on the database file.
43265**    * The journal file is open and the first header has been written
43266**      and synced to disk.
43267**    * The contents of the page cache have been modified (and possibly
43268**      written to disk).
43269**
43270**  WRITER_FINISHED:
43271**
43272**    It is not possible for a WAL connection to enter this state.
43273**
43274**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
43275**    state after the entire transaction has been successfully written into the
43276**    database file. In this state the transaction may be committed simply
43277**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
43278**    not possible to modify the database further. At this point, the upper
43279**    layer must either commit or rollback the transaction.
43280**
43281**    * A write transaction is active.
43282**    * An EXCLUSIVE or greater lock is held on the database file.
43283**    * All writing and syncing of journal and database data has finished.
43284**      If no error occurred, all that remains is to finalize the journal to
43285**      commit the transaction. If an error did occur, the caller will need
43286**      to rollback the transaction.
43287**
43288**  ERROR:
43289**
43290**    The ERROR state is entered when an IO or disk-full error (including
43291**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
43292**    difficult to be sure that the in-memory pager state (cache contents,
43293**    db size etc.) are consistent with the contents of the file-system.
43294**
43295**    Temporary pager files may enter the ERROR state, but in-memory pagers
43296**    cannot.
43297**
43298**    For example, if an IO error occurs while performing a rollback,
43299**    the contents of the page-cache may be left in an inconsistent state.
43300**    At this point it would be dangerous to change back to READER state
43301**    (as usually happens after a rollback). Any subsequent readers might
43302**    report database corruption (due to the inconsistent cache), and if
43303**    they upgrade to writers, they may inadvertently corrupt the database
43304**    file. To avoid this hazard, the pager switches into the ERROR state
43305**    instead of READER following such an error.
43306**
43307**    Once it has entered the ERROR state, any attempt to use the pager
43308**    to read or write data returns an error. Eventually, once all
43309**    outstanding transactions have been abandoned, the pager is able to
43310**    transition back to OPEN state, discarding the contents of the
43311**    page-cache and any other in-memory state at the same time. Everything
43312**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
43313**    when a read-transaction is next opened on the pager (transitioning
43314**    the pager into READER state). At that point the system has recovered
43315**    from the error.
43316**
43317**    Specifically, the pager jumps into the ERROR state if:
43318**
43319**      1. An error occurs while attempting a rollback. This happens in
43320**         function sqlite3PagerRollback().
43321**
43322**      2. An error occurs while attempting to finalize a journal file
43323**         following a commit in function sqlite3PagerCommitPhaseTwo().
43324**
43325**      3. An error occurs while attempting to write to the journal or
43326**         database file in function pagerStress() in order to free up
43327**         memory.
43328**
43329**    In other cases, the error is returned to the b-tree layer. The b-tree
43330**    layer then attempts a rollback operation. If the error condition
43331**    persists, the pager enters the ERROR state via condition (1) above.
43332**
43333**    Condition (3) is necessary because it can be triggered by a read-only
43334**    statement executed within a transaction. In this case, if the error
43335**    code were simply returned to the user, the b-tree layer would not
43336**    automatically attempt a rollback, as it assumes that an error in a
43337**    read-only statement cannot leave the pager in an internally inconsistent
43338**    state.
43339**
43340**    * The Pager.errCode variable is set to something other than SQLITE_OK.
43341**    * There are one or more outstanding references to pages (after the
43342**      last reference is dropped the pager should move back to OPEN state).
43343**    * The pager is not an in-memory pager.
43344**
43345**
43346** Notes:
43347**
43348**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
43349**     connection is open in WAL mode. A WAL connection is always in one
43350**     of the first four states.
43351**
43352**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
43353**     state. There are two exceptions: immediately after exclusive-mode has
43354**     been turned on (and before any read or write transactions are
43355**     executed), and when the pager is leaving the "error state".
43356**
43357**   * See also: assert_pager_state().
43358*/
43359#define PAGER_OPEN                  0
43360#define PAGER_READER                1
43361#define PAGER_WRITER_LOCKED         2
43362#define PAGER_WRITER_CACHEMOD       3
43363#define PAGER_WRITER_DBMOD          4
43364#define PAGER_WRITER_FINISHED       5
43365#define PAGER_ERROR                 6
43366
43367/*
43368** The Pager.eLock variable is almost always set to one of the
43369** following locking-states, according to the lock currently held on
43370** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
43371** This variable is kept up to date as locks are taken and released by
43372** the pagerLockDb() and pagerUnlockDb() wrappers.
43373**
43374** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
43375** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
43376** the operation was successful. In these circumstances pagerLockDb() and
43377** pagerUnlockDb() take a conservative approach - eLock is always updated
43378** when unlocking the file, and only updated when locking the file if the
43379** VFS call is successful. This way, the Pager.eLock variable may be set
43380** to a less exclusive (lower) value than the lock that is actually held
43381** at the system level, but it is never set to a more exclusive value.
43382**
43383** This is usually safe. If an xUnlock fails or appears to fail, there may
43384** be a few redundant xLock() calls or a lock may be held for longer than
43385** required, but nothing really goes wrong.
43386**
43387** The exception is when the database file is unlocked as the pager moves
43388** from ERROR to OPEN state. At this point there may be a hot-journal file
43389** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
43390** transition, by the same pager or any other). If the call to xUnlock()
43391** fails at this point and the pager is left holding an EXCLUSIVE lock, this
43392** can confuse the call to xCheckReservedLock() call made later as part
43393** of hot-journal detection.
43394**
43395** xCheckReservedLock() is defined as returning true "if there is a RESERVED
43396** lock held by this process or any others". So xCheckReservedLock may
43397** return true because the caller itself is holding an EXCLUSIVE lock (but
43398** doesn't know it because of a previous error in xUnlock). If this happens
43399** a hot-journal may be mistaken for a journal being created by an active
43400** transaction in another process, causing SQLite to read from the database
43401** without rolling it back.
43402**
43403** To work around this, if a call to xUnlock() fails when unlocking the
43404** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
43405** is only changed back to a real locking state after a successful call
43406** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
43407** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
43408** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
43409** lock on the database file before attempting to roll it back. See function
43410** PagerSharedLock() for more detail.
43411**
43412** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
43413** PAGER_OPEN state.
43414*/
43415#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
43416
43417/*
43418** A macro used for invoking the codec if there is one
43419*/
43420#ifdef SQLITE_HAS_CODEC
43421# define CODEC1(P,D,N,X,E) \
43422    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
43423# define CODEC2(P,D,N,X,E,O) \
43424    if( P->xCodec==0 ){ O=(char*)D; }else \
43425    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
43426#else
43427# define CODEC1(P,D,N,X,E)   /* NO-OP */
43428# define CODEC2(P,D,N,X,E,O) O=(char*)D
43429#endif
43430
43431/*
43432** The maximum allowed sector size. 64KiB. If the xSectorsize() method
43433** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
43434** This could conceivably cause corruption following a power failure on
43435** such a system. This is currently an undocumented limit.
43436*/
43437#define MAX_SECTOR_SIZE 0x10000
43438
43439/*
43440** An instance of the following structure is allocated for each active
43441** savepoint and statement transaction in the system. All such structures
43442** are stored in the Pager.aSavepoint[] array, which is allocated and
43443** resized using sqlite3Realloc().
43444**
43445** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
43446** set to 0. If a journal-header is written into the main journal while
43447** the savepoint is active, then iHdrOffset is set to the byte offset
43448** immediately following the last journal record written into the main
43449** journal before the journal-header. This is required during savepoint
43450** rollback (see pagerPlaybackSavepoint()).
43451*/
43452typedef struct PagerSavepoint PagerSavepoint;
43453struct PagerSavepoint {
43454  i64 iOffset;                 /* Starting offset in main journal */
43455  i64 iHdrOffset;              /* See above */
43456  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
43457  Pgno nOrig;                  /* Original number of pages in file */
43458  Pgno iSubRec;                /* Index of first record in sub-journal */
43459#ifndef SQLITE_OMIT_WAL
43460  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
43461#endif
43462};
43463
43464/*
43465** Bits of the Pager.doNotSpill flag.  See further description below.
43466*/
43467#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
43468#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
43469#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
43470
43471/*
43472** An open page cache is an instance of struct Pager. A description of
43473** some of the more important member variables follows:
43474**
43475** eState
43476**
43477**   The current 'state' of the pager object. See the comment and state
43478**   diagram above for a description of the pager state.
43479**
43480** eLock
43481**
43482**   For a real on-disk database, the current lock held on the database file -
43483**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
43484**
43485**   For a temporary or in-memory database (neither of which require any
43486**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
43487**   databases always have Pager.exclusiveMode==1, this tricks the pager
43488**   logic into thinking that it already has all the locks it will ever
43489**   need (and no reason to release them).
43490**
43491**   In some (obscure) circumstances, this variable may also be set to
43492**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
43493**   details.
43494**
43495** changeCountDone
43496**
43497**   This boolean variable is used to make sure that the change-counter
43498**   (the 4-byte header field at byte offset 24 of the database file) is
43499**   not updated more often than necessary.
43500**
43501**   It is set to true when the change-counter field is updated, which
43502**   can only happen if an exclusive lock is held on the database file.
43503**   It is cleared (set to false) whenever an exclusive lock is
43504**   relinquished on the database file. Each time a transaction is committed,
43505**   The changeCountDone flag is inspected. If it is true, the work of
43506**   updating the change-counter is omitted for the current transaction.
43507**
43508**   This mechanism means that when running in exclusive mode, a connection
43509**   need only update the change-counter once, for the first transaction
43510**   committed.
43511**
43512** setMaster
43513**
43514**   When PagerCommitPhaseOne() is called to commit a transaction, it may
43515**   (or may not) specify a master-journal name to be written into the
43516**   journal file before it is synced to disk.
43517**
43518**   Whether or not a journal file contains a master-journal pointer affects
43519**   the way in which the journal file is finalized after the transaction is
43520**   committed or rolled back when running in "journal_mode=PERSIST" mode.
43521**   If a journal file does not contain a master-journal pointer, it is
43522**   finalized by overwriting the first journal header with zeroes. If
43523**   it does contain a master-journal pointer the journal file is finalized
43524**   by truncating it to zero bytes, just as if the connection were
43525**   running in "journal_mode=truncate" mode.
43526**
43527**   Journal files that contain master journal pointers cannot be finalized
43528**   simply by overwriting the first journal-header with zeroes, as the
43529**   master journal pointer could interfere with hot-journal rollback of any
43530**   subsequently interrupted transaction that reuses the journal file.
43531**
43532**   The flag is cleared as soon as the journal file is finalized (either
43533**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
43534**   journal file from being successfully finalized, the setMaster flag
43535**   is cleared anyway (and the pager will move to ERROR state).
43536**
43537** doNotSpill
43538**
43539**   This variables control the behavior of cache-spills  (calls made by
43540**   the pcache module to the pagerStress() routine to write cached data
43541**   to the file-system in order to free up memory).
43542**
43543**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
43544**   writing to the database from pagerStress() is disabled altogether.
43545**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
43546**   comes up during savepoint rollback that requires the pcache module
43547**   to allocate a new page to prevent the journal file from being written
43548**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
43549**   case is a user preference.
43550**
43551**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
43552**   pagerStress() is permitted, but syncing the journal file is not.
43553**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
43554**   is larger than the database page-size in order to prevent a journal sync
43555**   from happening in between the journalling of two pages on the same sector.
43556**
43557** subjInMemory
43558**
43559**   This is a boolean variable. If true, then any required sub-journal
43560**   is opened as an in-memory journal file. If false, then in-memory
43561**   sub-journals are only used for in-memory pager files.
43562**
43563**   This variable is updated by the upper layer each time a new
43564**   write-transaction is opened.
43565**
43566** dbSize, dbOrigSize, dbFileSize
43567**
43568**   Variable dbSize is set to the number of pages in the database file.
43569**   It is valid in PAGER_READER and higher states (all states except for
43570**   OPEN and ERROR).
43571**
43572**   dbSize is set based on the size of the database file, which may be
43573**   larger than the size of the database (the value stored at offset
43574**   28 of the database header by the btree). If the size of the file
43575**   is not an integer multiple of the page-size, the value stored in
43576**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
43577**   Except, any file that is greater than 0 bytes in size is considered
43578**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
43579**   to dbSize==1).
43580**
43581**   During a write-transaction, if pages with page-numbers greater than
43582**   dbSize are modified in the cache, dbSize is updated accordingly.
43583**   Similarly, if the database is truncated using PagerTruncateImage(),
43584**   dbSize is updated.
43585**
43586**   Variables dbOrigSize and dbFileSize are valid in states
43587**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
43588**   variable at the start of the transaction. It is used during rollback,
43589**   and to determine whether or not pages need to be journalled before
43590**   being modified.
43591**
43592**   Throughout a write-transaction, dbFileSize contains the size of
43593**   the file on disk in pages. It is set to a copy of dbSize when the
43594**   write-transaction is first opened, and updated when VFS calls are made
43595**   to write or truncate the database file on disk.
43596**
43597**   The only reason the dbFileSize variable is required is to suppress
43598**   unnecessary calls to xTruncate() after committing a transaction. If,
43599**   when a transaction is committed, the dbFileSize variable indicates
43600**   that the database file is larger than the database image (Pager.dbSize),
43601**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
43602**   to measure the database file on disk, and then truncates it if required.
43603**   dbFileSize is not used when rolling back a transaction. In this case
43604**   pager_truncate() is called unconditionally (which means there may be
43605**   a call to xFilesize() that is not strictly required). In either case,
43606**   pager_truncate() may cause the file to become smaller or larger.
43607**
43608** dbHintSize
43609**
43610**   The dbHintSize variable is used to limit the number of calls made to
43611**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
43612**
43613**   dbHintSize is set to a copy of the dbSize variable when a
43614**   write-transaction is opened (at the same time as dbFileSize and
43615**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
43616**   dbHintSize is increased to the number of pages that correspond to the
43617**   size-hint passed to the method call. See pager_write_pagelist() for
43618**   details.
43619**
43620** errCode
43621**
43622**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
43623**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
43624**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
43625**   sub-codes.
43626*/
43627struct Pager {
43628  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
43629  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
43630  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
43631  u8 useJournal;              /* Use a rollback journal on this file */
43632  u8 noSync;                  /* Do not sync the journal if true */
43633  u8 fullSync;                /* Do extra syncs of the journal for robustness */
43634  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
43635  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
43636  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
43637  u8 tempFile;                /* zFilename is a temporary or immutable file */
43638  u8 noLock;                  /* Do not lock (except in WAL mode) */
43639  u8 readOnly;                /* True for a read-only database */
43640  u8 memDb;                   /* True to inhibit all file I/O */
43641
43642  /**************************************************************************
43643  ** The following block contains those class members that change during
43644  ** routine operation.  Class members not in this block are either fixed
43645  ** when the pager is first created or else only change when there is a
43646  ** significant mode change (such as changing the page_size, locking_mode,
43647  ** or the journal_mode).  From another view, these class members describe
43648  ** the "state" of the pager, while other class members describe the
43649  ** "configuration" of the pager.
43650  */
43651  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
43652  u8 eLock;                   /* Current lock held on database file */
43653  u8 changeCountDone;         /* Set after incrementing the change-counter */
43654  u8 setMaster;               /* True if a m-j name has been written to jrnl */
43655  u8 doNotSpill;              /* Do not spill the cache when non-zero */
43656  u8 subjInMemory;            /* True to use in-memory sub-journals */
43657  u8 bUseFetch;               /* True to use xFetch() */
43658  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
43659  Pgno dbSize;                /* Number of pages in the database */
43660  Pgno dbOrigSize;            /* dbSize before the current transaction */
43661  Pgno dbFileSize;            /* Number of pages in the database file */
43662  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
43663  int errCode;                /* One of several kinds of errors */
43664  int nRec;                   /* Pages journalled since last j-header written */
43665  u32 cksumInit;              /* Quasi-random value added to every checksum */
43666  u32 nSubRec;                /* Number of records written to sub-journal */
43667  Bitvec *pInJournal;         /* One bit for each page in the database file */
43668  sqlite3_file *fd;           /* File descriptor for database */
43669  sqlite3_file *jfd;          /* File descriptor for main journal */
43670  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
43671  i64 journalOff;             /* Current write offset in the journal file */
43672  i64 journalHdr;             /* Byte offset to previous journal header */
43673  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
43674  PagerSavepoint *aSavepoint; /* Array of active savepoints */
43675  int nSavepoint;             /* Number of elements in aSavepoint[] */
43676  u32 iDataVersion;           /* Changes whenever database content changes */
43677  char dbFileVers[16];        /* Changes whenever database file changes */
43678
43679  int nMmapOut;               /* Number of mmap pages currently outstanding */
43680  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
43681  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
43682  /*
43683  ** End of the routinely-changing class members
43684  ***************************************************************************/
43685
43686  u16 nExtra;                 /* Add this many bytes to each in-memory page */
43687  i16 nReserve;               /* Number of unused bytes at end of each page */
43688  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
43689  u32 sectorSize;             /* Assumed sector size during rollback */
43690  int pageSize;               /* Number of bytes in a page */
43691  Pgno mxPgno;                /* Maximum allowed size of the database */
43692  i64 journalSizeLimit;       /* Size limit for persistent journal files */
43693  char *zFilename;            /* Name of the database file */
43694  char *zJournal;             /* Name of the journal file */
43695  int (*xBusyHandler)(void*); /* Function to call when busy */
43696  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
43697  int aStat[3];               /* Total cache hits, misses and writes */
43698#ifdef SQLITE_TEST
43699  int nRead;                  /* Database pages read */
43700#endif
43701  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
43702#ifdef SQLITE_HAS_CODEC
43703  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
43704  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
43705  void (*xCodecFree)(void*);             /* Destructor for the codec */
43706  void *pCodec;               /* First argument to xCodec... methods */
43707#endif
43708  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
43709  PCache *pPCache;            /* Pointer to page cache object */
43710#ifndef SQLITE_OMIT_WAL
43711  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
43712  char *zWal;                 /* File name for write-ahead log */
43713#endif
43714};
43715
43716/*
43717** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
43718** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
43719** or CACHE_WRITE to sqlite3_db_status().
43720*/
43721#define PAGER_STAT_HIT   0
43722#define PAGER_STAT_MISS  1
43723#define PAGER_STAT_WRITE 2
43724
43725/*
43726** The following global variables hold counters used for
43727** testing purposes only.  These variables do not exist in
43728** a non-testing build.  These variables are not thread-safe.
43729*/
43730#ifdef SQLITE_TEST
43731SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
43732SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
43733SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
43734# define PAGER_INCR(v)  v++
43735#else
43736# define PAGER_INCR(v)
43737#endif
43738
43739
43740
43741/*
43742** Journal files begin with the following magic string.  The data
43743** was obtained from /dev/random.  It is used only as a sanity check.
43744**
43745** Since version 2.8.0, the journal format contains additional sanity
43746** checking information.  If the power fails while the journal is being
43747** written, semi-random garbage data might appear in the journal
43748** file after power is restored.  If an attempt is then made
43749** to roll the journal back, the database could be corrupted.  The additional
43750** sanity checking data is an attempt to discover the garbage in the
43751** journal and ignore it.
43752**
43753** The sanity checking information for the new journal format consists
43754** of a 32-bit checksum on each page of data.  The checksum covers both
43755** the page number and the pPager->pageSize bytes of data for the page.
43756** This cksum is initialized to a 32-bit random value that appears in the
43757** journal file right after the header.  The random initializer is important,
43758** because garbage data that appears at the end of a journal is likely
43759** data that was once in other files that have now been deleted.  If the
43760** garbage data came from an obsolete journal file, the checksums might
43761** be correct.  But by initializing the checksum to random value which
43762** is different for every journal, we minimize that risk.
43763*/
43764static const unsigned char aJournalMagic[] = {
43765  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
43766};
43767
43768/*
43769** The size of the of each page record in the journal is given by
43770** the following macro.
43771*/
43772#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
43773
43774/*
43775** The journal header size for this pager. This is usually the same
43776** size as a single disk sector. See also setSectorSize().
43777*/
43778#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
43779
43780/*
43781** The macro MEMDB is true if we are dealing with an in-memory database.
43782** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
43783** the value of MEMDB will be a constant and the compiler will optimize
43784** out code that would never execute.
43785*/
43786#ifdef SQLITE_OMIT_MEMORYDB
43787# define MEMDB 0
43788#else
43789# define MEMDB pPager->memDb
43790#endif
43791
43792/*
43793** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
43794** interfaces to access the database using memory-mapped I/O.
43795*/
43796#if SQLITE_MAX_MMAP_SIZE>0
43797# define USEFETCH(x) ((x)->bUseFetch)
43798#else
43799# define USEFETCH(x) 0
43800#endif
43801
43802/*
43803** The maximum legal page number is (2^31 - 1).
43804*/
43805#define PAGER_MAX_PGNO 2147483647
43806
43807/*
43808** The argument to this macro is a file descriptor (type sqlite3_file*).
43809** Return 0 if it is not open, or non-zero (but not 1) if it is.
43810**
43811** This is so that expressions can be written as:
43812**
43813**   if( isOpen(pPager->jfd) ){ ...
43814**
43815** instead of
43816**
43817**   if( pPager->jfd->pMethods ){ ...
43818*/
43819#define isOpen(pFd) ((pFd)->pMethods!=0)
43820
43821/*
43822** Return true if this pager uses a write-ahead log instead of the usual
43823** rollback journal. Otherwise false.
43824*/
43825#ifndef SQLITE_OMIT_WAL
43826static int pagerUseWal(Pager *pPager){
43827  return (pPager->pWal!=0);
43828}
43829#else
43830# define pagerUseWal(x) 0
43831# define pagerRollbackWal(x) 0
43832# define pagerWalFrames(v,w,x,y) 0
43833# define pagerOpenWalIfPresent(z) SQLITE_OK
43834# define pagerBeginReadTransaction(z) SQLITE_OK
43835#endif
43836
43837#ifndef NDEBUG
43838/*
43839** Usage:
43840**
43841**   assert( assert_pager_state(pPager) );
43842**
43843** This function runs many asserts to try to find inconsistencies in
43844** the internal state of the Pager object.
43845*/
43846static int assert_pager_state(Pager *p){
43847  Pager *pPager = p;
43848
43849  /* State must be valid. */
43850  assert( p->eState==PAGER_OPEN
43851       || p->eState==PAGER_READER
43852       || p->eState==PAGER_WRITER_LOCKED
43853       || p->eState==PAGER_WRITER_CACHEMOD
43854       || p->eState==PAGER_WRITER_DBMOD
43855       || p->eState==PAGER_WRITER_FINISHED
43856       || p->eState==PAGER_ERROR
43857  );
43858
43859  /* Regardless of the current state, a temp-file connection always behaves
43860  ** as if it has an exclusive lock on the database file. It never updates
43861  ** the change-counter field, so the changeCountDone flag is always set.
43862  */
43863  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
43864  assert( p->tempFile==0 || pPager->changeCountDone );
43865
43866  /* If the useJournal flag is clear, the journal-mode must be "OFF".
43867  ** And if the journal-mode is "OFF", the journal file must not be open.
43868  */
43869  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
43870  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
43871
43872  /* Check that MEMDB implies noSync. And an in-memory journal. Since
43873  ** this means an in-memory pager performs no IO at all, it cannot encounter
43874  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
43875  ** a journal file. (although the in-memory journal implementation may
43876  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
43877  ** is therefore not possible for an in-memory pager to enter the ERROR
43878  ** state.
43879  */
43880  if( MEMDB ){
43881    assert( p->noSync );
43882    assert( p->journalMode==PAGER_JOURNALMODE_OFF
43883         || p->journalMode==PAGER_JOURNALMODE_MEMORY
43884    );
43885    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
43886    assert( pagerUseWal(p)==0 );
43887  }
43888
43889  /* If changeCountDone is set, a RESERVED lock or greater must be held
43890  ** on the file.
43891  */
43892  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
43893  assert( p->eLock!=PENDING_LOCK );
43894
43895  switch( p->eState ){
43896    case PAGER_OPEN:
43897      assert( !MEMDB );
43898      assert( pPager->errCode==SQLITE_OK );
43899      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
43900      break;
43901
43902    case PAGER_READER:
43903      assert( pPager->errCode==SQLITE_OK );
43904      assert( p->eLock!=UNKNOWN_LOCK );
43905      assert( p->eLock>=SHARED_LOCK );
43906      break;
43907
43908    case PAGER_WRITER_LOCKED:
43909      assert( p->eLock!=UNKNOWN_LOCK );
43910      assert( pPager->errCode==SQLITE_OK );
43911      if( !pagerUseWal(pPager) ){
43912        assert( p->eLock>=RESERVED_LOCK );
43913      }
43914      assert( pPager->dbSize==pPager->dbOrigSize );
43915      assert( pPager->dbOrigSize==pPager->dbFileSize );
43916      assert( pPager->dbOrigSize==pPager->dbHintSize );
43917      assert( pPager->setMaster==0 );
43918      break;
43919
43920    case PAGER_WRITER_CACHEMOD:
43921      assert( p->eLock!=UNKNOWN_LOCK );
43922      assert( pPager->errCode==SQLITE_OK );
43923      if( !pagerUseWal(pPager) ){
43924        /* It is possible that if journal_mode=wal here that neither the
43925        ** journal file nor the WAL file are open. This happens during
43926        ** a rollback transaction that switches from journal_mode=off
43927        ** to journal_mode=wal.
43928        */
43929        assert( p->eLock>=RESERVED_LOCK );
43930        assert( isOpen(p->jfd)
43931             || p->journalMode==PAGER_JOURNALMODE_OFF
43932             || p->journalMode==PAGER_JOURNALMODE_WAL
43933        );
43934      }
43935      assert( pPager->dbOrigSize==pPager->dbFileSize );
43936      assert( pPager->dbOrigSize==pPager->dbHintSize );
43937      break;
43938
43939    case PAGER_WRITER_DBMOD:
43940      assert( p->eLock==EXCLUSIVE_LOCK );
43941      assert( pPager->errCode==SQLITE_OK );
43942      assert( !pagerUseWal(pPager) );
43943      assert( p->eLock>=EXCLUSIVE_LOCK );
43944      assert( isOpen(p->jfd)
43945           || p->journalMode==PAGER_JOURNALMODE_OFF
43946           || p->journalMode==PAGER_JOURNALMODE_WAL
43947      );
43948      assert( pPager->dbOrigSize<=pPager->dbHintSize );
43949      break;
43950
43951    case PAGER_WRITER_FINISHED:
43952      assert( p->eLock==EXCLUSIVE_LOCK );
43953      assert( pPager->errCode==SQLITE_OK );
43954      assert( !pagerUseWal(pPager) );
43955      assert( isOpen(p->jfd)
43956           || p->journalMode==PAGER_JOURNALMODE_OFF
43957           || p->journalMode==PAGER_JOURNALMODE_WAL
43958      );
43959      break;
43960
43961    case PAGER_ERROR:
43962      /* There must be at least one outstanding reference to the pager if
43963      ** in ERROR state. Otherwise the pager should have already dropped
43964      ** back to OPEN state.
43965      */
43966      assert( pPager->errCode!=SQLITE_OK );
43967      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
43968      break;
43969  }
43970
43971  return 1;
43972}
43973#endif /* ifndef NDEBUG */
43974
43975#ifdef SQLITE_DEBUG
43976/*
43977** Return a pointer to a human readable string in a static buffer
43978** containing the state of the Pager object passed as an argument. This
43979** is intended to be used within debuggers. For example, as an alternative
43980** to "print *pPager" in gdb:
43981**
43982** (gdb) printf "%s", print_pager_state(pPager)
43983*/
43984static char *print_pager_state(Pager *p){
43985  static char zRet[1024];
43986
43987  sqlite3_snprintf(1024, zRet,
43988      "Filename:      %s\n"
43989      "State:         %s errCode=%d\n"
43990      "Lock:          %s\n"
43991      "Locking mode:  locking_mode=%s\n"
43992      "Journal mode:  journal_mode=%s\n"
43993      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
43994      "Journal:       journalOff=%lld journalHdr=%lld\n"
43995      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
43996      , p->zFilename
43997      , p->eState==PAGER_OPEN            ? "OPEN" :
43998        p->eState==PAGER_READER          ? "READER" :
43999        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
44000        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
44001        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
44002        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
44003        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
44004      , (int)p->errCode
44005      , p->eLock==NO_LOCK         ? "NO_LOCK" :
44006        p->eLock==RESERVED_LOCK   ? "RESERVED" :
44007        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
44008        p->eLock==SHARED_LOCK     ? "SHARED" :
44009        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
44010      , p->exclusiveMode ? "exclusive" : "normal"
44011      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
44012        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
44013        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
44014        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
44015        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
44016        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
44017      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
44018      , p->journalOff, p->journalHdr
44019      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
44020  );
44021
44022  return zRet;
44023}
44024#endif
44025
44026/*
44027** Return true if it is necessary to write page *pPg into the sub-journal.
44028** A page needs to be written into the sub-journal if there exists one
44029** or more open savepoints for which:
44030**
44031**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
44032**   * The bit corresponding to the page-number is not set in
44033**     PagerSavepoint.pInSavepoint.
44034*/
44035static int subjRequiresPage(PgHdr *pPg){
44036  Pager *pPager = pPg->pPager;
44037  PagerSavepoint *p;
44038  Pgno pgno = pPg->pgno;
44039  int i;
44040  for(i=0; i<pPager->nSavepoint; i++){
44041    p = &pPager->aSavepoint[i];
44042    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
44043      return 1;
44044    }
44045  }
44046  return 0;
44047}
44048
44049#ifdef SQLITE_DEBUG
44050/*
44051** Return true if the page is already in the journal file.
44052*/
44053static int pageInJournal(Pager *pPager, PgHdr *pPg){
44054  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
44055}
44056#endif
44057
44058/*
44059** Read a 32-bit integer from the given file descriptor.  Store the integer
44060** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
44061** error code is something goes wrong.
44062**
44063** All values are stored on disk as big-endian.
44064*/
44065static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
44066  unsigned char ac[4];
44067  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
44068  if( rc==SQLITE_OK ){
44069    *pRes = sqlite3Get4byte(ac);
44070  }
44071  return rc;
44072}
44073
44074/*
44075** Write a 32-bit integer into a string buffer in big-endian byte order.
44076*/
44077#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
44078
44079
44080/*
44081** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
44082** on success or an error code is something goes wrong.
44083*/
44084static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
44085  char ac[4];
44086  put32bits(ac, val);
44087  return sqlite3OsWrite(fd, ac, 4, offset);
44088}
44089
44090/*
44091** Unlock the database file to level eLock, which must be either NO_LOCK
44092** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
44093** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
44094**
44095** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
44096** called, do not modify it. See the comment above the #define of
44097** UNKNOWN_LOCK for an explanation of this.
44098*/
44099static int pagerUnlockDb(Pager *pPager, int eLock){
44100  int rc = SQLITE_OK;
44101
44102  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
44103  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
44104  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
44105  if( isOpen(pPager->fd) ){
44106    assert( pPager->eLock>=eLock );
44107    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
44108    if( pPager->eLock!=UNKNOWN_LOCK ){
44109      pPager->eLock = (u8)eLock;
44110    }
44111    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
44112  }
44113  return rc;
44114}
44115
44116/*
44117** Lock the database file to level eLock, which must be either SHARED_LOCK,
44118** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
44119** Pager.eLock variable to the new locking state.
44120**
44121** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
44122** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
44123** See the comment above the #define of UNKNOWN_LOCK for an explanation
44124** of this.
44125*/
44126static int pagerLockDb(Pager *pPager, int eLock){
44127  int rc = SQLITE_OK;
44128
44129  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
44130  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
44131    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
44132    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
44133      pPager->eLock = (u8)eLock;
44134      IOTRACE(("LOCK %p %d\n", pPager, eLock))
44135    }
44136  }
44137  return rc;
44138}
44139
44140/*
44141** This function determines whether or not the atomic-write optimization
44142** can be used with this pager. The optimization can be used if:
44143**
44144**  (a) the value returned by OsDeviceCharacteristics() indicates that
44145**      a database page may be written atomically, and
44146**  (b) the value returned by OsSectorSize() is less than or equal
44147**      to the page size.
44148**
44149** The optimization is also always enabled for temporary files. It is
44150** an error to call this function if pPager is opened on an in-memory
44151** database.
44152**
44153** If the optimization cannot be used, 0 is returned. If it can be used,
44154** then the value returned is the size of the journal file when it
44155** contains rollback data for exactly one page.
44156*/
44157#ifdef SQLITE_ENABLE_ATOMIC_WRITE
44158static int jrnlBufferSize(Pager *pPager){
44159  assert( !MEMDB );
44160  if( !pPager->tempFile ){
44161    int dc;                           /* Device characteristics */
44162    int nSector;                      /* Sector size */
44163    int szPage;                       /* Page size */
44164
44165    assert( isOpen(pPager->fd) );
44166    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
44167    nSector = pPager->sectorSize;
44168    szPage = pPager->pageSize;
44169
44170    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
44171    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
44172    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
44173      return 0;
44174    }
44175  }
44176
44177  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
44178}
44179#endif
44180
44181/*
44182** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
44183** on the cache using a hash function.  This is used for testing
44184** and debugging only.
44185*/
44186#ifdef SQLITE_CHECK_PAGES
44187/*
44188** Return a 32-bit hash of the page data for pPage.
44189*/
44190static u32 pager_datahash(int nByte, unsigned char *pData){
44191  u32 hash = 0;
44192  int i;
44193  for(i=0; i<nByte; i++){
44194    hash = (hash*1039) + pData[i];
44195  }
44196  return hash;
44197}
44198static u32 pager_pagehash(PgHdr *pPage){
44199  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
44200}
44201static void pager_set_pagehash(PgHdr *pPage){
44202  pPage->pageHash = pager_pagehash(pPage);
44203}
44204
44205/*
44206** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
44207** is defined, and NDEBUG is not defined, an assert() statement checks
44208** that the page is either dirty or still matches the calculated page-hash.
44209*/
44210#define CHECK_PAGE(x) checkPage(x)
44211static void checkPage(PgHdr *pPg){
44212  Pager *pPager = pPg->pPager;
44213  assert( pPager->eState!=PAGER_ERROR );
44214  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
44215}
44216
44217#else
44218#define pager_datahash(X,Y)  0
44219#define pager_pagehash(X)  0
44220#define pager_set_pagehash(X)
44221#define CHECK_PAGE(x)
44222#endif  /* SQLITE_CHECK_PAGES */
44223
44224/*
44225** When this is called the journal file for pager pPager must be open.
44226** This function attempts to read a master journal file name from the
44227** end of the file and, if successful, copies it into memory supplied
44228** by the caller. See comments above writeMasterJournal() for the format
44229** used to store a master journal file name at the end of a journal file.
44230**
44231** zMaster must point to a buffer of at least nMaster bytes allocated by
44232** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
44233** enough space to write the master journal name). If the master journal
44234** name in the journal is longer than nMaster bytes (including a
44235** nul-terminator), then this is handled as if no master journal name
44236** were present in the journal.
44237**
44238** If a master journal file name is present at the end of the journal
44239** file, then it is copied into the buffer pointed to by zMaster. A
44240** nul-terminator byte is appended to the buffer following the master
44241** journal file name.
44242**
44243** If it is determined that no master journal file name is present
44244** zMaster[0] is set to 0 and SQLITE_OK returned.
44245**
44246** If an error occurs while reading from the journal file, an SQLite
44247** error code is returned.
44248*/
44249static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
44250  int rc;                    /* Return code */
44251  u32 len;                   /* Length in bytes of master journal name */
44252  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
44253  u32 cksum;                 /* MJ checksum value read from journal */
44254  u32 u;                     /* Unsigned loop counter */
44255  unsigned char aMagic[8];   /* A buffer to hold the magic header */
44256  zMaster[0] = '\0';
44257
44258  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
44259   || szJ<16
44260   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
44261   || len>=nMaster
44262   || len==0
44263   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
44264   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
44265   || memcmp(aMagic, aJournalMagic, 8)
44266   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
44267  ){
44268    return rc;
44269  }
44270
44271  /* See if the checksum matches the master journal name */
44272  for(u=0; u<len; u++){
44273    cksum -= zMaster[u];
44274  }
44275  if( cksum ){
44276    /* If the checksum doesn't add up, then one or more of the disk sectors
44277    ** containing the master journal filename is corrupted. This means
44278    ** definitely roll back, so just return SQLITE_OK and report a (nul)
44279    ** master-journal filename.
44280    */
44281    len = 0;
44282  }
44283  zMaster[len] = '\0';
44284
44285  return SQLITE_OK;
44286}
44287
44288/*
44289** Return the offset of the sector boundary at or immediately
44290** following the value in pPager->journalOff, assuming a sector
44291** size of pPager->sectorSize bytes.
44292**
44293** i.e for a sector size of 512:
44294**
44295**   Pager.journalOff          Return value
44296**   ---------------------------------------
44297**   0                         0
44298**   512                       512
44299**   100                       512
44300**   2000                      2048
44301**
44302*/
44303static i64 journalHdrOffset(Pager *pPager){
44304  i64 offset = 0;
44305  i64 c = pPager->journalOff;
44306  if( c ){
44307    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
44308  }
44309  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
44310  assert( offset>=c );
44311  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
44312  return offset;
44313}
44314
44315/*
44316** The journal file must be open when this function is called.
44317**
44318** This function is a no-op if the journal file has not been written to
44319** within the current transaction (i.e. if Pager.journalOff==0).
44320**
44321** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
44322** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
44323** zero the 28-byte header at the start of the journal file. In either case,
44324** if the pager is not in no-sync mode, sync the journal file immediately
44325** after writing or truncating it.
44326**
44327** If Pager.journalSizeLimit is set to a positive, non-zero value, and
44328** following the truncation or zeroing described above the size of the
44329** journal file in bytes is larger than this value, then truncate the
44330** journal file to Pager.journalSizeLimit bytes. The journal file does
44331** not need to be synced following this operation.
44332**
44333** If an IO error occurs, abandon processing and return the IO error code.
44334** Otherwise, return SQLITE_OK.
44335*/
44336static int zeroJournalHdr(Pager *pPager, int doTruncate){
44337  int rc = SQLITE_OK;                               /* Return code */
44338  assert( isOpen(pPager->jfd) );
44339  if( pPager->journalOff ){
44340    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
44341
44342    IOTRACE(("JZEROHDR %p\n", pPager))
44343    if( doTruncate || iLimit==0 ){
44344      rc = sqlite3OsTruncate(pPager->jfd, 0);
44345    }else{
44346      static const char zeroHdr[28] = {0};
44347      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
44348    }
44349    if( rc==SQLITE_OK && !pPager->noSync ){
44350      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
44351    }
44352
44353    /* At this point the transaction is committed but the write lock
44354    ** is still held on the file. If there is a size limit configured for
44355    ** the persistent journal and the journal file currently consumes more
44356    ** space than that limit allows for, truncate it now. There is no need
44357    ** to sync the file following this operation.
44358    */
44359    if( rc==SQLITE_OK && iLimit>0 ){
44360      i64 sz;
44361      rc = sqlite3OsFileSize(pPager->jfd, &sz);
44362      if( rc==SQLITE_OK && sz>iLimit ){
44363        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
44364      }
44365    }
44366  }
44367  return rc;
44368}
44369
44370/*
44371** The journal file must be open when this routine is called. A journal
44372** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
44373** current location.
44374**
44375** The format for the journal header is as follows:
44376** - 8 bytes: Magic identifying journal format.
44377** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
44378** - 4 bytes: Random number used for page hash.
44379** - 4 bytes: Initial database page count.
44380** - 4 bytes: Sector size used by the process that wrote this journal.
44381** - 4 bytes: Database page size.
44382**
44383** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
44384*/
44385static int writeJournalHdr(Pager *pPager){
44386  int rc = SQLITE_OK;                 /* Return code */
44387  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
44388  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
44389  u32 nWrite;                         /* Bytes of header sector written */
44390  int ii;                             /* Loop counter */
44391
44392  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
44393
44394  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
44395    nHeader = JOURNAL_HDR_SZ(pPager);
44396  }
44397
44398  /* If there are active savepoints and any of them were created
44399  ** since the most recent journal header was written, update the
44400  ** PagerSavepoint.iHdrOffset fields now.
44401  */
44402  for(ii=0; ii<pPager->nSavepoint; ii++){
44403    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
44404      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
44405    }
44406  }
44407
44408  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
44409
44410  /*
44411  ** Write the nRec Field - the number of page records that follow this
44412  ** journal header. Normally, zero is written to this value at this time.
44413  ** After the records are added to the journal (and the journal synced,
44414  ** if in full-sync mode), the zero is overwritten with the true number
44415  ** of records (see syncJournal()).
44416  **
44417  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
44418  ** reading the journal this value tells SQLite to assume that the
44419  ** rest of the journal file contains valid page records. This assumption
44420  ** is dangerous, as if a failure occurred whilst writing to the journal
44421  ** file it may contain some garbage data. There are two scenarios
44422  ** where this risk can be ignored:
44423  **
44424  **   * When the pager is in no-sync mode. Corruption can follow a
44425  **     power failure in this case anyway.
44426  **
44427  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
44428  **     that garbage data is never appended to the journal file.
44429  */
44430  assert( isOpen(pPager->fd) || pPager->noSync );
44431  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
44432   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
44433  ){
44434    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
44435    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
44436  }else{
44437    memset(zHeader, 0, sizeof(aJournalMagic)+4);
44438  }
44439
44440  /* The random check-hash initializer */
44441  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
44442  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
44443  /* The initial database size */
44444  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
44445  /* The assumed sector size for this process */
44446  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
44447
44448  /* The page size */
44449  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
44450
44451  /* Initializing the tail of the buffer is not necessary.  Everything
44452  ** works find if the following memset() is omitted.  But initializing
44453  ** the memory prevents valgrind from complaining, so we are willing to
44454  ** take the performance hit.
44455  */
44456  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
44457         nHeader-(sizeof(aJournalMagic)+20));
44458
44459  /* In theory, it is only necessary to write the 28 bytes that the
44460  ** journal header consumes to the journal file here. Then increment the
44461  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
44462  ** record is written to the following sector (leaving a gap in the file
44463  ** that will be implicitly filled in by the OS).
44464  **
44465  ** However it has been discovered that on some systems this pattern can
44466  ** be significantly slower than contiguously writing data to the file,
44467  ** even if that means explicitly writing data to the block of
44468  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
44469  ** is done.
44470  **
44471  ** The loop is required here in case the sector-size is larger than the
44472  ** database page size. Since the zHeader buffer is only Pager.pageSize
44473  ** bytes in size, more than one call to sqlite3OsWrite() may be required
44474  ** to populate the entire journal header sector.
44475  */
44476  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
44477    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
44478    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
44479    assert( pPager->journalHdr <= pPager->journalOff );
44480    pPager->journalOff += nHeader;
44481  }
44482
44483  return rc;
44484}
44485
44486/*
44487** The journal file must be open when this is called. A journal header file
44488** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
44489** file. The current location in the journal file is given by
44490** pPager->journalOff. See comments above function writeJournalHdr() for
44491** a description of the journal header format.
44492**
44493** If the header is read successfully, *pNRec is set to the number of
44494** page records following this header and *pDbSize is set to the size of the
44495** database before the transaction began, in pages. Also, pPager->cksumInit
44496** is set to the value read from the journal header. SQLITE_OK is returned
44497** in this case.
44498**
44499** If the journal header file appears to be corrupted, SQLITE_DONE is
44500** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
44501** cannot be read from the journal file an error code is returned.
44502*/
44503static int readJournalHdr(
44504  Pager *pPager,               /* Pager object */
44505  int isHot,
44506  i64 journalSize,             /* Size of the open journal file in bytes */
44507  u32 *pNRec,                  /* OUT: Value read from the nRec field */
44508  u32 *pDbSize                 /* OUT: Value of original database size field */
44509){
44510  int rc;                      /* Return code */
44511  unsigned char aMagic[8];     /* A buffer to hold the magic header */
44512  i64 iHdrOff;                 /* Offset of journal header being read */
44513
44514  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
44515
44516  /* Advance Pager.journalOff to the start of the next sector. If the
44517  ** journal file is too small for there to be a header stored at this
44518  ** point, return SQLITE_DONE.
44519  */
44520  pPager->journalOff = journalHdrOffset(pPager);
44521  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
44522    return SQLITE_DONE;
44523  }
44524  iHdrOff = pPager->journalOff;
44525
44526  /* Read in the first 8 bytes of the journal header. If they do not match
44527  ** the  magic string found at the start of each journal header, return
44528  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
44529  ** proceed.
44530  */
44531  if( isHot || iHdrOff!=pPager->journalHdr ){
44532    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
44533    if( rc ){
44534      return rc;
44535    }
44536    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
44537      return SQLITE_DONE;
44538    }
44539  }
44540
44541  /* Read the first three 32-bit fields of the journal header: The nRec
44542  ** field, the checksum-initializer and the database size at the start
44543  ** of the transaction. Return an error code if anything goes wrong.
44544  */
44545  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
44546   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
44547   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
44548  ){
44549    return rc;
44550  }
44551
44552  if( pPager->journalOff==0 ){
44553    u32 iPageSize;               /* Page-size field of journal header */
44554    u32 iSectorSize;             /* Sector-size field of journal header */
44555
44556    /* Read the page-size and sector-size journal header fields. */
44557    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
44558     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
44559    ){
44560      return rc;
44561    }
44562
44563    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
44564    ** journal header to zero. In this case, assume that the Pager.pageSize
44565    ** variable is already set to the correct page size.
44566    */
44567    if( iPageSize==0 ){
44568      iPageSize = pPager->pageSize;
44569    }
44570
44571    /* Check that the values read from the page-size and sector-size fields
44572    ** are within range. To be 'in range', both values need to be a power
44573    ** of two greater than or equal to 512 or 32, and not greater than their
44574    ** respective compile time maximum limits.
44575    */
44576    if( iPageSize<512                  || iSectorSize<32
44577     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
44578     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
44579    ){
44580      /* If the either the page-size or sector-size in the journal-header is
44581      ** invalid, then the process that wrote the journal-header must have
44582      ** crashed before the header was synced. In this case stop reading
44583      ** the journal file here.
44584      */
44585      return SQLITE_DONE;
44586    }
44587
44588    /* Update the page-size to match the value read from the journal.
44589    ** Use a testcase() macro to make sure that malloc failure within
44590    ** PagerSetPagesize() is tested.
44591    */
44592    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
44593    testcase( rc!=SQLITE_OK );
44594
44595    /* Update the assumed sector-size to match the value used by
44596    ** the process that created this journal. If this journal was
44597    ** created by a process other than this one, then this routine
44598    ** is being called from within pager_playback(). The local value
44599    ** of Pager.sectorSize is restored at the end of that routine.
44600    */
44601    pPager->sectorSize = iSectorSize;
44602  }
44603
44604  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
44605  return rc;
44606}
44607
44608
44609/*
44610** Write the supplied master journal name into the journal file for pager
44611** pPager at the current location. The master journal name must be the last
44612** thing written to a journal file. If the pager is in full-sync mode, the
44613** journal file descriptor is advanced to the next sector boundary before
44614** anything is written. The format is:
44615**
44616**   + 4 bytes: PAGER_MJ_PGNO.
44617**   + N bytes: Master journal filename in utf-8.
44618**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
44619**   + 4 bytes: Master journal name checksum.
44620**   + 8 bytes: aJournalMagic[].
44621**
44622** The master journal page checksum is the sum of the bytes in the master
44623** journal name, where each byte is interpreted as a signed 8-bit integer.
44624**
44625** If zMaster is a NULL pointer (occurs for a single database transaction),
44626** this call is a no-op.
44627*/
44628static int writeMasterJournal(Pager *pPager, const char *zMaster){
44629  int rc;                          /* Return code */
44630  int nMaster;                     /* Length of string zMaster */
44631  i64 iHdrOff;                     /* Offset of header in journal file */
44632  i64 jrnlSize;                    /* Size of journal file on disk */
44633  u32 cksum = 0;                   /* Checksum of string zMaster */
44634
44635  assert( pPager->setMaster==0 );
44636  assert( !pagerUseWal(pPager) );
44637
44638  if( !zMaster
44639   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
44640   || !isOpen(pPager->jfd)
44641  ){
44642    return SQLITE_OK;
44643  }
44644  pPager->setMaster = 1;
44645  assert( pPager->journalHdr <= pPager->journalOff );
44646
44647  /* Calculate the length in bytes and the checksum of zMaster */
44648  for(nMaster=0; zMaster[nMaster]; nMaster++){
44649    cksum += zMaster[nMaster];
44650  }
44651
44652  /* If in full-sync mode, advance to the next disk sector before writing
44653  ** the master journal name. This is in case the previous page written to
44654  ** the journal has already been synced.
44655  */
44656  if( pPager->fullSync ){
44657    pPager->journalOff = journalHdrOffset(pPager);
44658  }
44659  iHdrOff = pPager->journalOff;
44660
44661  /* Write the master journal data to the end of the journal file. If
44662  ** an error occurs, return the error code to the caller.
44663  */
44664  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
44665   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
44666   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
44667   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
44668   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
44669                                 iHdrOff+4+nMaster+8)))
44670  ){
44671    return rc;
44672  }
44673  pPager->journalOff += (nMaster+20);
44674
44675  /* If the pager is in peristent-journal mode, then the physical
44676  ** journal-file may extend past the end of the master-journal name
44677  ** and 8 bytes of magic data just written to the file. This is
44678  ** dangerous because the code to rollback a hot-journal file
44679  ** will not be able to find the master-journal name to determine
44680  ** whether or not the journal is hot.
44681  **
44682  ** Easiest thing to do in this scenario is to truncate the journal
44683  ** file to the required size.
44684  */
44685  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
44686   && jrnlSize>pPager->journalOff
44687  ){
44688    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
44689  }
44690  return rc;
44691}
44692
44693/*
44694** Discard the entire contents of the in-memory page-cache.
44695*/
44696static void pager_reset(Pager *pPager){
44697  pPager->iDataVersion++;
44698  sqlite3BackupRestart(pPager->pBackup);
44699  sqlite3PcacheClear(pPager->pPCache);
44700}
44701
44702/*
44703** Return the pPager->iDataVersion value
44704*/
44705SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
44706  assert( pPager->eState>PAGER_OPEN );
44707  return pPager->iDataVersion;
44708}
44709
44710/*
44711** Free all structures in the Pager.aSavepoint[] array and set both
44712** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
44713** if it is open and the pager is not in exclusive mode.
44714*/
44715static void releaseAllSavepoints(Pager *pPager){
44716  int ii;               /* Iterator for looping through Pager.aSavepoint */
44717  for(ii=0; ii<pPager->nSavepoint; ii++){
44718    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44719  }
44720  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
44721    sqlite3OsClose(pPager->sjfd);
44722  }
44723  sqlite3_free(pPager->aSavepoint);
44724  pPager->aSavepoint = 0;
44725  pPager->nSavepoint = 0;
44726  pPager->nSubRec = 0;
44727}
44728
44729/*
44730** Set the bit number pgno in the PagerSavepoint.pInSavepoint
44731** bitvecs of all open savepoints. Return SQLITE_OK if successful
44732** or SQLITE_NOMEM if a malloc failure occurs.
44733*/
44734static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
44735  int ii;                   /* Loop counter */
44736  int rc = SQLITE_OK;       /* Result code */
44737
44738  for(ii=0; ii<pPager->nSavepoint; ii++){
44739    PagerSavepoint *p = &pPager->aSavepoint[ii];
44740    if( pgno<=p->nOrig ){
44741      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
44742      testcase( rc==SQLITE_NOMEM );
44743      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44744    }
44745  }
44746  return rc;
44747}
44748
44749/*
44750** This function is a no-op if the pager is in exclusive mode and not
44751** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
44752** state.
44753**
44754** If the pager is not in exclusive-access mode, the database file is
44755** completely unlocked. If the file is unlocked and the file-system does
44756** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
44757** closed (if it is open).
44758**
44759** If the pager is in ERROR state when this function is called, the
44760** contents of the pager cache are discarded before switching back to
44761** the OPEN state. Regardless of whether the pager is in exclusive-mode
44762** or not, any journal file left in the file-system will be treated
44763** as a hot-journal and rolled back the next time a read-transaction
44764** is opened (by this or by any other connection).
44765*/
44766static void pager_unlock(Pager *pPager){
44767
44768  assert( pPager->eState==PAGER_READER
44769       || pPager->eState==PAGER_OPEN
44770       || pPager->eState==PAGER_ERROR
44771  );
44772
44773  sqlite3BitvecDestroy(pPager->pInJournal);
44774  pPager->pInJournal = 0;
44775  releaseAllSavepoints(pPager);
44776
44777  if( pagerUseWal(pPager) ){
44778    assert( !isOpen(pPager->jfd) );
44779    sqlite3WalEndReadTransaction(pPager->pWal);
44780    pPager->eState = PAGER_OPEN;
44781  }else if( !pPager->exclusiveMode ){
44782    int rc;                       /* Error code returned by pagerUnlockDb() */
44783    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
44784
44785    /* If the operating system support deletion of open files, then
44786    ** close the journal file when dropping the database lock.  Otherwise
44787    ** another connection with journal_mode=delete might delete the file
44788    ** out from under us.
44789    */
44790    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
44791    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
44792    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
44793    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
44794    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
44795    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
44796    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
44797     || 1!=(pPager->journalMode & 5)
44798    ){
44799      sqlite3OsClose(pPager->jfd);
44800    }
44801
44802    /* If the pager is in the ERROR state and the call to unlock the database
44803    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
44804    ** above the #define for UNKNOWN_LOCK for an explanation of why this
44805    ** is necessary.
44806    */
44807    rc = pagerUnlockDb(pPager, NO_LOCK);
44808    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
44809      pPager->eLock = UNKNOWN_LOCK;
44810    }
44811
44812    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
44813    ** without clearing the error code. This is intentional - the error
44814    ** code is cleared and the cache reset in the block below.
44815    */
44816    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
44817    pPager->changeCountDone = 0;
44818    pPager->eState = PAGER_OPEN;
44819  }
44820
44821  /* If Pager.errCode is set, the contents of the pager cache cannot be
44822  ** trusted. Now that there are no outstanding references to the pager,
44823  ** it can safely move back to PAGER_OPEN state. This happens in both
44824  ** normal and exclusive-locking mode.
44825  */
44826  if( pPager->errCode ){
44827    assert( !MEMDB );
44828    pager_reset(pPager);
44829    pPager->changeCountDone = pPager->tempFile;
44830    pPager->eState = PAGER_OPEN;
44831    pPager->errCode = SQLITE_OK;
44832    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44833  }
44834
44835  pPager->journalOff = 0;
44836  pPager->journalHdr = 0;
44837  pPager->setMaster = 0;
44838}
44839
44840/*
44841** This function is called whenever an IOERR or FULL error that requires
44842** the pager to transition into the ERROR state may ahve occurred.
44843** The first argument is a pointer to the pager structure, the second
44844** the error-code about to be returned by a pager API function. The
44845** value returned is a copy of the second argument to this function.
44846**
44847** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
44848** IOERR sub-codes, the pager enters the ERROR state and the error code
44849** is stored in Pager.errCode. While the pager remains in the ERROR state,
44850** all major API calls on the Pager will immediately return Pager.errCode.
44851**
44852** The ERROR state indicates that the contents of the pager-cache
44853** cannot be trusted. This state can be cleared by completely discarding
44854** the contents of the pager-cache. If a transaction was active when
44855** the persistent error occurred, then the rollback journal may need
44856** to be replayed to restore the contents of the database file (as if
44857** it were a hot-journal).
44858*/
44859static int pager_error(Pager *pPager, int rc){
44860  int rc2 = rc & 0xff;
44861  assert( rc==SQLITE_OK || !MEMDB );
44862  assert(
44863       pPager->errCode==SQLITE_FULL ||
44864       pPager->errCode==SQLITE_OK ||
44865       (pPager->errCode & 0xff)==SQLITE_IOERR
44866  );
44867  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
44868    pPager->errCode = rc;
44869    pPager->eState = PAGER_ERROR;
44870  }
44871  return rc;
44872}
44873
44874static int pager_truncate(Pager *pPager, Pgno nPage);
44875
44876/*
44877** This routine ends a transaction. A transaction is usually ended by
44878** either a COMMIT or a ROLLBACK operation. This routine may be called
44879** after rollback of a hot-journal, or if an error occurs while opening
44880** the journal file or writing the very first journal-header of a
44881** database transaction.
44882**
44883** This routine is never called in PAGER_ERROR state. If it is called
44884** in PAGER_NONE or PAGER_SHARED state and the lock held is less
44885** exclusive than a RESERVED lock, it is a no-op.
44886**
44887** Otherwise, any active savepoints are released.
44888**
44889** If the journal file is open, then it is "finalized". Once a journal
44890** file has been finalized it is not possible to use it to roll back a
44891** transaction. Nor will it be considered to be a hot-journal by this
44892** or any other database connection. Exactly how a journal is finalized
44893** depends on whether or not the pager is running in exclusive mode and
44894** the current journal-mode (Pager.journalMode value), as follows:
44895**
44896**   journalMode==MEMORY
44897**     Journal file descriptor is simply closed. This destroys an
44898**     in-memory journal.
44899**
44900**   journalMode==TRUNCATE
44901**     Journal file is truncated to zero bytes in size.
44902**
44903**   journalMode==PERSIST
44904**     The first 28 bytes of the journal file are zeroed. This invalidates
44905**     the first journal header in the file, and hence the entire journal
44906**     file. An invalid journal file cannot be rolled back.
44907**
44908**   journalMode==DELETE
44909**     The journal file is closed and deleted using sqlite3OsDelete().
44910**
44911**     If the pager is running in exclusive mode, this method of finalizing
44912**     the journal file is never used. Instead, if the journalMode is
44913**     DELETE and the pager is in exclusive mode, the method described under
44914**     journalMode==PERSIST is used instead.
44915**
44916** After the journal is finalized, the pager moves to PAGER_READER state.
44917** If running in non-exclusive rollback mode, the lock on the file is
44918** downgraded to a SHARED_LOCK.
44919**
44920** SQLITE_OK is returned if no error occurs. If an error occurs during
44921** any of the IO operations to finalize the journal file or unlock the
44922** database then the IO error code is returned to the user. If the
44923** operation to finalize the journal file fails, then the code still
44924** tries to unlock the database file if not in exclusive mode. If the
44925** unlock operation fails as well, then the first error code related
44926** to the first error encountered (the journal finalization one) is
44927** returned.
44928*/
44929static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
44930  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
44931  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
44932
44933  /* Do nothing if the pager does not have an open write transaction
44934  ** or at least a RESERVED lock. This function may be called when there
44935  ** is no write-transaction active but a RESERVED or greater lock is
44936  ** held under two circumstances:
44937  **
44938  **   1. After a successful hot-journal rollback, it is called with
44939  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
44940  **
44941  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
44942  **      lock switches back to locking_mode=normal and then executes a
44943  **      read-transaction, this function is called with eState==PAGER_READER
44944  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
44945  */
44946  assert( assert_pager_state(pPager) );
44947  assert( pPager->eState!=PAGER_ERROR );
44948  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
44949    return SQLITE_OK;
44950  }
44951
44952  releaseAllSavepoints(pPager);
44953  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
44954  if( isOpen(pPager->jfd) ){
44955    assert( !pagerUseWal(pPager) );
44956
44957    /* Finalize the journal file. */
44958    if( sqlite3IsMemJournal(pPager->jfd) ){
44959      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
44960      sqlite3OsClose(pPager->jfd);
44961    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
44962      if( pPager->journalOff==0 ){
44963        rc = SQLITE_OK;
44964      }else{
44965        rc = sqlite3OsTruncate(pPager->jfd, 0);
44966        if( rc==SQLITE_OK && pPager->fullSync ){
44967          /* Make sure the new file size is written into the inode right away.
44968          ** Otherwise the journal might resurrect following a power loss and
44969          ** cause the last transaction to roll back.  See
44970          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
44971          */
44972          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
44973        }
44974      }
44975      pPager->journalOff = 0;
44976    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44977      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
44978    ){
44979      rc = zeroJournalHdr(pPager, hasMaster);
44980      pPager->journalOff = 0;
44981    }else{
44982      /* This branch may be executed with Pager.journalMode==MEMORY if
44983      ** a hot-journal was just rolled back. In this case the journal
44984      ** file should be closed and deleted. If this connection writes to
44985      ** the database file, it will do so using an in-memory journal.
44986      */
44987      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
44988      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
44989           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
44990           || pPager->journalMode==PAGER_JOURNALMODE_WAL
44991      );
44992      sqlite3OsClose(pPager->jfd);
44993      if( bDelete ){
44994        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44995      }
44996    }
44997  }
44998
44999#ifdef SQLITE_CHECK_PAGES
45000  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
45001  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
45002    PgHdr *p = sqlite3PagerLookup(pPager, 1);
45003    if( p ){
45004      p->pageHash = 0;
45005      sqlite3PagerUnrefNotNull(p);
45006    }
45007  }
45008#endif
45009
45010  sqlite3BitvecDestroy(pPager->pInJournal);
45011  pPager->pInJournal = 0;
45012  pPager->nRec = 0;
45013  sqlite3PcacheCleanAll(pPager->pPCache);
45014  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
45015
45016  if( pagerUseWal(pPager) ){
45017    /* Drop the WAL write-lock, if any. Also, if the connection was in
45018    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
45019    ** lock held on the database file.
45020    */
45021    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
45022    assert( rc2==SQLITE_OK );
45023  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
45024    /* This branch is taken when committing a transaction in rollback-journal
45025    ** mode if the database file on disk is larger than the database image.
45026    ** At this point the journal has been finalized and the transaction
45027    ** successfully committed, but the EXCLUSIVE lock is still held on the
45028    ** file. So it is safe to truncate the database file to its minimum
45029    ** required size.  */
45030    assert( pPager->eLock==EXCLUSIVE_LOCK );
45031    rc = pager_truncate(pPager, pPager->dbSize);
45032  }
45033
45034  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
45035    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
45036    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
45037  }
45038
45039  if( !pPager->exclusiveMode
45040   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
45041  ){
45042    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
45043    pPager->changeCountDone = 0;
45044  }
45045  pPager->eState = PAGER_READER;
45046  pPager->setMaster = 0;
45047
45048  return (rc==SQLITE_OK?rc2:rc);
45049}
45050
45051/*
45052** Execute a rollback if a transaction is active and unlock the
45053** database file.
45054**
45055** If the pager has already entered the ERROR state, do not attempt
45056** the rollback at this time. Instead, pager_unlock() is called. The
45057** call to pager_unlock() will discard all in-memory pages, unlock
45058** the database file and move the pager back to OPEN state. If this
45059** means that there is a hot-journal left in the file-system, the next
45060** connection to obtain a shared lock on the pager (which may be this one)
45061** will roll it back.
45062**
45063** If the pager has not already entered the ERROR state, but an IO or
45064** malloc error occurs during a rollback, then this will itself cause
45065** the pager to enter the ERROR state. Which will be cleared by the
45066** call to pager_unlock(), as described above.
45067*/
45068static void pagerUnlockAndRollback(Pager *pPager){
45069  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
45070    assert( assert_pager_state(pPager) );
45071    if( pPager->eState>=PAGER_WRITER_LOCKED ){
45072      sqlite3BeginBenignMalloc();
45073      sqlite3PagerRollback(pPager);
45074      sqlite3EndBenignMalloc();
45075    }else if( !pPager->exclusiveMode ){
45076      assert( pPager->eState==PAGER_READER );
45077      pager_end_transaction(pPager, 0, 0);
45078    }
45079  }
45080  pager_unlock(pPager);
45081}
45082
45083/*
45084** Parameter aData must point to a buffer of pPager->pageSize bytes
45085** of data. Compute and return a checksum based ont the contents of the
45086** page of data and the current value of pPager->cksumInit.
45087**
45088** This is not a real checksum. It is really just the sum of the
45089** random initial value (pPager->cksumInit) and every 200th byte
45090** of the page data, starting with byte offset (pPager->pageSize%200).
45091** Each byte is interpreted as an 8-bit unsigned integer.
45092**
45093** Changing the formula used to compute this checksum results in an
45094** incompatible journal file format.
45095**
45096** If journal corruption occurs due to a power failure, the most likely
45097** scenario is that one end or the other of the record will be changed.
45098** It is much less likely that the two ends of the journal record will be
45099** correct and the middle be corrupt.  Thus, this "checksum" scheme,
45100** though fast and simple, catches the mostly likely kind of corruption.
45101*/
45102static u32 pager_cksum(Pager *pPager, const u8 *aData){
45103  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
45104  int i = pPager->pageSize-200;          /* Loop counter */
45105  while( i>0 ){
45106    cksum += aData[i];
45107    i -= 200;
45108  }
45109  return cksum;
45110}
45111
45112/*
45113** Report the current page size and number of reserved bytes back
45114** to the codec.
45115*/
45116#ifdef SQLITE_HAS_CODEC
45117static void pagerReportSize(Pager *pPager){
45118  if( pPager->xCodecSizeChng ){
45119    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
45120                           (int)pPager->nReserve);
45121  }
45122}
45123#else
45124# define pagerReportSize(X)     /* No-op if we do not support a codec */
45125#endif
45126
45127#ifdef SQLITE_HAS_CODEC
45128/*
45129** Make sure the number of reserved bits is the same in the destination
45130** pager as it is in the source.  This comes up when a VACUUM changes the
45131** number of reserved bits to the "optimal" amount.
45132*/
45133SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
45134  if( pDest->nReserve!=pSrc->nReserve ){
45135    pDest->nReserve = pSrc->nReserve;
45136    pagerReportSize(pDest);
45137  }
45138}
45139#endif
45140
45141/*
45142** Read a single page from either the journal file (if isMainJrnl==1) or
45143** from the sub-journal (if isMainJrnl==0) and playback that page.
45144** The page begins at offset *pOffset into the file. The *pOffset
45145** value is increased to the start of the next page in the journal.
45146**
45147** The main rollback journal uses checksums - the statement journal does
45148** not.
45149**
45150** If the page number of the page record read from the (sub-)journal file
45151** is greater than the current value of Pager.dbSize, then playback is
45152** skipped and SQLITE_OK is returned.
45153**
45154** If pDone is not NULL, then it is a record of pages that have already
45155** been played back.  If the page at *pOffset has already been played back
45156** (if the corresponding pDone bit is set) then skip the playback.
45157** Make sure the pDone bit corresponding to the *pOffset page is set
45158** prior to returning.
45159**
45160** If the page record is successfully read from the (sub-)journal file
45161** and played back, then SQLITE_OK is returned. If an IO error occurs
45162** while reading the record from the (sub-)journal file or while writing
45163** to the database file, then the IO error code is returned. If data
45164** is successfully read from the (sub-)journal file but appears to be
45165** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
45166** two circumstances:
45167**
45168**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
45169**   * If the record is being rolled back from the main journal file
45170**     and the checksum field does not match the record content.
45171**
45172** Neither of these two scenarios are possible during a savepoint rollback.
45173**
45174** If this is a savepoint rollback, then memory may have to be dynamically
45175** allocated by this function. If this is the case and an allocation fails,
45176** SQLITE_NOMEM is returned.
45177*/
45178static int pager_playback_one_page(
45179  Pager *pPager,                /* The pager being played back */
45180  i64 *pOffset,                 /* Offset of record to playback */
45181  Bitvec *pDone,                /* Bitvec of pages already played back */
45182  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
45183  int isSavepnt                 /* True for a savepoint rollback */
45184){
45185  int rc;
45186  PgHdr *pPg;                   /* An existing page in the cache */
45187  Pgno pgno;                    /* The page number of a page in journal */
45188  u32 cksum;                    /* Checksum used for sanity checking */
45189  char *aData;                  /* Temporary storage for the page */
45190  sqlite3_file *jfd;            /* The file descriptor for the journal file */
45191  int isSynced;                 /* True if journal page is synced */
45192
45193  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
45194  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
45195  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
45196  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
45197
45198  aData = pPager->pTmpSpace;
45199  assert( aData );         /* Temp storage must have already been allocated */
45200  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
45201
45202  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
45203  ** or savepoint rollback done at the request of the caller) or this is
45204  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
45205  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
45206  ** only reads from the main journal, not the sub-journal.
45207  */
45208  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
45209       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
45210  );
45211  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
45212
45213  /* Read the page number and page data from the journal or sub-journal
45214  ** file. Return an error code to the caller if an IO error occurs.
45215  */
45216  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
45217  rc = read32bits(jfd, *pOffset, &pgno);
45218  if( rc!=SQLITE_OK ) return rc;
45219  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
45220  if( rc!=SQLITE_OK ) return rc;
45221  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
45222
45223  /* Sanity checking on the page.  This is more important that I originally
45224  ** thought.  If a power failure occurs while the journal is being written,
45225  ** it could cause invalid data to be written into the journal.  We need to
45226  ** detect this invalid data (with high probability) and ignore it.
45227  */
45228  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
45229    assert( !isSavepnt );
45230    return SQLITE_DONE;
45231  }
45232  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
45233    return SQLITE_OK;
45234  }
45235  if( isMainJrnl ){
45236    rc = read32bits(jfd, (*pOffset)-4, &cksum);
45237    if( rc ) return rc;
45238    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
45239      return SQLITE_DONE;
45240    }
45241  }
45242
45243  /* If this page has already been played back before during the current
45244  ** rollback, then don't bother to play it back again.
45245  */
45246  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
45247    return rc;
45248  }
45249
45250  /* When playing back page 1, restore the nReserve setting
45251  */
45252  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
45253    pPager->nReserve = ((u8*)aData)[20];
45254    pagerReportSize(pPager);
45255  }
45256
45257  /* If the pager is in CACHEMOD state, then there must be a copy of this
45258  ** page in the pager cache. In this case just update the pager cache,
45259  ** not the database file. The page is left marked dirty in this case.
45260  **
45261  ** An exception to the above rule: If the database is in no-sync mode
45262  ** and a page is moved during an incremental vacuum then the page may
45263  ** not be in the pager cache. Later: if a malloc() or IO error occurs
45264  ** during a Movepage() call, then the page may not be in the cache
45265  ** either. So the condition described in the above paragraph is not
45266  ** assert()able.
45267  **
45268  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
45269  ** pager cache if it exists and the main file. The page is then marked
45270  ** not dirty. Since this code is only executed in PAGER_OPEN state for
45271  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
45272  ** if the pager is in OPEN state.
45273  **
45274  ** Ticket #1171:  The statement journal might contain page content that is
45275  ** different from the page content at the start of the transaction.
45276  ** This occurs when a page is changed prior to the start of a statement
45277  ** then changed again within the statement.  When rolling back such a
45278  ** statement we must not write to the original database unless we know
45279  ** for certain that original page contents are synced into the main rollback
45280  ** journal.  Otherwise, a power loss might leave modified data in the
45281  ** database file without an entry in the rollback journal that can
45282  ** restore the database to its original form.  Two conditions must be
45283  ** met before writing to the database files. (1) the database must be
45284  ** locked.  (2) we know that the original page content is fully synced
45285  ** in the main journal either because the page is not in cache or else
45286  ** the page is marked as needSync==0.
45287  **
45288  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
45289  ** is possible to fail a statement on a database that does not yet exist.
45290  ** Do not attempt to write if database file has never been opened.
45291  */
45292  if( pagerUseWal(pPager) ){
45293    pPg = 0;
45294  }else{
45295    pPg = sqlite3PagerLookup(pPager, pgno);
45296  }
45297  assert( pPg || !MEMDB );
45298  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
45299  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
45300           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
45301           (isMainJrnl?"main-journal":"sub-journal")
45302  ));
45303  if( isMainJrnl ){
45304    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
45305  }else{
45306    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
45307  }
45308  if( isOpen(pPager->fd)
45309   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45310   && isSynced
45311  ){
45312    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
45313    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
45314    assert( !pagerUseWal(pPager) );
45315    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
45316    if( pgno>pPager->dbFileSize ){
45317      pPager->dbFileSize = pgno;
45318    }
45319    if( pPager->pBackup ){
45320      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
45321      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
45322      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
45323    }
45324  }else if( !isMainJrnl && pPg==0 ){
45325    /* If this is a rollback of a savepoint and data was not written to
45326    ** the database and the page is not in-memory, there is a potential
45327    ** problem. When the page is next fetched by the b-tree layer, it
45328    ** will be read from the database file, which may or may not be
45329    ** current.
45330    **
45331    ** There are a couple of different ways this can happen. All are quite
45332    ** obscure. When running in synchronous mode, this can only happen
45333    ** if the page is on the free-list at the start of the transaction, then
45334    ** populated, then moved using sqlite3PagerMovepage().
45335    **
45336    ** The solution is to add an in-memory page to the cache containing
45337    ** the data just read from the sub-journal. Mark the page as dirty
45338    ** and if the pager requires a journal-sync, then mark the page as
45339    ** requiring a journal-sync before it is written.
45340    */
45341    assert( isSavepnt );
45342    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
45343    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
45344    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
45345    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
45346    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
45347    if( rc!=SQLITE_OK ) return rc;
45348    pPg->flags &= ~PGHDR_NEED_READ;
45349    sqlite3PcacheMakeDirty(pPg);
45350  }
45351  if( pPg ){
45352    /* No page should ever be explicitly rolled back that is in use, except
45353    ** for page 1 which is held in use in order to keep the lock on the
45354    ** database active. However such a page may be rolled back as a result
45355    ** of an internal error resulting in an automatic call to
45356    ** sqlite3PagerRollback().
45357    */
45358    void *pData;
45359    pData = pPg->pData;
45360    memcpy(pData, (u8*)aData, pPager->pageSize);
45361    pPager->xReiniter(pPg);
45362    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
45363      /* If the contents of this page were just restored from the main
45364      ** journal file, then its content must be as they were when the
45365      ** transaction was first opened. In this case we can mark the page
45366      ** as clean, since there will be no need to write it out to the
45367      ** database.
45368      **
45369      ** There is one exception to this rule. If the page is being rolled
45370      ** back as part of a savepoint (or statement) rollback from an
45371      ** unsynced portion of the main journal file, then it is not safe
45372      ** to mark the page as clean. This is because marking the page as
45373      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
45374      ** already in the journal file (recorded in Pager.pInJournal) and
45375      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
45376      ** again within this transaction, it will be marked as dirty but
45377      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
45378      ** be written out into the database file before its journal file
45379      ** segment is synced. If a crash occurs during or following this,
45380      ** database corruption may ensue.
45381      */
45382      assert( !pagerUseWal(pPager) );
45383      sqlite3PcacheMakeClean(pPg);
45384    }
45385    pager_set_pagehash(pPg);
45386
45387    /* If this was page 1, then restore the value of Pager.dbFileVers.
45388    ** Do this before any decoding. */
45389    if( pgno==1 ){
45390      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
45391    }
45392
45393    /* Decode the page just read from disk */
45394    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
45395    sqlite3PcacheRelease(pPg);
45396  }
45397  return rc;
45398}
45399
45400/*
45401** Parameter zMaster is the name of a master journal file. A single journal
45402** file that referred to the master journal file has just been rolled back.
45403** This routine checks if it is possible to delete the master journal file,
45404** and does so if it is.
45405**
45406** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
45407** available for use within this function.
45408**
45409** When a master journal file is created, it is populated with the names
45410** of all of its child journals, one after another, formatted as utf-8
45411** encoded text. The end of each child journal file is marked with a
45412** nul-terminator byte (0x00). i.e. the entire contents of a master journal
45413** file for a transaction involving two databases might be:
45414**
45415**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
45416**
45417** A master journal file may only be deleted once all of its child
45418** journals have been rolled back.
45419**
45420** This function reads the contents of the master-journal file into
45421** memory and loops through each of the child journal names. For
45422** each child journal, it checks if:
45423**
45424**   * if the child journal exists, and if so
45425**   * if the child journal contains a reference to master journal
45426**     file zMaster
45427**
45428** If a child journal can be found that matches both of the criteria
45429** above, this function returns without doing anything. Otherwise, if
45430** no such child journal can be found, file zMaster is deleted from
45431** the file-system using sqlite3OsDelete().
45432**
45433** If an IO error within this function, an error code is returned. This
45434** function allocates memory by calling sqlite3Malloc(). If an allocation
45435** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
45436** occur, SQLITE_OK is returned.
45437**
45438** TODO: This function allocates a single block of memory to load
45439** the entire contents of the master journal file. This could be
45440** a couple of kilobytes or so - potentially larger than the page
45441** size.
45442*/
45443static int pager_delmaster(Pager *pPager, const char *zMaster){
45444  sqlite3_vfs *pVfs = pPager->pVfs;
45445  int rc;                   /* Return code */
45446  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
45447  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
45448  char *zMasterJournal = 0; /* Contents of master journal file */
45449  i64 nMasterJournal;       /* Size of master journal file */
45450  char *zJournal;           /* Pointer to one journal within MJ file */
45451  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
45452  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
45453
45454  /* Allocate space for both the pJournal and pMaster file descriptors.
45455  ** If successful, open the master journal file for reading.
45456  */
45457  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
45458  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
45459  if( !pMaster ){
45460    rc = SQLITE_NOMEM;
45461  }else{
45462    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
45463    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
45464  }
45465  if( rc!=SQLITE_OK ) goto delmaster_out;
45466
45467  /* Load the entire master journal file into space obtained from
45468  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
45469  ** sufficient space (in zMasterPtr) to hold the names of master
45470  ** journal files extracted from regular rollback-journals.
45471  */
45472  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
45473  if( rc!=SQLITE_OK ) goto delmaster_out;
45474  nMasterPtr = pVfs->mxPathname+1;
45475  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
45476  if( !zMasterJournal ){
45477    rc = SQLITE_NOMEM;
45478    goto delmaster_out;
45479  }
45480  zMasterPtr = &zMasterJournal[nMasterJournal+1];
45481  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
45482  if( rc!=SQLITE_OK ) goto delmaster_out;
45483  zMasterJournal[nMasterJournal] = 0;
45484
45485  zJournal = zMasterJournal;
45486  while( (zJournal-zMasterJournal)<nMasterJournal ){
45487    int exists;
45488    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
45489    if( rc!=SQLITE_OK ){
45490      goto delmaster_out;
45491    }
45492    if( exists ){
45493      /* One of the journals pointed to by the master journal exists.
45494      ** Open it and check if it points at the master journal. If
45495      ** so, return without deleting the master journal file.
45496      */
45497      int c;
45498      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
45499      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
45500      if( rc!=SQLITE_OK ){
45501        goto delmaster_out;
45502      }
45503
45504      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
45505      sqlite3OsClose(pJournal);
45506      if( rc!=SQLITE_OK ){
45507        goto delmaster_out;
45508      }
45509
45510      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
45511      if( c ){
45512        /* We have a match. Do not delete the master journal file. */
45513        goto delmaster_out;
45514      }
45515    }
45516    zJournal += (sqlite3Strlen30(zJournal)+1);
45517  }
45518
45519  sqlite3OsClose(pMaster);
45520  rc = sqlite3OsDelete(pVfs, zMaster, 0);
45521
45522delmaster_out:
45523  sqlite3_free(zMasterJournal);
45524  if( pMaster ){
45525    sqlite3OsClose(pMaster);
45526    assert( !isOpen(pJournal) );
45527    sqlite3_free(pMaster);
45528  }
45529  return rc;
45530}
45531
45532
45533/*
45534** This function is used to change the actual size of the database
45535** file in the file-system. This only happens when committing a transaction,
45536** or rolling back a transaction (including rolling back a hot-journal).
45537**
45538** If the main database file is not open, or the pager is not in either
45539** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
45540** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
45541** If the file on disk is currently larger than nPage pages, then use the VFS
45542** xTruncate() method to truncate it.
45543**
45544** Or, it might be the case that the file on disk is smaller than
45545** nPage pages. Some operating system implementations can get confused if
45546** you try to truncate a file to some size that is larger than it
45547** currently is, so detect this case and write a single zero byte to
45548** the end of the new file instead.
45549**
45550** If successful, return SQLITE_OK. If an IO error occurs while modifying
45551** the database file, return the error code to the caller.
45552*/
45553static int pager_truncate(Pager *pPager, Pgno nPage){
45554  int rc = SQLITE_OK;
45555  assert( pPager->eState!=PAGER_ERROR );
45556  assert( pPager->eState!=PAGER_READER );
45557
45558  if( isOpen(pPager->fd)
45559   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45560  ){
45561    i64 currentSize, newSize;
45562    int szPage = pPager->pageSize;
45563    assert( pPager->eLock==EXCLUSIVE_LOCK );
45564    /* TODO: Is it safe to use Pager.dbFileSize here? */
45565    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
45566    newSize = szPage*(i64)nPage;
45567    if( rc==SQLITE_OK && currentSize!=newSize ){
45568      if( currentSize>newSize ){
45569        rc = sqlite3OsTruncate(pPager->fd, newSize);
45570      }else if( (currentSize+szPage)<=newSize ){
45571        char *pTmp = pPager->pTmpSpace;
45572        memset(pTmp, 0, szPage);
45573        testcase( (newSize-szPage) == currentSize );
45574        testcase( (newSize-szPage) >  currentSize );
45575        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
45576      }
45577      if( rc==SQLITE_OK ){
45578        pPager->dbFileSize = nPage;
45579      }
45580    }
45581  }
45582  return rc;
45583}
45584
45585/*
45586** Return a sanitized version of the sector-size of OS file pFile. The
45587** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
45588*/
45589SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
45590  int iRet = sqlite3OsSectorSize(pFile);
45591  if( iRet<32 ){
45592    iRet = 512;
45593  }else if( iRet>MAX_SECTOR_SIZE ){
45594    assert( MAX_SECTOR_SIZE>=512 );
45595    iRet = MAX_SECTOR_SIZE;
45596  }
45597  return iRet;
45598}
45599
45600/*
45601** Set the value of the Pager.sectorSize variable for the given
45602** pager based on the value returned by the xSectorSize method
45603** of the open database file. The sector size will be used
45604** to determine the size and alignment of journal header and
45605** master journal pointers within created journal files.
45606**
45607** For temporary files the effective sector size is always 512 bytes.
45608**
45609** Otherwise, for non-temporary files, the effective sector size is
45610** the value returned by the xSectorSize() method rounded up to 32 if
45611** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
45612** is greater than MAX_SECTOR_SIZE.
45613**
45614** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
45615** the effective sector size to its minimum value (512).  The purpose of
45616** pPager->sectorSize is to define the "blast radius" of bytes that
45617** might change if a crash occurs while writing to a single byte in
45618** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
45619** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
45620** size.  For backwards compatibility of the rollback journal file format,
45621** we cannot reduce the effective sector size below 512.
45622*/
45623static void setSectorSize(Pager *pPager){
45624  assert( isOpen(pPager->fd) || pPager->tempFile );
45625
45626  if( pPager->tempFile
45627   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
45628              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
45629  ){
45630    /* Sector size doesn't matter for temporary files. Also, the file
45631    ** may not have been opened yet, in which case the OsSectorSize()
45632    ** call will segfault. */
45633    pPager->sectorSize = 512;
45634  }else{
45635    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
45636  }
45637}
45638
45639/*
45640** Playback the journal and thus restore the database file to
45641** the state it was in before we started making changes.
45642**
45643** The journal file format is as follows:
45644**
45645**  (1)  8 byte prefix.  A copy of aJournalMagic[].
45646**  (2)  4 byte big-endian integer which is the number of valid page records
45647**       in the journal.  If this value is 0xffffffff, then compute the
45648**       number of page records from the journal size.
45649**  (3)  4 byte big-endian integer which is the initial value for the
45650**       sanity checksum.
45651**  (4)  4 byte integer which is the number of pages to truncate the
45652**       database to during a rollback.
45653**  (5)  4 byte big-endian integer which is the sector size.  The header
45654**       is this many bytes in size.
45655**  (6)  4 byte big-endian integer which is the page size.
45656**  (7)  zero padding out to the next sector size.
45657**  (8)  Zero or more pages instances, each as follows:
45658**        +  4 byte page number.
45659**        +  pPager->pageSize bytes of data.
45660**        +  4 byte checksum
45661**
45662** When we speak of the journal header, we mean the first 7 items above.
45663** Each entry in the journal is an instance of the 8th item.
45664**
45665** Call the value from the second bullet "nRec".  nRec is the number of
45666** valid page entries in the journal.  In most cases, you can compute the
45667** value of nRec from the size of the journal file.  But if a power
45668** failure occurred while the journal was being written, it could be the
45669** case that the size of the journal file had already been increased but
45670** the extra entries had not yet made it safely to disk.  In such a case,
45671** the value of nRec computed from the file size would be too large.  For
45672** that reason, we always use the nRec value in the header.
45673**
45674** If the nRec value is 0xffffffff it means that nRec should be computed
45675** from the file size.  This value is used when the user selects the
45676** no-sync option for the journal.  A power failure could lead to corruption
45677** in this case.  But for things like temporary table (which will be
45678** deleted when the power is restored) we don't care.
45679**
45680** If the file opened as the journal file is not a well-formed
45681** journal file then all pages up to the first corrupted page are rolled
45682** back (or no pages if the journal header is corrupted). The journal file
45683** is then deleted and SQLITE_OK returned, just as if no corruption had
45684** been encountered.
45685**
45686** If an I/O or malloc() error occurs, the journal-file is not deleted
45687** and an error code is returned.
45688**
45689** The isHot parameter indicates that we are trying to rollback a journal
45690** that might be a hot journal.  Or, it could be that the journal is
45691** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
45692** If the journal really is hot, reset the pager cache prior rolling
45693** back any content.  If the journal is merely persistent, no reset is
45694** needed.
45695*/
45696static int pager_playback(Pager *pPager, int isHot){
45697  sqlite3_vfs *pVfs = pPager->pVfs;
45698  i64 szJ;                 /* Size of the journal file in bytes */
45699  u32 nRec;                /* Number of Records in the journal */
45700  u32 u;                   /* Unsigned loop counter */
45701  Pgno mxPg = 0;           /* Size of the original file in pages */
45702  int rc;                  /* Result code of a subroutine */
45703  int res = 1;             /* Value returned by sqlite3OsAccess() */
45704  char *zMaster = 0;       /* Name of master journal file if any */
45705  int needPagerReset;      /* True to reset page prior to first page rollback */
45706  int nPlayback = 0;       /* Total number of pages restored from journal */
45707
45708  /* Figure out how many records are in the journal.  Abort early if
45709  ** the journal is empty.
45710  */
45711  assert( isOpen(pPager->jfd) );
45712  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
45713  if( rc!=SQLITE_OK ){
45714    goto end_playback;
45715  }
45716
45717  /* Read the master journal name from the journal, if it is present.
45718  ** If a master journal file name is specified, but the file is not
45719  ** present on disk, then the journal is not hot and does not need to be
45720  ** played back.
45721  **
45722  ** TODO: Technically the following is an error because it assumes that
45723  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
45724  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
45725  **  mxPathname is 512, which is the same as the minimum allowable value
45726  ** for pageSize.
45727  */
45728  zMaster = pPager->pTmpSpace;
45729  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
45730  if( rc==SQLITE_OK && zMaster[0] ){
45731    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
45732  }
45733  zMaster = 0;
45734  if( rc!=SQLITE_OK || !res ){
45735    goto end_playback;
45736  }
45737  pPager->journalOff = 0;
45738  needPagerReset = isHot;
45739
45740  /* This loop terminates either when a readJournalHdr() or
45741  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
45742  ** occurs.
45743  */
45744  while( 1 ){
45745    /* Read the next journal header from the journal file.  If there are
45746    ** not enough bytes left in the journal file for a complete header, or
45747    ** it is corrupted, then a process must have failed while writing it.
45748    ** This indicates nothing more needs to be rolled back.
45749    */
45750    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
45751    if( rc!=SQLITE_OK ){
45752      if( rc==SQLITE_DONE ){
45753        rc = SQLITE_OK;
45754      }
45755      goto end_playback;
45756    }
45757
45758    /* If nRec is 0xffffffff, then this journal was created by a process
45759    ** working in no-sync mode. This means that the rest of the journal
45760    ** file consists of pages, there are no more journal headers. Compute
45761    ** the value of nRec based on this assumption.
45762    */
45763    if( nRec==0xffffffff ){
45764      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
45765      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
45766    }
45767
45768    /* If nRec is 0 and this rollback is of a transaction created by this
45769    ** process and if this is the final header in the journal, then it means
45770    ** that this part of the journal was being filled but has not yet been
45771    ** synced to disk.  Compute the number of pages based on the remaining
45772    ** size of the file.
45773    **
45774    ** The third term of the test was added to fix ticket #2565.
45775    ** When rolling back a hot journal, nRec==0 always means that the next
45776    ** chunk of the journal contains zero pages to be rolled back.  But
45777    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
45778    ** the journal, it means that the journal might contain additional
45779    ** pages that need to be rolled back and that the number of pages
45780    ** should be computed based on the journal file size.
45781    */
45782    if( nRec==0 && !isHot &&
45783        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
45784      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
45785    }
45786
45787    /* If this is the first header read from the journal, truncate the
45788    ** database file back to its original size.
45789    */
45790    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
45791      rc = pager_truncate(pPager, mxPg);
45792      if( rc!=SQLITE_OK ){
45793        goto end_playback;
45794      }
45795      pPager->dbSize = mxPg;
45796    }
45797
45798    /* Copy original pages out of the journal and back into the
45799    ** database file and/or page cache.
45800    */
45801    for(u=0; u<nRec; u++){
45802      if( needPagerReset ){
45803        pager_reset(pPager);
45804        needPagerReset = 0;
45805      }
45806      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
45807      if( rc==SQLITE_OK ){
45808        nPlayback++;
45809      }else{
45810        if( rc==SQLITE_DONE ){
45811          pPager->journalOff = szJ;
45812          break;
45813        }else if( rc==SQLITE_IOERR_SHORT_READ ){
45814          /* If the journal has been truncated, simply stop reading and
45815          ** processing the journal. This might happen if the journal was
45816          ** not completely written and synced prior to a crash.  In that
45817          ** case, the database should have never been written in the
45818          ** first place so it is OK to simply abandon the rollback. */
45819          rc = SQLITE_OK;
45820          goto end_playback;
45821        }else{
45822          /* If we are unable to rollback, quit and return the error
45823          ** code.  This will cause the pager to enter the error state
45824          ** so that no further harm will be done.  Perhaps the next
45825          ** process to come along will be able to rollback the database.
45826          */
45827          goto end_playback;
45828        }
45829      }
45830    }
45831  }
45832  /*NOTREACHED*/
45833  assert( 0 );
45834
45835end_playback:
45836  /* Following a rollback, the database file should be back in its original
45837  ** state prior to the start of the transaction, so invoke the
45838  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
45839  ** assertion that the transaction counter was modified.
45840  */
45841#ifdef SQLITE_DEBUG
45842  if( pPager->fd->pMethods ){
45843    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
45844  }
45845#endif
45846
45847  /* If this playback is happening automatically as a result of an IO or
45848  ** malloc error that occurred after the change-counter was updated but
45849  ** before the transaction was committed, then the change-counter
45850  ** modification may just have been reverted. If this happens in exclusive
45851  ** mode, then subsequent transactions performed by the connection will not
45852  ** update the change-counter at all. This may lead to cache inconsistency
45853  ** problems for other processes at some point in the future. So, just
45854  ** in case this has happened, clear the changeCountDone flag now.
45855  */
45856  pPager->changeCountDone = pPager->tempFile;
45857
45858  if( rc==SQLITE_OK ){
45859    zMaster = pPager->pTmpSpace;
45860    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
45861    testcase( rc!=SQLITE_OK );
45862  }
45863  if( rc==SQLITE_OK
45864   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45865  ){
45866    rc = sqlite3PagerSync(pPager, 0);
45867  }
45868  if( rc==SQLITE_OK ){
45869    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
45870    testcase( rc!=SQLITE_OK );
45871  }
45872  if( rc==SQLITE_OK && zMaster[0] && res ){
45873    /* If there was a master journal and this routine will return success,
45874    ** see if it is possible to delete the master journal.
45875    */
45876    rc = pager_delmaster(pPager, zMaster);
45877    testcase( rc!=SQLITE_OK );
45878  }
45879  if( isHot && nPlayback ){
45880    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
45881                nPlayback, pPager->zJournal);
45882  }
45883
45884  /* The Pager.sectorSize variable may have been updated while rolling
45885  ** back a journal created by a process with a different sector size
45886  ** value. Reset it to the correct value for this process.
45887  */
45888  setSectorSize(pPager);
45889  return rc;
45890}
45891
45892
45893/*
45894** Read the content for page pPg out of the database file and into
45895** pPg->pData. A shared lock or greater must be held on the database
45896** file before this function is called.
45897**
45898** If page 1 is read, then the value of Pager.dbFileVers[] is set to
45899** the value read from the database file.
45900**
45901** If an IO error occurs, then the IO error is returned to the caller.
45902** Otherwise, SQLITE_OK is returned.
45903*/
45904static int readDbPage(PgHdr *pPg, u32 iFrame){
45905  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
45906  Pgno pgno = pPg->pgno;       /* Page number to read */
45907  int rc = SQLITE_OK;          /* Return code */
45908  int pgsz = pPager->pageSize; /* Number of bytes to read */
45909
45910  assert( pPager->eState>=PAGER_READER && !MEMDB );
45911  assert( isOpen(pPager->fd) );
45912
45913#ifndef SQLITE_OMIT_WAL
45914  if( iFrame ){
45915    /* Try to pull the page from the write-ahead log. */
45916    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
45917  }else
45918#endif
45919  {
45920    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
45921    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
45922    if( rc==SQLITE_IOERR_SHORT_READ ){
45923      rc = SQLITE_OK;
45924    }
45925  }
45926
45927  if( pgno==1 ){
45928    if( rc ){
45929      /* If the read is unsuccessful, set the dbFileVers[] to something
45930      ** that will never be a valid file version.  dbFileVers[] is a copy
45931      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
45932      ** zero or the size of the database in page. Bytes 32..35 and 35..39
45933      ** should be page numbers which are never 0xffffffff.  So filling
45934      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
45935      **
45936      ** For an encrypted database, the situation is more complex:  bytes
45937      ** 24..39 of the database are white noise.  But the probability of
45938      ** white noise equaling 16 bytes of 0xff is vanishingly small so
45939      ** we should still be ok.
45940      */
45941      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
45942    }else{
45943      u8 *dbFileVers = &((u8*)pPg->pData)[24];
45944      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
45945    }
45946  }
45947  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
45948
45949  PAGER_INCR(sqlite3_pager_readdb_count);
45950  PAGER_INCR(pPager->nRead);
45951  IOTRACE(("PGIN %p %d\n", pPager, pgno));
45952  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
45953               PAGERID(pPager), pgno, pager_pagehash(pPg)));
45954
45955  return rc;
45956}
45957
45958/*
45959** Update the value of the change-counter at offsets 24 and 92 in
45960** the header and the sqlite version number at offset 96.
45961**
45962** This is an unconditional update.  See also the pager_incr_changecounter()
45963** routine which only updates the change-counter if the update is actually
45964** needed, as determined by the pPager->changeCountDone state variable.
45965*/
45966static void pager_write_changecounter(PgHdr *pPg){
45967  u32 change_counter;
45968
45969  /* Increment the value just read and write it back to byte 24. */
45970  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
45971  put32bits(((char*)pPg->pData)+24, change_counter);
45972
45973  /* Also store the SQLite version number in bytes 96..99 and in
45974  ** bytes 92..95 store the change counter for which the version number
45975  ** is valid. */
45976  put32bits(((char*)pPg->pData)+92, change_counter);
45977  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
45978}
45979
45980#ifndef SQLITE_OMIT_WAL
45981/*
45982** This function is invoked once for each page that has already been
45983** written into the log file when a WAL transaction is rolled back.
45984** Parameter iPg is the page number of said page. The pCtx argument
45985** is actually a pointer to the Pager structure.
45986**
45987** If page iPg is present in the cache, and has no outstanding references,
45988** it is discarded. Otherwise, if there are one or more outstanding
45989** references, the page content is reloaded from the database. If the
45990** attempt to reload content from the database is required and fails,
45991** return an SQLite error code. Otherwise, SQLITE_OK.
45992*/
45993static int pagerUndoCallback(void *pCtx, Pgno iPg){
45994  int rc = SQLITE_OK;
45995  Pager *pPager = (Pager *)pCtx;
45996  PgHdr *pPg;
45997
45998  assert( pagerUseWal(pPager) );
45999  pPg = sqlite3PagerLookup(pPager, iPg);
46000  if( pPg ){
46001    if( sqlite3PcachePageRefcount(pPg)==1 ){
46002      sqlite3PcacheDrop(pPg);
46003    }else{
46004      u32 iFrame = 0;
46005      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
46006      if( rc==SQLITE_OK ){
46007        rc = readDbPage(pPg, iFrame);
46008      }
46009      if( rc==SQLITE_OK ){
46010        pPager->xReiniter(pPg);
46011      }
46012      sqlite3PagerUnrefNotNull(pPg);
46013    }
46014  }
46015
46016  /* Normally, if a transaction is rolled back, any backup processes are
46017  ** updated as data is copied out of the rollback journal and into the
46018  ** database. This is not generally possible with a WAL database, as
46019  ** rollback involves simply truncating the log file. Therefore, if one
46020  ** or more frames have already been written to the log (and therefore
46021  ** also copied into the backup databases) as part of this transaction,
46022  ** the backups must be restarted.
46023  */
46024  sqlite3BackupRestart(pPager->pBackup);
46025
46026  return rc;
46027}
46028
46029/*
46030** This function is called to rollback a transaction on a WAL database.
46031*/
46032static int pagerRollbackWal(Pager *pPager){
46033  int rc;                         /* Return Code */
46034  PgHdr *pList;                   /* List of dirty pages to revert */
46035
46036  /* For all pages in the cache that are currently dirty or have already
46037  ** been written (but not committed) to the log file, do one of the
46038  ** following:
46039  **
46040  **   + Discard the cached page (if refcount==0), or
46041  **   + Reload page content from the database (if refcount>0).
46042  */
46043  pPager->dbSize = pPager->dbOrigSize;
46044  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
46045  pList = sqlite3PcacheDirtyList(pPager->pPCache);
46046  while( pList && rc==SQLITE_OK ){
46047    PgHdr *pNext = pList->pDirty;
46048    rc = pagerUndoCallback((void *)pPager, pList->pgno);
46049    pList = pNext;
46050  }
46051
46052  return rc;
46053}
46054
46055/*
46056** This function is a wrapper around sqlite3WalFrames(). As well as logging
46057** the contents of the list of pages headed by pList (connected by pDirty),
46058** this function notifies any active backup processes that the pages have
46059** changed.
46060**
46061** The list of pages passed into this routine is always sorted by page number.
46062** Hence, if page 1 appears anywhere on the list, it will be the first page.
46063*/
46064static int pagerWalFrames(
46065  Pager *pPager,                  /* Pager object */
46066  PgHdr *pList,                   /* List of frames to log */
46067  Pgno nTruncate,                 /* Database size after this commit */
46068  int isCommit                    /* True if this is a commit */
46069){
46070  int rc;                         /* Return code */
46071  int nList;                      /* Number of pages in pList */
46072  PgHdr *p;                       /* For looping over pages */
46073
46074  assert( pPager->pWal );
46075  assert( pList );
46076#ifdef SQLITE_DEBUG
46077  /* Verify that the page list is in accending order */
46078  for(p=pList; p && p->pDirty; p=p->pDirty){
46079    assert( p->pgno < p->pDirty->pgno );
46080  }
46081#endif
46082
46083  assert( pList->pDirty==0 || isCommit );
46084  if( isCommit ){
46085    /* If a WAL transaction is being committed, there is no point in writing
46086    ** any pages with page numbers greater than nTruncate into the WAL file.
46087    ** They will never be read by any client. So remove them from the pDirty
46088    ** list here. */
46089    PgHdr **ppNext = &pList;
46090    nList = 0;
46091    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
46092      if( p->pgno<=nTruncate ){
46093        ppNext = &p->pDirty;
46094        nList++;
46095      }
46096    }
46097    assert( pList );
46098  }else{
46099    nList = 1;
46100  }
46101  pPager->aStat[PAGER_STAT_WRITE] += nList;
46102
46103  if( pList->pgno==1 ) pager_write_changecounter(pList);
46104  rc = sqlite3WalFrames(pPager->pWal,
46105      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
46106  );
46107  if( rc==SQLITE_OK && pPager->pBackup ){
46108    for(p=pList; p; p=p->pDirty){
46109      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
46110    }
46111  }
46112
46113#ifdef SQLITE_CHECK_PAGES
46114  pList = sqlite3PcacheDirtyList(pPager->pPCache);
46115  for(p=pList; p; p=p->pDirty){
46116    pager_set_pagehash(p);
46117  }
46118#endif
46119
46120  return rc;
46121}
46122
46123/*
46124** Begin a read transaction on the WAL.
46125**
46126** This routine used to be called "pagerOpenSnapshot()" because it essentially
46127** makes a snapshot of the database at the current point in time and preserves
46128** that snapshot for use by the reader in spite of concurrently changes by
46129** other writers or checkpointers.
46130*/
46131static int pagerBeginReadTransaction(Pager *pPager){
46132  int rc;                         /* Return code */
46133  int changed = 0;                /* True if cache must be reset */
46134
46135  assert( pagerUseWal(pPager) );
46136  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
46137
46138  /* sqlite3WalEndReadTransaction() was not called for the previous
46139  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
46140  ** are in locking_mode=NORMAL and EndRead() was previously called,
46141  ** the duplicate call is harmless.
46142  */
46143  sqlite3WalEndReadTransaction(pPager->pWal);
46144
46145  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
46146  if( rc!=SQLITE_OK || changed ){
46147    pager_reset(pPager);
46148    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
46149  }
46150
46151  return rc;
46152}
46153#endif
46154
46155/*
46156** This function is called as part of the transition from PAGER_OPEN
46157** to PAGER_READER state to determine the size of the database file
46158** in pages (assuming the page size currently stored in Pager.pageSize).
46159**
46160** If no error occurs, SQLITE_OK is returned and the size of the database
46161** in pages is stored in *pnPage. Otherwise, an error code (perhaps
46162** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
46163*/
46164static int pagerPagecount(Pager *pPager, Pgno *pnPage){
46165  Pgno nPage;                     /* Value to return via *pnPage */
46166
46167  /* Query the WAL sub-system for the database size. The WalDbsize()
46168  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
46169  ** if the database size is not available. The database size is not
46170  ** available from the WAL sub-system if the log file is empty or
46171  ** contains no valid committed transactions.
46172  */
46173  assert( pPager->eState==PAGER_OPEN );
46174  assert( pPager->eLock>=SHARED_LOCK );
46175  nPage = sqlite3WalDbsize(pPager->pWal);
46176
46177  /* If the number of pages in the database is not available from the
46178  ** WAL sub-system, determine the page counte based on the size of
46179  ** the database file.  If the size of the database file is not an
46180  ** integer multiple of the page-size, round up the result.
46181  */
46182  if( nPage==0 ){
46183    i64 n = 0;                    /* Size of db file in bytes */
46184    assert( isOpen(pPager->fd) || pPager->tempFile );
46185    if( isOpen(pPager->fd) ){
46186      int rc = sqlite3OsFileSize(pPager->fd, &n);
46187      if( rc!=SQLITE_OK ){
46188        return rc;
46189      }
46190    }
46191    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
46192  }
46193
46194  /* If the current number of pages in the file is greater than the
46195  ** configured maximum pager number, increase the allowed limit so
46196  ** that the file can be read.
46197  */
46198  if( nPage>pPager->mxPgno ){
46199    pPager->mxPgno = (Pgno)nPage;
46200  }
46201
46202  *pnPage = nPage;
46203  return SQLITE_OK;
46204}
46205
46206#ifndef SQLITE_OMIT_WAL
46207/*
46208** Check if the *-wal file that corresponds to the database opened by pPager
46209** exists if the database is not empy, or verify that the *-wal file does
46210** not exist (by deleting it) if the database file is empty.
46211**
46212** If the database is not empty and the *-wal file exists, open the pager
46213** in WAL mode.  If the database is empty or if no *-wal file exists and
46214** if no error occurs, make sure Pager.journalMode is not set to
46215** PAGER_JOURNALMODE_WAL.
46216**
46217** Return SQLITE_OK or an error code.
46218**
46219** The caller must hold a SHARED lock on the database file to call this
46220** function. Because an EXCLUSIVE lock on the db file is required to delete
46221** a WAL on a none-empty database, this ensures there is no race condition
46222** between the xAccess() below and an xDelete() being executed by some
46223** other connection.
46224*/
46225static int pagerOpenWalIfPresent(Pager *pPager){
46226  int rc = SQLITE_OK;
46227  assert( pPager->eState==PAGER_OPEN );
46228  assert( pPager->eLock>=SHARED_LOCK );
46229
46230  if( !pPager->tempFile ){
46231    int isWal;                    /* True if WAL file exists */
46232    Pgno nPage;                   /* Size of the database file */
46233
46234    rc = pagerPagecount(pPager, &nPage);
46235    if( rc ) return rc;
46236    if( nPage==0 ){
46237      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
46238      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
46239      isWal = 0;
46240    }else{
46241      rc = sqlite3OsAccess(
46242          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
46243      );
46244    }
46245    if( rc==SQLITE_OK ){
46246      if( isWal ){
46247        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
46248        rc = sqlite3PagerOpenWal(pPager, 0);
46249      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
46250        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
46251      }
46252    }
46253  }
46254  return rc;
46255}
46256#endif
46257
46258/*
46259** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
46260** the entire master journal file. The case pSavepoint==NULL occurs when
46261** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
46262** savepoint.
46263**
46264** When pSavepoint is not NULL (meaning a non-transaction savepoint is
46265** being rolled back), then the rollback consists of up to three stages,
46266** performed in the order specified:
46267**
46268**   * Pages are played back from the main journal starting at byte
46269**     offset PagerSavepoint.iOffset and continuing to
46270**     PagerSavepoint.iHdrOffset, or to the end of the main journal
46271**     file if PagerSavepoint.iHdrOffset is zero.
46272**
46273**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
46274**     back starting from the journal header immediately following
46275**     PagerSavepoint.iHdrOffset to the end of the main journal file.
46276**
46277**   * Pages are then played back from the sub-journal file, starting
46278**     with the PagerSavepoint.iSubRec and continuing to the end of
46279**     the journal file.
46280**
46281** Throughout the rollback process, each time a page is rolled back, the
46282** corresponding bit is set in a bitvec structure (variable pDone in the
46283** implementation below). This is used to ensure that a page is only
46284** rolled back the first time it is encountered in either journal.
46285**
46286** If pSavepoint is NULL, then pages are only played back from the main
46287** journal file. There is no need for a bitvec in this case.
46288**
46289** In either case, before playback commences the Pager.dbSize variable
46290** is reset to the value that it held at the start of the savepoint
46291** (or transaction). No page with a page-number greater than this value
46292** is played back. If one is encountered it is simply skipped.
46293*/
46294static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
46295  i64 szJ;                 /* Effective size of the main journal */
46296  i64 iHdrOff;             /* End of first segment of main-journal records */
46297  int rc = SQLITE_OK;      /* Return code */
46298  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
46299
46300  assert( pPager->eState!=PAGER_ERROR );
46301  assert( pPager->eState>=PAGER_WRITER_LOCKED );
46302
46303  /* Allocate a bitvec to use to store the set of pages rolled back */
46304  if( pSavepoint ){
46305    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
46306    if( !pDone ){
46307      return SQLITE_NOMEM;
46308    }
46309  }
46310
46311  /* Set the database size back to the value it was before the savepoint
46312  ** being reverted was opened.
46313  */
46314  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
46315  pPager->changeCountDone = pPager->tempFile;
46316
46317  if( !pSavepoint && pagerUseWal(pPager) ){
46318    return pagerRollbackWal(pPager);
46319  }
46320
46321  /* Use pPager->journalOff as the effective size of the main rollback
46322  ** journal.  The actual file might be larger than this in
46323  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
46324  ** past pPager->journalOff is off-limits to us.
46325  */
46326  szJ = pPager->journalOff;
46327  assert( pagerUseWal(pPager)==0 || szJ==0 );
46328
46329  /* Begin by rolling back records from the main journal starting at
46330  ** PagerSavepoint.iOffset and continuing to the next journal header.
46331  ** There might be records in the main journal that have a page number
46332  ** greater than the current database size (pPager->dbSize) but those
46333  ** will be skipped automatically.  Pages are added to pDone as they
46334  ** are played back.
46335  */
46336  if( pSavepoint && !pagerUseWal(pPager) ){
46337    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
46338    pPager->journalOff = pSavepoint->iOffset;
46339    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
46340      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
46341    }
46342    assert( rc!=SQLITE_DONE );
46343  }else{
46344    pPager->journalOff = 0;
46345  }
46346
46347  /* Continue rolling back records out of the main journal starting at
46348  ** the first journal header seen and continuing until the effective end
46349  ** of the main journal file.  Continue to skip out-of-range pages and
46350  ** continue adding pages rolled back to pDone.
46351  */
46352  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
46353    u32 ii;            /* Loop counter */
46354    u32 nJRec = 0;     /* Number of Journal Records */
46355    u32 dummy;
46356    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
46357    assert( rc!=SQLITE_DONE );
46358
46359    /*
46360    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
46361    ** test is related to ticket #2565.  See the discussion in the
46362    ** pager_playback() function for additional information.
46363    */
46364    if( nJRec==0
46365     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
46366    ){
46367      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
46368    }
46369    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
46370      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
46371    }
46372    assert( rc!=SQLITE_DONE );
46373  }
46374  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
46375
46376  /* Finally,  rollback pages from the sub-journal.  Page that were
46377  ** previously rolled back out of the main journal (and are hence in pDone)
46378  ** will be skipped.  Out-of-range pages are also skipped.
46379  */
46380  if( pSavepoint ){
46381    u32 ii;            /* Loop counter */
46382    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
46383
46384    if( pagerUseWal(pPager) ){
46385      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
46386    }
46387    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
46388      assert( offset==(i64)ii*(4+pPager->pageSize) );
46389      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
46390    }
46391    assert( rc!=SQLITE_DONE );
46392  }
46393
46394  sqlite3BitvecDestroy(pDone);
46395  if( rc==SQLITE_OK ){
46396    pPager->journalOff = szJ;
46397  }
46398
46399  return rc;
46400}
46401
46402/*
46403** Change the maximum number of in-memory pages that are allowed.
46404*/
46405SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
46406  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
46407}
46408
46409/*
46410** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
46411*/
46412static void pagerFixMaplimit(Pager *pPager){
46413#if SQLITE_MAX_MMAP_SIZE>0
46414  sqlite3_file *fd = pPager->fd;
46415  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
46416    sqlite3_int64 sz;
46417    sz = pPager->szMmap;
46418    pPager->bUseFetch = (sz>0);
46419    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
46420  }
46421#endif
46422}
46423
46424/*
46425** Change the maximum size of any memory mapping made of the database file.
46426*/
46427SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
46428  pPager->szMmap = szMmap;
46429  pagerFixMaplimit(pPager);
46430}
46431
46432/*
46433** Free as much memory as possible from the pager.
46434*/
46435SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
46436  sqlite3PcacheShrink(pPager->pPCache);
46437}
46438
46439/*
46440** Adjust settings of the pager to those specified in the pgFlags parameter.
46441**
46442** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
46443** of the database to damage due to OS crashes or power failures by
46444** changing the number of syncs()s when writing the journals.
46445** There are three levels:
46446**
46447**    OFF       sqlite3OsSync() is never called.  This is the default
46448**              for temporary and transient files.
46449**
46450**    NORMAL    The journal is synced once before writes begin on the
46451**              database.  This is normally adequate protection, but
46452**              it is theoretically possible, though very unlikely,
46453**              that an inopertune power failure could leave the journal
46454**              in a state which would cause damage to the database
46455**              when it is rolled back.
46456**
46457**    FULL      The journal is synced twice before writes begin on the
46458**              database (with some additional information - the nRec field
46459**              of the journal header - being written in between the two
46460**              syncs).  If we assume that writing a
46461**              single disk sector is atomic, then this mode provides
46462**              assurance that the journal will not be corrupted to the
46463**              point of causing damage to the database during rollback.
46464**
46465** The above is for a rollback-journal mode.  For WAL mode, OFF continues
46466** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
46467** prior to the start of checkpoint and that the database file is synced
46468** at the conclusion of the checkpoint if the entire content of the WAL
46469** was written back into the database.  But no sync operations occur for
46470** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
46471** file is synced following each commit operation, in addition to the
46472** syncs associated with NORMAL.
46473**
46474** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
46475** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
46476** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
46477** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
46478** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
46479** synchronous=FULL versus synchronous=NORMAL setting determines when
46480** the xSync primitive is called and is relevant to all platforms.
46481**
46482** Numeric values associated with these states are OFF==1, NORMAL=2,
46483** and FULL=3.
46484*/
46485#ifndef SQLITE_OMIT_PAGER_PRAGMAS
46486SQLITE_PRIVATE void sqlite3PagerSetFlags(
46487  Pager *pPager,        /* The pager to set safety level for */
46488  unsigned pgFlags      /* Various flags */
46489){
46490  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
46491  assert( level>=1 && level<=3 );
46492  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
46493  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
46494  if( pPager->noSync ){
46495    pPager->syncFlags = 0;
46496    pPager->ckptSyncFlags = 0;
46497  }else if( pgFlags & PAGER_FULLFSYNC ){
46498    pPager->syncFlags = SQLITE_SYNC_FULL;
46499    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
46500  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
46501    pPager->syncFlags = SQLITE_SYNC_NORMAL;
46502    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
46503  }else{
46504    pPager->syncFlags = SQLITE_SYNC_NORMAL;
46505    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
46506  }
46507  pPager->walSyncFlags = pPager->syncFlags;
46508  if( pPager->fullSync ){
46509    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
46510  }
46511  if( pgFlags & PAGER_CACHESPILL ){
46512    pPager->doNotSpill &= ~SPILLFLAG_OFF;
46513  }else{
46514    pPager->doNotSpill |= SPILLFLAG_OFF;
46515  }
46516}
46517#endif
46518
46519/*
46520** The following global variable is incremented whenever the library
46521** attempts to open a temporary file.  This information is used for
46522** testing and analysis only.
46523*/
46524#ifdef SQLITE_TEST
46525SQLITE_API int sqlite3_opentemp_count = 0;
46526#endif
46527
46528/*
46529** Open a temporary file.
46530**
46531** Write the file descriptor into *pFile. Return SQLITE_OK on success
46532** or some other error code if we fail. The OS will automatically
46533** delete the temporary file when it is closed.
46534**
46535** The flags passed to the VFS layer xOpen() call are those specified
46536** by parameter vfsFlags ORed with the following:
46537**
46538**     SQLITE_OPEN_READWRITE
46539**     SQLITE_OPEN_CREATE
46540**     SQLITE_OPEN_EXCLUSIVE
46541**     SQLITE_OPEN_DELETEONCLOSE
46542*/
46543static int pagerOpentemp(
46544  Pager *pPager,        /* The pager object */
46545  sqlite3_file *pFile,  /* Write the file descriptor here */
46546  int vfsFlags          /* Flags passed through to the VFS */
46547){
46548  int rc;               /* Return code */
46549
46550#ifdef SQLITE_TEST
46551  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
46552#endif
46553
46554  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
46555            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
46556  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
46557  assert( rc!=SQLITE_OK || isOpen(pFile) );
46558  return rc;
46559}
46560
46561/*
46562** Set the busy handler function.
46563**
46564** The pager invokes the busy-handler if sqlite3OsLock() returns
46565** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
46566** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
46567** lock. It does *not* invoke the busy handler when upgrading from
46568** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
46569** (which occurs during hot-journal rollback). Summary:
46570**
46571**   Transition                        | Invokes xBusyHandler
46572**   --------------------------------------------------------
46573**   NO_LOCK       -> SHARED_LOCK      | Yes
46574**   SHARED_LOCK   -> RESERVED_LOCK    | No
46575**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
46576**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
46577**
46578** If the busy-handler callback returns non-zero, the lock is
46579** retried. If it returns zero, then the SQLITE_BUSY error is
46580** returned to the caller of the pager API function.
46581*/
46582SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
46583  Pager *pPager,                       /* Pager object */
46584  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
46585  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
46586){
46587  pPager->xBusyHandler = xBusyHandler;
46588  pPager->pBusyHandlerArg = pBusyHandlerArg;
46589
46590  if( isOpen(pPager->fd) ){
46591    void **ap = (void **)&pPager->xBusyHandler;
46592    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
46593    assert( ap[1]==pBusyHandlerArg );
46594    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
46595  }
46596}
46597
46598/*
46599** Change the page size used by the Pager object. The new page size
46600** is passed in *pPageSize.
46601**
46602** If the pager is in the error state when this function is called, it
46603** is a no-op. The value returned is the error state error code (i.e.
46604** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
46605**
46606** Otherwise, if all of the following are true:
46607**
46608**   * the new page size (value of *pPageSize) is valid (a power
46609**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
46610**
46611**   * there are no outstanding page references, and
46612**
46613**   * the database is either not an in-memory database or it is
46614**     an in-memory database that currently consists of zero pages.
46615**
46616** then the pager object page size is set to *pPageSize.
46617**
46618** If the page size is changed, then this function uses sqlite3PagerMalloc()
46619** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
46620** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
46621** In all other cases, SQLITE_OK is returned.
46622**
46623** If the page size is not changed, either because one of the enumerated
46624** conditions above is not true, the pager was in error state when this
46625** function was called, or because the memory allocation attempt failed,
46626** then *pPageSize is set to the old, retained page size before returning.
46627*/
46628SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
46629  int rc = SQLITE_OK;
46630
46631  /* It is not possible to do a full assert_pager_state() here, as this
46632  ** function may be called from within PagerOpen(), before the state
46633  ** of the Pager object is internally consistent.
46634  **
46635  ** At one point this function returned an error if the pager was in
46636  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
46637  ** there is at least one outstanding page reference, this function
46638  ** is a no-op for that case anyhow.
46639  */
46640
46641  u32 pageSize = *pPageSize;
46642  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
46643  if( (pPager->memDb==0 || pPager->dbSize==0)
46644   && sqlite3PcacheRefCount(pPager->pPCache)==0
46645   && pageSize && pageSize!=(u32)pPager->pageSize
46646  ){
46647    char *pNew = NULL;             /* New temp space */
46648    i64 nByte = 0;
46649
46650    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
46651      rc = sqlite3OsFileSize(pPager->fd, &nByte);
46652    }
46653    if( rc==SQLITE_OK ){
46654      pNew = (char *)sqlite3PageMalloc(pageSize);
46655      if( !pNew ) rc = SQLITE_NOMEM;
46656    }
46657
46658    if( rc==SQLITE_OK ){
46659      pager_reset(pPager);
46660      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
46661    }
46662    if( rc==SQLITE_OK ){
46663      sqlite3PageFree(pPager->pTmpSpace);
46664      pPager->pTmpSpace = pNew;
46665      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
46666      pPager->pageSize = pageSize;
46667    }else{
46668      sqlite3PageFree(pNew);
46669    }
46670  }
46671
46672  *pPageSize = pPager->pageSize;
46673  if( rc==SQLITE_OK ){
46674    if( nReserve<0 ) nReserve = pPager->nReserve;
46675    assert( nReserve>=0 && nReserve<1000 );
46676    pPager->nReserve = (i16)nReserve;
46677    pagerReportSize(pPager);
46678    pagerFixMaplimit(pPager);
46679  }
46680  return rc;
46681}
46682
46683/*
46684** Return a pointer to the "temporary page" buffer held internally
46685** by the pager.  This is a buffer that is big enough to hold the
46686** entire content of a database page.  This buffer is used internally
46687** during rollback and will be overwritten whenever a rollback
46688** occurs.  But other modules are free to use it too, as long as
46689** no rollbacks are happening.
46690*/
46691SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
46692  return pPager->pTmpSpace;
46693}
46694
46695/*
46696** Attempt to set the maximum database page count if mxPage is positive.
46697** Make no changes if mxPage is zero or negative.  And never reduce the
46698** maximum page count below the current size of the database.
46699**
46700** Regardless of mxPage, return the current maximum page count.
46701*/
46702SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
46703  if( mxPage>0 ){
46704    pPager->mxPgno = mxPage;
46705  }
46706  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
46707  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
46708  return pPager->mxPgno;
46709}
46710
46711/*
46712** The following set of routines are used to disable the simulated
46713** I/O error mechanism.  These routines are used to avoid simulated
46714** errors in places where we do not care about errors.
46715**
46716** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
46717** and generate no code.
46718*/
46719#ifdef SQLITE_TEST
46720SQLITE_API extern int sqlite3_io_error_pending;
46721SQLITE_API extern int sqlite3_io_error_hit;
46722static int saved_cnt;
46723void disable_simulated_io_errors(void){
46724  saved_cnt = sqlite3_io_error_pending;
46725  sqlite3_io_error_pending = -1;
46726}
46727void enable_simulated_io_errors(void){
46728  sqlite3_io_error_pending = saved_cnt;
46729}
46730#else
46731# define disable_simulated_io_errors()
46732# define enable_simulated_io_errors()
46733#endif
46734
46735/*
46736** Read the first N bytes from the beginning of the file into memory
46737** that pDest points to.
46738**
46739** If the pager was opened on a transient file (zFilename==""), or
46740** opened on a file less than N bytes in size, the output buffer is
46741** zeroed and SQLITE_OK returned. The rationale for this is that this
46742** function is used to read database headers, and a new transient or
46743** zero sized database has a header than consists entirely of zeroes.
46744**
46745** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
46746** the error code is returned to the caller and the contents of the
46747** output buffer undefined.
46748*/
46749SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
46750  int rc = SQLITE_OK;
46751  memset(pDest, 0, N);
46752  assert( isOpen(pPager->fd) || pPager->tempFile );
46753
46754  /* This routine is only called by btree immediately after creating
46755  ** the Pager object.  There has not been an opportunity to transition
46756  ** to WAL mode yet.
46757  */
46758  assert( !pagerUseWal(pPager) );
46759
46760  if( isOpen(pPager->fd) ){
46761    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
46762    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
46763    if( rc==SQLITE_IOERR_SHORT_READ ){
46764      rc = SQLITE_OK;
46765    }
46766  }
46767  return rc;
46768}
46769
46770/*
46771** This function may only be called when a read-transaction is open on
46772** the pager. It returns the total number of pages in the database.
46773**
46774** However, if the file is between 1 and <page-size> bytes in size, then
46775** this is considered a 1 page file.
46776*/
46777SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
46778  assert( pPager->eState>=PAGER_READER );
46779  assert( pPager->eState!=PAGER_WRITER_FINISHED );
46780  *pnPage = (int)pPager->dbSize;
46781}
46782
46783
46784/*
46785** Try to obtain a lock of type locktype on the database file. If
46786** a similar or greater lock is already held, this function is a no-op
46787** (returning SQLITE_OK immediately).
46788**
46789** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
46790** the busy callback if the lock is currently not available. Repeat
46791** until the busy callback returns false or until the attempt to
46792** obtain the lock succeeds.
46793**
46794** Return SQLITE_OK on success and an error code if we cannot obtain
46795** the lock. If the lock is obtained successfully, set the Pager.state
46796** variable to locktype before returning.
46797*/
46798static int pager_wait_on_lock(Pager *pPager, int locktype){
46799  int rc;                              /* Return code */
46800
46801  /* Check that this is either a no-op (because the requested lock is
46802  ** already held), or one of the transitions that the busy-handler
46803  ** may be invoked during, according to the comment above
46804  ** sqlite3PagerSetBusyhandler().
46805  */
46806  assert( (pPager->eLock>=locktype)
46807       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
46808       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
46809  );
46810
46811  do {
46812    rc = pagerLockDb(pPager, locktype);
46813  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
46814  return rc;
46815}
46816
46817/*
46818** Function assertTruncateConstraint(pPager) checks that one of the
46819** following is true for all dirty pages currently in the page-cache:
46820**
46821**   a) The page number is less than or equal to the size of the
46822**      current database image, in pages, OR
46823**
46824**   b) if the page content were written at this time, it would not
46825**      be necessary to write the current content out to the sub-journal
46826**      (as determined by function subjRequiresPage()).
46827**
46828** If the condition asserted by this function were not true, and the
46829** dirty page were to be discarded from the cache via the pagerStress()
46830** routine, pagerStress() would not write the current page content to
46831** the database file. If a savepoint transaction were rolled back after
46832** this happened, the correct behavior would be to restore the current
46833** content of the page. However, since this content is not present in either
46834** the database file or the portion of the rollback journal and
46835** sub-journal rolled back the content could not be restored and the
46836** database image would become corrupt. It is therefore fortunate that
46837** this circumstance cannot arise.
46838*/
46839#if defined(SQLITE_DEBUG)
46840static void assertTruncateConstraintCb(PgHdr *pPg){
46841  assert( pPg->flags&PGHDR_DIRTY );
46842  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
46843}
46844static void assertTruncateConstraint(Pager *pPager){
46845  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
46846}
46847#else
46848# define assertTruncateConstraint(pPager)
46849#endif
46850
46851/*
46852** Truncate the in-memory database file image to nPage pages. This
46853** function does not actually modify the database file on disk. It
46854** just sets the internal state of the pager object so that the
46855** truncation will be done when the current transaction is committed.
46856**
46857** This function is only called right before committing a transaction.
46858** Once this function has been called, the transaction must either be
46859** rolled back or committed. It is not safe to call this function and
46860** then continue writing to the database.
46861*/
46862SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
46863  assert( pPager->dbSize>=nPage );
46864  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
46865  pPager->dbSize = nPage;
46866
46867  /* At one point the code here called assertTruncateConstraint() to
46868  ** ensure that all pages being truncated away by this operation are,
46869  ** if one or more savepoints are open, present in the savepoint
46870  ** journal so that they can be restored if the savepoint is rolled
46871  ** back. This is no longer necessary as this function is now only
46872  ** called right before committing a transaction. So although the
46873  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
46874  ** they cannot be rolled back. So the assertTruncateConstraint() call
46875  ** is no longer correct. */
46876}
46877
46878
46879/*
46880** This function is called before attempting a hot-journal rollback. It
46881** syncs the journal file to disk, then sets pPager->journalHdr to the
46882** size of the journal file so that the pager_playback() routine knows
46883** that the entire journal file has been synced.
46884**
46885** Syncing a hot-journal to disk before attempting to roll it back ensures
46886** that if a power-failure occurs during the rollback, the process that
46887** attempts rollback following system recovery sees the same journal
46888** content as this process.
46889**
46890** If everything goes as planned, SQLITE_OK is returned. Otherwise,
46891** an SQLite error code.
46892*/
46893static int pagerSyncHotJournal(Pager *pPager){
46894  int rc = SQLITE_OK;
46895  if( !pPager->noSync ){
46896    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
46897  }
46898  if( rc==SQLITE_OK ){
46899    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
46900  }
46901  return rc;
46902}
46903
46904/*
46905** Obtain a reference to a memory mapped page object for page number pgno.
46906** The new object will use the pointer pData, obtained from xFetch().
46907** If successful, set *ppPage to point to the new page reference
46908** and return SQLITE_OK. Otherwise, return an SQLite error code and set
46909** *ppPage to zero.
46910**
46911** Page references obtained by calling this function should be released
46912** by calling pagerReleaseMapPage().
46913*/
46914static int pagerAcquireMapPage(
46915  Pager *pPager,                  /* Pager object */
46916  Pgno pgno,                      /* Page number */
46917  void *pData,                    /* xFetch()'d data for this page */
46918  PgHdr **ppPage                  /* OUT: Acquired page object */
46919){
46920  PgHdr *p;                       /* Memory mapped page to return */
46921
46922  if( pPager->pMmapFreelist ){
46923    *ppPage = p = pPager->pMmapFreelist;
46924    pPager->pMmapFreelist = p->pDirty;
46925    p->pDirty = 0;
46926    memset(p->pExtra, 0, pPager->nExtra);
46927  }else{
46928    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
46929    if( p==0 ){
46930      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
46931      return SQLITE_NOMEM;
46932    }
46933    p->pExtra = (void *)&p[1];
46934    p->flags = PGHDR_MMAP;
46935    p->nRef = 1;
46936    p->pPager = pPager;
46937  }
46938
46939  assert( p->pExtra==(void *)&p[1] );
46940  assert( p->pPage==0 );
46941  assert( p->flags==PGHDR_MMAP );
46942  assert( p->pPager==pPager );
46943  assert( p->nRef==1 );
46944
46945  p->pgno = pgno;
46946  p->pData = pData;
46947  pPager->nMmapOut++;
46948
46949  return SQLITE_OK;
46950}
46951
46952/*
46953** Release a reference to page pPg. pPg must have been returned by an
46954** earlier call to pagerAcquireMapPage().
46955*/
46956static void pagerReleaseMapPage(PgHdr *pPg){
46957  Pager *pPager = pPg->pPager;
46958  pPager->nMmapOut--;
46959  pPg->pDirty = pPager->pMmapFreelist;
46960  pPager->pMmapFreelist = pPg;
46961
46962  assert( pPager->fd->pMethods->iVersion>=3 );
46963  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
46964}
46965
46966/*
46967** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
46968*/
46969static void pagerFreeMapHdrs(Pager *pPager){
46970  PgHdr *p;
46971  PgHdr *pNext;
46972  for(p=pPager->pMmapFreelist; p; p=pNext){
46973    pNext = p->pDirty;
46974    sqlite3_free(p);
46975  }
46976}
46977
46978
46979/*
46980** Shutdown the page cache.  Free all memory and close all files.
46981**
46982** If a transaction was in progress when this routine is called, that
46983** transaction is rolled back.  All outstanding pages are invalidated
46984** and their memory is freed.  Any attempt to use a page associated
46985** with this page cache after this function returns will likely
46986** result in a coredump.
46987**
46988** This function always succeeds. If a transaction is active an attempt
46989** is made to roll it back. If an error occurs during the rollback
46990** a hot journal may be left in the filesystem but no error is returned
46991** to the caller.
46992*/
46993SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
46994  u8 *pTmp = (u8 *)pPager->pTmpSpace;
46995
46996  assert( assert_pager_state(pPager) );
46997  disable_simulated_io_errors();
46998  sqlite3BeginBenignMalloc();
46999  pagerFreeMapHdrs(pPager);
47000  /* pPager->errCode = 0; */
47001  pPager->exclusiveMode = 0;
47002#ifndef SQLITE_OMIT_WAL
47003  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
47004  pPager->pWal = 0;
47005#endif
47006  pager_reset(pPager);
47007  if( MEMDB ){
47008    pager_unlock(pPager);
47009  }else{
47010    /* If it is open, sync the journal file before calling UnlockAndRollback.
47011    ** If this is not done, then an unsynced portion of the open journal
47012    ** file may be played back into the database. If a power failure occurs
47013    ** while this is happening, the database could become corrupt.
47014    **
47015    ** If an error occurs while trying to sync the journal, shift the pager
47016    ** into the ERROR state. This causes UnlockAndRollback to unlock the
47017    ** database and close the journal file without attempting to roll it
47018    ** back or finalize it. The next database user will have to do hot-journal
47019    ** rollback before accessing the database file.
47020    */
47021    if( isOpen(pPager->jfd) ){
47022      pager_error(pPager, pagerSyncHotJournal(pPager));
47023    }
47024    pagerUnlockAndRollback(pPager);
47025  }
47026  sqlite3EndBenignMalloc();
47027  enable_simulated_io_errors();
47028  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
47029  IOTRACE(("CLOSE %p\n", pPager))
47030  sqlite3OsClose(pPager->jfd);
47031  sqlite3OsClose(pPager->fd);
47032  sqlite3PageFree(pTmp);
47033  sqlite3PcacheClose(pPager->pPCache);
47034
47035#ifdef SQLITE_HAS_CODEC
47036  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
47037#endif
47038
47039  assert( !pPager->aSavepoint && !pPager->pInJournal );
47040  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
47041
47042  sqlite3_free(pPager);
47043  return SQLITE_OK;
47044}
47045
47046#if !defined(NDEBUG) || defined(SQLITE_TEST)
47047/*
47048** Return the page number for page pPg.
47049*/
47050SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
47051  return pPg->pgno;
47052}
47053#endif
47054
47055/*
47056** Increment the reference count for page pPg.
47057*/
47058SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
47059  sqlite3PcacheRef(pPg);
47060}
47061
47062/*
47063** Sync the journal. In other words, make sure all the pages that have
47064** been written to the journal have actually reached the surface of the
47065** disk and can be restored in the event of a hot-journal rollback.
47066**
47067** If the Pager.noSync flag is set, then this function is a no-op.
47068** Otherwise, the actions required depend on the journal-mode and the
47069** device characteristics of the file-system, as follows:
47070**
47071**   * If the journal file is an in-memory journal file, no action need
47072**     be taken.
47073**
47074**   * Otherwise, if the device does not support the SAFE_APPEND property,
47075**     then the nRec field of the most recently written journal header
47076**     is updated to contain the number of journal records that have
47077**     been written following it. If the pager is operating in full-sync
47078**     mode, then the journal file is synced before this field is updated.
47079**
47080**   * If the device does not support the SEQUENTIAL property, then
47081**     journal file is synced.
47082**
47083** Or, in pseudo-code:
47084**
47085**   if( NOT <in-memory journal> ){
47086**     if( NOT SAFE_APPEND ){
47087**       if( <full-sync mode> ) xSync(<journal file>);
47088**       <update nRec field>
47089**     }
47090**     if( NOT SEQUENTIAL ) xSync(<journal file>);
47091**   }
47092**
47093** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
47094** page currently held in memory before returning SQLITE_OK. If an IO
47095** error is encountered, then the IO error code is returned to the caller.
47096*/
47097static int syncJournal(Pager *pPager, int newHdr){
47098  int rc;                         /* Return code */
47099
47100  assert( pPager->eState==PAGER_WRITER_CACHEMOD
47101       || pPager->eState==PAGER_WRITER_DBMOD
47102  );
47103  assert( assert_pager_state(pPager) );
47104  assert( !pagerUseWal(pPager) );
47105
47106  rc = sqlite3PagerExclusiveLock(pPager);
47107  if( rc!=SQLITE_OK ) return rc;
47108
47109  if( !pPager->noSync ){
47110    assert( !pPager->tempFile );
47111    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
47112      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
47113      assert( isOpen(pPager->jfd) );
47114
47115      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
47116        /* This block deals with an obscure problem. If the last connection
47117        ** that wrote to this database was operating in persistent-journal
47118        ** mode, then the journal file may at this point actually be larger
47119        ** than Pager.journalOff bytes. If the next thing in the journal
47120        ** file happens to be a journal-header (written as part of the
47121        ** previous connection's transaction), and a crash or power-failure
47122        ** occurs after nRec is updated but before this connection writes
47123        ** anything else to the journal file (or commits/rolls back its
47124        ** transaction), then SQLite may become confused when doing the
47125        ** hot-journal rollback following recovery. It may roll back all
47126        ** of this connections data, then proceed to rolling back the old,
47127        ** out-of-date data that follows it. Database corruption.
47128        **
47129        ** To work around this, if the journal file does appear to contain
47130        ** a valid header following Pager.journalOff, then write a 0x00
47131        ** byte to the start of it to prevent it from being recognized.
47132        **
47133        ** Variable iNextHdrOffset is set to the offset at which this
47134        ** problematic header will occur, if it exists. aMagic is used
47135        ** as a temporary buffer to inspect the first couple of bytes of
47136        ** the potential journal header.
47137        */
47138        i64 iNextHdrOffset;
47139        u8 aMagic[8];
47140        u8 zHeader[sizeof(aJournalMagic)+4];
47141
47142        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47143        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
47144
47145        iNextHdrOffset = journalHdrOffset(pPager);
47146        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
47147        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
47148          static const u8 zerobyte = 0;
47149          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
47150        }
47151        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
47152          return rc;
47153        }
47154
47155        /* Write the nRec value into the journal file header. If in
47156        ** full-synchronous mode, sync the journal first. This ensures that
47157        ** all data has really hit the disk before nRec is updated to mark
47158        ** it as a candidate for rollback.
47159        **
47160        ** This is not required if the persistent media supports the
47161        ** SAFE_APPEND property. Because in this case it is not possible
47162        ** for garbage data to be appended to the file, the nRec field
47163        ** is populated with 0xFFFFFFFF when the journal header is written
47164        ** and never needs to be updated.
47165        */
47166        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
47167          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
47168          IOTRACE(("JSYNC %p\n", pPager))
47169          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
47170          if( rc!=SQLITE_OK ) return rc;
47171        }
47172        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
47173        rc = sqlite3OsWrite(
47174            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
47175        );
47176        if( rc!=SQLITE_OK ) return rc;
47177      }
47178      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
47179        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
47180        IOTRACE(("JSYNC %p\n", pPager))
47181        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
47182          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
47183        );
47184        if( rc!=SQLITE_OK ) return rc;
47185      }
47186
47187      pPager->journalHdr = pPager->journalOff;
47188      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
47189        pPager->nRec = 0;
47190        rc = writeJournalHdr(pPager);
47191        if( rc!=SQLITE_OK ) return rc;
47192      }
47193    }else{
47194      pPager->journalHdr = pPager->journalOff;
47195    }
47196  }
47197
47198  /* Unless the pager is in noSync mode, the journal file was just
47199  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
47200  ** all pages.
47201  */
47202  sqlite3PcacheClearSyncFlags(pPager->pPCache);
47203  pPager->eState = PAGER_WRITER_DBMOD;
47204  assert( assert_pager_state(pPager) );
47205  return SQLITE_OK;
47206}
47207
47208/*
47209** The argument is the first in a linked list of dirty pages connected
47210** by the PgHdr.pDirty pointer. This function writes each one of the
47211** in-memory pages in the list to the database file. The argument may
47212** be NULL, representing an empty list. In this case this function is
47213** a no-op.
47214**
47215** The pager must hold at least a RESERVED lock when this function
47216** is called. Before writing anything to the database file, this lock
47217** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
47218** SQLITE_BUSY is returned and no data is written to the database file.
47219**
47220** If the pager is a temp-file pager and the actual file-system file
47221** is not yet open, it is created and opened before any data is
47222** written out.
47223**
47224** Once the lock has been upgraded and, if necessary, the file opened,
47225** the pages are written out to the database file in list order. Writing
47226** a page is skipped if it meets either of the following criteria:
47227**
47228**   * The page number is greater than Pager.dbSize, or
47229**   * The PGHDR_DONT_WRITE flag is set on the page.
47230**
47231** If writing out a page causes the database file to grow, Pager.dbFileSize
47232** is updated accordingly. If page 1 is written out, then the value cached
47233** in Pager.dbFileVers[] is updated to match the new value stored in
47234** the database file.
47235**
47236** If everything is successful, SQLITE_OK is returned. If an IO error
47237** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
47238** be obtained, SQLITE_BUSY is returned.
47239*/
47240static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
47241  int rc = SQLITE_OK;                  /* Return code */
47242
47243  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
47244  assert( !pagerUseWal(pPager) );
47245  assert( pPager->eState==PAGER_WRITER_DBMOD );
47246  assert( pPager->eLock==EXCLUSIVE_LOCK );
47247
47248  /* If the file is a temp-file has not yet been opened, open it now. It
47249  ** is not possible for rc to be other than SQLITE_OK if this branch
47250  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
47251  */
47252  if( !isOpen(pPager->fd) ){
47253    assert( pPager->tempFile && rc==SQLITE_OK );
47254    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
47255  }
47256
47257  /* Before the first write, give the VFS a hint of what the final
47258  ** file size will be.
47259  */
47260  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
47261  if( rc==SQLITE_OK
47262   && pPager->dbHintSize<pPager->dbSize
47263   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
47264  ){
47265    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
47266    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
47267    pPager->dbHintSize = pPager->dbSize;
47268  }
47269
47270  while( rc==SQLITE_OK && pList ){
47271    Pgno pgno = pList->pgno;
47272
47273    /* If there are dirty pages in the page cache with page numbers greater
47274    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
47275    ** make the file smaller (presumably by auto-vacuum code). Do not write
47276    ** any such pages to the file.
47277    **
47278    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
47279    ** set (set by sqlite3PagerDontWrite()).
47280    */
47281    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
47282      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
47283      char *pData;                                   /* Data to write */
47284
47285      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
47286      if( pList->pgno==1 ) pager_write_changecounter(pList);
47287
47288      /* Encode the database */
47289      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
47290
47291      /* Write out the page data. */
47292      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
47293
47294      /* If page 1 was just written, update Pager.dbFileVers to match
47295      ** the value now stored in the database file. If writing this
47296      ** page caused the database file to grow, update dbFileSize.
47297      */
47298      if( pgno==1 ){
47299        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
47300      }
47301      if( pgno>pPager->dbFileSize ){
47302        pPager->dbFileSize = pgno;
47303      }
47304      pPager->aStat[PAGER_STAT_WRITE]++;
47305
47306      /* Update any backup objects copying the contents of this pager. */
47307      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
47308
47309      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
47310                   PAGERID(pPager), pgno, pager_pagehash(pList)));
47311      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
47312      PAGER_INCR(sqlite3_pager_writedb_count);
47313    }else{
47314      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
47315    }
47316    pager_set_pagehash(pList);
47317    pList = pList->pDirty;
47318  }
47319
47320  return rc;
47321}
47322
47323/*
47324** Ensure that the sub-journal file is open. If it is already open, this
47325** function is a no-op.
47326**
47327** SQLITE_OK is returned if everything goes according to plan. An
47328** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
47329** fails.
47330*/
47331static int openSubJournal(Pager *pPager){
47332  int rc = SQLITE_OK;
47333  if( !isOpen(pPager->sjfd) ){
47334    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
47335      sqlite3MemJournalOpen(pPager->sjfd);
47336    }else{
47337      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
47338    }
47339  }
47340  return rc;
47341}
47342
47343/*
47344** Append a record of the current state of page pPg to the sub-journal.
47345**
47346** If successful, set the bit corresponding to pPg->pgno in the bitvecs
47347** for all open savepoints before returning.
47348**
47349** This function returns SQLITE_OK if everything is successful, an IO
47350** error code if the attempt to write to the sub-journal fails, or
47351** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
47352** bitvec.
47353*/
47354static int subjournalPage(PgHdr *pPg){
47355  int rc = SQLITE_OK;
47356  Pager *pPager = pPg->pPager;
47357  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
47358
47359    /* Open the sub-journal, if it has not already been opened */
47360    assert( pPager->useJournal );
47361    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
47362    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
47363    assert( pagerUseWal(pPager)
47364         || pageInJournal(pPager, pPg)
47365         || pPg->pgno>pPager->dbOrigSize
47366    );
47367    rc = openSubJournal(pPager);
47368
47369    /* If the sub-journal was opened successfully (or was already open),
47370    ** write the journal record into the file.  */
47371    if( rc==SQLITE_OK ){
47372      void *pData = pPg->pData;
47373      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
47374      char *pData2;
47375
47376      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
47377      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
47378      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
47379      if( rc==SQLITE_OK ){
47380        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
47381      }
47382    }
47383  }
47384  if( rc==SQLITE_OK ){
47385    pPager->nSubRec++;
47386    assert( pPager->nSavepoint>0 );
47387    rc = addToSavepointBitvecs(pPager, pPg->pgno);
47388  }
47389  return rc;
47390}
47391static int subjournalPageIfRequired(PgHdr *pPg){
47392  if( subjRequiresPage(pPg) ){
47393    return subjournalPage(pPg);
47394  }else{
47395    return SQLITE_OK;
47396  }
47397}
47398
47399/*
47400** This function is called by the pcache layer when it has reached some
47401** soft memory limit. The first argument is a pointer to a Pager object
47402** (cast as a void*). The pager is always 'purgeable' (not an in-memory
47403** database). The second argument is a reference to a page that is
47404** currently dirty but has no outstanding references. The page
47405** is always associated with the Pager object passed as the first
47406** argument.
47407**
47408** The job of this function is to make pPg clean by writing its contents
47409** out to the database file, if possible. This may involve syncing the
47410** journal file.
47411**
47412** If successful, sqlite3PcacheMakeClean() is called on the page and
47413** SQLITE_OK returned. If an IO error occurs while trying to make the
47414** page clean, the IO error code is returned. If the page cannot be
47415** made clean for some other reason, but no error occurs, then SQLITE_OK
47416** is returned by sqlite3PcacheMakeClean() is not called.
47417*/
47418static int pagerStress(void *p, PgHdr *pPg){
47419  Pager *pPager = (Pager *)p;
47420  int rc = SQLITE_OK;
47421
47422  assert( pPg->pPager==pPager );
47423  assert( pPg->flags&PGHDR_DIRTY );
47424
47425  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
47426  ** journal (and adding a new header) is not allowed.  This occurs
47427  ** during calls to sqlite3PagerWrite() while trying to journal multiple
47428  ** pages belonging to the same sector.
47429  **
47430  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
47431  ** regardless of whether or not a sync is required.  This is set during
47432  ** a rollback or by user request, respectively.
47433  **
47434  ** Spilling is also prohibited when in an error state since that could
47435  ** lead to database corruption.   In the current implementation it
47436  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
47437  ** while in the error state, hence it is impossible for this routine to
47438  ** be called in the error state.  Nevertheless, we include a NEVER()
47439  ** test for the error state as a safeguard against future changes.
47440  */
47441  if( NEVER(pPager->errCode) ) return SQLITE_OK;
47442  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
47443  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
47444  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
47445  if( pPager->doNotSpill
47446   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
47447      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
47448  ){
47449    return SQLITE_OK;
47450  }
47451
47452  pPg->pDirty = 0;
47453  if( pagerUseWal(pPager) ){
47454    /* Write a single frame for this page to the log. */
47455    rc = subjournalPageIfRequired(pPg);
47456    if( rc==SQLITE_OK ){
47457      rc = pagerWalFrames(pPager, pPg, 0, 0);
47458    }
47459  }else{
47460
47461    /* Sync the journal file if required. */
47462    if( pPg->flags&PGHDR_NEED_SYNC
47463     || pPager->eState==PAGER_WRITER_CACHEMOD
47464    ){
47465      rc = syncJournal(pPager, 1);
47466    }
47467
47468    /* Write the contents of the page out to the database file. */
47469    if( rc==SQLITE_OK ){
47470      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
47471      rc = pager_write_pagelist(pPager, pPg);
47472    }
47473  }
47474
47475  /* Mark the page as clean. */
47476  if( rc==SQLITE_OK ){
47477    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
47478    sqlite3PcacheMakeClean(pPg);
47479  }
47480
47481  return pager_error(pPager, rc);
47482}
47483
47484
47485/*
47486** Allocate and initialize a new Pager object and put a pointer to it
47487** in *ppPager. The pager should eventually be freed by passing it
47488** to sqlite3PagerClose().
47489**
47490** The zFilename argument is the path to the database file to open.
47491** If zFilename is NULL then a randomly-named temporary file is created
47492** and used as the file to be cached. Temporary files are be deleted
47493** automatically when they are closed. If zFilename is ":memory:" then
47494** all information is held in cache. It is never written to disk.
47495** This can be used to implement an in-memory database.
47496**
47497** The nExtra parameter specifies the number of bytes of space allocated
47498** along with each page reference. This space is available to the user
47499** via the sqlite3PagerGetExtra() API.
47500**
47501** The flags argument is used to specify properties that affect the
47502** operation of the pager. It should be passed some bitwise combination
47503** of the PAGER_* flags.
47504**
47505** The vfsFlags parameter is a bitmask to pass to the flags parameter
47506** of the xOpen() method of the supplied VFS when opening files.
47507**
47508** If the pager object is allocated and the specified file opened
47509** successfully, SQLITE_OK is returned and *ppPager set to point to
47510** the new pager object. If an error occurs, *ppPager is set to NULL
47511** and error code returned. This function may return SQLITE_NOMEM
47512** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
47513** various SQLITE_IO_XXX errors.
47514*/
47515SQLITE_PRIVATE int sqlite3PagerOpen(
47516  sqlite3_vfs *pVfs,       /* The virtual file system to use */
47517  Pager **ppPager,         /* OUT: Return the Pager structure here */
47518  const char *zFilename,   /* Name of the database file to open */
47519  int nExtra,              /* Extra bytes append to each in-memory page */
47520  int flags,               /* flags controlling this file */
47521  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
47522  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
47523){
47524  u8 *pPtr;
47525  Pager *pPager = 0;       /* Pager object to allocate and return */
47526  int rc = SQLITE_OK;      /* Return code */
47527  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
47528  int memDb = 0;           /* True if this is an in-memory file */
47529  int readOnly = 0;        /* True if this is a read-only file */
47530  int journalFileSize;     /* Bytes to allocate for each journal fd */
47531  char *zPathname = 0;     /* Full path to database file */
47532  int nPathname = 0;       /* Number of bytes in zPathname */
47533  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
47534  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
47535  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
47536  const char *zUri = 0;    /* URI args to copy */
47537  int nUri = 0;            /* Number of bytes of URI args at *zUri */
47538
47539  /* Figure out how much space is required for each journal file-handle
47540  ** (there are two of them, the main journal and the sub-journal). This
47541  ** is the maximum space required for an in-memory journal file handle
47542  ** and a regular journal file-handle. Note that a "regular journal-handle"
47543  ** may be a wrapper capable of caching the first portion of the journal
47544  ** file in memory to implement the atomic-write optimization (see
47545  ** source file journal.c).
47546  */
47547  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
47548    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
47549  }else{
47550    journalFileSize = ROUND8(sqlite3MemJournalSize());
47551  }
47552
47553  /* Set the output variable to NULL in case an error occurs. */
47554  *ppPager = 0;
47555
47556#ifndef SQLITE_OMIT_MEMORYDB
47557  if( flags & PAGER_MEMORY ){
47558    memDb = 1;
47559    if( zFilename && zFilename[0] ){
47560      zPathname = sqlite3DbStrDup(0, zFilename);
47561      if( zPathname==0  ) return SQLITE_NOMEM;
47562      nPathname = sqlite3Strlen30(zPathname);
47563      zFilename = 0;
47564    }
47565  }
47566#endif
47567
47568  /* Compute and store the full pathname in an allocated buffer pointed
47569  ** to by zPathname, length nPathname. Or, if this is a temporary file,
47570  ** leave both nPathname and zPathname set to 0.
47571  */
47572  if( zFilename && zFilename[0] ){
47573    const char *z;
47574    nPathname = pVfs->mxPathname+1;
47575    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
47576    if( zPathname==0 ){
47577      return SQLITE_NOMEM;
47578    }
47579    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
47580    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
47581    nPathname = sqlite3Strlen30(zPathname);
47582    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
47583    while( *z ){
47584      z += sqlite3Strlen30(z)+1;
47585      z += sqlite3Strlen30(z)+1;
47586    }
47587    nUri = (int)(&z[1] - zUri);
47588    assert( nUri>=0 );
47589    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
47590      /* This branch is taken when the journal path required by
47591      ** the database being opened will be more than pVfs->mxPathname
47592      ** bytes in length. This means the database cannot be opened,
47593      ** as it will not be possible to open the journal file or even
47594      ** check for a hot-journal before reading.
47595      */
47596      rc = SQLITE_CANTOPEN_BKPT;
47597    }
47598    if( rc!=SQLITE_OK ){
47599      sqlite3DbFree(0, zPathname);
47600      return rc;
47601    }
47602  }
47603
47604  /* Allocate memory for the Pager structure, PCache object, the
47605  ** three file descriptors, the database file name and the journal
47606  ** file name. The layout in memory is as follows:
47607  **
47608  **     Pager object                    (sizeof(Pager) bytes)
47609  **     PCache object                   (sqlite3PcacheSize() bytes)
47610  **     Database file handle            (pVfs->szOsFile bytes)
47611  **     Sub-journal file handle         (journalFileSize bytes)
47612  **     Main journal file handle        (journalFileSize bytes)
47613  **     Database file name              (nPathname+1 bytes)
47614  **     Journal file name               (nPathname+8+1 bytes)
47615  */
47616  pPtr = (u8 *)sqlite3MallocZero(
47617    ROUND8(sizeof(*pPager)) +      /* Pager structure */
47618    ROUND8(pcacheSize) +           /* PCache object */
47619    ROUND8(pVfs->szOsFile) +       /* The main db file */
47620    journalFileSize * 2 +          /* The two journal files */
47621    nPathname + 1 + nUri +         /* zFilename */
47622    nPathname + 8 + 2              /* zJournal */
47623#ifndef SQLITE_OMIT_WAL
47624    + nPathname + 4 + 2            /* zWal */
47625#endif
47626  );
47627  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
47628  if( !pPtr ){
47629    sqlite3DbFree(0, zPathname);
47630    return SQLITE_NOMEM;
47631  }
47632  pPager =              (Pager*)(pPtr);
47633  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
47634  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
47635  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
47636  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
47637  pPager->zFilename =    (char*)(pPtr += journalFileSize);
47638  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
47639
47640  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
47641  if( zPathname ){
47642    assert( nPathname>0 );
47643    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
47644    memcpy(pPager->zFilename, zPathname, nPathname);
47645    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
47646    memcpy(pPager->zJournal, zPathname, nPathname);
47647    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
47648    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
47649#ifndef SQLITE_OMIT_WAL
47650    pPager->zWal = &pPager->zJournal[nPathname+8+1];
47651    memcpy(pPager->zWal, zPathname, nPathname);
47652    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
47653    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
47654#endif
47655    sqlite3DbFree(0, zPathname);
47656  }
47657  pPager->pVfs = pVfs;
47658  pPager->vfsFlags = vfsFlags;
47659
47660  /* Open the pager file.
47661  */
47662  if( zFilename && zFilename[0] ){
47663    int fout = 0;                    /* VFS flags returned by xOpen() */
47664    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
47665    assert( !memDb );
47666    readOnly = (fout&SQLITE_OPEN_READONLY);
47667
47668    /* If the file was successfully opened for read/write access,
47669    ** choose a default page size in case we have to create the
47670    ** database file. The default page size is the maximum of:
47671    **
47672    **    + SQLITE_DEFAULT_PAGE_SIZE,
47673    **    + The value returned by sqlite3OsSectorSize()
47674    **    + The largest page size that can be written atomically.
47675    */
47676    if( rc==SQLITE_OK ){
47677      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
47678      if( !readOnly ){
47679        setSectorSize(pPager);
47680        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
47681        if( szPageDflt<pPager->sectorSize ){
47682          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
47683            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
47684          }else{
47685            szPageDflt = (u32)pPager->sectorSize;
47686          }
47687        }
47688#ifdef SQLITE_ENABLE_ATOMIC_WRITE
47689        {
47690          int ii;
47691          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47692          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47693          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
47694          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
47695            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
47696              szPageDflt = ii;
47697            }
47698          }
47699        }
47700#endif
47701      }
47702      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
47703      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
47704       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
47705          vfsFlags |= SQLITE_OPEN_READONLY;
47706          goto act_like_temp_file;
47707      }
47708    }
47709  }else{
47710    /* If a temporary file is requested, it is not opened immediately.
47711    ** In this case we accept the default page size and delay actually
47712    ** opening the file until the first call to OsWrite().
47713    **
47714    ** This branch is also run for an in-memory database. An in-memory
47715    ** database is the same as a temp-file that is never written out to
47716    ** disk and uses an in-memory rollback journal.
47717    **
47718    ** This branch also runs for files marked as immutable.
47719    */
47720act_like_temp_file:
47721    tempFile = 1;
47722    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
47723    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
47724    pPager->noLock = 1;                /* Do no locking */
47725    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
47726  }
47727
47728  /* The following call to PagerSetPagesize() serves to set the value of
47729  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
47730  */
47731  if( rc==SQLITE_OK ){
47732    assert( pPager->memDb==0 );
47733    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
47734    testcase( rc!=SQLITE_OK );
47735  }
47736
47737  /* Initialize the PCache object. */
47738  if( rc==SQLITE_OK ){
47739    assert( nExtra<1000 );
47740    nExtra = ROUND8(nExtra);
47741    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
47742                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
47743  }
47744
47745  /* If an error occurred above, free the  Pager structure and close the file.
47746  */
47747  if( rc!=SQLITE_OK ){
47748    sqlite3OsClose(pPager->fd);
47749    sqlite3PageFree(pPager->pTmpSpace);
47750    sqlite3_free(pPager);
47751    return rc;
47752  }
47753
47754  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
47755  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
47756
47757  pPager->useJournal = (u8)useJournal;
47758  /* pPager->stmtOpen = 0; */
47759  /* pPager->stmtInUse = 0; */
47760  /* pPager->nRef = 0; */
47761  /* pPager->stmtSize = 0; */
47762  /* pPager->stmtJSize = 0; */
47763  /* pPager->nPage = 0; */
47764  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
47765  /* pPager->state = PAGER_UNLOCK; */
47766  /* pPager->errMask = 0; */
47767  pPager->tempFile = (u8)tempFile;
47768  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
47769          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
47770  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
47771  pPager->exclusiveMode = (u8)tempFile;
47772  pPager->changeCountDone = pPager->tempFile;
47773  pPager->memDb = (u8)memDb;
47774  pPager->readOnly = (u8)readOnly;
47775  assert( useJournal || pPager->tempFile );
47776  pPager->noSync = pPager->tempFile;
47777  if( pPager->noSync ){
47778    assert( pPager->fullSync==0 );
47779    assert( pPager->syncFlags==0 );
47780    assert( pPager->walSyncFlags==0 );
47781    assert( pPager->ckptSyncFlags==0 );
47782  }else{
47783    pPager->fullSync = 1;
47784    pPager->syncFlags = SQLITE_SYNC_NORMAL;
47785    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
47786    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
47787  }
47788  /* pPager->pFirst = 0; */
47789  /* pPager->pFirstSynced = 0; */
47790  /* pPager->pLast = 0; */
47791  pPager->nExtra = (u16)nExtra;
47792  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
47793  assert( isOpen(pPager->fd) || tempFile );
47794  setSectorSize(pPager);
47795  if( !useJournal ){
47796    pPager->journalMode = PAGER_JOURNALMODE_OFF;
47797  }else if( memDb ){
47798    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
47799  }
47800  /* pPager->xBusyHandler = 0; */
47801  /* pPager->pBusyHandlerArg = 0; */
47802  pPager->xReiniter = xReinit;
47803  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
47804  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
47805
47806  *ppPager = pPager;
47807  return SQLITE_OK;
47808}
47809
47810
47811/* Verify that the database file has not be deleted or renamed out from
47812** under the pager.  Return SQLITE_OK if the database is still were it ought
47813** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
47814** code from sqlite3OsAccess()) if the database has gone missing.
47815*/
47816static int databaseIsUnmoved(Pager *pPager){
47817  int bHasMoved = 0;
47818  int rc;
47819
47820  if( pPager->tempFile ) return SQLITE_OK;
47821  if( pPager->dbSize==0 ) return SQLITE_OK;
47822  assert( pPager->zFilename && pPager->zFilename[0] );
47823  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
47824  if( rc==SQLITE_NOTFOUND ){
47825    /* If the HAS_MOVED file-control is unimplemented, assume that the file
47826    ** has not been moved.  That is the historical behavior of SQLite: prior to
47827    ** version 3.8.3, it never checked */
47828    rc = SQLITE_OK;
47829  }else if( rc==SQLITE_OK && bHasMoved ){
47830    rc = SQLITE_READONLY_DBMOVED;
47831  }
47832  return rc;
47833}
47834
47835
47836/*
47837** This function is called after transitioning from PAGER_UNLOCK to
47838** PAGER_SHARED state. It tests if there is a hot journal present in
47839** the file-system for the given pager. A hot journal is one that
47840** needs to be played back. According to this function, a hot-journal
47841** file exists if the following criteria are met:
47842**
47843**   * The journal file exists in the file system, and
47844**   * No process holds a RESERVED or greater lock on the database file, and
47845**   * The database file itself is greater than 0 bytes in size, and
47846**   * The first byte of the journal file exists and is not 0x00.
47847**
47848** If the current size of the database file is 0 but a journal file
47849** exists, that is probably an old journal left over from a prior
47850** database with the same name. In this case the journal file is
47851** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
47852** is returned.
47853**
47854** This routine does not check if there is a master journal filename
47855** at the end of the file. If there is, and that master journal file
47856** does not exist, then the journal file is not really hot. In this
47857** case this routine will return a false-positive. The pager_playback()
47858** routine will discover that the journal file is not really hot and
47859** will not roll it back.
47860**
47861** If a hot-journal file is found to exist, *pExists is set to 1 and
47862** SQLITE_OK returned. If no hot-journal file is present, *pExists is
47863** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
47864** to determine whether or not a hot-journal file exists, the IO error
47865** code is returned and the value of *pExists is undefined.
47866*/
47867static int hasHotJournal(Pager *pPager, int *pExists){
47868  sqlite3_vfs * const pVfs = pPager->pVfs;
47869  int rc = SQLITE_OK;           /* Return code */
47870  int exists = 1;               /* True if a journal file is present */
47871  int jrnlOpen = !!isOpen(pPager->jfd);
47872
47873  assert( pPager->useJournal );
47874  assert( isOpen(pPager->fd) );
47875  assert( pPager->eState==PAGER_OPEN );
47876
47877  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
47878    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
47879  ));
47880
47881  *pExists = 0;
47882  if( !jrnlOpen ){
47883    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
47884  }
47885  if( rc==SQLITE_OK && exists ){
47886    int locked = 0;             /* True if some process holds a RESERVED lock */
47887
47888    /* Race condition here:  Another process might have been holding the
47889    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
47890    ** call above, but then delete the journal and drop the lock before
47891    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
47892    ** is the case, this routine might think there is a hot journal when
47893    ** in fact there is none.  This results in a false-positive which will
47894    ** be dealt with by the playback routine.  Ticket #3883.
47895    */
47896    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
47897    if( rc==SQLITE_OK && !locked ){
47898      Pgno nPage;                 /* Number of pages in database file */
47899
47900      rc = pagerPagecount(pPager, &nPage);
47901      if( rc==SQLITE_OK ){
47902        /* If the database is zero pages in size, that means that either (1) the
47903        ** journal is a remnant from a prior database with the same name where
47904        ** the database file but not the journal was deleted, or (2) the initial
47905        ** transaction that populates a new database is being rolled back.
47906        ** In either case, the journal file can be deleted.  However, take care
47907        ** not to delete the journal file if it is already open due to
47908        ** journal_mode=PERSIST.
47909        */
47910        if( nPage==0 && !jrnlOpen ){
47911          sqlite3BeginBenignMalloc();
47912          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
47913            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
47914            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
47915          }
47916          sqlite3EndBenignMalloc();
47917        }else{
47918          /* The journal file exists and no other connection has a reserved
47919          ** or greater lock on the database file. Now check that there is
47920          ** at least one non-zero bytes at the start of the journal file.
47921          ** If there is, then we consider this journal to be hot. If not,
47922          ** it can be ignored.
47923          */
47924          if( !jrnlOpen ){
47925            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
47926            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
47927          }
47928          if( rc==SQLITE_OK ){
47929            u8 first = 0;
47930            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
47931            if( rc==SQLITE_IOERR_SHORT_READ ){
47932              rc = SQLITE_OK;
47933            }
47934            if( !jrnlOpen ){
47935              sqlite3OsClose(pPager->jfd);
47936            }
47937            *pExists = (first!=0);
47938          }else if( rc==SQLITE_CANTOPEN ){
47939            /* If we cannot open the rollback journal file in order to see if
47940            ** it has a zero header, that might be due to an I/O error, or
47941            ** it might be due to the race condition described above and in
47942            ** ticket #3883.  Either way, assume that the journal is hot.
47943            ** This might be a false positive.  But if it is, then the
47944            ** automatic journal playback and recovery mechanism will deal
47945            ** with it under an EXCLUSIVE lock where we do not need to
47946            ** worry so much with race conditions.
47947            */
47948            *pExists = 1;
47949            rc = SQLITE_OK;
47950          }
47951        }
47952      }
47953    }
47954  }
47955
47956  return rc;
47957}
47958
47959/*
47960** This function is called to obtain a shared lock on the database file.
47961** It is illegal to call sqlite3PagerAcquire() until after this function
47962** has been successfully called. If a shared-lock is already held when
47963** this function is called, it is a no-op.
47964**
47965** The following operations are also performed by this function.
47966**
47967**   1) If the pager is currently in PAGER_OPEN state (no lock held
47968**      on the database file), then an attempt is made to obtain a
47969**      SHARED lock on the database file. Immediately after obtaining
47970**      the SHARED lock, the file-system is checked for a hot-journal,
47971**      which is played back if present. Following any hot-journal
47972**      rollback, the contents of the cache are validated by checking
47973**      the 'change-counter' field of the database file header and
47974**      discarded if they are found to be invalid.
47975**
47976**   2) If the pager is running in exclusive-mode, and there are currently
47977**      no outstanding references to any pages, and is in the error state,
47978**      then an attempt is made to clear the error state by discarding
47979**      the contents of the page cache and rolling back any open journal
47980**      file.
47981**
47982** If everything is successful, SQLITE_OK is returned. If an IO error
47983** occurs while locking the database, checking for a hot-journal file or
47984** rolling back a journal file, the IO error code is returned.
47985*/
47986SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
47987  int rc = SQLITE_OK;                /* Return code */
47988
47989  /* This routine is only called from b-tree and only when there are no
47990  ** outstanding pages. This implies that the pager state should either
47991  ** be OPEN or READER. READER is only possible if the pager is or was in
47992  ** exclusive access mode.
47993  */
47994  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
47995  assert( assert_pager_state(pPager) );
47996  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
47997  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
47998
47999  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
48000    int bHotJournal = 1;          /* True if there exists a hot journal-file */
48001
48002    assert( !MEMDB );
48003
48004    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
48005    if( rc!=SQLITE_OK ){
48006      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
48007      goto failed;
48008    }
48009
48010    /* If a journal file exists, and there is no RESERVED lock on the
48011    ** database file, then it either needs to be played back or deleted.
48012    */
48013    if( pPager->eLock<=SHARED_LOCK ){
48014      rc = hasHotJournal(pPager, &bHotJournal);
48015    }
48016    if( rc!=SQLITE_OK ){
48017      goto failed;
48018    }
48019    if( bHotJournal ){
48020      if( pPager->readOnly ){
48021        rc = SQLITE_READONLY_ROLLBACK;
48022        goto failed;
48023      }
48024
48025      /* Get an EXCLUSIVE lock on the database file. At this point it is
48026      ** important that a RESERVED lock is not obtained on the way to the
48027      ** EXCLUSIVE lock. If it were, another process might open the
48028      ** database file, detect the RESERVED lock, and conclude that the
48029      ** database is safe to read while this process is still rolling the
48030      ** hot-journal back.
48031      **
48032      ** Because the intermediate RESERVED lock is not requested, any
48033      ** other process attempting to access the database file will get to
48034      ** this point in the code and fail to obtain its own EXCLUSIVE lock
48035      ** on the database file.
48036      **
48037      ** Unless the pager is in locking_mode=exclusive mode, the lock is
48038      ** downgraded to SHARED_LOCK before this function returns.
48039      */
48040      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48041      if( rc!=SQLITE_OK ){
48042        goto failed;
48043      }
48044
48045      /* If it is not already open and the file exists on disk, open the
48046      ** journal for read/write access. Write access is required because
48047      ** in exclusive-access mode the file descriptor will be kept open
48048      ** and possibly used for a transaction later on. Also, write-access
48049      ** is usually required to finalize the journal in journal_mode=persist
48050      ** mode (and also for journal_mode=truncate on some systems).
48051      **
48052      ** If the journal does not exist, it usually means that some
48053      ** other connection managed to get in and roll it back before
48054      ** this connection obtained the exclusive lock above. Or, it
48055      ** may mean that the pager was in the error-state when this
48056      ** function was called and the journal file does not exist.
48057      */
48058      if( !isOpen(pPager->jfd) ){
48059        sqlite3_vfs * const pVfs = pPager->pVfs;
48060        int bExists;              /* True if journal file exists */
48061        rc = sqlite3OsAccess(
48062            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
48063        if( rc==SQLITE_OK && bExists ){
48064          int fout = 0;
48065          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
48066          assert( !pPager->tempFile );
48067          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
48068          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
48069          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
48070            rc = SQLITE_CANTOPEN_BKPT;
48071            sqlite3OsClose(pPager->jfd);
48072          }
48073        }
48074      }
48075
48076      /* Playback and delete the journal.  Drop the database write
48077      ** lock and reacquire the read lock. Purge the cache before
48078      ** playing back the hot-journal so that we don't end up with
48079      ** an inconsistent cache.  Sync the hot journal before playing
48080      ** it back since the process that crashed and left the hot journal
48081      ** probably did not sync it and we are required to always sync
48082      ** the journal before playing it back.
48083      */
48084      if( isOpen(pPager->jfd) ){
48085        assert( rc==SQLITE_OK );
48086        rc = pagerSyncHotJournal(pPager);
48087        if( rc==SQLITE_OK ){
48088          rc = pager_playback(pPager, 1);
48089          pPager->eState = PAGER_OPEN;
48090        }
48091      }else if( !pPager->exclusiveMode ){
48092        pagerUnlockDb(pPager, SHARED_LOCK);
48093      }
48094
48095      if( rc!=SQLITE_OK ){
48096        /* This branch is taken if an error occurs while trying to open
48097        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
48098        ** pager_unlock() routine will be called before returning to unlock
48099        ** the file. If the unlock attempt fails, then Pager.eLock must be
48100        ** set to UNKNOWN_LOCK (see the comment above the #define for
48101        ** UNKNOWN_LOCK above for an explanation).
48102        **
48103        ** In order to get pager_unlock() to do this, set Pager.eState to
48104        ** PAGER_ERROR now. This is not actually counted as a transition
48105        ** to ERROR state in the state diagram at the top of this file,
48106        ** since we know that the same call to pager_unlock() will very
48107        ** shortly transition the pager object to the OPEN state. Calling
48108        ** assert_pager_state() would fail now, as it should not be possible
48109        ** to be in ERROR state when there are zero outstanding page
48110        ** references.
48111        */
48112        pager_error(pPager, rc);
48113        goto failed;
48114      }
48115
48116      assert( pPager->eState==PAGER_OPEN );
48117      assert( (pPager->eLock==SHARED_LOCK)
48118           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
48119      );
48120    }
48121
48122    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
48123      /* The shared-lock has just been acquired then check to
48124      ** see if the database has been modified.  If the database has changed,
48125      ** flush the cache.  The hasHeldSharedLock flag prevents this from
48126      ** occurring on the very first access to a file, in order to save a
48127      ** single unnecessary sqlite3OsRead() call at the start-up.
48128      **
48129      ** Database changes are detected by looking at 15 bytes beginning
48130      ** at offset 24 into the file.  The first 4 of these 16 bytes are
48131      ** a 32-bit counter that is incremented with each change.  The
48132      ** other bytes change randomly with each file change when
48133      ** a codec is in use.
48134      **
48135      ** There is a vanishingly small chance that a change will not be
48136      ** detected.  The chance of an undetected change is so small that
48137      ** it can be neglected.
48138      */
48139      Pgno nPage = 0;
48140      char dbFileVers[sizeof(pPager->dbFileVers)];
48141
48142      rc = pagerPagecount(pPager, &nPage);
48143      if( rc ) goto failed;
48144
48145      if( nPage>0 ){
48146        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
48147        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
48148        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
48149          goto failed;
48150        }
48151      }else{
48152        memset(dbFileVers, 0, sizeof(dbFileVers));
48153      }
48154
48155      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
48156        pager_reset(pPager);
48157
48158        /* Unmap the database file. It is possible that external processes
48159        ** may have truncated the database file and then extended it back
48160        ** to its original size while this process was not holding a lock.
48161        ** In this case there may exist a Pager.pMap mapping that appears
48162        ** to be the right size but is not actually valid. Avoid this
48163        ** possibility by unmapping the db here. */
48164        if( USEFETCH(pPager) ){
48165          sqlite3OsUnfetch(pPager->fd, 0, 0);
48166        }
48167      }
48168    }
48169
48170    /* If there is a WAL file in the file-system, open this database in WAL
48171    ** mode. Otherwise, the following function call is a no-op.
48172    */
48173    rc = pagerOpenWalIfPresent(pPager);
48174#ifndef SQLITE_OMIT_WAL
48175    assert( pPager->pWal==0 || rc==SQLITE_OK );
48176#endif
48177  }
48178
48179  if( pagerUseWal(pPager) ){
48180    assert( rc==SQLITE_OK );
48181    rc = pagerBeginReadTransaction(pPager);
48182  }
48183
48184  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
48185    rc = pagerPagecount(pPager, &pPager->dbSize);
48186  }
48187
48188 failed:
48189  if( rc!=SQLITE_OK ){
48190    assert( !MEMDB );
48191    pager_unlock(pPager);
48192    assert( pPager->eState==PAGER_OPEN );
48193  }else{
48194    pPager->eState = PAGER_READER;
48195    pPager->hasHeldSharedLock = 1;
48196  }
48197  return rc;
48198}
48199
48200/*
48201** If the reference count has reached zero, rollback any active
48202** transaction and unlock the pager.
48203**
48204** Except, in locking_mode=EXCLUSIVE when there is nothing to in
48205** the rollback journal, the unlock is not performed and there is
48206** nothing to rollback, so this routine is a no-op.
48207*/
48208static void pagerUnlockIfUnused(Pager *pPager){
48209  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
48210    pagerUnlockAndRollback(pPager);
48211  }
48212}
48213
48214/*
48215** Acquire a reference to page number pgno in pager pPager (a page
48216** reference has type DbPage*). If the requested reference is
48217** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
48218**
48219** If the requested page is already in the cache, it is returned.
48220** Otherwise, a new page object is allocated and populated with data
48221** read from the database file. In some cases, the pcache module may
48222** choose not to allocate a new page object and may reuse an existing
48223** object with no outstanding references.
48224**
48225** The extra data appended to a page is always initialized to zeros the
48226** first time a page is loaded into memory. If the page requested is
48227** already in the cache when this function is called, then the extra
48228** data is left as it was when the page object was last used.
48229**
48230** If the database image is smaller than the requested page or if a
48231** non-zero value is passed as the noContent parameter and the
48232** requested page is not already stored in the cache, then no
48233** actual disk read occurs. In this case the memory image of the
48234** page is initialized to all zeros.
48235**
48236** If noContent is true, it means that we do not care about the contents
48237** of the page. This occurs in two scenarios:
48238**
48239**   a) When reading a free-list leaf page from the database, and
48240**
48241**   b) When a savepoint is being rolled back and we need to load
48242**      a new page into the cache to be filled with the data read
48243**      from the savepoint journal.
48244**
48245** If noContent is true, then the data returned is zeroed instead of
48246** being read from the database. Additionally, the bits corresponding
48247** to pgno in Pager.pInJournal (bitvec of pages already written to the
48248** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
48249** savepoints are set. This means if the page is made writable at any
48250** point in the future, using a call to sqlite3PagerWrite(), its contents
48251** will not be journaled. This saves IO.
48252**
48253** The acquisition might fail for several reasons.  In all cases,
48254** an appropriate error code is returned and *ppPage is set to NULL.
48255**
48256** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
48257** to find a page in the in-memory cache first.  If the page is not already
48258** in memory, this routine goes to disk to read it in whereas Lookup()
48259** just returns 0.  This routine acquires a read-lock the first time it
48260** has to go to disk, and could also playback an old journal if necessary.
48261** Since Lookup() never goes to disk, it never has to deal with locks
48262** or journal files.
48263*/
48264SQLITE_PRIVATE int sqlite3PagerAcquire(
48265  Pager *pPager,      /* The pager open on the database file */
48266  Pgno pgno,          /* Page number to fetch */
48267  DbPage **ppPage,    /* Write a pointer to the page here */
48268  int flags           /* PAGER_GET_XXX flags */
48269){
48270  int rc = SQLITE_OK;
48271  PgHdr *pPg = 0;
48272  u32 iFrame = 0;                 /* Frame to read from WAL file */
48273  const int noContent = (flags & PAGER_GET_NOCONTENT);
48274
48275  /* It is acceptable to use a read-only (mmap) page for any page except
48276  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
48277  ** flag was specified by the caller. And so long as the db is not a
48278  ** temporary or in-memory database.  */
48279  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
48280   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
48281#ifdef SQLITE_HAS_CODEC
48282   && pPager->xCodec==0
48283#endif
48284  );
48285
48286  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
48287  ** allows the compiler optimizer to reuse the results of the "pgno>1"
48288  ** test in the previous statement, and avoid testing pgno==0 in the
48289  ** common case where pgno is large. */
48290  if( pgno<=1 && pgno==0 ){
48291    return SQLITE_CORRUPT_BKPT;
48292  }
48293  assert( pPager->eState>=PAGER_READER );
48294  assert( assert_pager_state(pPager) );
48295  assert( noContent==0 || bMmapOk==0 );
48296
48297  assert( pPager->hasHeldSharedLock==1 );
48298
48299  /* If the pager is in the error state, return an error immediately.
48300  ** Otherwise, request the page from the PCache layer. */
48301  if( pPager->errCode!=SQLITE_OK ){
48302    rc = pPager->errCode;
48303  }else{
48304    if( bMmapOk && pagerUseWal(pPager) ){
48305      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
48306      if( rc!=SQLITE_OK ) goto pager_acquire_err;
48307    }
48308
48309    if( bMmapOk && iFrame==0 ){
48310      void *pData = 0;
48311
48312      rc = sqlite3OsFetch(pPager->fd,
48313          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
48314      );
48315
48316      if( rc==SQLITE_OK && pData ){
48317        if( pPager->eState>PAGER_READER ){
48318          pPg = sqlite3PagerLookup(pPager, pgno);
48319        }
48320        if( pPg==0 ){
48321          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
48322        }else{
48323          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
48324        }
48325        if( pPg ){
48326          assert( rc==SQLITE_OK );
48327          *ppPage = pPg;
48328          return SQLITE_OK;
48329        }
48330      }
48331      if( rc!=SQLITE_OK ){
48332        goto pager_acquire_err;
48333      }
48334    }
48335
48336    {
48337      sqlite3_pcache_page *pBase;
48338      pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
48339      if( pBase==0 ){
48340        rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
48341        if( rc!=SQLITE_OK ) goto pager_acquire_err;
48342        if( pBase==0 ){
48343          pPg = *ppPage = 0;
48344          rc = SQLITE_NOMEM;
48345          goto pager_acquire_err;
48346        }
48347      }
48348      pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
48349      assert( pPg!=0 );
48350    }
48351  }
48352
48353  if( rc!=SQLITE_OK ){
48354    /* Either the call to sqlite3PcacheFetch() returned an error or the
48355    ** pager was already in the error-state when this function was called.
48356    ** Set pPg to 0 and jump to the exception handler.  */
48357    pPg = 0;
48358    goto pager_acquire_err;
48359  }
48360  assert( pPg==(*ppPage) );
48361  assert( pPg->pgno==pgno );
48362  assert( pPg->pPager==pPager || pPg->pPager==0 );
48363
48364  if( pPg->pPager && !noContent ){
48365    /* In this case the pcache already contains an initialized copy of
48366    ** the page. Return without further ado.  */
48367    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
48368    pPager->aStat[PAGER_STAT_HIT]++;
48369    return SQLITE_OK;
48370
48371  }else{
48372    /* The pager cache has created a new page. Its content needs to
48373    ** be initialized.  */
48374
48375    pPg->pPager = pPager;
48376
48377    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
48378    ** number greater than this, or the unused locking-page, is requested. */
48379    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
48380      rc = SQLITE_CORRUPT_BKPT;
48381      goto pager_acquire_err;
48382    }
48383
48384    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
48385      if( pgno>pPager->mxPgno ){
48386        rc = SQLITE_FULL;
48387        goto pager_acquire_err;
48388      }
48389      if( noContent ){
48390        /* Failure to set the bits in the InJournal bit-vectors is benign.
48391        ** It merely means that we might do some extra work to journal a
48392        ** page that does not need to be journaled.  Nevertheless, be sure
48393        ** to test the case where a malloc error occurs while trying to set
48394        ** a bit in a bit vector.
48395        */
48396        sqlite3BeginBenignMalloc();
48397        if( pgno<=pPager->dbOrigSize ){
48398          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
48399          testcase( rc==SQLITE_NOMEM );
48400        }
48401        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
48402        testcase( rc==SQLITE_NOMEM );
48403        sqlite3EndBenignMalloc();
48404      }
48405      memset(pPg->pData, 0, pPager->pageSize);
48406      IOTRACE(("ZERO %p %d\n", pPager, pgno));
48407    }else{
48408      if( pagerUseWal(pPager) && bMmapOk==0 ){
48409        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
48410        if( rc!=SQLITE_OK ) goto pager_acquire_err;
48411      }
48412      assert( pPg->pPager==pPager );
48413      pPager->aStat[PAGER_STAT_MISS]++;
48414      rc = readDbPage(pPg, iFrame);
48415      if( rc!=SQLITE_OK ){
48416        goto pager_acquire_err;
48417      }
48418    }
48419    pager_set_pagehash(pPg);
48420  }
48421
48422  return SQLITE_OK;
48423
48424pager_acquire_err:
48425  assert( rc!=SQLITE_OK );
48426  if( pPg ){
48427    sqlite3PcacheDrop(pPg);
48428  }
48429  pagerUnlockIfUnused(pPager);
48430
48431  *ppPage = 0;
48432  return rc;
48433}
48434
48435/*
48436** Acquire a page if it is already in the in-memory cache.  Do
48437** not read the page from disk.  Return a pointer to the page,
48438** or 0 if the page is not in cache.
48439**
48440** See also sqlite3PagerGet().  The difference between this routine
48441** and sqlite3PagerGet() is that _get() will go to the disk and read
48442** in the page if the page is not already in cache.  This routine
48443** returns NULL if the page is not in cache or if a disk I/O error
48444** has ever happened.
48445*/
48446SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
48447  sqlite3_pcache_page *pPage;
48448  assert( pPager!=0 );
48449  assert( pgno!=0 );
48450  assert( pPager->pPCache!=0 );
48451  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
48452  assert( pPage==0 || pPager->hasHeldSharedLock );
48453  if( pPage==0 ) return 0;
48454  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
48455}
48456
48457/*
48458** Release a page reference.
48459**
48460** If the number of references to the page drop to zero, then the
48461** page is added to the LRU list.  When all references to all pages
48462** are released, a rollback occurs and the lock on the database is
48463** removed.
48464*/
48465SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
48466  Pager *pPager;
48467  assert( pPg!=0 );
48468  pPager = pPg->pPager;
48469  if( pPg->flags & PGHDR_MMAP ){
48470    pagerReleaseMapPage(pPg);
48471  }else{
48472    sqlite3PcacheRelease(pPg);
48473  }
48474  pagerUnlockIfUnused(pPager);
48475}
48476SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
48477  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
48478}
48479
48480/*
48481** This function is called at the start of every write transaction.
48482** There must already be a RESERVED or EXCLUSIVE lock on the database
48483** file when this routine is called.
48484**
48485** Open the journal file for pager pPager and write a journal header
48486** to the start of it. If there are active savepoints, open the sub-journal
48487** as well. This function is only used when the journal file is being
48488** opened to write a rollback log for a transaction. It is not used
48489** when opening a hot journal file to roll it back.
48490**
48491** If the journal file is already open (as it may be in exclusive mode),
48492** then this function just writes a journal header to the start of the
48493** already open file.
48494**
48495** Whether or not the journal file is opened by this function, the
48496** Pager.pInJournal bitvec structure is allocated.
48497**
48498** Return SQLITE_OK if everything is successful. Otherwise, return
48499** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
48500** an IO error code if opening or writing the journal file fails.
48501*/
48502static int pager_open_journal(Pager *pPager){
48503  int rc = SQLITE_OK;                        /* Return code */
48504  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
48505
48506  assert( pPager->eState==PAGER_WRITER_LOCKED );
48507  assert( assert_pager_state(pPager) );
48508  assert( pPager->pInJournal==0 );
48509
48510  /* If already in the error state, this function is a no-op.  But on
48511  ** the other hand, this routine is never called if we are already in
48512  ** an error state. */
48513  if( NEVER(pPager->errCode) ) return pPager->errCode;
48514
48515  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
48516    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
48517    if( pPager->pInJournal==0 ){
48518      return SQLITE_NOMEM;
48519    }
48520
48521    /* Open the journal file if it is not already open. */
48522    if( !isOpen(pPager->jfd) ){
48523      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
48524        sqlite3MemJournalOpen(pPager->jfd);
48525      }else{
48526        const int flags =                   /* VFS flags to open journal file */
48527          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
48528          (pPager->tempFile ?
48529            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
48530            (SQLITE_OPEN_MAIN_JOURNAL)
48531          );
48532
48533        /* Verify that the database still has the same name as it did when
48534        ** it was originally opened. */
48535        rc = databaseIsUnmoved(pPager);
48536        if( rc==SQLITE_OK ){
48537#ifdef SQLITE_ENABLE_ATOMIC_WRITE
48538          rc = sqlite3JournalOpen(
48539              pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
48540          );
48541#else
48542          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
48543#endif
48544        }
48545      }
48546      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
48547    }
48548
48549
48550    /* Write the first journal header to the journal file and open
48551    ** the sub-journal if necessary.
48552    */
48553    if( rc==SQLITE_OK ){
48554      /* TODO: Check if all of these are really required. */
48555      pPager->nRec = 0;
48556      pPager->journalOff = 0;
48557      pPager->setMaster = 0;
48558      pPager->journalHdr = 0;
48559      rc = writeJournalHdr(pPager);
48560    }
48561  }
48562
48563  if( rc!=SQLITE_OK ){
48564    sqlite3BitvecDestroy(pPager->pInJournal);
48565    pPager->pInJournal = 0;
48566  }else{
48567    assert( pPager->eState==PAGER_WRITER_LOCKED );
48568    pPager->eState = PAGER_WRITER_CACHEMOD;
48569  }
48570
48571  return rc;
48572}
48573
48574/*
48575** Begin a write-transaction on the specified pager object. If a
48576** write-transaction has already been opened, this function is a no-op.
48577**
48578** If the exFlag argument is false, then acquire at least a RESERVED
48579** lock on the database file. If exFlag is true, then acquire at least
48580** an EXCLUSIVE lock. If such a lock is already held, no locking
48581** functions need be called.
48582**
48583** If the subjInMemory argument is non-zero, then any sub-journal opened
48584** within this transaction will be opened as an in-memory file. This
48585** has no effect if the sub-journal is already opened (as it may be when
48586** running in exclusive mode) or if the transaction does not require a
48587** sub-journal. If the subjInMemory argument is zero, then any required
48588** sub-journal is implemented in-memory if pPager is an in-memory database,
48589** or using a temporary file otherwise.
48590*/
48591SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
48592  int rc = SQLITE_OK;
48593
48594  if( pPager->errCode ) return pPager->errCode;
48595  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
48596  pPager->subjInMemory = (u8)subjInMemory;
48597
48598  if( ALWAYS(pPager->eState==PAGER_READER) ){
48599    assert( pPager->pInJournal==0 );
48600
48601    if( pagerUseWal(pPager) ){
48602      /* If the pager is configured to use locking_mode=exclusive, and an
48603      ** exclusive lock on the database is not already held, obtain it now.
48604      */
48605      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
48606        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48607        if( rc!=SQLITE_OK ){
48608          return rc;
48609        }
48610        sqlite3WalExclusiveMode(pPager->pWal, 1);
48611      }
48612
48613      /* Grab the write lock on the log file. If successful, upgrade to
48614      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
48615      ** The busy-handler is not invoked if another connection already
48616      ** holds the write-lock. If possible, the upper layer will call it.
48617      */
48618      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
48619    }else{
48620      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
48621      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
48622      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
48623      ** lock, but not when obtaining the RESERVED lock.
48624      */
48625      rc = pagerLockDb(pPager, RESERVED_LOCK);
48626      if( rc==SQLITE_OK && exFlag ){
48627        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
48628      }
48629    }
48630
48631    if( rc==SQLITE_OK ){
48632      /* Change to WRITER_LOCKED state.
48633      **
48634      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
48635      ** when it has an open transaction, but never to DBMOD or FINISHED.
48636      ** This is because in those states the code to roll back savepoint
48637      ** transactions may copy data from the sub-journal into the database
48638      ** file as well as into the page cache. Which would be incorrect in
48639      ** WAL mode.
48640      */
48641      pPager->eState = PAGER_WRITER_LOCKED;
48642      pPager->dbHintSize = pPager->dbSize;
48643      pPager->dbFileSize = pPager->dbSize;
48644      pPager->dbOrigSize = pPager->dbSize;
48645      pPager->journalOff = 0;
48646    }
48647
48648    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
48649    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
48650    assert( assert_pager_state(pPager) );
48651  }
48652
48653  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
48654  return rc;
48655}
48656
48657/*
48658** Write page pPg onto the end of the rollback journal.
48659*/
48660static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
48661  Pager *pPager = pPg->pPager;
48662  int rc;
48663  u32 cksum;
48664  char *pData2;
48665  i64 iOff = pPager->journalOff;
48666
48667  /* We should never write to the journal file the page that
48668  ** contains the database locks.  The following assert verifies
48669  ** that we do not. */
48670  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
48671
48672  assert( pPager->journalHdr<=pPager->journalOff );
48673  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
48674  cksum = pager_cksum(pPager, (u8*)pData2);
48675
48676  /* Even if an IO or diskfull error occurs while journalling the
48677  ** page in the block above, set the need-sync flag for the page.
48678  ** Otherwise, when the transaction is rolled back, the logic in
48679  ** playback_one_page() will think that the page needs to be restored
48680  ** in the database file. And if an IO error occurs while doing so,
48681  ** then corruption may follow.
48682  */
48683  pPg->flags |= PGHDR_NEED_SYNC;
48684
48685  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
48686  if( rc!=SQLITE_OK ) return rc;
48687  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
48688  if( rc!=SQLITE_OK ) return rc;
48689  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
48690  if( rc!=SQLITE_OK ) return rc;
48691
48692  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
48693           pPager->journalOff, pPager->pageSize));
48694  PAGER_INCR(sqlite3_pager_writej_count);
48695  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
48696       PAGERID(pPager), pPg->pgno,
48697       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
48698
48699  pPager->journalOff += 8 + pPager->pageSize;
48700  pPager->nRec++;
48701  assert( pPager->pInJournal!=0 );
48702  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
48703  testcase( rc==SQLITE_NOMEM );
48704  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48705  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
48706  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48707  return rc;
48708}
48709
48710/*
48711** Mark a single data page as writeable. The page is written into the
48712** main journal or sub-journal as required. If the page is written into
48713** one of the journals, the corresponding bit is set in the
48714** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
48715** of any open savepoints as appropriate.
48716*/
48717static int pager_write(PgHdr *pPg){
48718  Pager *pPager = pPg->pPager;
48719  int rc = SQLITE_OK;
48720
48721  /* This routine is not called unless a write-transaction has already
48722  ** been started. The journal file may or may not be open at this point.
48723  ** It is never called in the ERROR state.
48724  */
48725  assert( pPager->eState==PAGER_WRITER_LOCKED
48726       || pPager->eState==PAGER_WRITER_CACHEMOD
48727       || pPager->eState==PAGER_WRITER_DBMOD
48728  );
48729  assert( assert_pager_state(pPager) );
48730  assert( pPager->errCode==0 );
48731  assert( pPager->readOnly==0 );
48732  CHECK_PAGE(pPg);
48733
48734  /* The journal file needs to be opened. Higher level routines have already
48735  ** obtained the necessary locks to begin the write-transaction, but the
48736  ** rollback journal might not yet be open. Open it now if this is the case.
48737  **
48738  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
48739  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
48740  ** an error might occur and the pager would end up in WRITER_LOCKED state
48741  ** with pages marked as dirty in the cache.
48742  */
48743  if( pPager->eState==PAGER_WRITER_LOCKED ){
48744    rc = pager_open_journal(pPager);
48745    if( rc!=SQLITE_OK ) return rc;
48746  }
48747  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
48748  assert( assert_pager_state(pPager) );
48749
48750  /* Mark the page that is about to be modified as dirty. */
48751  sqlite3PcacheMakeDirty(pPg);
48752
48753  /* If a rollback journal is in use, them make sure the page that is about
48754  ** to change is in the rollback journal, or if the page is a new page off
48755  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
48756  */
48757  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
48758  if( pPager->pInJournal!=0
48759   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
48760  ){
48761    assert( pagerUseWal(pPager)==0 );
48762    if( pPg->pgno<=pPager->dbOrigSize ){
48763      rc = pagerAddPageToRollbackJournal(pPg);
48764      if( rc!=SQLITE_OK ){
48765        return rc;
48766      }
48767    }else{
48768      if( pPager->eState!=PAGER_WRITER_DBMOD ){
48769        pPg->flags |= PGHDR_NEED_SYNC;
48770      }
48771      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
48772              PAGERID(pPager), pPg->pgno,
48773             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
48774    }
48775  }
48776
48777  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
48778  ** and before writing the page into the rollback journal.  Wait until now,
48779  ** after the page has been successfully journalled, before setting the
48780  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
48781  */
48782  pPg->flags |= PGHDR_WRITEABLE;
48783
48784  /* If the statement journal is open and the page is not in it,
48785  ** then write the page into the statement journal.
48786  */
48787  if( pPager->nSavepoint>0 ){
48788    rc = subjournalPageIfRequired(pPg);
48789  }
48790
48791  /* Update the database size and return. */
48792  if( pPager->dbSize<pPg->pgno ){
48793    pPager->dbSize = pPg->pgno;
48794  }
48795  return rc;
48796}
48797
48798/*
48799** This is a variant of sqlite3PagerWrite() that runs when the sector size
48800** is larger than the page size.  SQLite makes the (reasonable) assumption that
48801** all bytes of a sector are written together by hardware.  Hence, all bytes of
48802** a sector need to be journalled in case of a power loss in the middle of
48803** a write.
48804**
48805** Usually, the sector size is less than or equal to the page size, in which
48806** case pages can be individually written.  This routine only runs in the
48807** exceptional case where the page size is smaller than the sector size.
48808*/
48809static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
48810  int rc = SQLITE_OK;          /* Return code */
48811  Pgno nPageCount;             /* Total number of pages in database file */
48812  Pgno pg1;                    /* First page of the sector pPg is located on. */
48813  int nPage = 0;               /* Number of pages starting at pg1 to journal */
48814  int ii;                      /* Loop counter */
48815  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
48816  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
48817  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
48818
48819  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
48820  ** a journal header to be written between the pages journaled by
48821  ** this function.
48822  */
48823  assert( !MEMDB );
48824  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
48825  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
48826
48827  /* This trick assumes that both the page-size and sector-size are
48828  ** an integer power of 2. It sets variable pg1 to the identifier
48829  ** of the first page of the sector pPg is located on.
48830  */
48831  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
48832
48833  nPageCount = pPager->dbSize;
48834  if( pPg->pgno>nPageCount ){
48835    nPage = (pPg->pgno - pg1)+1;
48836  }else if( (pg1+nPagePerSector-1)>nPageCount ){
48837    nPage = nPageCount+1-pg1;
48838  }else{
48839    nPage = nPagePerSector;
48840  }
48841  assert(nPage>0);
48842  assert(pg1<=pPg->pgno);
48843  assert((pg1+nPage)>pPg->pgno);
48844
48845  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
48846    Pgno pg = pg1+ii;
48847    PgHdr *pPage;
48848    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
48849      if( pg!=PAGER_MJ_PGNO(pPager) ){
48850        rc = sqlite3PagerGet(pPager, pg, &pPage);
48851        if( rc==SQLITE_OK ){
48852          rc = pager_write(pPage);
48853          if( pPage->flags&PGHDR_NEED_SYNC ){
48854            needSync = 1;
48855          }
48856          sqlite3PagerUnrefNotNull(pPage);
48857        }
48858      }
48859    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
48860      if( pPage->flags&PGHDR_NEED_SYNC ){
48861        needSync = 1;
48862      }
48863      sqlite3PagerUnrefNotNull(pPage);
48864    }
48865  }
48866
48867  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
48868  ** starting at pg1, then it needs to be set for all of them. Because
48869  ** writing to any of these nPage pages may damage the others, the
48870  ** journal file must contain sync()ed copies of all of them
48871  ** before any of them can be written out to the database file.
48872  */
48873  if( rc==SQLITE_OK && needSync ){
48874    assert( !MEMDB );
48875    for(ii=0; ii<nPage; ii++){
48876      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
48877      if( pPage ){
48878        pPage->flags |= PGHDR_NEED_SYNC;
48879        sqlite3PagerUnrefNotNull(pPage);
48880      }
48881    }
48882  }
48883
48884  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
48885  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
48886  return rc;
48887}
48888
48889/*
48890** Mark a data page as writeable. This routine must be called before
48891** making changes to a page. The caller must check the return value
48892** of this function and be careful not to change any page data unless
48893** this routine returns SQLITE_OK.
48894**
48895** The difference between this function and pager_write() is that this
48896** function also deals with the special case where 2 or more pages
48897** fit on a single disk sector. In this case all co-resident pages
48898** must have been written to the journal file before returning.
48899**
48900** If an error occurs, SQLITE_NOMEM or an IO error code is returned
48901** as appropriate. Otherwise, SQLITE_OK.
48902*/
48903SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
48904  Pager *pPager = pPg->pPager;
48905  assert( (pPg->flags & PGHDR_MMAP)==0 );
48906  assert( pPager->eState>=PAGER_WRITER_LOCKED );
48907  assert( pPager->eState!=PAGER_ERROR );
48908  assert( assert_pager_state(pPager) );
48909  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
48910    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
48911    return SQLITE_OK;
48912  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
48913    return pagerWriteLargeSector(pPg);
48914  }else{
48915    return pager_write(pPg);
48916  }
48917}
48918
48919/*
48920** Return TRUE if the page given in the argument was previously passed
48921** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
48922** to change the content of the page.
48923*/
48924#ifndef NDEBUG
48925SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
48926  return pPg->flags & PGHDR_WRITEABLE;
48927}
48928#endif
48929
48930/*
48931** A call to this routine tells the pager that it is not necessary to
48932** write the information on page pPg back to the disk, even though
48933** that page might be marked as dirty.  This happens, for example, when
48934** the page has been added as a leaf of the freelist and so its
48935** content no longer matters.
48936**
48937** The overlying software layer calls this routine when all of the data
48938** on the given page is unused. The pager marks the page as clean so
48939** that it does not get written to disk.
48940**
48941** Tests show that this optimization can quadruple the speed of large
48942** DELETE operations.
48943*/
48944SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
48945  Pager *pPager = pPg->pPager;
48946  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
48947    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
48948    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
48949    pPg->flags |= PGHDR_DONT_WRITE;
48950    pPg->flags &= ~PGHDR_WRITEABLE;
48951    pager_set_pagehash(pPg);
48952  }
48953}
48954
48955/*
48956** This routine is called to increment the value of the database file
48957** change-counter, stored as a 4-byte big-endian integer starting at
48958** byte offset 24 of the pager file.  The secondary change counter at
48959** 92 is also updated, as is the SQLite version number at offset 96.
48960**
48961** But this only happens if the pPager->changeCountDone flag is false.
48962** To avoid excess churning of page 1, the update only happens once.
48963** See also the pager_write_changecounter() routine that does an
48964** unconditional update of the change counters.
48965**
48966** If the isDirectMode flag is zero, then this is done by calling
48967** sqlite3PagerWrite() on page 1, then modifying the contents of the
48968** page data. In this case the file will be updated when the current
48969** transaction is committed.
48970**
48971** The isDirectMode flag may only be non-zero if the library was compiled
48972** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
48973** if isDirect is non-zero, then the database file is updated directly
48974** by writing an updated version of page 1 using a call to the
48975** sqlite3OsWrite() function.
48976*/
48977static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
48978  int rc = SQLITE_OK;
48979
48980  assert( pPager->eState==PAGER_WRITER_CACHEMOD
48981       || pPager->eState==PAGER_WRITER_DBMOD
48982  );
48983  assert( assert_pager_state(pPager) );
48984
48985  /* Declare and initialize constant integer 'isDirect'. If the
48986  ** atomic-write optimization is enabled in this build, then isDirect
48987  ** is initialized to the value passed as the isDirectMode parameter
48988  ** to this function. Otherwise, it is always set to zero.
48989  **
48990  ** The idea is that if the atomic-write optimization is not
48991  ** enabled at compile time, the compiler can omit the tests of
48992  ** 'isDirect' below, as well as the block enclosed in the
48993  ** "if( isDirect )" condition.
48994  */
48995#ifndef SQLITE_ENABLE_ATOMIC_WRITE
48996# define DIRECT_MODE 0
48997  assert( isDirectMode==0 );
48998  UNUSED_PARAMETER(isDirectMode);
48999#else
49000# define DIRECT_MODE isDirectMode
49001#endif
49002
49003  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
49004    PgHdr *pPgHdr;                /* Reference to page 1 */
49005
49006    assert( !pPager->tempFile && isOpen(pPager->fd) );
49007
49008    /* Open page 1 of the file for writing. */
49009    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
49010    assert( pPgHdr==0 || rc==SQLITE_OK );
49011
49012    /* If page one was fetched successfully, and this function is not
49013    ** operating in direct-mode, make page 1 writable.  When not in
49014    ** direct mode, page 1 is always held in cache and hence the PagerGet()
49015    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
49016    */
49017    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
49018      rc = sqlite3PagerWrite(pPgHdr);
49019    }
49020
49021    if( rc==SQLITE_OK ){
49022      /* Actually do the update of the change counter */
49023      pager_write_changecounter(pPgHdr);
49024
49025      /* If running in direct mode, write the contents of page 1 to the file. */
49026      if( DIRECT_MODE ){
49027        const void *zBuf;
49028        assert( pPager->dbFileSize>0 );
49029        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
49030        if( rc==SQLITE_OK ){
49031          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
49032          pPager->aStat[PAGER_STAT_WRITE]++;
49033        }
49034        if( rc==SQLITE_OK ){
49035          /* Update the pager's copy of the change-counter. Otherwise, the
49036          ** next time a read transaction is opened the cache will be
49037          ** flushed (as the change-counter values will not match).  */
49038          const void *pCopy = (const void *)&((const char *)zBuf)[24];
49039          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
49040          pPager->changeCountDone = 1;
49041        }
49042      }else{
49043        pPager->changeCountDone = 1;
49044      }
49045    }
49046
49047    /* Release the page reference. */
49048    sqlite3PagerUnref(pPgHdr);
49049  }
49050  return rc;
49051}
49052
49053/*
49054** Sync the database file to disk. This is a no-op for in-memory databases
49055** or pages with the Pager.noSync flag set.
49056**
49057** If successful, or if called on a pager for which it is a no-op, this
49058** function returns SQLITE_OK. Otherwise, an IO error code is returned.
49059*/
49060SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
49061  int rc = SQLITE_OK;
49062
49063  if( isOpen(pPager->fd) ){
49064    void *pArg = (void*)zMaster;
49065    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
49066    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
49067  }
49068  if( rc==SQLITE_OK && !pPager->noSync ){
49069    assert( !MEMDB );
49070    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
49071  }
49072  return rc;
49073}
49074
49075/*
49076** This function may only be called while a write-transaction is active in
49077** rollback. If the connection is in WAL mode, this call is a no-op.
49078** Otherwise, if the connection does not already have an EXCLUSIVE lock on
49079** the database file, an attempt is made to obtain one.
49080**
49081** If the EXCLUSIVE lock is already held or the attempt to obtain it is
49082** successful, or the connection is in WAL mode, SQLITE_OK is returned.
49083** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
49084** returned.
49085*/
49086SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
49087  int rc = SQLITE_OK;
49088  assert( pPager->eState==PAGER_WRITER_CACHEMOD
49089       || pPager->eState==PAGER_WRITER_DBMOD
49090       || pPager->eState==PAGER_WRITER_LOCKED
49091  );
49092  assert( assert_pager_state(pPager) );
49093  if( 0==pagerUseWal(pPager) ){
49094    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
49095  }
49096  return rc;
49097}
49098
49099/*
49100** Sync the database file for the pager pPager. zMaster points to the name
49101** of a master journal file that should be written into the individual
49102** journal file. zMaster may be NULL, which is interpreted as no master
49103** journal (a single database transaction).
49104**
49105** This routine ensures that:
49106**
49107**   * The database file change-counter is updated,
49108**   * the journal is synced (unless the atomic-write optimization is used),
49109**   * all dirty pages are written to the database file,
49110**   * the database file is truncated (if required), and
49111**   * the database file synced.
49112**
49113** The only thing that remains to commit the transaction is to finalize
49114** (delete, truncate or zero the first part of) the journal file (or
49115** delete the master journal file if specified).
49116**
49117** Note that if zMaster==NULL, this does not overwrite a previous value
49118** passed to an sqlite3PagerCommitPhaseOne() call.
49119**
49120** If the final parameter - noSync - is true, then the database file itself
49121** is not synced. The caller must call sqlite3PagerSync() directly to
49122** sync the database file before calling CommitPhaseTwo() to delete the
49123** journal file in this case.
49124*/
49125SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
49126  Pager *pPager,                  /* Pager object */
49127  const char *zMaster,            /* If not NULL, the master journal name */
49128  int noSync                      /* True to omit the xSync on the db file */
49129){
49130  int rc = SQLITE_OK;             /* Return code */
49131
49132  assert( pPager->eState==PAGER_WRITER_LOCKED
49133       || pPager->eState==PAGER_WRITER_CACHEMOD
49134       || pPager->eState==PAGER_WRITER_DBMOD
49135       || pPager->eState==PAGER_ERROR
49136  );
49137  assert( assert_pager_state(pPager) );
49138
49139  /* If a prior error occurred, report that error again. */
49140  if( NEVER(pPager->errCode) ) return pPager->errCode;
49141
49142  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
49143      pPager->zFilename, zMaster, pPager->dbSize));
49144
49145  /* If no database changes have been made, return early. */
49146  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
49147
49148  if( MEMDB ){
49149    /* If this is an in-memory db, or no pages have been written to, or this
49150    ** function has already been called, it is mostly a no-op.  However, any
49151    ** backup in progress needs to be restarted.
49152    */
49153    sqlite3BackupRestart(pPager->pBackup);
49154  }else{
49155    if( pagerUseWal(pPager) ){
49156      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
49157      PgHdr *pPageOne = 0;
49158      if( pList==0 ){
49159        /* Must have at least one page for the WAL commit flag.
49160        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
49161        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
49162        pList = pPageOne;
49163        pList->pDirty = 0;
49164      }
49165      assert( rc==SQLITE_OK );
49166      if( ALWAYS(pList) ){
49167        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
49168      }
49169      sqlite3PagerUnref(pPageOne);
49170      if( rc==SQLITE_OK ){
49171        sqlite3PcacheCleanAll(pPager->pPCache);
49172      }
49173    }else{
49174      /* The following block updates the change-counter. Exactly how it
49175      ** does this depends on whether or not the atomic-update optimization
49176      ** was enabled at compile time, and if this transaction meets the
49177      ** runtime criteria to use the operation:
49178      **
49179      **    * The file-system supports the atomic-write property for
49180      **      blocks of size page-size, and
49181      **    * This commit is not part of a multi-file transaction, and
49182      **    * Exactly one page has been modified and store in the journal file.
49183      **
49184      ** If the optimization was not enabled at compile time, then the
49185      ** pager_incr_changecounter() function is called to update the change
49186      ** counter in 'indirect-mode'. If the optimization is compiled in but
49187      ** is not applicable to this transaction, call sqlite3JournalCreate()
49188      ** to make sure the journal file has actually been created, then call
49189      ** pager_incr_changecounter() to update the change-counter in indirect
49190      ** mode.
49191      **
49192      ** Otherwise, if the optimization is both enabled and applicable,
49193      ** then call pager_incr_changecounter() to update the change-counter
49194      ** in 'direct' mode. In this case the journal file will never be
49195      ** created for this transaction.
49196      */
49197  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
49198      PgHdr *pPg;
49199      assert( isOpen(pPager->jfd)
49200           || pPager->journalMode==PAGER_JOURNALMODE_OFF
49201           || pPager->journalMode==PAGER_JOURNALMODE_WAL
49202      );
49203      if( !zMaster && isOpen(pPager->jfd)
49204       && pPager->journalOff==jrnlBufferSize(pPager)
49205       && pPager->dbSize>=pPager->dbOrigSize
49206       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
49207      ){
49208        /* Update the db file change counter via the direct-write method. The
49209        ** following call will modify the in-memory representation of page 1
49210        ** to include the updated change counter and then write page 1
49211        ** directly to the database file. Because of the atomic-write
49212        ** property of the host file-system, this is safe.
49213        */
49214        rc = pager_incr_changecounter(pPager, 1);
49215      }else{
49216        rc = sqlite3JournalCreate(pPager->jfd);
49217        if( rc==SQLITE_OK ){
49218          rc = pager_incr_changecounter(pPager, 0);
49219        }
49220      }
49221  #else
49222      rc = pager_incr_changecounter(pPager, 0);
49223  #endif
49224      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49225
49226      /* Write the master journal name into the journal file. If a master
49227      ** journal file name has already been written to the journal file,
49228      ** or if zMaster is NULL (no master journal), then this call is a no-op.
49229      */
49230      rc = writeMasterJournal(pPager, zMaster);
49231      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49232
49233      /* Sync the journal file and write all dirty pages to the database.
49234      ** If the atomic-update optimization is being used, this sync will not
49235      ** create the journal file or perform any real IO.
49236      **
49237      ** Because the change-counter page was just modified, unless the
49238      ** atomic-update optimization is used it is almost certain that the
49239      ** journal requires a sync here. However, in locking_mode=exclusive
49240      ** on a system under memory pressure it is just possible that this is
49241      ** not the case. In this case it is likely enough that the redundant
49242      ** xSync() call will be changed to a no-op by the OS anyhow.
49243      */
49244      rc = syncJournal(pPager, 0);
49245      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49246
49247      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
49248      if( rc!=SQLITE_OK ){
49249        assert( rc!=SQLITE_IOERR_BLOCKED );
49250        goto commit_phase_one_exit;
49251      }
49252      sqlite3PcacheCleanAll(pPager->pPCache);
49253
49254      /* If the file on disk is smaller than the database image, use
49255      ** pager_truncate to grow the file here. This can happen if the database
49256      ** image was extended as part of the current transaction and then the
49257      ** last page in the db image moved to the free-list. In this case the
49258      ** last page is never written out to disk, leaving the database file
49259      ** undersized. Fix this now if it is the case.  */
49260      if( pPager->dbSize>pPager->dbFileSize ){
49261        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
49262        assert( pPager->eState==PAGER_WRITER_DBMOD );
49263        rc = pager_truncate(pPager, nNew);
49264        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49265      }
49266
49267      /* Finally, sync the database file. */
49268      if( !noSync ){
49269        rc = sqlite3PagerSync(pPager, zMaster);
49270      }
49271      IOTRACE(("DBSYNC %p\n", pPager))
49272    }
49273  }
49274
49275commit_phase_one_exit:
49276  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
49277    pPager->eState = PAGER_WRITER_FINISHED;
49278  }
49279  return rc;
49280}
49281
49282
49283/*
49284** When this function is called, the database file has been completely
49285** updated to reflect the changes made by the current transaction and
49286** synced to disk. The journal file still exists in the file-system
49287** though, and if a failure occurs at this point it will eventually
49288** be used as a hot-journal and the current transaction rolled back.
49289**
49290** This function finalizes the journal file, either by deleting,
49291** truncating or partially zeroing it, so that it cannot be used
49292** for hot-journal rollback. Once this is done the transaction is
49293** irrevocably committed.
49294**
49295** If an error occurs, an IO error code is returned and the pager
49296** moves into the error state. Otherwise, SQLITE_OK is returned.
49297*/
49298SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
49299  int rc = SQLITE_OK;                  /* Return code */
49300
49301  /* This routine should not be called if a prior error has occurred.
49302  ** But if (due to a coding error elsewhere in the system) it does get
49303  ** called, just return the same error code without doing anything. */
49304  if( NEVER(pPager->errCode) ) return pPager->errCode;
49305
49306  assert( pPager->eState==PAGER_WRITER_LOCKED
49307       || pPager->eState==PAGER_WRITER_FINISHED
49308       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
49309  );
49310  assert( assert_pager_state(pPager) );
49311
49312  /* An optimization. If the database was not actually modified during
49313  ** this transaction, the pager is running in exclusive-mode and is
49314  ** using persistent journals, then this function is a no-op.
49315  **
49316  ** The start of the journal file currently contains a single journal
49317  ** header with the nRec field set to 0. If such a journal is used as
49318  ** a hot-journal during hot-journal rollback, 0 changes will be made
49319  ** to the database file. So there is no need to zero the journal
49320  ** header. Since the pager is in exclusive mode, there is no need
49321  ** to drop any locks either.
49322  */
49323  if( pPager->eState==PAGER_WRITER_LOCKED
49324   && pPager->exclusiveMode
49325   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
49326  ){
49327    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
49328    pPager->eState = PAGER_READER;
49329    return SQLITE_OK;
49330  }
49331
49332  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
49333  pPager->iDataVersion++;
49334  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
49335  return pager_error(pPager, rc);
49336}
49337
49338/*
49339** If a write transaction is open, then all changes made within the
49340** transaction are reverted and the current write-transaction is closed.
49341** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
49342** state if an error occurs.
49343**
49344** If the pager is already in PAGER_ERROR state when this function is called,
49345** it returns Pager.errCode immediately. No work is performed in this case.
49346**
49347** Otherwise, in rollback mode, this function performs two functions:
49348**
49349**   1) It rolls back the journal file, restoring all database file and
49350**      in-memory cache pages to the state they were in when the transaction
49351**      was opened, and
49352**
49353**   2) It finalizes the journal file, so that it is not used for hot
49354**      rollback at any point in the future.
49355**
49356** Finalization of the journal file (task 2) is only performed if the
49357** rollback is successful.
49358**
49359** In WAL mode, all cache-entries containing data modified within the
49360** current transaction are either expelled from the cache or reverted to
49361** their pre-transaction state by re-reading data from the database or
49362** WAL files. The WAL transaction is then closed.
49363*/
49364SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
49365  int rc = SQLITE_OK;                  /* Return code */
49366  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
49367
49368  /* PagerRollback() is a no-op if called in READER or OPEN state. If
49369  ** the pager is already in the ERROR state, the rollback is not
49370  ** attempted here. Instead, the error code is returned to the caller.
49371  */
49372  assert( assert_pager_state(pPager) );
49373  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
49374  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
49375
49376  if( pagerUseWal(pPager) ){
49377    int rc2;
49378    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
49379    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
49380    if( rc==SQLITE_OK ) rc = rc2;
49381  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
49382    int eState = pPager->eState;
49383    rc = pager_end_transaction(pPager, 0, 0);
49384    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
49385      /* This can happen using journal_mode=off. Move the pager to the error
49386      ** state to indicate that the contents of the cache may not be trusted.
49387      ** Any active readers will get SQLITE_ABORT.
49388      */
49389      pPager->errCode = SQLITE_ABORT;
49390      pPager->eState = PAGER_ERROR;
49391      return rc;
49392    }
49393  }else{
49394    rc = pager_playback(pPager, 0);
49395  }
49396
49397  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
49398  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
49399          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
49400          || rc==SQLITE_CANTOPEN
49401  );
49402
49403  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
49404  ** cache. So call pager_error() on the way out to make any error persistent.
49405  */
49406  return pager_error(pPager, rc);
49407}
49408
49409/*
49410** Return TRUE if the database file is opened read-only.  Return FALSE
49411** if the database is (in theory) writable.
49412*/
49413SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
49414  return pPager->readOnly;
49415}
49416
49417#ifdef SQLITE_DEBUG
49418/*
49419** Return the sum of the reference counts for all pages held by pPager.
49420*/
49421SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
49422  return sqlite3PcacheRefCount(pPager->pPCache);
49423}
49424#endif
49425
49426/*
49427** Return the approximate number of bytes of memory currently
49428** used by the pager and its associated cache.
49429*/
49430SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
49431  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
49432                                     + 5*sizeof(void*);
49433  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
49434           + sqlite3MallocSize(pPager)
49435           + pPager->pageSize;
49436}
49437
49438/*
49439** Return the number of references to the specified page.
49440*/
49441SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
49442  return sqlite3PcachePageRefcount(pPage);
49443}
49444
49445#ifdef SQLITE_TEST
49446/*
49447** This routine is used for testing and analysis only.
49448*/
49449SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
49450  static int a[11];
49451  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
49452  a[1] = sqlite3PcachePagecount(pPager->pPCache);
49453  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
49454  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
49455  a[4] = pPager->eState;
49456  a[5] = pPager->errCode;
49457  a[6] = pPager->aStat[PAGER_STAT_HIT];
49458  a[7] = pPager->aStat[PAGER_STAT_MISS];
49459  a[8] = 0;  /* Used to be pPager->nOvfl */
49460  a[9] = pPager->nRead;
49461  a[10] = pPager->aStat[PAGER_STAT_WRITE];
49462  return a;
49463}
49464#endif
49465
49466/*
49467** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
49468** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
49469** current cache hit or miss count, according to the value of eStat. If the
49470** reset parameter is non-zero, the cache hit or miss count is zeroed before
49471** returning.
49472*/
49473SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
49474
49475  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
49476       || eStat==SQLITE_DBSTATUS_CACHE_MISS
49477       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
49478  );
49479
49480  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
49481  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
49482  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
49483
49484  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
49485  if( reset ){
49486    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
49487  }
49488}
49489
49490/*
49491** Return true if this is an in-memory pager.
49492*/
49493SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
49494  return MEMDB;
49495}
49496
49497/*
49498** Check that there are at least nSavepoint savepoints open. If there are
49499** currently less than nSavepoints open, then open one or more savepoints
49500** to make up the difference. If the number of savepoints is already
49501** equal to nSavepoint, then this function is a no-op.
49502**
49503** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
49504** occurs while opening the sub-journal file, then an IO error code is
49505** returned. Otherwise, SQLITE_OK.
49506*/
49507static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
49508  int rc = SQLITE_OK;                       /* Return code */
49509  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
49510  int ii;                                   /* Iterator variable */
49511  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
49512
49513  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49514  assert( assert_pager_state(pPager) );
49515  assert( nSavepoint>nCurrent && pPager->useJournal );
49516
49517  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
49518  ** if the allocation fails. Otherwise, zero the new portion in case a
49519  ** malloc failure occurs while populating it in the for(...) loop below.
49520  */
49521  aNew = (PagerSavepoint *)sqlite3Realloc(
49522      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
49523  );
49524  if( !aNew ){
49525    return SQLITE_NOMEM;
49526  }
49527  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
49528  pPager->aSavepoint = aNew;
49529
49530  /* Populate the PagerSavepoint structures just allocated. */
49531  for(ii=nCurrent; ii<nSavepoint; ii++){
49532    aNew[ii].nOrig = pPager->dbSize;
49533    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
49534      aNew[ii].iOffset = pPager->journalOff;
49535    }else{
49536      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
49537    }
49538    aNew[ii].iSubRec = pPager->nSubRec;
49539    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
49540    if( !aNew[ii].pInSavepoint ){
49541      return SQLITE_NOMEM;
49542    }
49543    if( pagerUseWal(pPager) ){
49544      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
49545    }
49546    pPager->nSavepoint = ii+1;
49547  }
49548  assert( pPager->nSavepoint==nSavepoint );
49549  assertTruncateConstraint(pPager);
49550  return rc;
49551}
49552SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
49553  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49554  assert( assert_pager_state(pPager) );
49555
49556  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
49557    return pagerOpenSavepoint(pPager, nSavepoint);
49558  }else{
49559    return SQLITE_OK;
49560  }
49561}
49562
49563
49564/*
49565** This function is called to rollback or release (commit) a savepoint.
49566** The savepoint to release or rollback need not be the most recently
49567** created savepoint.
49568**
49569** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
49570** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
49571** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
49572** that have occurred since the specified savepoint was created.
49573**
49574** The savepoint to rollback or release is identified by parameter
49575** iSavepoint. A value of 0 means to operate on the outermost savepoint
49576** (the first created). A value of (Pager.nSavepoint-1) means operate
49577** on the most recently created savepoint. If iSavepoint is greater than
49578** (Pager.nSavepoint-1), then this function is a no-op.
49579**
49580** If a negative value is passed to this function, then the current
49581** transaction is rolled back. This is different to calling
49582** sqlite3PagerRollback() because this function does not terminate
49583** the transaction or unlock the database, it just restores the
49584** contents of the database to its original state.
49585**
49586** In any case, all savepoints with an index greater than iSavepoint
49587** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
49588** then savepoint iSavepoint is also destroyed.
49589**
49590** This function may return SQLITE_NOMEM if a memory allocation fails,
49591** or an IO error code if an IO error occurs while rolling back a
49592** savepoint. If no errors occur, SQLITE_OK is returned.
49593*/
49594SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
49595  int rc = pPager->errCode;       /* Return code */
49596
49597  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
49598  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
49599
49600  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
49601    int ii;            /* Iterator variable */
49602    int nNew;          /* Number of remaining savepoints after this op. */
49603
49604    /* Figure out how many savepoints will still be active after this
49605    ** operation. Store this value in nNew. Then free resources associated
49606    ** with any savepoints that are destroyed by this operation.
49607    */
49608    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
49609    for(ii=nNew; ii<pPager->nSavepoint; ii++){
49610      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
49611    }
49612    pPager->nSavepoint = nNew;
49613
49614    /* If this is a release of the outermost savepoint, truncate
49615    ** the sub-journal to zero bytes in size. */
49616    if( op==SAVEPOINT_RELEASE ){
49617      if( nNew==0 && isOpen(pPager->sjfd) ){
49618        /* Only truncate if it is an in-memory sub-journal. */
49619        if( sqlite3IsMemJournal(pPager->sjfd) ){
49620          rc = sqlite3OsTruncate(pPager->sjfd, 0);
49621          assert( rc==SQLITE_OK );
49622        }
49623        pPager->nSubRec = 0;
49624      }
49625    }
49626    /* Else this is a rollback operation, playback the specified savepoint.
49627    ** If this is a temp-file, it is possible that the journal file has
49628    ** not yet been opened. In this case there have been no changes to
49629    ** the database file, so the playback operation can be skipped.
49630    */
49631    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
49632      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
49633      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
49634      assert(rc!=SQLITE_DONE);
49635    }
49636  }
49637
49638  return rc;
49639}
49640
49641/*
49642** Return the full pathname of the database file.
49643**
49644** Except, if the pager is in-memory only, then return an empty string if
49645** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
49646** used to report the filename to the user, for compatibility with legacy
49647** behavior.  But when the Btree needs to know the filename for matching to
49648** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
49649** participate in shared-cache.
49650*/
49651SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
49652  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
49653}
49654
49655/*
49656** Return the VFS structure for the pager.
49657*/
49658SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
49659  return pPager->pVfs;
49660}
49661
49662/*
49663** Return the file handle for the database file associated
49664** with the pager.  This might return NULL if the file has
49665** not yet been opened.
49666*/
49667SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
49668  return pPager->fd;
49669}
49670
49671/*
49672** Return the full pathname of the journal file.
49673*/
49674SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
49675  return pPager->zJournal;
49676}
49677
49678/*
49679** Return true if fsync() calls are disabled for this pager.  Return FALSE
49680** if fsync()s are executed normally.
49681*/
49682SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
49683  return pPager->noSync;
49684}
49685
49686#ifdef SQLITE_HAS_CODEC
49687/*
49688** Set or retrieve the codec for this pager
49689*/
49690SQLITE_PRIVATE void sqlite3PagerSetCodec(
49691  Pager *pPager,
49692  void *(*xCodec)(void*,void*,Pgno,int),
49693  void (*xCodecSizeChng)(void*,int,int),
49694  void (*xCodecFree)(void*),
49695  void *pCodec
49696){
49697  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
49698  pPager->xCodec = pPager->memDb ? 0 : xCodec;
49699  pPager->xCodecSizeChng = xCodecSizeChng;
49700  pPager->xCodecFree = xCodecFree;
49701  pPager->pCodec = pCodec;
49702  pagerReportSize(pPager);
49703}
49704SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
49705  return pPager->pCodec;
49706}
49707
49708/*
49709** This function is called by the wal module when writing page content
49710** into the log file.
49711**
49712** This function returns a pointer to a buffer containing the encrypted
49713** page content. If a malloc fails, this function may return NULL.
49714*/
49715SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
49716  void *aData = 0;
49717  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
49718  return aData;
49719}
49720
49721/*
49722** Return the current pager state
49723*/
49724SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
49725  return pPager->eState;
49726}
49727#endif /* SQLITE_HAS_CODEC */
49728
49729#ifndef SQLITE_OMIT_AUTOVACUUM
49730/*
49731** Move the page pPg to location pgno in the file.
49732**
49733** There must be no references to the page previously located at
49734** pgno (which we call pPgOld) though that page is allowed to be
49735** in cache.  If the page previously located at pgno is not already
49736** in the rollback journal, it is not put there by by this routine.
49737**
49738** References to the page pPg remain valid. Updating any
49739** meta-data associated with pPg (i.e. data stored in the nExtra bytes
49740** allocated along with the page) is the responsibility of the caller.
49741**
49742** A transaction must be active when this routine is called. It used to be
49743** required that a statement transaction was not active, but this restriction
49744** has been removed (CREATE INDEX needs to move a page when a statement
49745** transaction is active).
49746**
49747** If the fourth argument, isCommit, is non-zero, then this page is being
49748** moved as part of a database reorganization just before the transaction
49749** is being committed. In this case, it is guaranteed that the database page
49750** pPg refers to will not be written to again within this transaction.
49751**
49752** This function may return SQLITE_NOMEM or an IO error code if an error
49753** occurs. Otherwise, it returns SQLITE_OK.
49754*/
49755SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
49756  PgHdr *pPgOld;               /* The page being overwritten. */
49757  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
49758  int rc;                      /* Return code */
49759  Pgno origPgno;               /* The original page number */
49760
49761  assert( pPg->nRef>0 );
49762  assert( pPager->eState==PAGER_WRITER_CACHEMOD
49763       || pPager->eState==PAGER_WRITER_DBMOD
49764  );
49765  assert( assert_pager_state(pPager) );
49766
49767  /* In order to be able to rollback, an in-memory database must journal
49768  ** the page we are moving from.
49769  */
49770  if( MEMDB ){
49771    rc = sqlite3PagerWrite(pPg);
49772    if( rc ) return rc;
49773  }
49774
49775  /* If the page being moved is dirty and has not been saved by the latest
49776  ** savepoint, then save the current contents of the page into the
49777  ** sub-journal now. This is required to handle the following scenario:
49778  **
49779  **   BEGIN;
49780  **     <journal page X, then modify it in memory>
49781  **     SAVEPOINT one;
49782  **       <Move page X to location Y>
49783  **     ROLLBACK TO one;
49784  **
49785  ** If page X were not written to the sub-journal here, it would not
49786  ** be possible to restore its contents when the "ROLLBACK TO one"
49787  ** statement were is processed.
49788  **
49789  ** subjournalPage() may need to allocate space to store pPg->pgno into
49790  ** one or more savepoint bitvecs. This is the reason this function
49791  ** may return SQLITE_NOMEM.
49792  */
49793  if( (pPg->flags & PGHDR_DIRTY)!=0
49794   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
49795  ){
49796    return rc;
49797  }
49798
49799  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
49800      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
49801  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
49802
49803  /* If the journal needs to be sync()ed before page pPg->pgno can
49804  ** be written to, store pPg->pgno in local variable needSyncPgno.
49805  **
49806  ** If the isCommit flag is set, there is no need to remember that
49807  ** the journal needs to be sync()ed before database page pPg->pgno
49808  ** can be written to. The caller has already promised not to write to it.
49809  */
49810  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
49811    needSyncPgno = pPg->pgno;
49812    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
49813            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
49814    assert( pPg->flags&PGHDR_DIRTY );
49815  }
49816
49817  /* If the cache contains a page with page-number pgno, remove it
49818  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
49819  ** page pgno before the 'move' operation, it needs to be retained
49820  ** for the page moved there.
49821  */
49822  pPg->flags &= ~PGHDR_NEED_SYNC;
49823  pPgOld = sqlite3PagerLookup(pPager, pgno);
49824  assert( !pPgOld || pPgOld->nRef==1 );
49825  if( pPgOld ){
49826    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
49827    if( MEMDB ){
49828      /* Do not discard pages from an in-memory database since we might
49829      ** need to rollback later.  Just move the page out of the way. */
49830      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
49831    }else{
49832      sqlite3PcacheDrop(pPgOld);
49833    }
49834  }
49835
49836  origPgno = pPg->pgno;
49837  sqlite3PcacheMove(pPg, pgno);
49838  sqlite3PcacheMakeDirty(pPg);
49839
49840  /* For an in-memory database, make sure the original page continues
49841  ** to exist, in case the transaction needs to roll back.  Use pPgOld
49842  ** as the original page since it has already been allocated.
49843  */
49844  if( MEMDB ){
49845    assert( pPgOld );
49846    sqlite3PcacheMove(pPgOld, origPgno);
49847    sqlite3PagerUnrefNotNull(pPgOld);
49848  }
49849
49850  if( needSyncPgno ){
49851    /* If needSyncPgno is non-zero, then the journal file needs to be
49852    ** sync()ed before any data is written to database file page needSyncPgno.
49853    ** Currently, no such page exists in the page-cache and the
49854    ** "is journaled" bitvec flag has been set. This needs to be remedied by
49855    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
49856    ** flag.
49857    **
49858    ** If the attempt to load the page into the page-cache fails, (due
49859    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
49860    ** array. Otherwise, if the page is loaded and written again in
49861    ** this transaction, it may be written to the database file before
49862    ** it is synced into the journal file. This way, it may end up in
49863    ** the journal file twice, but that is not a problem.
49864    */
49865    PgHdr *pPgHdr;
49866    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
49867    if( rc!=SQLITE_OK ){
49868      if( needSyncPgno<=pPager->dbOrigSize ){
49869        assert( pPager->pTmpSpace!=0 );
49870        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
49871      }
49872      return rc;
49873    }
49874    pPgHdr->flags |= PGHDR_NEED_SYNC;
49875    sqlite3PcacheMakeDirty(pPgHdr);
49876    sqlite3PagerUnrefNotNull(pPgHdr);
49877  }
49878
49879  return SQLITE_OK;
49880}
49881#endif
49882
49883/*
49884** The page handle passed as the first argument refers to a dirty page
49885** with a page number other than iNew. This function changes the page's
49886** page number to iNew and sets the value of the PgHdr.flags field to
49887** the value passed as the third parameter.
49888*/
49889SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
49890  assert( pPg->pgno!=iNew );
49891  pPg->flags = flags;
49892  sqlite3PcacheMove(pPg, iNew);
49893}
49894
49895/*
49896** Return a pointer to the data for the specified page.
49897*/
49898SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
49899  assert( pPg->nRef>0 || pPg->pPager->memDb );
49900  return pPg->pData;
49901}
49902
49903/*
49904** Return a pointer to the Pager.nExtra bytes of "extra" space
49905** allocated along with the specified page.
49906*/
49907SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
49908  return pPg->pExtra;
49909}
49910
49911/*
49912** Get/set the locking-mode for this pager. Parameter eMode must be one
49913** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
49914** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
49915** the locking-mode is set to the value specified.
49916**
49917** The returned value is either PAGER_LOCKINGMODE_NORMAL or
49918** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
49919** locking-mode.
49920*/
49921SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
49922  assert( eMode==PAGER_LOCKINGMODE_QUERY
49923            || eMode==PAGER_LOCKINGMODE_NORMAL
49924            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
49925  assert( PAGER_LOCKINGMODE_QUERY<0 );
49926  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
49927  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
49928  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
49929    pPager->exclusiveMode = (u8)eMode;
49930  }
49931  return (int)pPager->exclusiveMode;
49932}
49933
49934/*
49935** Set the journal-mode for this pager. Parameter eMode must be one of:
49936**
49937**    PAGER_JOURNALMODE_DELETE
49938**    PAGER_JOURNALMODE_TRUNCATE
49939**    PAGER_JOURNALMODE_PERSIST
49940**    PAGER_JOURNALMODE_OFF
49941**    PAGER_JOURNALMODE_MEMORY
49942**    PAGER_JOURNALMODE_WAL
49943**
49944** The journalmode is set to the value specified if the change is allowed.
49945** The change may be disallowed for the following reasons:
49946**
49947**   *  An in-memory database can only have its journal_mode set to _OFF
49948**      or _MEMORY.
49949**
49950**   *  Temporary databases cannot have _WAL journalmode.
49951**
49952** The returned indicate the current (possibly updated) journal-mode.
49953*/
49954SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
49955  u8 eOld = pPager->journalMode;    /* Prior journalmode */
49956
49957#ifdef SQLITE_DEBUG
49958  /* The print_pager_state() routine is intended to be used by the debugger
49959  ** only.  We invoke it once here to suppress a compiler warning. */
49960  print_pager_state(pPager);
49961#endif
49962
49963
49964  /* The eMode parameter is always valid */
49965  assert(      eMode==PAGER_JOURNALMODE_DELETE
49966            || eMode==PAGER_JOURNALMODE_TRUNCATE
49967            || eMode==PAGER_JOURNALMODE_PERSIST
49968            || eMode==PAGER_JOURNALMODE_OFF
49969            || eMode==PAGER_JOURNALMODE_WAL
49970            || eMode==PAGER_JOURNALMODE_MEMORY );
49971
49972  /* This routine is only called from the OP_JournalMode opcode, and
49973  ** the logic there will never allow a temporary file to be changed
49974  ** to WAL mode.
49975  */
49976  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
49977
49978  /* Do allow the journalmode of an in-memory database to be set to
49979  ** anything other than MEMORY or OFF
49980  */
49981  if( MEMDB ){
49982    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
49983    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
49984      eMode = eOld;
49985    }
49986  }
49987
49988  if( eMode!=eOld ){
49989
49990    /* Change the journal mode. */
49991    assert( pPager->eState!=PAGER_ERROR );
49992    pPager->journalMode = (u8)eMode;
49993
49994    /* When transistioning from TRUNCATE or PERSIST to any other journal
49995    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
49996    ** delete the journal file.
49997    */
49998    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
49999    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
50000    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
50001    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
50002    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
50003    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
50004
50005    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
50006    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
50007
50008      /* In this case we would like to delete the journal file. If it is
50009      ** not possible, then that is not a problem. Deleting the journal file
50010      ** here is an optimization only.
50011      **
50012      ** Before deleting the journal file, obtain a RESERVED lock on the
50013      ** database file. This ensures that the journal file is not deleted
50014      ** while it is in use by some other client.
50015      */
50016      sqlite3OsClose(pPager->jfd);
50017      if( pPager->eLock>=RESERVED_LOCK ){
50018        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
50019      }else{
50020        int rc = SQLITE_OK;
50021        int state = pPager->eState;
50022        assert( state==PAGER_OPEN || state==PAGER_READER );
50023        if( state==PAGER_OPEN ){
50024          rc = sqlite3PagerSharedLock(pPager);
50025        }
50026        if( pPager->eState==PAGER_READER ){
50027          assert( rc==SQLITE_OK );
50028          rc = pagerLockDb(pPager, RESERVED_LOCK);
50029        }
50030        if( rc==SQLITE_OK ){
50031          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
50032        }
50033        if( rc==SQLITE_OK && state==PAGER_READER ){
50034          pagerUnlockDb(pPager, SHARED_LOCK);
50035        }else if( state==PAGER_OPEN ){
50036          pager_unlock(pPager);
50037        }
50038        assert( state==pPager->eState );
50039      }
50040    }else if( eMode==PAGER_JOURNALMODE_OFF ){
50041      sqlite3OsClose(pPager->jfd);
50042    }
50043  }
50044
50045  /* Return the new journal mode */
50046  return (int)pPager->journalMode;
50047}
50048
50049/*
50050** Return the current journal mode.
50051*/
50052SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
50053  return (int)pPager->journalMode;
50054}
50055
50056/*
50057** Return TRUE if the pager is in a state where it is OK to change the
50058** journalmode.  Journalmode changes can only happen when the database
50059** is unmodified.
50060*/
50061SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
50062  assert( assert_pager_state(pPager) );
50063  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
50064  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
50065  return 1;
50066}
50067
50068/*
50069** Get/set the size-limit used for persistent journal files.
50070**
50071** Setting the size limit to -1 means no limit is enforced.
50072** An attempt to set a limit smaller than -1 is a no-op.
50073*/
50074SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
50075  if( iLimit>=-1 ){
50076    pPager->journalSizeLimit = iLimit;
50077    sqlite3WalLimit(pPager->pWal, iLimit);
50078  }
50079  return pPager->journalSizeLimit;
50080}
50081
50082/*
50083** Return a pointer to the pPager->pBackup variable. The backup module
50084** in backup.c maintains the content of this variable. This module
50085** uses it opaquely as an argument to sqlite3BackupRestart() and
50086** sqlite3BackupUpdate() only.
50087*/
50088SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
50089  return &pPager->pBackup;
50090}
50091
50092#ifndef SQLITE_OMIT_VACUUM
50093/*
50094** Unless this is an in-memory or temporary database, clear the pager cache.
50095*/
50096SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
50097  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
50098}
50099#endif
50100
50101#ifndef SQLITE_OMIT_WAL
50102/*
50103** This function is called when the user invokes "PRAGMA wal_checkpoint",
50104** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
50105** or wal_blocking_checkpoint() API functions.
50106**
50107** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
50108*/
50109SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
50110  int rc = SQLITE_OK;
50111  if( pPager->pWal ){
50112    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
50113        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
50114        pPager->pBusyHandlerArg,
50115        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
50116        pnLog, pnCkpt
50117    );
50118  }
50119  return rc;
50120}
50121
50122SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
50123  return sqlite3WalCallback(pPager->pWal);
50124}
50125
50126/*
50127** Return true if the underlying VFS for the given pager supports the
50128** primitives necessary for write-ahead logging.
50129*/
50130SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
50131  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
50132  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
50133}
50134
50135/*
50136** Attempt to take an exclusive lock on the database file. If a PENDING lock
50137** is obtained instead, immediately release it.
50138*/
50139static int pagerExclusiveLock(Pager *pPager){
50140  int rc;                         /* Return code */
50141
50142  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
50143  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
50144  if( rc!=SQLITE_OK ){
50145    /* If the attempt to grab the exclusive lock failed, release the
50146    ** pending lock that may have been obtained instead.  */
50147    pagerUnlockDb(pPager, SHARED_LOCK);
50148  }
50149
50150  return rc;
50151}
50152
50153/*
50154** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
50155** exclusive-locking mode when this function is called, take an EXCLUSIVE
50156** lock on the database file and use heap-memory to store the wal-index
50157** in. Otherwise, use the normal shared-memory.
50158*/
50159static int pagerOpenWal(Pager *pPager){
50160  int rc = SQLITE_OK;
50161
50162  assert( pPager->pWal==0 && pPager->tempFile==0 );
50163  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
50164
50165  /* If the pager is already in exclusive-mode, the WAL module will use
50166  ** heap-memory for the wal-index instead of the VFS shared-memory
50167  ** implementation. Take the exclusive lock now, before opening the WAL
50168  ** file, to make sure this is safe.
50169  */
50170  if( pPager->exclusiveMode ){
50171    rc = pagerExclusiveLock(pPager);
50172  }
50173
50174  /* Open the connection to the log file. If this operation fails,
50175  ** (e.g. due to malloc() failure), return an error code.
50176  */
50177  if( rc==SQLITE_OK ){
50178    rc = sqlite3WalOpen(pPager->pVfs,
50179        pPager->fd, pPager->zWal, pPager->exclusiveMode,
50180        pPager->journalSizeLimit, &pPager->pWal
50181    );
50182  }
50183  pagerFixMaplimit(pPager);
50184
50185  return rc;
50186}
50187
50188
50189/*
50190** The caller must be holding a SHARED lock on the database file to call
50191** this function.
50192**
50193** If the pager passed as the first argument is open on a real database
50194** file (not a temp file or an in-memory database), and the WAL file
50195** is not already open, make an attempt to open it now. If successful,
50196** return SQLITE_OK. If an error occurs or the VFS used by the pager does
50197** not support the xShmXXX() methods, return an error code. *pbOpen is
50198** not modified in either case.
50199**
50200** If the pager is open on a temp-file (or in-memory database), or if
50201** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
50202** without doing anything.
50203*/
50204SQLITE_PRIVATE int sqlite3PagerOpenWal(
50205  Pager *pPager,                  /* Pager object */
50206  int *pbOpen                     /* OUT: Set to true if call is a no-op */
50207){
50208  int rc = SQLITE_OK;             /* Return code */
50209
50210  assert( assert_pager_state(pPager) );
50211  assert( pPager->eState==PAGER_OPEN   || pbOpen );
50212  assert( pPager->eState==PAGER_READER || !pbOpen );
50213  assert( pbOpen==0 || *pbOpen==0 );
50214  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
50215
50216  if( !pPager->tempFile && !pPager->pWal ){
50217    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
50218
50219    /* Close any rollback journal previously open */
50220    sqlite3OsClose(pPager->jfd);
50221
50222    rc = pagerOpenWal(pPager);
50223    if( rc==SQLITE_OK ){
50224      pPager->journalMode = PAGER_JOURNALMODE_WAL;
50225      pPager->eState = PAGER_OPEN;
50226    }
50227  }else{
50228    *pbOpen = 1;
50229  }
50230
50231  return rc;
50232}
50233
50234/*
50235** This function is called to close the connection to the log file prior
50236** to switching from WAL to rollback mode.
50237**
50238** Before closing the log file, this function attempts to take an
50239** EXCLUSIVE lock on the database file. If this cannot be obtained, an
50240** error (SQLITE_BUSY) is returned and the log connection is not closed.
50241** If successful, the EXCLUSIVE lock is not released before returning.
50242*/
50243SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
50244  int rc = SQLITE_OK;
50245
50246  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
50247
50248  /* If the log file is not already open, but does exist in the file-system,
50249  ** it may need to be checkpointed before the connection can switch to
50250  ** rollback mode. Open it now so this can happen.
50251  */
50252  if( !pPager->pWal ){
50253    int logexists = 0;
50254    rc = pagerLockDb(pPager, SHARED_LOCK);
50255    if( rc==SQLITE_OK ){
50256      rc = sqlite3OsAccess(
50257          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
50258      );
50259    }
50260    if( rc==SQLITE_OK && logexists ){
50261      rc = pagerOpenWal(pPager);
50262    }
50263  }
50264
50265  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
50266  ** the database file, the log and log-summary files will be deleted.
50267  */
50268  if( rc==SQLITE_OK && pPager->pWal ){
50269    rc = pagerExclusiveLock(pPager);
50270    if( rc==SQLITE_OK ){
50271      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
50272                           pPager->pageSize, (u8*)pPager->pTmpSpace);
50273      pPager->pWal = 0;
50274      pagerFixMaplimit(pPager);
50275    }
50276  }
50277  return rc;
50278}
50279
50280#endif /* !SQLITE_OMIT_WAL */
50281
50282#ifdef SQLITE_ENABLE_ZIPVFS
50283/*
50284** A read-lock must be held on the pager when this function is called. If
50285** the pager is in WAL mode and the WAL file currently contains one or more
50286** frames, return the size in bytes of the page images stored within the
50287** WAL frames. Otherwise, if this is not a WAL database or the WAL file
50288** is empty, return 0.
50289*/
50290SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
50291  assert( pPager->eState>=PAGER_READER );
50292  return sqlite3WalFramesize(pPager->pWal);
50293}
50294#endif
50295
50296
50297#endif /* SQLITE_OMIT_DISKIO */
50298
50299/************** End of pager.c ***********************************************/
50300/************** Begin file wal.c *********************************************/
50301/*
50302** 2010 February 1
50303**
50304** The author disclaims copyright to this source code.  In place of
50305** a legal notice, here is a blessing:
50306**
50307**    May you do good and not evil.
50308**    May you find forgiveness for yourself and forgive others.
50309**    May you share freely, never taking more than you give.
50310**
50311*************************************************************************
50312**
50313** This file contains the implementation of a write-ahead log (WAL) used in
50314** "journal_mode=WAL" mode.
50315**
50316** WRITE-AHEAD LOG (WAL) FILE FORMAT
50317**
50318** A WAL file consists of a header followed by zero or more "frames".
50319** Each frame records the revised content of a single page from the
50320** database file.  All changes to the database are recorded by writing
50321** frames into the WAL.  Transactions commit when a frame is written that
50322** contains a commit marker.  A single WAL can and usually does record
50323** multiple transactions.  Periodically, the content of the WAL is
50324** transferred back into the database file in an operation called a
50325** "checkpoint".
50326**
50327** A single WAL file can be used multiple times.  In other words, the
50328** WAL can fill up with frames and then be checkpointed and then new
50329** frames can overwrite the old ones.  A WAL always grows from beginning
50330** toward the end.  Checksums and counters attached to each frame are
50331** used to determine which frames within the WAL are valid and which
50332** are leftovers from prior checkpoints.
50333**
50334** The WAL header is 32 bytes in size and consists of the following eight
50335** big-endian 32-bit unsigned integer values:
50336**
50337**     0: Magic number.  0x377f0682 or 0x377f0683
50338**     4: File format version.  Currently 3007000
50339**     8: Database page size.  Example: 1024
50340**    12: Checkpoint sequence number
50341**    16: Salt-1, random integer incremented with each checkpoint
50342**    20: Salt-2, a different random integer changing with each ckpt
50343**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
50344**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
50345**
50346** Immediately following the wal-header are zero or more frames. Each
50347** frame consists of a 24-byte frame-header followed by a <page-size> bytes
50348** of page data. The frame-header is six big-endian 32-bit unsigned
50349** integer values, as follows:
50350**
50351**     0: Page number.
50352**     4: For commit records, the size of the database image in pages
50353**        after the commit. For all other records, zero.
50354**     8: Salt-1 (copied from the header)
50355**    12: Salt-2 (copied from the header)
50356**    16: Checksum-1.
50357**    20: Checksum-2.
50358**
50359** A frame is considered valid if and only if the following conditions are
50360** true:
50361**
50362**    (1) The salt-1 and salt-2 values in the frame-header match
50363**        salt values in the wal-header
50364**
50365**    (2) The checksum values in the final 8 bytes of the frame-header
50366**        exactly match the checksum computed consecutively on the
50367**        WAL header and the first 8 bytes and the content of all frames
50368**        up to and including the current frame.
50369**
50370** The checksum is computed using 32-bit big-endian integers if the
50371** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
50372** is computed using little-endian if the magic number is 0x377f0682.
50373** The checksum values are always stored in the frame header in a
50374** big-endian format regardless of which byte order is used to compute
50375** the checksum.  The checksum is computed by interpreting the input as
50376** an even number of unsigned 32-bit integers: x[0] through x[N].  The
50377** algorithm used for the checksum is as follows:
50378**
50379**   for i from 0 to n-1 step 2:
50380**     s0 += x[i] + s1;
50381**     s1 += x[i+1] + s0;
50382**   endfor
50383**
50384** Note that s0 and s1 are both weighted checksums using fibonacci weights
50385** in reverse order (the largest fibonacci weight occurs on the first element
50386** of the sequence being summed.)  The s1 value spans all 32-bit
50387** terms of the sequence whereas s0 omits the final term.
50388**
50389** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
50390** WAL is transferred into the database, then the database is VFS.xSync-ed.
50391** The VFS.xSync operations serve as write barriers - all writes launched
50392** before the xSync must complete before any write that launches after the
50393** xSync begins.
50394**
50395** After each checkpoint, the salt-1 value is incremented and the salt-2
50396** value is randomized.  This prevents old and new frames in the WAL from
50397** being considered valid at the same time and being checkpointing together
50398** following a crash.
50399**
50400** READER ALGORITHM
50401**
50402** To read a page from the database (call it page number P), a reader
50403** first checks the WAL to see if it contains page P.  If so, then the
50404** last valid instance of page P that is a followed by a commit frame
50405** or is a commit frame itself becomes the value read.  If the WAL
50406** contains no copies of page P that are valid and which are a commit
50407** frame or are followed by a commit frame, then page P is read from
50408** the database file.
50409**
50410** To start a read transaction, the reader records the index of the last
50411** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
50412** for all subsequent read operations.  New transactions can be appended
50413** to the WAL, but as long as the reader uses its original mxFrame value
50414** and ignores the newly appended content, it will see a consistent snapshot
50415** of the database from a single point in time.  This technique allows
50416** multiple concurrent readers to view different versions of the database
50417** content simultaneously.
50418**
50419** The reader algorithm in the previous paragraphs works correctly, but
50420** because frames for page P can appear anywhere within the WAL, the
50421** reader has to scan the entire WAL looking for page P frames.  If the
50422** WAL is large (multiple megabytes is typical) that scan can be slow,
50423** and read performance suffers.  To overcome this problem, a separate
50424** data structure called the wal-index is maintained to expedite the
50425** search for frames of a particular page.
50426**
50427** WAL-INDEX FORMAT
50428**
50429** Conceptually, the wal-index is shared memory, though VFS implementations
50430** might choose to implement the wal-index using a mmapped file.  Because
50431** the wal-index is shared memory, SQLite does not support journal_mode=WAL
50432** on a network filesystem.  All users of the database must be able to
50433** share memory.
50434**
50435** The wal-index is transient.  After a crash, the wal-index can (and should
50436** be) reconstructed from the original WAL file.  In fact, the VFS is required
50437** to either truncate or zero the header of the wal-index when the last
50438** connection to it closes.  Because the wal-index is transient, it can
50439** use an architecture-specific format; it does not have to be cross-platform.
50440** Hence, unlike the database and WAL file formats which store all values
50441** as big endian, the wal-index can store multi-byte values in the native
50442** byte order of the host computer.
50443**
50444** The purpose of the wal-index is to answer this question quickly:  Given
50445** a page number P and a maximum frame index M, return the index of the
50446** last frame in the wal before frame M for page P in the WAL, or return
50447** NULL if there are no frames for page P in the WAL prior to M.
50448**
50449** The wal-index consists of a header region, followed by an one or
50450** more index blocks.
50451**
50452** The wal-index header contains the total number of frames within the WAL
50453** in the mxFrame field.
50454**
50455** Each index block except for the first contains information on
50456** HASHTABLE_NPAGE frames. The first index block contains information on
50457** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
50458** HASHTABLE_NPAGE are selected so that together the wal-index header and
50459** first index block are the same size as all other index blocks in the
50460** wal-index.
50461**
50462** Each index block contains two sections, a page-mapping that contains the
50463** database page number associated with each wal frame, and a hash-table
50464** that allows readers to query an index block for a specific page number.
50465** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
50466** for the first index block) 32-bit page numbers. The first entry in the
50467** first index-block contains the database page number corresponding to the
50468** first frame in the WAL file. The first entry in the second index block
50469** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
50470** the log, and so on.
50471**
50472** The last index block in a wal-index usually contains less than the full
50473** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
50474** depending on the contents of the WAL file. This does not change the
50475** allocated size of the page-mapping array - the page-mapping array merely
50476** contains unused entries.
50477**
50478** Even without using the hash table, the last frame for page P
50479** can be found by scanning the page-mapping sections of each index block
50480** starting with the last index block and moving toward the first, and
50481** within each index block, starting at the end and moving toward the
50482** beginning.  The first entry that equals P corresponds to the frame
50483** holding the content for that page.
50484**
50485** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
50486** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
50487** hash table for each page number in the mapping section, so the hash
50488** table is never more than half full.  The expected number of collisions
50489** prior to finding a match is 1.  Each entry of the hash table is an
50490** 1-based index of an entry in the mapping section of the same
50491** index block.   Let K be the 1-based index of the largest entry in
50492** the mapping section.  (For index blocks other than the last, K will
50493** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
50494** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
50495** contain a value of 0.
50496**
50497** To look for page P in the hash table, first compute a hash iKey on
50498** P as follows:
50499**
50500**      iKey = (P * 383) % HASHTABLE_NSLOT
50501**
50502** Then start scanning entries of the hash table, starting with iKey
50503** (wrapping around to the beginning when the end of the hash table is
50504** reached) until an unused hash slot is found. Let the first unused slot
50505** be at index iUnused.  (iUnused might be less than iKey if there was
50506** wrap-around.) Because the hash table is never more than half full,
50507** the search is guaranteed to eventually hit an unused entry.  Let
50508** iMax be the value between iKey and iUnused, closest to iUnused,
50509** where aHash[iMax]==P.  If there is no iMax entry (if there exists
50510** no hash slot such that aHash[i]==p) then page P is not in the
50511** current index block.  Otherwise the iMax-th mapping entry of the
50512** current index block corresponds to the last entry that references
50513** page P.
50514**
50515** A hash search begins with the last index block and moves toward the
50516** first index block, looking for entries corresponding to page P.  On
50517** average, only two or three slots in each index block need to be
50518** examined in order to either find the last entry for page P, or to
50519** establish that no such entry exists in the block.  Each index block
50520** holds over 4000 entries.  So two or three index blocks are sufficient
50521** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
50522** comparisons (on average) suffice to either locate a frame in the
50523** WAL or to establish that the frame does not exist in the WAL.  This
50524** is much faster than scanning the entire 10MB WAL.
50525**
50526** Note that entries are added in order of increasing K.  Hence, one
50527** reader might be using some value K0 and a second reader that started
50528** at a later time (after additional transactions were added to the WAL
50529** and to the wal-index) might be using a different value K1, where K1>K0.
50530** Both readers can use the same hash table and mapping section to get
50531** the correct result.  There may be entries in the hash table with
50532** K>K0 but to the first reader, those entries will appear to be unused
50533** slots in the hash table and so the first reader will get an answer as
50534** if no values greater than K0 had ever been inserted into the hash table
50535** in the first place - which is what reader one wants.  Meanwhile, the
50536** second reader using K1 will see additional values that were inserted
50537** later, which is exactly what reader two wants.
50538**
50539** When a rollback occurs, the value of K is decreased. Hash table entries
50540** that correspond to frames greater than the new K value are removed
50541** from the hash table at this point.
50542*/
50543#ifndef SQLITE_OMIT_WAL
50544
50545/* #include "wal.h" */
50546
50547/*
50548** Trace output macros
50549*/
50550#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
50551SQLITE_PRIVATE int sqlite3WalTrace = 0;
50552# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
50553#else
50554# define WALTRACE(X)
50555#endif
50556
50557/*
50558** The maximum (and only) versions of the wal and wal-index formats
50559** that may be interpreted by this version of SQLite.
50560**
50561** If a client begins recovering a WAL file and finds that (a) the checksum
50562** values in the wal-header are correct and (b) the version field is not
50563** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
50564**
50565** Similarly, if a client successfully reads a wal-index header (i.e. the
50566** checksum test is successful) and finds that the version field is not
50567** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
50568** returns SQLITE_CANTOPEN.
50569*/
50570#define WAL_MAX_VERSION      3007000
50571#define WALINDEX_MAX_VERSION 3007000
50572
50573/*
50574** Indices of various locking bytes.   WAL_NREADER is the number
50575** of available reader locks and should be at least 3.
50576*/
50577#define WAL_WRITE_LOCK         0
50578#define WAL_ALL_BUT_WRITE      1
50579#define WAL_CKPT_LOCK          1
50580#define WAL_RECOVER_LOCK       2
50581#define WAL_READ_LOCK(I)       (3+(I))
50582#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
50583
50584
50585/* Object declarations */
50586typedef struct WalIndexHdr WalIndexHdr;
50587typedef struct WalIterator WalIterator;
50588typedef struct WalCkptInfo WalCkptInfo;
50589
50590
50591/*
50592** The following object holds a copy of the wal-index header content.
50593**
50594** The actual header in the wal-index consists of two copies of this
50595** object.
50596**
50597** The szPage value can be any power of 2 between 512 and 32768, inclusive.
50598** Or it can be 1 to represent a 65536-byte page.  The latter case was
50599** added in 3.7.1 when support for 64K pages was added.
50600*/
50601struct WalIndexHdr {
50602  u32 iVersion;                   /* Wal-index version */
50603  u32 unused;                     /* Unused (padding) field */
50604  u32 iChange;                    /* Counter incremented each transaction */
50605  u8 isInit;                      /* 1 when initialized */
50606  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
50607  u16 szPage;                     /* Database page size in bytes. 1==64K */
50608  u32 mxFrame;                    /* Index of last valid frame in the WAL */
50609  u32 nPage;                      /* Size of database in pages */
50610  u32 aFrameCksum[2];             /* Checksum of last frame in log */
50611  u32 aSalt[2];                   /* Two salt values copied from WAL header */
50612  u32 aCksum[2];                  /* Checksum over all prior fields */
50613};
50614
50615/*
50616** A copy of the following object occurs in the wal-index immediately
50617** following the second copy of the WalIndexHdr.  This object stores
50618** information used by checkpoint.
50619**
50620** nBackfill is the number of frames in the WAL that have been written
50621** back into the database. (We call the act of moving content from WAL to
50622** database "backfilling".)  The nBackfill number is never greater than
50623** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
50624** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
50625** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
50626** mxFrame back to zero when the WAL is reset.
50627**
50628** There is one entry in aReadMark[] for each reader lock.  If a reader
50629** holds read-lock K, then the value in aReadMark[K] is no greater than
50630** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
50631** for any aReadMark[] means that entry is unused.  aReadMark[0] is
50632** a special case; its value is never used and it exists as a place-holder
50633** to avoid having to offset aReadMark[] indexs by one.  Readers holding
50634** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
50635** directly from the database.
50636**
50637** The value of aReadMark[K] may only be changed by a thread that
50638** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
50639** aReadMark[K] cannot changed while there is a reader is using that mark
50640** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
50641**
50642** The checkpointer may only transfer frames from WAL to database where
50643** the frame numbers are less than or equal to every aReadMark[] that is
50644** in use (that is, every aReadMark[j] for which there is a corresponding
50645** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
50646** largest value and will increase an unused aReadMark[] to mxFrame if there
50647** is not already an aReadMark[] equal to mxFrame.  The exception to the
50648** previous sentence is when nBackfill equals mxFrame (meaning that everything
50649** in the WAL has been backfilled into the database) then new readers
50650** will choose aReadMark[0] which has value 0 and hence such reader will
50651** get all their all content directly from the database file and ignore
50652** the WAL.
50653**
50654** Writers normally append new frames to the end of the WAL.  However,
50655** if nBackfill equals mxFrame (meaning that all WAL content has been
50656** written back into the database) and if no readers are using the WAL
50657** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
50658** the writer will first "reset" the WAL back to the beginning and start
50659** writing new content beginning at frame 1.
50660**
50661** We assume that 32-bit loads are atomic and so no locks are needed in
50662** order to read from any aReadMark[] entries.
50663*/
50664struct WalCkptInfo {
50665  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
50666  u32 aReadMark[WAL_NREADER];     /* Reader marks */
50667};
50668#define READMARK_NOT_USED  0xffffffff
50669
50670
50671/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
50672** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
50673** only support mandatory file-locks, we do not read or write data
50674** from the region of the file on which locks are applied.
50675*/
50676#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
50677#define WALINDEX_LOCK_RESERVED 16
50678#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
50679
50680/* Size of header before each frame in wal */
50681#define WAL_FRAME_HDRSIZE 24
50682
50683/* Size of write ahead log header, including checksum. */
50684/* #define WAL_HDRSIZE 24 */
50685#define WAL_HDRSIZE 32
50686
50687/* WAL magic value. Either this value, or the same value with the least
50688** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
50689** big-endian format in the first 4 bytes of a WAL file.
50690**
50691** If the LSB is set, then the checksums for each frame within the WAL
50692** file are calculated by treating all data as an array of 32-bit
50693** big-endian words. Otherwise, they are calculated by interpreting
50694** all data as 32-bit little-endian words.
50695*/
50696#define WAL_MAGIC 0x377f0682
50697
50698/*
50699** Return the offset of frame iFrame in the write-ahead log file,
50700** assuming a database page size of szPage bytes. The offset returned
50701** is to the start of the write-ahead log frame-header.
50702*/
50703#define walFrameOffset(iFrame, szPage) (                               \
50704  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
50705)
50706
50707/*
50708** An open write-ahead log file is represented by an instance of the
50709** following object.
50710*/
50711struct Wal {
50712  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
50713  sqlite3_file *pDbFd;       /* File handle for the database file */
50714  sqlite3_file *pWalFd;      /* File handle for WAL file */
50715  u32 iCallback;             /* Value to pass to log callback (or 0) */
50716  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
50717  int nWiData;               /* Size of array apWiData */
50718  int szFirstBlock;          /* Size of first block written to WAL file */
50719  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
50720  u32 szPage;                /* Database page size */
50721  i16 readLock;              /* Which read lock is being held.  -1 for none */
50722  u8 syncFlags;              /* Flags to use to sync header writes */
50723  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
50724  u8 writeLock;              /* True if in a write transaction */
50725  u8 ckptLock;               /* True if holding a checkpoint lock */
50726  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
50727  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
50728  u8 syncHeader;             /* Fsync the WAL header if true */
50729  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
50730  WalIndexHdr hdr;           /* Wal-index header for current transaction */
50731  u32 minFrame;              /* Ignore wal frames before this one */
50732  const char *zWalName;      /* Name of WAL file */
50733  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
50734#ifdef SQLITE_DEBUG
50735  u8 lockError;              /* True if a locking error has occurred */
50736#endif
50737};
50738
50739/*
50740** Candidate values for Wal.exclusiveMode.
50741*/
50742#define WAL_NORMAL_MODE     0
50743#define WAL_EXCLUSIVE_MODE  1
50744#define WAL_HEAPMEMORY_MODE 2
50745
50746/*
50747** Possible values for WAL.readOnly
50748*/
50749#define WAL_RDWR        0    /* Normal read/write connection */
50750#define WAL_RDONLY      1    /* The WAL file is readonly */
50751#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
50752
50753/*
50754** Each page of the wal-index mapping contains a hash-table made up of
50755** an array of HASHTABLE_NSLOT elements of the following type.
50756*/
50757typedef u16 ht_slot;
50758
50759/*
50760** This structure is used to implement an iterator that loops through
50761** all frames in the WAL in database page order. Where two or more frames
50762** correspond to the same database page, the iterator visits only the
50763** frame most recently written to the WAL (in other words, the frame with
50764** the largest index).
50765**
50766** The internals of this structure are only accessed by:
50767**
50768**   walIteratorInit() - Create a new iterator,
50769**   walIteratorNext() - Step an iterator,
50770**   walIteratorFree() - Free an iterator.
50771**
50772** This functionality is used by the checkpoint code (see walCheckpoint()).
50773*/
50774struct WalIterator {
50775  int iPrior;                     /* Last result returned from the iterator */
50776  int nSegment;                   /* Number of entries in aSegment[] */
50777  struct WalSegment {
50778    int iNext;                    /* Next slot in aIndex[] not yet returned */
50779    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
50780    u32 *aPgno;                   /* Array of page numbers. */
50781    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
50782    int iZero;                    /* Frame number associated with aPgno[0] */
50783  } aSegment[1];                  /* One for every 32KB page in the wal-index */
50784};
50785
50786/*
50787** Define the parameters of the hash tables in the wal-index file. There
50788** is a hash-table following every HASHTABLE_NPAGE page numbers in the
50789** wal-index.
50790**
50791** Changing any of these constants will alter the wal-index format and
50792** create incompatibilities.
50793*/
50794#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
50795#define HASHTABLE_HASH_1     383                  /* Should be prime */
50796#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
50797
50798/*
50799** The block of page numbers associated with the first hash-table in a
50800** wal-index is smaller than usual. This is so that there is a complete
50801** hash-table on each aligned 32KB page of the wal-index.
50802*/
50803#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
50804
50805/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
50806#define WALINDEX_PGSZ   (                                         \
50807    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
50808)
50809
50810/*
50811** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
50812** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
50813** numbered from zero.
50814**
50815** If this call is successful, *ppPage is set to point to the wal-index
50816** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
50817** then an SQLite error code is returned and *ppPage is set to 0.
50818*/
50819static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
50820  int rc = SQLITE_OK;
50821
50822  /* Enlarge the pWal->apWiData[] array if required */
50823  if( pWal->nWiData<=iPage ){
50824    int nByte = sizeof(u32*)*(iPage+1);
50825    volatile u32 **apNew;
50826    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
50827    if( !apNew ){
50828      *ppPage = 0;
50829      return SQLITE_NOMEM;
50830    }
50831    memset((void*)&apNew[pWal->nWiData], 0,
50832           sizeof(u32*)*(iPage+1-pWal->nWiData));
50833    pWal->apWiData = apNew;
50834    pWal->nWiData = iPage+1;
50835  }
50836
50837  /* Request a pointer to the required page from the VFS */
50838  if( pWal->apWiData[iPage]==0 ){
50839    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
50840      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
50841      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
50842    }else{
50843      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
50844          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
50845      );
50846      if( rc==SQLITE_READONLY ){
50847        pWal->readOnly |= WAL_SHM_RDONLY;
50848        rc = SQLITE_OK;
50849      }
50850    }
50851  }
50852
50853  *ppPage = pWal->apWiData[iPage];
50854  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
50855  return rc;
50856}
50857
50858/*
50859** Return a pointer to the WalCkptInfo structure in the wal-index.
50860*/
50861static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
50862  assert( pWal->nWiData>0 && pWal->apWiData[0] );
50863  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
50864}
50865
50866/*
50867** Return a pointer to the WalIndexHdr structure in the wal-index.
50868*/
50869static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
50870  assert( pWal->nWiData>0 && pWal->apWiData[0] );
50871  return (volatile WalIndexHdr*)pWal->apWiData[0];
50872}
50873
50874/*
50875** The argument to this macro must be of type u32. On a little-endian
50876** architecture, it returns the u32 value that results from interpreting
50877** the 4 bytes as a big-endian value. On a big-endian architecture, it
50878** returns the value that would be produced by interpreting the 4 bytes
50879** of the input value as a little-endian integer.
50880*/
50881#define BYTESWAP32(x) ( \
50882    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
50883  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
50884)
50885
50886/*
50887** Generate or extend an 8 byte checksum based on the data in
50888** array aByte[] and the initial values of aIn[0] and aIn[1] (or
50889** initial values of 0 and 0 if aIn==NULL).
50890**
50891** The checksum is written back into aOut[] before returning.
50892**
50893** nByte must be a positive multiple of 8.
50894*/
50895static void walChecksumBytes(
50896  int nativeCksum, /* True for native byte-order, false for non-native */
50897  u8 *a,           /* Content to be checksummed */
50898  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
50899  const u32 *aIn,  /* Initial checksum value input */
50900  u32 *aOut        /* OUT: Final checksum value output */
50901){
50902  u32 s1, s2;
50903  u32 *aData = (u32 *)a;
50904  u32 *aEnd = (u32 *)&a[nByte];
50905
50906  if( aIn ){
50907    s1 = aIn[0];
50908    s2 = aIn[1];
50909  }else{
50910    s1 = s2 = 0;
50911  }
50912
50913  assert( nByte>=8 );
50914  assert( (nByte&0x00000007)==0 );
50915
50916  if( nativeCksum ){
50917    do {
50918      s1 += *aData++ + s2;
50919      s2 += *aData++ + s1;
50920    }while( aData<aEnd );
50921  }else{
50922    do {
50923      s1 += BYTESWAP32(aData[0]) + s2;
50924      s2 += BYTESWAP32(aData[1]) + s1;
50925      aData += 2;
50926    }while( aData<aEnd );
50927  }
50928
50929  aOut[0] = s1;
50930  aOut[1] = s2;
50931}
50932
50933static void walShmBarrier(Wal *pWal){
50934  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
50935    sqlite3OsShmBarrier(pWal->pDbFd);
50936  }
50937}
50938
50939/*
50940** Write the header information in pWal->hdr into the wal-index.
50941**
50942** The checksum on pWal->hdr is updated before it is written.
50943*/
50944static void walIndexWriteHdr(Wal *pWal){
50945  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
50946  const int nCksum = offsetof(WalIndexHdr, aCksum);
50947
50948  assert( pWal->writeLock );
50949  pWal->hdr.isInit = 1;
50950  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
50951  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
50952  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
50953  walShmBarrier(pWal);
50954  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
50955}
50956
50957/*
50958** This function encodes a single frame header and writes it to a buffer
50959** supplied by the caller. A frame-header is made up of a series of
50960** 4-byte big-endian integers, as follows:
50961**
50962**     0: Page number.
50963**     4: For commit records, the size of the database image in pages
50964**        after the commit. For all other records, zero.
50965**     8: Salt-1 (copied from the wal-header)
50966**    12: Salt-2 (copied from the wal-header)
50967**    16: Checksum-1.
50968**    20: Checksum-2.
50969*/
50970static void walEncodeFrame(
50971  Wal *pWal,                      /* The write-ahead log */
50972  u32 iPage,                      /* Database page number for frame */
50973  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
50974  u8 *aData,                      /* Pointer to page data */
50975  u8 *aFrame                      /* OUT: Write encoded frame here */
50976){
50977  int nativeCksum;                /* True for native byte-order checksums */
50978  u32 *aCksum = pWal->hdr.aFrameCksum;
50979  assert( WAL_FRAME_HDRSIZE==24 );
50980  sqlite3Put4byte(&aFrame[0], iPage);
50981  sqlite3Put4byte(&aFrame[4], nTruncate);
50982  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
50983
50984  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
50985  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
50986  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
50987
50988  sqlite3Put4byte(&aFrame[16], aCksum[0]);
50989  sqlite3Put4byte(&aFrame[20], aCksum[1]);
50990}
50991
50992/*
50993** Check to see if the frame with header in aFrame[] and content
50994** in aData[] is valid.  If it is a valid frame, fill *piPage and
50995** *pnTruncate and return true.  Return if the frame is not valid.
50996*/
50997static int walDecodeFrame(
50998  Wal *pWal,                      /* The write-ahead log */
50999  u32 *piPage,                    /* OUT: Database page number for frame */
51000  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
51001  u8 *aData,                      /* Pointer to page data (for checksum) */
51002  u8 *aFrame                      /* Frame data */
51003){
51004  int nativeCksum;                /* True for native byte-order checksums */
51005  u32 *aCksum = pWal->hdr.aFrameCksum;
51006  u32 pgno;                       /* Page number of the frame */
51007  assert( WAL_FRAME_HDRSIZE==24 );
51008
51009  /* A frame is only valid if the salt values in the frame-header
51010  ** match the salt values in the wal-header.
51011  */
51012  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
51013    return 0;
51014  }
51015
51016  /* A frame is only valid if the page number is creater than zero.
51017  */
51018  pgno = sqlite3Get4byte(&aFrame[0]);
51019  if( pgno==0 ){
51020    return 0;
51021  }
51022
51023  /* A frame is only valid if a checksum of the WAL header,
51024  ** all prior frams, the first 16 bytes of this frame-header,
51025  ** and the frame-data matches the checksum in the last 8
51026  ** bytes of this frame-header.
51027  */
51028  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
51029  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
51030  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
51031  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
51032   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
51033  ){
51034    /* Checksum failed. */
51035    return 0;
51036  }
51037
51038  /* If we reach this point, the frame is valid.  Return the page number
51039  ** and the new database size.
51040  */
51041  *piPage = pgno;
51042  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
51043  return 1;
51044}
51045
51046
51047#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
51048/*
51049** Names of locks.  This routine is used to provide debugging output and is not
51050** a part of an ordinary build.
51051*/
51052static const char *walLockName(int lockIdx){
51053  if( lockIdx==WAL_WRITE_LOCK ){
51054    return "WRITE-LOCK";
51055  }else if( lockIdx==WAL_CKPT_LOCK ){
51056    return "CKPT-LOCK";
51057  }else if( lockIdx==WAL_RECOVER_LOCK ){
51058    return "RECOVER-LOCK";
51059  }else{
51060    static char zName[15];
51061    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
51062                     lockIdx-WAL_READ_LOCK(0));
51063    return zName;
51064  }
51065}
51066#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
51067
51068
51069/*
51070** Set or release locks on the WAL.  Locks are either shared or exclusive.
51071** A lock cannot be moved directly between shared and exclusive - it must go
51072** through the unlocked state first.
51073**
51074** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
51075*/
51076static int walLockShared(Wal *pWal, int lockIdx){
51077  int rc;
51078  if( pWal->exclusiveMode ) return SQLITE_OK;
51079  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
51080                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
51081  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
51082            walLockName(lockIdx), rc ? "failed" : "ok"));
51083  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
51084  return rc;
51085}
51086static void walUnlockShared(Wal *pWal, int lockIdx){
51087  if( pWal->exclusiveMode ) return;
51088  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
51089                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
51090  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
51091}
51092static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
51093  int rc;
51094  if( pWal->exclusiveMode ) return SQLITE_OK;
51095  if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
51096  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
51097                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
51098  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
51099            walLockName(lockIdx), n, rc ? "failed" : "ok"));
51100  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
51101  return rc;
51102}
51103static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
51104  if( pWal->exclusiveMode ) return;
51105  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
51106                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
51107  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
51108             walLockName(lockIdx), n));
51109}
51110
51111/*
51112** Compute a hash on a page number.  The resulting hash value must land
51113** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
51114** the hash to the next value in the event of a collision.
51115*/
51116static int walHash(u32 iPage){
51117  assert( iPage>0 );
51118  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
51119  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
51120}
51121static int walNextHash(int iPriorHash){
51122  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
51123}
51124
51125/*
51126** Return pointers to the hash table and page number array stored on
51127** page iHash of the wal-index. The wal-index is broken into 32KB pages
51128** numbered starting from 0.
51129**
51130** Set output variable *paHash to point to the start of the hash table
51131** in the wal-index file. Set *piZero to one less than the frame
51132** number of the first frame indexed by this hash table. If a
51133** slot in the hash table is set to N, it refers to frame number
51134** (*piZero+N) in the log.
51135**
51136** Finally, set *paPgno so that *paPgno[1] is the page number of the
51137** first frame indexed by the hash table, frame (*piZero+1).
51138*/
51139static int walHashGet(
51140  Wal *pWal,                      /* WAL handle */
51141  int iHash,                      /* Find the iHash'th table */
51142  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
51143  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
51144  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
51145){
51146  int rc;                         /* Return code */
51147  volatile u32 *aPgno;
51148
51149  rc = walIndexPage(pWal, iHash, &aPgno);
51150  assert( rc==SQLITE_OK || iHash>0 );
51151
51152  if( rc==SQLITE_OK ){
51153    u32 iZero;
51154    volatile ht_slot *aHash;
51155
51156    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
51157    if( iHash==0 ){
51158      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
51159      iZero = 0;
51160    }else{
51161      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
51162    }
51163
51164    *paPgno = &aPgno[-1];
51165    *paHash = aHash;
51166    *piZero = iZero;
51167  }
51168  return rc;
51169}
51170
51171/*
51172** Return the number of the wal-index page that contains the hash-table
51173** and page-number array that contain entries corresponding to WAL frame
51174** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
51175** are numbered starting from 0.
51176*/
51177static int walFramePage(u32 iFrame){
51178  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
51179  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
51180       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
51181       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
51182       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
51183       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
51184  );
51185  return iHash;
51186}
51187
51188/*
51189** Return the page number associated with frame iFrame in this WAL.
51190*/
51191static u32 walFramePgno(Wal *pWal, u32 iFrame){
51192  int iHash = walFramePage(iFrame);
51193  if( iHash==0 ){
51194    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
51195  }
51196  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
51197}
51198
51199/*
51200** Remove entries from the hash table that point to WAL slots greater
51201** than pWal->hdr.mxFrame.
51202**
51203** This function is called whenever pWal->hdr.mxFrame is decreased due
51204** to a rollback or savepoint.
51205**
51206** At most only the hash table containing pWal->hdr.mxFrame needs to be
51207** updated.  Any later hash tables will be automatically cleared when
51208** pWal->hdr.mxFrame advances to the point where those hash tables are
51209** actually needed.
51210*/
51211static void walCleanupHash(Wal *pWal){
51212  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
51213  volatile u32 *aPgno = 0;        /* Page number array for hash table */
51214  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
51215  int iLimit = 0;                 /* Zero values greater than this */
51216  int nByte;                      /* Number of bytes to zero in aPgno[] */
51217  int i;                          /* Used to iterate through aHash[] */
51218
51219  assert( pWal->writeLock );
51220  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
51221  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
51222  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
51223
51224  if( pWal->hdr.mxFrame==0 ) return;
51225
51226  /* Obtain pointers to the hash-table and page-number array containing
51227  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
51228  ** that the page said hash-table and array reside on is already mapped.
51229  */
51230  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
51231  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
51232  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
51233
51234  /* Zero all hash-table entries that correspond to frame numbers greater
51235  ** than pWal->hdr.mxFrame.
51236  */
51237  iLimit = pWal->hdr.mxFrame - iZero;
51238  assert( iLimit>0 );
51239  for(i=0; i<HASHTABLE_NSLOT; i++){
51240    if( aHash[i]>iLimit ){
51241      aHash[i] = 0;
51242    }
51243  }
51244
51245  /* Zero the entries in the aPgno array that correspond to frames with
51246  ** frame numbers greater than pWal->hdr.mxFrame.
51247  */
51248  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
51249  memset((void *)&aPgno[iLimit+1], 0, nByte);
51250
51251#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51252  /* Verify that the every entry in the mapping region is still reachable
51253  ** via the hash table even after the cleanup.
51254  */
51255  if( iLimit ){
51256    int j;           /* Loop counter */
51257    int iKey;        /* Hash key */
51258    for(j=1; j<=iLimit; j++){
51259      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
51260        if( aHash[iKey]==j ) break;
51261      }
51262      assert( aHash[iKey]==j );
51263    }
51264  }
51265#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
51266}
51267
51268
51269/*
51270** Set an entry in the wal-index that will map database page number
51271** pPage into WAL frame iFrame.
51272*/
51273static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
51274  int rc;                         /* Return code */
51275  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
51276  volatile u32 *aPgno = 0;        /* Page number array */
51277  volatile ht_slot *aHash = 0;    /* Hash table */
51278
51279  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
51280
51281  /* Assuming the wal-index file was successfully mapped, populate the
51282  ** page number array and hash table entry.
51283  */
51284  if( rc==SQLITE_OK ){
51285    int iKey;                     /* Hash table key */
51286    int idx;                      /* Value to write to hash-table slot */
51287    int nCollide;                 /* Number of hash collisions */
51288
51289    idx = iFrame - iZero;
51290    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
51291
51292    /* If this is the first entry to be added to this hash-table, zero the
51293    ** entire hash table and aPgno[] array before proceeding.
51294    */
51295    if( idx==1 ){
51296      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
51297      memset((void*)&aPgno[1], 0, nByte);
51298    }
51299
51300    /* If the entry in aPgno[] is already set, then the previous writer
51301    ** must have exited unexpectedly in the middle of a transaction (after
51302    ** writing one or more dirty pages to the WAL to free up memory).
51303    ** Remove the remnants of that writers uncommitted transaction from
51304    ** the hash-table before writing any new entries.
51305    */
51306    if( aPgno[idx] ){
51307      walCleanupHash(pWal);
51308      assert( !aPgno[idx] );
51309    }
51310
51311    /* Write the aPgno[] array entry and the hash-table slot. */
51312    nCollide = idx;
51313    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
51314      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
51315    }
51316    aPgno[idx] = iPage;
51317    aHash[iKey] = (ht_slot)idx;
51318
51319#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51320    /* Verify that the number of entries in the hash table exactly equals
51321    ** the number of entries in the mapping region.
51322    */
51323    {
51324      int i;           /* Loop counter */
51325      int nEntry = 0;  /* Number of entries in the hash table */
51326      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
51327      assert( nEntry==idx );
51328    }
51329
51330    /* Verify that the every entry in the mapping region is reachable
51331    ** via the hash table.  This turns out to be a really, really expensive
51332    ** thing to check, so only do this occasionally - not on every
51333    ** iteration.
51334    */
51335    if( (idx&0x3ff)==0 ){
51336      int i;           /* Loop counter */
51337      for(i=1; i<=idx; i++){
51338        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
51339          if( aHash[iKey]==i ) break;
51340        }
51341        assert( aHash[iKey]==i );
51342      }
51343    }
51344#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
51345  }
51346
51347
51348  return rc;
51349}
51350
51351
51352/*
51353** Recover the wal-index by reading the write-ahead log file.
51354**
51355** This routine first tries to establish an exclusive lock on the
51356** wal-index to prevent other threads/processes from doing anything
51357** with the WAL or wal-index while recovery is running.  The
51358** WAL_RECOVER_LOCK is also held so that other threads will know
51359** that this thread is running recovery.  If unable to establish
51360** the necessary locks, this routine returns SQLITE_BUSY.
51361*/
51362static int walIndexRecover(Wal *pWal){
51363  int rc;                         /* Return Code */
51364  i64 nSize;                      /* Size of log file */
51365  u32 aFrameCksum[2] = {0, 0};
51366  int iLock;                      /* Lock offset to lock for checkpoint */
51367  int nLock;                      /* Number of locks to hold */
51368
51369  /* Obtain an exclusive lock on all byte in the locking range not already
51370  ** locked by the caller. The caller is guaranteed to have locked the
51371  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
51372  ** If successful, the same bytes that are locked here are unlocked before
51373  ** this function returns.
51374  */
51375  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
51376  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
51377  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
51378  assert( pWal->writeLock );
51379  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
51380  nLock = SQLITE_SHM_NLOCK - iLock;
51381  rc = walLockExclusive(pWal, iLock, nLock, 0);
51382  if( rc ){
51383    return rc;
51384  }
51385  WALTRACE(("WAL%p: recovery begin...\n", pWal));
51386
51387  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51388
51389  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
51390  if( rc!=SQLITE_OK ){
51391    goto recovery_error;
51392  }
51393
51394  if( nSize>WAL_HDRSIZE ){
51395    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
51396    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
51397    int szFrame;                  /* Number of bytes in buffer aFrame[] */
51398    u8 *aData;                    /* Pointer to data part of aFrame buffer */
51399    int iFrame;                   /* Index of last frame read */
51400    i64 iOffset;                  /* Next offset to read from log file */
51401    int szPage;                   /* Page size according to the log */
51402    u32 magic;                    /* Magic value read from WAL header */
51403    u32 version;                  /* Magic value read from WAL header */
51404    int isValid;                  /* True if this frame is valid */
51405
51406    /* Read in the WAL header. */
51407    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
51408    if( rc!=SQLITE_OK ){
51409      goto recovery_error;
51410    }
51411
51412    /* If the database page size is not a power of two, or is greater than
51413    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
51414    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
51415    ** WAL file.
51416    */
51417    magic = sqlite3Get4byte(&aBuf[0]);
51418    szPage = sqlite3Get4byte(&aBuf[8]);
51419    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
51420     || szPage&(szPage-1)
51421     || szPage>SQLITE_MAX_PAGE_SIZE
51422     || szPage<512
51423    ){
51424      goto finished;
51425    }
51426    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
51427    pWal->szPage = szPage;
51428    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
51429    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
51430
51431    /* Verify that the WAL header checksum is correct */
51432    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
51433        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
51434    );
51435    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
51436     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
51437    ){
51438      goto finished;
51439    }
51440
51441    /* Verify that the version number on the WAL format is one that
51442    ** are able to understand */
51443    version = sqlite3Get4byte(&aBuf[4]);
51444    if( version!=WAL_MAX_VERSION ){
51445      rc = SQLITE_CANTOPEN_BKPT;
51446      goto finished;
51447    }
51448
51449    /* Malloc a buffer to read frames into. */
51450    szFrame = szPage + WAL_FRAME_HDRSIZE;
51451    aFrame = (u8 *)sqlite3_malloc64(szFrame);
51452    if( !aFrame ){
51453      rc = SQLITE_NOMEM;
51454      goto recovery_error;
51455    }
51456    aData = &aFrame[WAL_FRAME_HDRSIZE];
51457
51458    /* Read all frames from the log file. */
51459    iFrame = 0;
51460    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
51461      u32 pgno;                   /* Database page number for frame */
51462      u32 nTruncate;              /* dbsize field from frame header */
51463
51464      /* Read and decode the next log frame. */
51465      iFrame++;
51466      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
51467      if( rc!=SQLITE_OK ) break;
51468      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
51469      if( !isValid ) break;
51470      rc = walIndexAppend(pWal, iFrame, pgno);
51471      if( rc!=SQLITE_OK ) break;
51472
51473      /* If nTruncate is non-zero, this is a commit record. */
51474      if( nTruncate ){
51475        pWal->hdr.mxFrame = iFrame;
51476        pWal->hdr.nPage = nTruncate;
51477        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51478        testcase( szPage<=32768 );
51479        testcase( szPage>=65536 );
51480        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
51481        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
51482      }
51483    }
51484
51485    sqlite3_free(aFrame);
51486  }
51487
51488finished:
51489  if( rc==SQLITE_OK ){
51490    volatile WalCkptInfo *pInfo;
51491    int i;
51492    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
51493    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
51494    walIndexWriteHdr(pWal);
51495
51496    /* Reset the checkpoint-header. This is safe because this thread is
51497    ** currently holding locks that exclude all other readers, writers and
51498    ** checkpointers.
51499    */
51500    pInfo = walCkptInfo(pWal);
51501    pInfo->nBackfill = 0;
51502    pInfo->aReadMark[0] = 0;
51503    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
51504    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
51505
51506    /* If more than one frame was recovered from the log file, report an
51507    ** event via sqlite3_log(). This is to help with identifying performance
51508    ** problems caused by applications routinely shutting down without
51509    ** checkpointing the log file.
51510    */
51511    if( pWal->hdr.nPage ){
51512      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
51513          "recovered %d frames from WAL file %s",
51514          pWal->hdr.mxFrame, pWal->zWalName
51515      );
51516    }
51517  }
51518
51519recovery_error:
51520  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
51521  walUnlockExclusive(pWal, iLock, nLock);
51522  return rc;
51523}
51524
51525/*
51526** Close an open wal-index.
51527*/
51528static void walIndexClose(Wal *pWal, int isDelete){
51529  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
51530    int i;
51531    for(i=0; i<pWal->nWiData; i++){
51532      sqlite3_free((void *)pWal->apWiData[i]);
51533      pWal->apWiData[i] = 0;
51534    }
51535  }else{
51536    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
51537  }
51538}
51539
51540/*
51541** Open a connection to the WAL file zWalName. The database file must
51542** already be opened on connection pDbFd. The buffer that zWalName points
51543** to must remain valid for the lifetime of the returned Wal* handle.
51544**
51545** A SHARED lock should be held on the database file when this function
51546** is called. The purpose of this SHARED lock is to prevent any other
51547** client from unlinking the WAL or wal-index file. If another process
51548** were to do this just after this client opened one of these files, the
51549** system would be badly broken.
51550**
51551** If the log file is successfully opened, SQLITE_OK is returned and
51552** *ppWal is set to point to a new WAL handle. If an error occurs,
51553** an SQLite error code is returned and *ppWal is left unmodified.
51554*/
51555SQLITE_PRIVATE int sqlite3WalOpen(
51556  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
51557  sqlite3_file *pDbFd,            /* The open database file */
51558  const char *zWalName,           /* Name of the WAL file */
51559  int bNoShm,                     /* True to run in heap-memory mode */
51560  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
51561  Wal **ppWal                     /* OUT: Allocated Wal handle */
51562){
51563  int rc;                         /* Return Code */
51564  Wal *pRet;                      /* Object to allocate and return */
51565  int flags;                      /* Flags passed to OsOpen() */
51566
51567  assert( zWalName && zWalName[0] );
51568  assert( pDbFd );
51569
51570  /* In the amalgamation, the os_unix.c and os_win.c source files come before
51571  ** this source file.  Verify that the #defines of the locking byte offsets
51572  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
51573  */
51574#ifdef WIN_SHM_BASE
51575  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
51576#endif
51577#ifdef UNIX_SHM_BASE
51578  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
51579#endif
51580
51581
51582  /* Allocate an instance of struct Wal to return. */
51583  *ppWal = 0;
51584  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
51585  if( !pRet ){
51586    return SQLITE_NOMEM;
51587  }
51588
51589  pRet->pVfs = pVfs;
51590  pRet->pWalFd = (sqlite3_file *)&pRet[1];
51591  pRet->pDbFd = pDbFd;
51592  pRet->readLock = -1;
51593  pRet->mxWalSize = mxWalSize;
51594  pRet->zWalName = zWalName;
51595  pRet->syncHeader = 1;
51596  pRet->padToSectorBoundary = 1;
51597  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
51598
51599  /* Open file handle on the write-ahead log file. */
51600  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
51601  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
51602  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
51603    pRet->readOnly = WAL_RDONLY;
51604  }
51605
51606  if( rc!=SQLITE_OK ){
51607    walIndexClose(pRet, 0);
51608    sqlite3OsClose(pRet->pWalFd);
51609    sqlite3_free(pRet);
51610  }else{
51611    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
51612    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
51613    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
51614      pRet->padToSectorBoundary = 0;
51615    }
51616    *ppWal = pRet;
51617    WALTRACE(("WAL%d: opened\n", pRet));
51618  }
51619  return rc;
51620}
51621
51622/*
51623** Change the size to which the WAL file is trucated on each reset.
51624*/
51625SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
51626  if( pWal ) pWal->mxWalSize = iLimit;
51627}
51628
51629/*
51630** Find the smallest page number out of all pages held in the WAL that
51631** has not been returned by any prior invocation of this method on the
51632** same WalIterator object.   Write into *piFrame the frame index where
51633** that page was last written into the WAL.  Write into *piPage the page
51634** number.
51635**
51636** Return 0 on success.  If there are no pages in the WAL with a page
51637** number larger than *piPage, then return 1.
51638*/
51639static int walIteratorNext(
51640  WalIterator *p,               /* Iterator */
51641  u32 *piPage,                  /* OUT: The page number of the next page */
51642  u32 *piFrame                  /* OUT: Wal frame index of next page */
51643){
51644  u32 iMin;                     /* Result pgno must be greater than iMin */
51645  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
51646  int i;                        /* For looping through segments */
51647
51648  iMin = p->iPrior;
51649  assert( iMin<0xffffffff );
51650  for(i=p->nSegment-1; i>=0; i--){
51651    struct WalSegment *pSegment = &p->aSegment[i];
51652    while( pSegment->iNext<pSegment->nEntry ){
51653      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
51654      if( iPg>iMin ){
51655        if( iPg<iRet ){
51656          iRet = iPg;
51657          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
51658        }
51659        break;
51660      }
51661      pSegment->iNext++;
51662    }
51663  }
51664
51665  *piPage = p->iPrior = iRet;
51666  return (iRet==0xFFFFFFFF);
51667}
51668
51669/*
51670** This function merges two sorted lists into a single sorted list.
51671**
51672** aLeft[] and aRight[] are arrays of indices.  The sort key is
51673** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
51674** is guaranteed for all J<K:
51675**
51676**        aContent[aLeft[J]] < aContent[aLeft[K]]
51677**        aContent[aRight[J]] < aContent[aRight[K]]
51678**
51679** This routine overwrites aRight[] with a new (probably longer) sequence
51680** of indices such that the aRight[] contains every index that appears in
51681** either aLeft[] or the old aRight[] and such that the second condition
51682** above is still met.
51683**
51684** The aContent[aLeft[X]] values will be unique for all X.  And the
51685** aContent[aRight[X]] values will be unique too.  But there might be
51686** one or more combinations of X and Y such that
51687**
51688**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
51689**
51690** When that happens, omit the aLeft[X] and use the aRight[Y] index.
51691*/
51692static void walMerge(
51693  const u32 *aContent,            /* Pages in wal - keys for the sort */
51694  ht_slot *aLeft,                 /* IN: Left hand input list */
51695  int nLeft,                      /* IN: Elements in array *paLeft */
51696  ht_slot **paRight,              /* IN/OUT: Right hand input list */
51697  int *pnRight,                   /* IN/OUT: Elements in *paRight */
51698  ht_slot *aTmp                   /* Temporary buffer */
51699){
51700  int iLeft = 0;                  /* Current index in aLeft */
51701  int iRight = 0;                 /* Current index in aRight */
51702  int iOut = 0;                   /* Current index in output buffer */
51703  int nRight = *pnRight;
51704  ht_slot *aRight = *paRight;
51705
51706  assert( nLeft>0 && nRight>0 );
51707  while( iRight<nRight || iLeft<nLeft ){
51708    ht_slot logpage;
51709    Pgno dbpage;
51710
51711    if( (iLeft<nLeft)
51712     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
51713    ){
51714      logpage = aLeft[iLeft++];
51715    }else{
51716      logpage = aRight[iRight++];
51717    }
51718    dbpage = aContent[logpage];
51719
51720    aTmp[iOut++] = logpage;
51721    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
51722
51723    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
51724    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
51725  }
51726
51727  *paRight = aLeft;
51728  *pnRight = iOut;
51729  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
51730}
51731
51732/*
51733** Sort the elements in list aList using aContent[] as the sort key.
51734** Remove elements with duplicate keys, preferring to keep the
51735** larger aList[] values.
51736**
51737** The aList[] entries are indices into aContent[].  The values in
51738** aList[] are to be sorted so that for all J<K:
51739**
51740**      aContent[aList[J]] < aContent[aList[K]]
51741**
51742** For any X and Y such that
51743**
51744**      aContent[aList[X]] == aContent[aList[Y]]
51745**
51746** Keep the larger of the two values aList[X] and aList[Y] and discard
51747** the smaller.
51748*/
51749static void walMergesort(
51750  const u32 *aContent,            /* Pages in wal */
51751  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
51752  ht_slot *aList,                 /* IN/OUT: List to sort */
51753  int *pnList                     /* IN/OUT: Number of elements in aList[] */
51754){
51755  struct Sublist {
51756    int nList;                    /* Number of elements in aList */
51757    ht_slot *aList;               /* Pointer to sub-list content */
51758  };
51759
51760  const int nList = *pnList;      /* Size of input list */
51761  int nMerge = 0;                 /* Number of elements in list aMerge */
51762  ht_slot *aMerge = 0;            /* List to be merged */
51763  int iList;                      /* Index into input list */
51764  u32 iSub = 0;                   /* Index into aSub array */
51765  struct Sublist aSub[13];        /* Array of sub-lists */
51766
51767  memset(aSub, 0, sizeof(aSub));
51768  assert( nList<=HASHTABLE_NPAGE && nList>0 );
51769  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
51770
51771  for(iList=0; iList<nList; iList++){
51772    nMerge = 1;
51773    aMerge = &aList[iList];
51774    for(iSub=0; iList & (1<<iSub); iSub++){
51775      struct Sublist *p;
51776      assert( iSub<ArraySize(aSub) );
51777      p = &aSub[iSub];
51778      assert( p->aList && p->nList<=(1<<iSub) );
51779      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
51780      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
51781    }
51782    aSub[iSub].aList = aMerge;
51783    aSub[iSub].nList = nMerge;
51784  }
51785
51786  for(iSub++; iSub<ArraySize(aSub); iSub++){
51787    if( nList & (1<<iSub) ){
51788      struct Sublist *p;
51789      assert( iSub<ArraySize(aSub) );
51790      p = &aSub[iSub];
51791      assert( p->nList<=(1<<iSub) );
51792      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
51793      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
51794    }
51795  }
51796  assert( aMerge==aList );
51797  *pnList = nMerge;
51798
51799#ifdef SQLITE_DEBUG
51800  {
51801    int i;
51802    for(i=1; i<*pnList; i++){
51803      assert( aContent[aList[i]] > aContent[aList[i-1]] );
51804    }
51805  }
51806#endif
51807}
51808
51809/*
51810** Free an iterator allocated by walIteratorInit().
51811*/
51812static void walIteratorFree(WalIterator *p){
51813  sqlite3_free(p);
51814}
51815
51816/*
51817** Construct a WalInterator object that can be used to loop over all
51818** pages in the WAL in ascending order. The caller must hold the checkpoint
51819** lock.
51820**
51821** On success, make *pp point to the newly allocated WalInterator object
51822** return SQLITE_OK. Otherwise, return an error code. If this routine
51823** returns an error, the value of *pp is undefined.
51824**
51825** The calling routine should invoke walIteratorFree() to destroy the
51826** WalIterator object when it has finished with it.
51827*/
51828static int walIteratorInit(Wal *pWal, WalIterator **pp){
51829  WalIterator *p;                 /* Return value */
51830  int nSegment;                   /* Number of segments to merge */
51831  u32 iLast;                      /* Last frame in log */
51832  int nByte;                      /* Number of bytes to allocate */
51833  int i;                          /* Iterator variable */
51834  ht_slot *aTmp;                  /* Temp space used by merge-sort */
51835  int rc = SQLITE_OK;             /* Return Code */
51836
51837  /* This routine only runs while holding the checkpoint lock. And
51838  ** it only runs if there is actually content in the log (mxFrame>0).
51839  */
51840  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
51841  iLast = pWal->hdr.mxFrame;
51842
51843  /* Allocate space for the WalIterator object. */
51844  nSegment = walFramePage(iLast) + 1;
51845  nByte = sizeof(WalIterator)
51846        + (nSegment-1)*sizeof(struct WalSegment)
51847        + iLast*sizeof(ht_slot);
51848  p = (WalIterator *)sqlite3_malloc64(nByte);
51849  if( !p ){
51850    return SQLITE_NOMEM;
51851  }
51852  memset(p, 0, nByte);
51853  p->nSegment = nSegment;
51854
51855  /* Allocate temporary space used by the merge-sort routine. This block
51856  ** of memory will be freed before this function returns.
51857  */
51858  aTmp = (ht_slot *)sqlite3_malloc64(
51859      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
51860  );
51861  if( !aTmp ){
51862    rc = SQLITE_NOMEM;
51863  }
51864
51865  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
51866    volatile ht_slot *aHash;
51867    u32 iZero;
51868    volatile u32 *aPgno;
51869
51870    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
51871    if( rc==SQLITE_OK ){
51872      int j;                      /* Counter variable */
51873      int nEntry;                 /* Number of entries in this segment */
51874      ht_slot *aIndex;            /* Sorted index for this segment */
51875
51876      aPgno++;
51877      if( (i+1)==nSegment ){
51878        nEntry = (int)(iLast - iZero);
51879      }else{
51880        nEntry = (int)((u32*)aHash - (u32*)aPgno);
51881      }
51882      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
51883      iZero++;
51884
51885      for(j=0; j<nEntry; j++){
51886        aIndex[j] = (ht_slot)j;
51887      }
51888      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
51889      p->aSegment[i].iZero = iZero;
51890      p->aSegment[i].nEntry = nEntry;
51891      p->aSegment[i].aIndex = aIndex;
51892      p->aSegment[i].aPgno = (u32 *)aPgno;
51893    }
51894  }
51895  sqlite3_free(aTmp);
51896
51897  if( rc!=SQLITE_OK ){
51898    walIteratorFree(p);
51899  }
51900  *pp = p;
51901  return rc;
51902}
51903
51904/*
51905** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
51906** n. If the attempt fails and parameter xBusy is not NULL, then it is a
51907** busy-handler function. Invoke it and retry the lock until either the
51908** lock is successfully obtained or the busy-handler returns 0.
51909*/
51910static int walBusyLock(
51911  Wal *pWal,                      /* WAL connection */
51912  int (*xBusy)(void*),            /* Function to call when busy */
51913  void *pBusyArg,                 /* Context argument for xBusyHandler */
51914  int lockIdx,                    /* Offset of first byte to lock */
51915  int n                           /* Number of bytes to lock */
51916){
51917  int rc;
51918  do {
51919    rc = walLockExclusive(pWal, lockIdx, n, 0);
51920  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
51921  return rc;
51922}
51923
51924/*
51925** The cache of the wal-index header must be valid to call this function.
51926** Return the page-size in bytes used by the database.
51927*/
51928static int walPagesize(Wal *pWal){
51929  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
51930}
51931
51932/*
51933** The following is guaranteed when this function is called:
51934**
51935**   a) the WRITER lock is held,
51936**   b) the entire log file has been checkpointed, and
51937**   c) any existing readers are reading exclusively from the database
51938**      file - there are no readers that may attempt to read a frame from
51939**      the log file.
51940**
51941** This function updates the shared-memory structures so that the next
51942** client to write to the database (which may be this one) does so by
51943** writing frames into the start of the log file.
51944**
51945** The value of parameter salt1 is used as the aSalt[1] value in the
51946** new wal-index header. It should be passed a pseudo-random value (i.e.
51947** one obtained from sqlite3_randomness()).
51948*/
51949static void walRestartHdr(Wal *pWal, u32 salt1){
51950  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
51951  int i;                          /* Loop counter */
51952  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
51953  pWal->nCkpt++;
51954  pWal->hdr.mxFrame = 0;
51955  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
51956  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
51957  walIndexWriteHdr(pWal);
51958  pInfo->nBackfill = 0;
51959  pInfo->aReadMark[1] = 0;
51960  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
51961  assert( pInfo->aReadMark[0]==0 );
51962}
51963
51964/*
51965** Copy as much content as we can from the WAL back into the database file
51966** in response to an sqlite3_wal_checkpoint() request or the equivalent.
51967**
51968** The amount of information copies from WAL to database might be limited
51969** by active readers.  This routine will never overwrite a database page
51970** that a concurrent reader might be using.
51971**
51972** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
51973** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
51974** checkpoints are always run by a background thread or background
51975** process, foreground threads will never block on a lengthy fsync call.
51976**
51977** Fsync is called on the WAL before writing content out of the WAL and
51978** into the database.  This ensures that if the new content is persistent
51979** in the WAL and can be recovered following a power-loss or hard reset.
51980**
51981** Fsync is also called on the database file if (and only if) the entire
51982** WAL content is copied into the database file.  This second fsync makes
51983** it safe to delete the WAL since the new content will persist in the
51984** database file.
51985**
51986** This routine uses and updates the nBackfill field of the wal-index header.
51987** This is the only routine that will increase the value of nBackfill.
51988** (A WAL reset or recovery will revert nBackfill to zero, but not increase
51989** its value.)
51990**
51991** The caller must be holding sufficient locks to ensure that no other
51992** checkpoint is running (in any other thread or process) at the same
51993** time.
51994*/
51995static int walCheckpoint(
51996  Wal *pWal,                      /* Wal connection */
51997  int eMode,                      /* One of PASSIVE, FULL or RESTART */
51998  int (*xBusy)(void*),            /* Function to call when busy */
51999  void *pBusyArg,                 /* Context argument for xBusyHandler */
52000  int sync_flags,                 /* Flags for OsSync() (or 0) */
52001  u8 *zBuf                        /* Temporary buffer to use */
52002){
52003  int rc = SQLITE_OK;             /* Return code */
52004  int szPage;                     /* Database page-size */
52005  WalIterator *pIter = 0;         /* Wal iterator context */
52006  u32 iDbpage = 0;                /* Next database page to write */
52007  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
52008  u32 mxSafeFrame;                /* Max frame that can be backfilled */
52009  u32 mxPage;                     /* Max database page to write */
52010  int i;                          /* Loop counter */
52011  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
52012
52013  szPage = walPagesize(pWal);
52014  testcase( szPage<=32768 );
52015  testcase( szPage>=65536 );
52016  pInfo = walCkptInfo(pWal);
52017  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
52018
52019    /* Allocate the iterator */
52020    rc = walIteratorInit(pWal, &pIter);
52021    if( rc!=SQLITE_OK ){
52022      return rc;
52023    }
52024    assert( pIter );
52025
52026    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
52027    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
52028    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
52029
52030    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
52031    ** safe to write into the database.  Frames beyond mxSafeFrame might
52032    ** overwrite database pages that are in use by active readers and thus
52033    ** cannot be backfilled from the WAL.
52034    */
52035    mxSafeFrame = pWal->hdr.mxFrame;
52036    mxPage = pWal->hdr.nPage;
52037    for(i=1; i<WAL_NREADER; i++){
52038      /* Thread-sanitizer reports that the following is an unsafe read,
52039      ** as some other thread may be in the process of updating the value
52040      ** of the aReadMark[] slot. The assumption here is that if that is
52041      ** happening, the other client may only be increasing the value,
52042      ** not decreasing it. So assuming either that either the "old" or
52043      ** "new" version of the value is read, and not some arbitrary value
52044      ** that would never be written by a real client, things are still
52045      ** safe.  */
52046      u32 y = pInfo->aReadMark[i];
52047      if( mxSafeFrame>y ){
52048        assert( y<=pWal->hdr.mxFrame );
52049        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
52050        if( rc==SQLITE_OK ){
52051          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
52052          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
52053        }else if( rc==SQLITE_BUSY ){
52054          mxSafeFrame = y;
52055          xBusy = 0;
52056        }else{
52057          goto walcheckpoint_out;
52058        }
52059      }
52060    }
52061
52062    if( pInfo->nBackfill<mxSafeFrame
52063     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
52064    ){
52065      i64 nSize;                    /* Current size of database file */
52066      u32 nBackfill = pInfo->nBackfill;
52067
52068      /* Sync the WAL to disk */
52069      if( sync_flags ){
52070        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
52071      }
52072
52073      /* If the database may grow as a result of this checkpoint, hint
52074      ** about the eventual size of the db file to the VFS layer.
52075      */
52076      if( rc==SQLITE_OK ){
52077        i64 nReq = ((i64)mxPage * szPage);
52078        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
52079        if( rc==SQLITE_OK && nSize<nReq ){
52080          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
52081        }
52082      }
52083
52084
52085      /* Iterate through the contents of the WAL, copying data to the db file */
52086      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
52087        i64 iOffset;
52088        assert( walFramePgno(pWal, iFrame)==iDbpage );
52089        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
52090          continue;
52091        }
52092        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
52093        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
52094        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
52095        if( rc!=SQLITE_OK ) break;
52096        iOffset = (iDbpage-1)*(i64)szPage;
52097        testcase( IS_BIG_INT(iOffset) );
52098        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
52099        if( rc!=SQLITE_OK ) break;
52100      }
52101
52102      /* If work was actually accomplished... */
52103      if( rc==SQLITE_OK ){
52104        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
52105          i64 szDb = pWal->hdr.nPage*(i64)szPage;
52106          testcase( IS_BIG_INT(szDb) );
52107          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
52108          if( rc==SQLITE_OK && sync_flags ){
52109            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
52110          }
52111        }
52112        if( rc==SQLITE_OK ){
52113          pInfo->nBackfill = mxSafeFrame;
52114        }
52115      }
52116
52117      /* Release the reader lock held while backfilling */
52118      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
52119    }
52120
52121    if( rc==SQLITE_BUSY ){
52122      /* Reset the return code so as not to report a checkpoint failure
52123      ** just because there are active readers.  */
52124      rc = SQLITE_OK;
52125    }
52126  }
52127
52128  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
52129  ** entire wal file has been copied into the database file, then block
52130  ** until all readers have finished using the wal file. This ensures that
52131  ** the next process to write to the database restarts the wal file.
52132  */
52133  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
52134    assert( pWal->writeLock );
52135    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
52136      rc = SQLITE_BUSY;
52137    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
52138      u32 salt1;
52139      sqlite3_randomness(4, &salt1);
52140      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
52141      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
52142      if( rc==SQLITE_OK ){
52143        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
52144          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
52145          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
52146          ** truncates the log file to zero bytes just prior to a
52147          ** successful return.
52148          **
52149          ** In theory, it might be safe to do this without updating the
52150          ** wal-index header in shared memory, as all subsequent reader or
52151          ** writer clients should see that the entire log file has been
52152          ** checkpointed and behave accordingly. This seems unsafe though,
52153          ** as it would leave the system in a state where the contents of
52154          ** the wal-index header do not match the contents of the
52155          ** file-system. To avoid this, update the wal-index header to
52156          ** indicate that the log file contains zero valid frames.  */
52157          walRestartHdr(pWal, salt1);
52158          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
52159        }
52160        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
52161      }
52162    }
52163  }
52164
52165 walcheckpoint_out:
52166  walIteratorFree(pIter);
52167  return rc;
52168}
52169
52170/*
52171** If the WAL file is currently larger than nMax bytes in size, truncate
52172** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
52173*/
52174static void walLimitSize(Wal *pWal, i64 nMax){
52175  i64 sz;
52176  int rx;
52177  sqlite3BeginBenignMalloc();
52178  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
52179  if( rx==SQLITE_OK && (sz > nMax ) ){
52180    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
52181  }
52182  sqlite3EndBenignMalloc();
52183  if( rx ){
52184    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
52185  }
52186}
52187
52188/*
52189** Close a connection to a log file.
52190*/
52191SQLITE_PRIVATE int sqlite3WalClose(
52192  Wal *pWal,                      /* Wal to close */
52193  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
52194  int nBuf,
52195  u8 *zBuf                        /* Buffer of at least nBuf bytes */
52196){
52197  int rc = SQLITE_OK;
52198  if( pWal ){
52199    int isDelete = 0;             /* True to unlink wal and wal-index files */
52200
52201    /* If an EXCLUSIVE lock can be obtained on the database file (using the
52202    ** ordinary, rollback-mode locking methods, this guarantees that the
52203    ** connection associated with this log file is the only connection to
52204    ** the database. In this case checkpoint the database and unlink both
52205    ** the wal and wal-index files.
52206    **
52207    ** The EXCLUSIVE lock is not released before returning.
52208    */
52209    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
52210    if( rc==SQLITE_OK ){
52211      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
52212        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
52213      }
52214      rc = sqlite3WalCheckpoint(
52215          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
52216      );
52217      if( rc==SQLITE_OK ){
52218        int bPersist = -1;
52219        sqlite3OsFileControlHint(
52220            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
52221        );
52222        if( bPersist!=1 ){
52223          /* Try to delete the WAL file if the checkpoint completed and
52224          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
52225          ** mode (!bPersist) */
52226          isDelete = 1;
52227        }else if( pWal->mxWalSize>=0 ){
52228          /* Try to truncate the WAL file to zero bytes if the checkpoint
52229          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
52230          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
52231          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
52232          ** to zero bytes as truncating to the journal_size_limit might
52233          ** leave a corrupt WAL file on disk. */
52234          walLimitSize(pWal, 0);
52235        }
52236      }
52237    }
52238
52239    walIndexClose(pWal, isDelete);
52240    sqlite3OsClose(pWal->pWalFd);
52241    if( isDelete ){
52242      sqlite3BeginBenignMalloc();
52243      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
52244      sqlite3EndBenignMalloc();
52245    }
52246    WALTRACE(("WAL%p: closed\n", pWal));
52247    sqlite3_free((void *)pWal->apWiData);
52248    sqlite3_free(pWal);
52249  }
52250  return rc;
52251}
52252
52253/*
52254** Try to read the wal-index header.  Return 0 on success and 1 if
52255** there is a problem.
52256**
52257** The wal-index is in shared memory.  Another thread or process might
52258** be writing the header at the same time this procedure is trying to
52259** read it, which might result in inconsistency.  A dirty read is detected
52260** by verifying that both copies of the header are the same and also by
52261** a checksum on the header.
52262**
52263** If and only if the read is consistent and the header is different from
52264** pWal->hdr, then pWal->hdr is updated to the content of the new header
52265** and *pChanged is set to 1.
52266**
52267** If the checksum cannot be verified return non-zero. If the header
52268** is read successfully and the checksum verified, return zero.
52269*/
52270static int walIndexTryHdr(Wal *pWal, int *pChanged){
52271  u32 aCksum[2];                  /* Checksum on the header content */
52272  WalIndexHdr h1, h2;             /* Two copies of the header content */
52273  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
52274
52275  /* The first page of the wal-index must be mapped at this point. */
52276  assert( pWal->nWiData>0 && pWal->apWiData[0] );
52277
52278  /* Read the header. This might happen concurrently with a write to the
52279  ** same area of shared memory on a different CPU in a SMP,
52280  ** meaning it is possible that an inconsistent snapshot is read
52281  ** from the file. If this happens, return non-zero.
52282  **
52283  ** There are two copies of the header at the beginning of the wal-index.
52284  ** When reading, read [0] first then [1].  Writes are in the reverse order.
52285  ** Memory barriers are used to prevent the compiler or the hardware from
52286  ** reordering the reads and writes.
52287  */
52288  aHdr = walIndexHdr(pWal);
52289  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
52290  walShmBarrier(pWal);
52291  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
52292
52293  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
52294    return 1;   /* Dirty read */
52295  }
52296  if( h1.isInit==0 ){
52297    return 1;   /* Malformed header - probably all zeros */
52298  }
52299  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
52300  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
52301    return 1;   /* Checksum does not match */
52302  }
52303
52304  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
52305    *pChanged = 1;
52306    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
52307    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
52308    testcase( pWal->szPage<=32768 );
52309    testcase( pWal->szPage>=65536 );
52310  }
52311
52312  /* The header was successfully read. Return zero. */
52313  return 0;
52314}
52315
52316/*
52317** Read the wal-index header from the wal-index and into pWal->hdr.
52318** If the wal-header appears to be corrupt, try to reconstruct the
52319** wal-index from the WAL before returning.
52320**
52321** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
52322** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
52323** to 0.
52324**
52325** If the wal-index header is successfully read, return SQLITE_OK.
52326** Otherwise an SQLite error code.
52327*/
52328static int walIndexReadHdr(Wal *pWal, int *pChanged){
52329  int rc;                         /* Return code */
52330  int badHdr;                     /* True if a header read failed */
52331  volatile u32 *page0;            /* Chunk of wal-index containing header */
52332
52333  /* Ensure that page 0 of the wal-index (the page that contains the
52334  ** wal-index header) is mapped. Return early if an error occurs here.
52335  */
52336  assert( pChanged );
52337  rc = walIndexPage(pWal, 0, &page0);
52338  if( rc!=SQLITE_OK ){
52339    return rc;
52340  };
52341  assert( page0 || pWal->writeLock==0 );
52342
52343  /* If the first page of the wal-index has been mapped, try to read the
52344  ** wal-index header immediately, without holding any lock. This usually
52345  ** works, but may fail if the wal-index header is corrupt or currently
52346  ** being modified by another thread or process.
52347  */
52348  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
52349
52350  /* If the first attempt failed, it might have been due to a race
52351  ** with a writer.  So get a WRITE lock and try again.
52352  */
52353  assert( badHdr==0 || pWal->writeLock==0 );
52354  if( badHdr ){
52355    if( pWal->readOnly & WAL_SHM_RDONLY ){
52356      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
52357        walUnlockShared(pWal, WAL_WRITE_LOCK);
52358        rc = SQLITE_READONLY_RECOVERY;
52359      }
52360    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
52361      pWal->writeLock = 1;
52362      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
52363        badHdr = walIndexTryHdr(pWal, pChanged);
52364        if( badHdr ){
52365          /* If the wal-index header is still malformed even while holding
52366          ** a WRITE lock, it can only mean that the header is corrupted and
52367          ** needs to be reconstructed.  So run recovery to do exactly that.
52368          */
52369          rc = walIndexRecover(pWal);
52370          *pChanged = 1;
52371        }
52372      }
52373      pWal->writeLock = 0;
52374      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52375    }
52376  }
52377
52378  /* If the header is read successfully, check the version number to make
52379  ** sure the wal-index was not constructed with some future format that
52380  ** this version of SQLite cannot understand.
52381  */
52382  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
52383    rc = SQLITE_CANTOPEN_BKPT;
52384  }
52385
52386  return rc;
52387}
52388
52389/*
52390** This is the value that walTryBeginRead returns when it needs to
52391** be retried.
52392*/
52393#define WAL_RETRY  (-1)
52394
52395/*
52396** Attempt to start a read transaction.  This might fail due to a race or
52397** other transient condition.  When that happens, it returns WAL_RETRY to
52398** indicate to the caller that it is safe to retry immediately.
52399**
52400** On success return SQLITE_OK.  On a permanent failure (such an
52401** I/O error or an SQLITE_BUSY because another process is running
52402** recovery) return a positive error code.
52403**
52404** The useWal parameter is true to force the use of the WAL and disable
52405** the case where the WAL is bypassed because it has been completely
52406** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
52407** to make a copy of the wal-index header into pWal->hdr.  If the
52408** wal-index header has changed, *pChanged is set to 1 (as an indication
52409** to the caller that the local paget cache is obsolete and needs to be
52410** flushed.)  When useWal==1, the wal-index header is assumed to already
52411** be loaded and the pChanged parameter is unused.
52412**
52413** The caller must set the cnt parameter to the number of prior calls to
52414** this routine during the current read attempt that returned WAL_RETRY.
52415** This routine will start taking more aggressive measures to clear the
52416** race conditions after multiple WAL_RETRY returns, and after an excessive
52417** number of errors will ultimately return SQLITE_PROTOCOL.  The
52418** SQLITE_PROTOCOL return indicates that some other process has gone rogue
52419** and is not honoring the locking protocol.  There is a vanishingly small
52420** chance that SQLITE_PROTOCOL could be returned because of a run of really
52421** bad luck when there is lots of contention for the wal-index, but that
52422** possibility is so small that it can be safely neglected, we believe.
52423**
52424** On success, this routine obtains a read lock on
52425** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
52426** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
52427** that means the Wal does not hold any read lock.  The reader must not
52428** access any database page that is modified by a WAL frame up to and
52429** including frame number aReadMark[pWal->readLock].  The reader will
52430** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
52431** Or if pWal->readLock==0, then the reader will ignore the WAL
52432** completely and get all content directly from the database file.
52433** If the useWal parameter is 1 then the WAL will never be ignored and
52434** this routine will always set pWal->readLock>0 on success.
52435** When the read transaction is completed, the caller must release the
52436** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
52437**
52438** This routine uses the nBackfill and aReadMark[] fields of the header
52439** to select a particular WAL_READ_LOCK() that strives to let the
52440** checkpoint process do as much work as possible.  This routine might
52441** update values of the aReadMark[] array in the header, but if it does
52442** so it takes care to hold an exclusive lock on the corresponding
52443** WAL_READ_LOCK() while changing values.
52444*/
52445static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
52446  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
52447  u32 mxReadMark;                 /* Largest aReadMark[] value */
52448  int mxI;                        /* Index of largest aReadMark[] value */
52449  int i;                          /* Loop counter */
52450  int rc = SQLITE_OK;             /* Return code  */
52451
52452  assert( pWal->readLock<0 );     /* Not currently locked */
52453
52454  /* Take steps to avoid spinning forever if there is a protocol error.
52455  **
52456  ** Circumstances that cause a RETRY should only last for the briefest
52457  ** instances of time.  No I/O or other system calls are done while the
52458  ** locks are held, so the locks should not be held for very long. But
52459  ** if we are unlucky, another process that is holding a lock might get
52460  ** paged out or take a page-fault that is time-consuming to resolve,
52461  ** during the few nanoseconds that it is holding the lock.  In that case,
52462  ** it might take longer than normal for the lock to free.
52463  **
52464  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
52465  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
52466  ** is more of a scheduler yield than an actual delay.  But on the 10th
52467  ** an subsequent retries, the delays start becoming longer and longer,
52468  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
52469  ** The total delay time before giving up is less than 10 seconds.
52470  */
52471  if( cnt>5 ){
52472    int nDelay = 1;                      /* Pause time in microseconds */
52473    if( cnt>100 ){
52474      VVA_ONLY( pWal->lockError = 1; )
52475      return SQLITE_PROTOCOL;
52476    }
52477    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
52478    sqlite3OsSleep(pWal->pVfs, nDelay);
52479  }
52480
52481  if( !useWal ){
52482    rc = walIndexReadHdr(pWal, pChanged);
52483    if( rc==SQLITE_BUSY ){
52484      /* If there is not a recovery running in another thread or process
52485      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
52486      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
52487      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
52488      ** would be technically correct.  But the race is benign since with
52489      ** WAL_RETRY this routine will be called again and will probably be
52490      ** right on the second iteration.
52491      */
52492      if( pWal->apWiData[0]==0 ){
52493        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
52494        ** We assume this is a transient condition, so return WAL_RETRY. The
52495        ** xShmMap() implementation used by the default unix and win32 VFS
52496        ** modules may return SQLITE_BUSY due to a race condition in the
52497        ** code that determines whether or not the shared-memory region
52498        ** must be zeroed before the requested page is returned.
52499        */
52500        rc = WAL_RETRY;
52501      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
52502        walUnlockShared(pWal, WAL_RECOVER_LOCK);
52503        rc = WAL_RETRY;
52504      }else if( rc==SQLITE_BUSY ){
52505        rc = SQLITE_BUSY_RECOVERY;
52506      }
52507    }
52508    if( rc!=SQLITE_OK ){
52509      return rc;
52510    }
52511  }
52512
52513  pInfo = walCkptInfo(pWal);
52514  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
52515    /* The WAL has been completely backfilled (or it is empty).
52516    ** and can be safely ignored.
52517    */
52518    rc = walLockShared(pWal, WAL_READ_LOCK(0));
52519    walShmBarrier(pWal);
52520    if( rc==SQLITE_OK ){
52521      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
52522        /* It is not safe to allow the reader to continue here if frames
52523        ** may have been appended to the log before READ_LOCK(0) was obtained.
52524        ** When holding READ_LOCK(0), the reader ignores the entire log file,
52525        ** which implies that the database file contains a trustworthy
52526        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
52527        ** happening, this is usually correct.
52528        **
52529        ** However, if frames have been appended to the log (or if the log
52530        ** is wrapped and written for that matter) before the READ_LOCK(0)
52531        ** is obtained, that is not necessarily true. A checkpointer may
52532        ** have started to backfill the appended frames but crashed before
52533        ** it finished. Leaving a corrupt image in the database file.
52534        */
52535        walUnlockShared(pWal, WAL_READ_LOCK(0));
52536        return WAL_RETRY;
52537      }
52538      pWal->readLock = 0;
52539      return SQLITE_OK;
52540    }else if( rc!=SQLITE_BUSY ){
52541      return rc;
52542    }
52543  }
52544
52545  /* If we get this far, it means that the reader will want to use
52546  ** the WAL to get at content from recent commits.  The job now is
52547  ** to select one of the aReadMark[] entries that is closest to
52548  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
52549  */
52550  mxReadMark = 0;
52551  mxI = 0;
52552  for(i=1; i<WAL_NREADER; i++){
52553    u32 thisMark = pInfo->aReadMark[i];
52554    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
52555      assert( thisMark!=READMARK_NOT_USED );
52556      mxReadMark = thisMark;
52557      mxI = i;
52558    }
52559  }
52560  /* There was once an "if" here. The extra "{" is to preserve indentation. */
52561  {
52562    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
52563     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
52564    ){
52565      for(i=1; i<WAL_NREADER; i++){
52566        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
52567        if( rc==SQLITE_OK ){
52568          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
52569          mxI = i;
52570          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
52571          break;
52572        }else if( rc!=SQLITE_BUSY ){
52573          return rc;
52574        }
52575      }
52576    }
52577    if( mxI==0 ){
52578      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
52579      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
52580    }
52581
52582    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
52583    if( rc ){
52584      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
52585    }
52586    /* Now that the read-lock has been obtained, check that neither the
52587    ** value in the aReadMark[] array or the contents of the wal-index
52588    ** header have changed.
52589    **
52590    ** It is necessary to check that the wal-index header did not change
52591    ** between the time it was read and when the shared-lock was obtained
52592    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
52593    ** that the log file may have been wrapped by a writer, or that frames
52594    ** that occur later in the log than pWal->hdr.mxFrame may have been
52595    ** copied into the database by a checkpointer. If either of these things
52596    ** happened, then reading the database with the current value of
52597    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
52598    ** instead.
52599    **
52600    ** Before checking that the live wal-index header has not changed
52601    ** since it was read, set Wal.minFrame to the first frame in the wal
52602    ** file that has not yet been checkpointed. This client will not need
52603    ** to read any frames earlier than minFrame from the wal file - they
52604    ** can be safely read directly from the database file.
52605    **
52606    ** Because a ShmBarrier() call is made between taking the copy of
52607    ** nBackfill and checking that the wal-header in shared-memory still
52608    ** matches the one cached in pWal->hdr, it is guaranteed that the
52609    ** checkpointer that set nBackfill was not working with a wal-index
52610    ** header newer than that cached in pWal->hdr. If it were, that could
52611    ** cause a problem. The checkpointer could omit to checkpoint
52612    ** a version of page X that lies before pWal->minFrame (call that version
52613    ** A) on the basis that there is a newer version (version B) of the same
52614    ** page later in the wal file. But if version B happens to like past
52615    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
52616    ** that it can read version A from the database file. However, since
52617    ** we can guarantee that the checkpointer that set nBackfill could not
52618    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
52619    */
52620    pWal->minFrame = pInfo->nBackfill+1;
52621    walShmBarrier(pWal);
52622    if( pInfo->aReadMark[mxI]!=mxReadMark
52623     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
52624    ){
52625      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
52626      return WAL_RETRY;
52627    }else{
52628      assert( mxReadMark<=pWal->hdr.mxFrame );
52629      pWal->readLock = (i16)mxI;
52630    }
52631  }
52632  return rc;
52633}
52634
52635/*
52636** Begin a read transaction on the database.
52637**
52638** This routine used to be called sqlite3OpenSnapshot() and with good reason:
52639** it takes a snapshot of the state of the WAL and wal-index for the current
52640** instant in time.  The current thread will continue to use this snapshot.
52641** Other threads might append new content to the WAL and wal-index but
52642** that extra content is ignored by the current thread.
52643**
52644** If the database contents have changes since the previous read
52645** transaction, then *pChanged is set to 1 before returning.  The
52646** Pager layer will use this to know that is cache is stale and
52647** needs to be flushed.
52648*/
52649SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
52650  int rc;                         /* Return code */
52651  int cnt = 0;                    /* Number of TryBeginRead attempts */
52652
52653  do{
52654    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
52655  }while( rc==WAL_RETRY );
52656  testcase( (rc&0xff)==SQLITE_BUSY );
52657  testcase( (rc&0xff)==SQLITE_IOERR );
52658  testcase( rc==SQLITE_PROTOCOL );
52659  testcase( rc==SQLITE_OK );
52660  return rc;
52661}
52662
52663/*
52664** Finish with a read transaction.  All this does is release the
52665** read-lock.
52666*/
52667SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
52668  sqlite3WalEndWriteTransaction(pWal);
52669  if( pWal->readLock>=0 ){
52670    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
52671    pWal->readLock = -1;
52672  }
52673}
52674
52675/*
52676** Search the wal file for page pgno. If found, set *piRead to the frame that
52677** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
52678** to zero.
52679**
52680** Return SQLITE_OK if successful, or an error code if an error occurs. If an
52681** error does occur, the final value of *piRead is undefined.
52682*/
52683SQLITE_PRIVATE int sqlite3WalFindFrame(
52684  Wal *pWal,                      /* WAL handle */
52685  Pgno pgno,                      /* Database page number to read data for */
52686  u32 *piRead                     /* OUT: Frame number (or zero) */
52687){
52688  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
52689  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
52690  int iHash;                      /* Used to loop through N hash tables */
52691  int iMinHash;
52692
52693  /* This routine is only be called from within a read transaction. */
52694  assert( pWal->readLock>=0 || pWal->lockError );
52695
52696  /* If the "last page" field of the wal-index header snapshot is 0, then
52697  ** no data will be read from the wal under any circumstances. Return early
52698  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
52699  ** then the WAL is ignored by the reader so return early, as if the
52700  ** WAL were empty.
52701  */
52702  if( iLast==0 || pWal->readLock==0 ){
52703    *piRead = 0;
52704    return SQLITE_OK;
52705  }
52706
52707  /* Search the hash table or tables for an entry matching page number
52708  ** pgno. Each iteration of the following for() loop searches one
52709  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
52710  **
52711  ** This code might run concurrently to the code in walIndexAppend()
52712  ** that adds entries to the wal-index (and possibly to this hash
52713  ** table). This means the value just read from the hash
52714  ** slot (aHash[iKey]) may have been added before or after the
52715  ** current read transaction was opened. Values added after the
52716  ** read transaction was opened may have been written incorrectly -
52717  ** i.e. these slots may contain garbage data. However, we assume
52718  ** that any slots written before the current read transaction was
52719  ** opened remain unmodified.
52720  **
52721  ** For the reasons above, the if(...) condition featured in the inner
52722  ** loop of the following block is more stringent that would be required
52723  ** if we had exclusive access to the hash-table:
52724  **
52725  **   (aPgno[iFrame]==pgno):
52726  **     This condition filters out normal hash-table collisions.
52727  **
52728  **   (iFrame<=iLast):
52729  **     This condition filters out entries that were added to the hash
52730  **     table after the current read-transaction had started.
52731  */
52732  iMinHash = walFramePage(pWal->minFrame);
52733  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
52734    volatile ht_slot *aHash;      /* Pointer to hash table */
52735    volatile u32 *aPgno;          /* Pointer to array of page numbers */
52736    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
52737    int iKey;                     /* Hash slot index */
52738    int nCollide;                 /* Number of hash collisions remaining */
52739    int rc;                       /* Error code */
52740
52741    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
52742    if( rc!=SQLITE_OK ){
52743      return rc;
52744    }
52745    nCollide = HASHTABLE_NSLOT;
52746    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
52747      u32 iFrame = aHash[iKey] + iZero;
52748      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
52749        assert( iFrame>iRead || CORRUPT_DB );
52750        iRead = iFrame;
52751      }
52752      if( (nCollide--)==0 ){
52753        return SQLITE_CORRUPT_BKPT;
52754      }
52755    }
52756  }
52757
52758#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
52759  /* If expensive assert() statements are available, do a linear search
52760  ** of the wal-index file content. Make sure the results agree with the
52761  ** result obtained using the hash indexes above.  */
52762  {
52763    u32 iRead2 = 0;
52764    u32 iTest;
52765    assert( pWal->minFrame>0 );
52766    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
52767      if( walFramePgno(pWal, iTest)==pgno ){
52768        iRead2 = iTest;
52769        break;
52770      }
52771    }
52772    assert( iRead==iRead2 );
52773  }
52774#endif
52775
52776  *piRead = iRead;
52777  return SQLITE_OK;
52778}
52779
52780/*
52781** Read the contents of frame iRead from the wal file into buffer pOut
52782** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
52783** error code otherwise.
52784*/
52785SQLITE_PRIVATE int sqlite3WalReadFrame(
52786  Wal *pWal,                      /* WAL handle */
52787  u32 iRead,                      /* Frame to read */
52788  int nOut,                       /* Size of buffer pOut in bytes */
52789  u8 *pOut                        /* Buffer to write page data to */
52790){
52791  int sz;
52792  i64 iOffset;
52793  sz = pWal->hdr.szPage;
52794  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
52795  testcase( sz<=32768 );
52796  testcase( sz>=65536 );
52797  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
52798  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
52799  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
52800}
52801
52802/*
52803** Return the size of the database in pages (or zero, if unknown).
52804*/
52805SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
52806  if( pWal && ALWAYS(pWal->readLock>=0) ){
52807    return pWal->hdr.nPage;
52808  }
52809  return 0;
52810}
52811
52812
52813/*
52814** This function starts a write transaction on the WAL.
52815**
52816** A read transaction must have already been started by a prior call
52817** to sqlite3WalBeginReadTransaction().
52818**
52819** If another thread or process has written into the database since
52820** the read transaction was started, then it is not possible for this
52821** thread to write as doing so would cause a fork.  So this routine
52822** returns SQLITE_BUSY in that case and no write transaction is started.
52823**
52824** There can only be a single writer active at a time.
52825*/
52826SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
52827  int rc;
52828
52829  /* Cannot start a write transaction without first holding a read
52830  ** transaction. */
52831  assert( pWal->readLock>=0 );
52832
52833  if( pWal->readOnly ){
52834    return SQLITE_READONLY;
52835  }
52836
52837  /* Only one writer allowed at a time.  Get the write lock.  Return
52838  ** SQLITE_BUSY if unable.
52839  */
52840  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
52841  if( rc ){
52842    return rc;
52843  }
52844  pWal->writeLock = 1;
52845
52846  /* If another connection has written to the database file since the
52847  ** time the read transaction on this connection was started, then
52848  ** the write is disallowed.
52849  */
52850  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
52851    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52852    pWal->writeLock = 0;
52853    rc = SQLITE_BUSY_SNAPSHOT;
52854  }
52855
52856  return rc;
52857}
52858
52859/*
52860** End a write transaction.  The commit has already been done.  This
52861** routine merely releases the lock.
52862*/
52863SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
52864  if( pWal->writeLock ){
52865    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52866    pWal->writeLock = 0;
52867    pWal->truncateOnCommit = 0;
52868  }
52869  return SQLITE_OK;
52870}
52871
52872/*
52873** If any data has been written (but not committed) to the log file, this
52874** function moves the write-pointer back to the start of the transaction.
52875**
52876** Additionally, the callback function is invoked for each frame written
52877** to the WAL since the start of the transaction. If the callback returns
52878** other than SQLITE_OK, it is not invoked again and the error code is
52879** returned to the caller.
52880**
52881** Otherwise, if the callback function does not return an error, this
52882** function returns SQLITE_OK.
52883*/
52884SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
52885  int rc = SQLITE_OK;
52886  if( ALWAYS(pWal->writeLock) ){
52887    Pgno iMax = pWal->hdr.mxFrame;
52888    Pgno iFrame;
52889
52890    /* Restore the clients cache of the wal-index header to the state it
52891    ** was in before the client began writing to the database.
52892    */
52893    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
52894
52895    for(iFrame=pWal->hdr.mxFrame+1;
52896        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
52897        iFrame++
52898    ){
52899      /* This call cannot fail. Unless the page for which the page number
52900      ** is passed as the second argument is (a) in the cache and
52901      ** (b) has an outstanding reference, then xUndo is either a no-op
52902      ** (if (a) is false) or simply expels the page from the cache (if (b)
52903      ** is false).
52904      **
52905      ** If the upper layer is doing a rollback, it is guaranteed that there
52906      ** are no outstanding references to any page other than page 1. And
52907      ** page 1 is never written to the log until the transaction is
52908      ** committed. As a result, the call to xUndo may not fail.
52909      */
52910      assert( walFramePgno(pWal, iFrame)!=1 );
52911      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
52912    }
52913    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
52914  }
52915  return rc;
52916}
52917
52918/*
52919** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
52920** values. This function populates the array with values required to
52921** "rollback" the write position of the WAL handle back to the current
52922** point in the event of a savepoint rollback (via WalSavepointUndo()).
52923*/
52924SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
52925  assert( pWal->writeLock );
52926  aWalData[0] = pWal->hdr.mxFrame;
52927  aWalData[1] = pWal->hdr.aFrameCksum[0];
52928  aWalData[2] = pWal->hdr.aFrameCksum[1];
52929  aWalData[3] = pWal->nCkpt;
52930}
52931
52932/*
52933** Move the write position of the WAL back to the point identified by
52934** the values in the aWalData[] array. aWalData must point to an array
52935** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
52936** by a call to WalSavepoint().
52937*/
52938SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
52939  int rc = SQLITE_OK;
52940
52941  assert( pWal->writeLock );
52942  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
52943
52944  if( aWalData[3]!=pWal->nCkpt ){
52945    /* This savepoint was opened immediately after the write-transaction
52946    ** was started. Right after that, the writer decided to wrap around
52947    ** to the start of the log. Update the savepoint values to match.
52948    */
52949    aWalData[0] = 0;
52950    aWalData[3] = pWal->nCkpt;
52951  }
52952
52953  if( aWalData[0]<pWal->hdr.mxFrame ){
52954    pWal->hdr.mxFrame = aWalData[0];
52955    pWal->hdr.aFrameCksum[0] = aWalData[1];
52956    pWal->hdr.aFrameCksum[1] = aWalData[2];
52957    walCleanupHash(pWal);
52958  }
52959
52960  return rc;
52961}
52962
52963/*
52964** This function is called just before writing a set of frames to the log
52965** file (see sqlite3WalFrames()). It checks to see if, instead of appending
52966** to the current log file, it is possible to overwrite the start of the
52967** existing log file with the new frames (i.e. "reset" the log). If so,
52968** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
52969** unchanged.
52970**
52971** SQLITE_OK is returned if no error is encountered (regardless of whether
52972** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
52973** if an error occurs.
52974*/
52975static int walRestartLog(Wal *pWal){
52976  int rc = SQLITE_OK;
52977  int cnt;
52978
52979  if( pWal->readLock==0 ){
52980    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
52981    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
52982    if( pInfo->nBackfill>0 ){
52983      u32 salt1;
52984      sqlite3_randomness(4, &salt1);
52985      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
52986      if( rc==SQLITE_OK ){
52987        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
52988        ** readers are currently using the WAL), then the transactions
52989        ** frames will overwrite the start of the existing log. Update the
52990        ** wal-index header to reflect this.
52991        **
52992        ** In theory it would be Ok to update the cache of the header only
52993        ** at this point. But updating the actual wal-index header is also
52994        ** safe and means there is no special case for sqlite3WalUndo()
52995        ** to handle if this transaction is rolled back.  */
52996        walRestartHdr(pWal, salt1);
52997        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
52998      }else if( rc!=SQLITE_BUSY ){
52999        return rc;
53000      }
53001    }
53002    walUnlockShared(pWal, WAL_READ_LOCK(0));
53003    pWal->readLock = -1;
53004    cnt = 0;
53005    do{
53006      int notUsed;
53007      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
53008    }while( rc==WAL_RETRY );
53009    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
53010    testcase( (rc&0xff)==SQLITE_IOERR );
53011    testcase( rc==SQLITE_PROTOCOL );
53012    testcase( rc==SQLITE_OK );
53013  }
53014  return rc;
53015}
53016
53017/*
53018** Information about the current state of the WAL file and where
53019** the next fsync should occur - passed from sqlite3WalFrames() into
53020** walWriteToLog().
53021*/
53022typedef struct WalWriter {
53023  Wal *pWal;                   /* The complete WAL information */
53024  sqlite3_file *pFd;           /* The WAL file to which we write */
53025  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
53026  int syncFlags;               /* Flags for the fsync */
53027  int szPage;                  /* Size of one page */
53028} WalWriter;
53029
53030/*
53031** Write iAmt bytes of content into the WAL file beginning at iOffset.
53032** Do a sync when crossing the p->iSyncPoint boundary.
53033**
53034** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
53035** first write the part before iSyncPoint, then sync, then write the
53036** rest.
53037*/
53038static int walWriteToLog(
53039  WalWriter *p,              /* WAL to write to */
53040  void *pContent,            /* Content to be written */
53041  int iAmt,                  /* Number of bytes to write */
53042  sqlite3_int64 iOffset      /* Start writing at this offset */
53043){
53044  int rc;
53045  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
53046    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
53047    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
53048    if( rc ) return rc;
53049    iOffset += iFirstAmt;
53050    iAmt -= iFirstAmt;
53051    pContent = (void*)(iFirstAmt + (char*)pContent);
53052    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
53053    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
53054    if( iAmt==0 || rc ) return rc;
53055  }
53056  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
53057  return rc;
53058}
53059
53060/*
53061** Write out a single frame of the WAL
53062*/
53063static int walWriteOneFrame(
53064  WalWriter *p,               /* Where to write the frame */
53065  PgHdr *pPage,               /* The page of the frame to be written */
53066  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
53067  sqlite3_int64 iOffset       /* Byte offset at which to write */
53068){
53069  int rc;                         /* Result code from subfunctions */
53070  void *pData;                    /* Data actually written */
53071  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
53072#if defined(SQLITE_HAS_CODEC)
53073  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
53074#else
53075  pData = pPage->pData;
53076#endif
53077  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
53078  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
53079  if( rc ) return rc;
53080  /* Write the page data */
53081  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
53082  return rc;
53083}
53084
53085/*
53086** Write a set of frames to the log. The caller must hold the write-lock
53087** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
53088*/
53089SQLITE_PRIVATE int sqlite3WalFrames(
53090  Wal *pWal,                      /* Wal handle to write to */
53091  int szPage,                     /* Database page-size in bytes */
53092  PgHdr *pList,                   /* List of dirty pages to write */
53093  Pgno nTruncate,                 /* Database size after this commit */
53094  int isCommit,                   /* True if this is a commit */
53095  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
53096){
53097  int rc;                         /* Used to catch return codes */
53098  u32 iFrame;                     /* Next frame address */
53099  PgHdr *p;                       /* Iterator to run through pList with. */
53100  PgHdr *pLast = 0;               /* Last frame in list */
53101  int nExtra = 0;                 /* Number of extra copies of last page */
53102  int szFrame;                    /* The size of a single frame */
53103  i64 iOffset;                    /* Next byte to write in WAL file */
53104  WalWriter w;                    /* The writer */
53105
53106  assert( pList );
53107  assert( pWal->writeLock );
53108
53109  /* If this frame set completes a transaction, then nTruncate>0.  If
53110  ** nTruncate==0 then this frame set does not complete the transaction. */
53111  assert( (isCommit!=0)==(nTruncate!=0) );
53112
53113#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53114  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
53115    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
53116              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
53117  }
53118#endif
53119
53120  /* See if it is possible to write these frames into the start of the
53121  ** log file, instead of appending to it at pWal->hdr.mxFrame.
53122  */
53123  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
53124    return rc;
53125  }
53126
53127  /* If this is the first frame written into the log, write the WAL
53128  ** header to the start of the WAL file. See comments at the top of
53129  ** this source file for a description of the WAL header format.
53130  */
53131  iFrame = pWal->hdr.mxFrame;
53132  if( iFrame==0 ){
53133    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
53134    u32 aCksum[2];                /* Checksum for wal-header */
53135
53136    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
53137    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
53138    sqlite3Put4byte(&aWalHdr[8], szPage);
53139    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
53140    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
53141    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
53142    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
53143    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
53144    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
53145
53146    pWal->szPage = szPage;
53147    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
53148    pWal->hdr.aFrameCksum[0] = aCksum[0];
53149    pWal->hdr.aFrameCksum[1] = aCksum[1];
53150    pWal->truncateOnCommit = 1;
53151
53152    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
53153    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
53154    if( rc!=SQLITE_OK ){
53155      return rc;
53156    }
53157
53158    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
53159    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
53160    ** an out-of-order write following a WAL restart could result in
53161    ** database corruption.  See the ticket:
53162    **
53163    **     http://localhost:591/sqlite/info/ff5be73dee
53164    */
53165    if( pWal->syncHeader && sync_flags ){
53166      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
53167      if( rc ) return rc;
53168    }
53169  }
53170  assert( (int)pWal->szPage==szPage );
53171
53172  /* Setup information needed to write frames into the WAL */
53173  w.pWal = pWal;
53174  w.pFd = pWal->pWalFd;
53175  w.iSyncPoint = 0;
53176  w.syncFlags = sync_flags;
53177  w.szPage = szPage;
53178  iOffset = walFrameOffset(iFrame+1, szPage);
53179  szFrame = szPage + WAL_FRAME_HDRSIZE;
53180
53181  /* Write all frames into the log file exactly once */
53182  for(p=pList; p; p=p->pDirty){
53183    int nDbSize;   /* 0 normally.  Positive == commit flag */
53184    iFrame++;
53185    assert( iOffset==walFrameOffset(iFrame, szPage) );
53186    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
53187    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
53188    if( rc ) return rc;
53189    pLast = p;
53190    iOffset += szFrame;
53191  }
53192
53193  /* If this is the end of a transaction, then we might need to pad
53194  ** the transaction and/or sync the WAL file.
53195  **
53196  ** Padding and syncing only occur if this set of frames complete a
53197  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
53198  ** or synchronous==OFF, then no padding or syncing are needed.
53199  **
53200  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
53201  ** needed and only the sync is done.  If padding is needed, then the
53202  ** final frame is repeated (with its commit mark) until the next sector
53203  ** boundary is crossed.  Only the part of the WAL prior to the last
53204  ** sector boundary is synced; the part of the last frame that extends
53205  ** past the sector boundary is written after the sync.
53206  */
53207  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
53208    if( pWal->padToSectorBoundary ){
53209      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
53210      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
53211      while( iOffset<w.iSyncPoint ){
53212        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
53213        if( rc ) return rc;
53214        iOffset += szFrame;
53215        nExtra++;
53216      }
53217    }else{
53218      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
53219    }
53220  }
53221
53222  /* If this frame set completes the first transaction in the WAL and
53223  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
53224  ** journal size limit, if possible.
53225  */
53226  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
53227    i64 sz = pWal->mxWalSize;
53228    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
53229      sz = walFrameOffset(iFrame+nExtra+1, szPage);
53230    }
53231    walLimitSize(pWal, sz);
53232    pWal->truncateOnCommit = 0;
53233  }
53234
53235  /* Append data to the wal-index. It is not necessary to lock the
53236  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
53237  ** guarantees that there are no other writers, and no data that may
53238  ** be in use by existing readers is being overwritten.
53239  */
53240  iFrame = pWal->hdr.mxFrame;
53241  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
53242    iFrame++;
53243    rc = walIndexAppend(pWal, iFrame, p->pgno);
53244  }
53245  while( rc==SQLITE_OK && nExtra>0 ){
53246    iFrame++;
53247    nExtra--;
53248    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
53249  }
53250
53251  if( rc==SQLITE_OK ){
53252    /* Update the private copy of the header. */
53253    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
53254    testcase( szPage<=32768 );
53255    testcase( szPage>=65536 );
53256    pWal->hdr.mxFrame = iFrame;
53257    if( isCommit ){
53258      pWal->hdr.iChange++;
53259      pWal->hdr.nPage = nTruncate;
53260    }
53261    /* If this is a commit, update the wal-index header too. */
53262    if( isCommit ){
53263      walIndexWriteHdr(pWal);
53264      pWal->iCallback = iFrame;
53265    }
53266  }
53267
53268  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
53269  return rc;
53270}
53271
53272/*
53273** This routine is called to implement sqlite3_wal_checkpoint() and
53274** related interfaces.
53275**
53276** Obtain a CHECKPOINT lock and then backfill as much information as
53277** we can from WAL into the database.
53278**
53279** If parameter xBusy is not NULL, it is a pointer to a busy-handler
53280** callback. In this case this function runs a blocking checkpoint.
53281*/
53282SQLITE_PRIVATE int sqlite3WalCheckpoint(
53283  Wal *pWal,                      /* Wal connection */
53284  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
53285  int (*xBusy)(void*),            /* Function to call when busy */
53286  void *pBusyArg,                 /* Context argument for xBusyHandler */
53287  int sync_flags,                 /* Flags to sync db file with (or 0) */
53288  int nBuf,                       /* Size of temporary buffer */
53289  u8 *zBuf,                       /* Temporary buffer to use */
53290  int *pnLog,                     /* OUT: Number of frames in WAL */
53291  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
53292){
53293  int rc;                         /* Return code */
53294  int isChanged = 0;              /* True if a new wal-index header is loaded */
53295  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
53296  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
53297
53298  assert( pWal->ckptLock==0 );
53299  assert( pWal->writeLock==0 );
53300
53301  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
53302  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
53303  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
53304
53305  if( pWal->readOnly ) return SQLITE_READONLY;
53306  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
53307
53308  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
53309  ** "checkpoint" lock on the database file. */
53310  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
53311  if( rc ){
53312    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
53313    ** checkpoint operation at the same time, the lock cannot be obtained and
53314    ** SQLITE_BUSY is returned.
53315    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
53316    ** it will not be invoked in this case.
53317    */
53318    testcase( rc==SQLITE_BUSY );
53319    testcase( xBusy!=0 );
53320    return rc;
53321  }
53322  pWal->ckptLock = 1;
53323
53324  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
53325  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
53326  ** file.
53327  **
53328  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
53329  ** immediately, and a busy-handler is configured, it is invoked and the
53330  ** writer lock retried until either the busy-handler returns 0 or the
53331  ** lock is successfully obtained.
53332  */
53333  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
53334    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
53335    if( rc==SQLITE_OK ){
53336      pWal->writeLock = 1;
53337    }else if( rc==SQLITE_BUSY ){
53338      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
53339      xBusy2 = 0;
53340      rc = SQLITE_OK;
53341    }
53342  }
53343
53344  /* Read the wal-index header. */
53345  if( rc==SQLITE_OK ){
53346    rc = walIndexReadHdr(pWal, &isChanged);
53347    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
53348      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
53349    }
53350  }
53351
53352  /* Copy data from the log to the database file. */
53353  if( rc==SQLITE_OK ){
53354    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
53355      rc = SQLITE_CORRUPT_BKPT;
53356    }else{
53357      rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
53358    }
53359
53360    /* If no error occurred, set the output variables. */
53361    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
53362      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
53363      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
53364    }
53365  }
53366
53367  if( isChanged ){
53368    /* If a new wal-index header was loaded before the checkpoint was
53369    ** performed, then the pager-cache associated with pWal is now
53370    ** out of date. So zero the cached wal-index header to ensure that
53371    ** next time the pager opens a snapshot on this database it knows that
53372    ** the cache needs to be reset.
53373    */
53374    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
53375  }
53376
53377  /* Release the locks. */
53378  sqlite3WalEndWriteTransaction(pWal);
53379  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
53380  pWal->ckptLock = 0;
53381  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
53382  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
53383}
53384
53385/* Return the value to pass to a sqlite3_wal_hook callback, the
53386** number of frames in the WAL at the point of the last commit since
53387** sqlite3WalCallback() was called.  If no commits have occurred since
53388** the last call, then return 0.
53389*/
53390SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
53391  u32 ret = 0;
53392  if( pWal ){
53393    ret = pWal->iCallback;
53394    pWal->iCallback = 0;
53395  }
53396  return (int)ret;
53397}
53398
53399/*
53400** This function is called to change the WAL subsystem into or out
53401** of locking_mode=EXCLUSIVE.
53402**
53403** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
53404** into locking_mode=NORMAL.  This means that we must acquire a lock
53405** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
53406** or if the acquisition of the lock fails, then return 0.  If the
53407** transition out of exclusive-mode is successful, return 1.  This
53408** operation must occur while the pager is still holding the exclusive
53409** lock on the main database file.
53410**
53411** If op is one, then change from locking_mode=NORMAL into
53412** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
53413** be released.  Return 1 if the transition is made and 0 if the
53414** WAL is already in exclusive-locking mode - meaning that this
53415** routine is a no-op.  The pager must already hold the exclusive lock
53416** on the main database file before invoking this operation.
53417**
53418** If op is negative, then do a dry-run of the op==1 case but do
53419** not actually change anything. The pager uses this to see if it
53420** should acquire the database exclusive lock prior to invoking
53421** the op==1 case.
53422*/
53423SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
53424  int rc;
53425  assert( pWal->writeLock==0 );
53426  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
53427
53428  /* pWal->readLock is usually set, but might be -1 if there was a
53429  ** prior error while attempting to acquire are read-lock. This cannot
53430  ** happen if the connection is actually in exclusive mode (as no xShmLock
53431  ** locks are taken in this case). Nor should the pager attempt to
53432  ** upgrade to exclusive-mode following such an error.
53433  */
53434  assert( pWal->readLock>=0 || pWal->lockError );
53435  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
53436
53437  if( op==0 ){
53438    if( pWal->exclusiveMode ){
53439      pWal->exclusiveMode = 0;
53440      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
53441        pWal->exclusiveMode = 1;
53442      }
53443      rc = pWal->exclusiveMode==0;
53444    }else{
53445      /* Already in locking_mode=NORMAL */
53446      rc = 0;
53447    }
53448  }else if( op>0 ){
53449    assert( pWal->exclusiveMode==0 );
53450    assert( pWal->readLock>=0 );
53451    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
53452    pWal->exclusiveMode = 1;
53453    rc = 1;
53454  }else{
53455    rc = pWal->exclusiveMode==0;
53456  }
53457  return rc;
53458}
53459
53460/*
53461** Return true if the argument is non-NULL and the WAL module is using
53462** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
53463** WAL module is using shared-memory, return false.
53464*/
53465SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
53466  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
53467}
53468
53469#ifdef SQLITE_ENABLE_ZIPVFS
53470/*
53471** If the argument is not NULL, it points to a Wal object that holds a
53472** read-lock. This function returns the database page-size if it is known,
53473** or zero if it is not (or if pWal is NULL).
53474*/
53475SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
53476  assert( pWal==0 || pWal->readLock>=0 );
53477  return (pWal ? pWal->szPage : 0);
53478}
53479#endif
53480
53481#endif /* #ifndef SQLITE_OMIT_WAL */
53482
53483/************** End of wal.c *************************************************/
53484/************** Begin file btmutex.c *****************************************/
53485/*
53486** 2007 August 27
53487**
53488** The author disclaims copyright to this source code.  In place of
53489** a legal notice, here is a blessing:
53490**
53491**    May you do good and not evil.
53492**    May you find forgiveness for yourself and forgive others.
53493**    May you share freely, never taking more than you give.
53494**
53495*************************************************************************
53496**
53497** This file contains code used to implement mutexes on Btree objects.
53498** This code really belongs in btree.c.  But btree.c is getting too
53499** big and we want to break it down some.  This packaged seemed like
53500** a good breakout.
53501*/
53502/************** Include btreeInt.h in the middle of btmutex.c ****************/
53503/************** Begin file btreeInt.h ****************************************/
53504/*
53505** 2004 April 6
53506**
53507** The author disclaims copyright to this source code.  In place of
53508** a legal notice, here is a blessing:
53509**
53510**    May you do good and not evil.
53511**    May you find forgiveness for yourself and forgive others.
53512**    May you share freely, never taking more than you give.
53513**
53514*************************************************************************
53515** This file implements an external (disk-based) database using BTrees.
53516** For a detailed discussion of BTrees, refer to
53517**
53518**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
53519**     "Sorting And Searching", pages 473-480. Addison-Wesley
53520**     Publishing Company, Reading, Massachusetts.
53521**
53522** The basic idea is that each page of the file contains N database
53523** entries and N+1 pointers to subpages.
53524**
53525**   ----------------------------------------------------------------
53526**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
53527**   ----------------------------------------------------------------
53528**
53529** All of the keys on the page that Ptr(0) points to have values less
53530** than Key(0).  All of the keys on page Ptr(1) and its subpages have
53531** values greater than Key(0) and less than Key(1).  All of the keys
53532** on Ptr(N) and its subpages have values greater than Key(N-1).  And
53533** so forth.
53534**
53535** Finding a particular key requires reading O(log(M)) pages from the
53536** disk where M is the number of entries in the tree.
53537**
53538** In this implementation, a single file can hold one or more separate
53539** BTrees.  Each BTree is identified by the index of its root page.  The
53540** key and data for any entry are combined to form the "payload".  A
53541** fixed amount of payload can be carried directly on the database
53542** page.  If the payload is larger than the preset amount then surplus
53543** bytes are stored on overflow pages.  The payload for an entry
53544** and the preceding pointer are combined to form a "Cell".  Each
53545** page has a small header which contains the Ptr(N) pointer and other
53546** information such as the size of key and data.
53547**
53548** FORMAT DETAILS
53549**
53550** The file is divided into pages.  The first page is called page 1,
53551** the second is page 2, and so forth.  A page number of zero indicates
53552** "no such page".  The page size can be any power of 2 between 512 and 65536.
53553** Each page can be either a btree page, a freelist page, an overflow
53554** page, or a pointer-map page.
53555**
53556** The first page is always a btree page.  The first 100 bytes of the first
53557** page contain a special header (the "file header") that describes the file.
53558** The format of the file header is as follows:
53559**
53560**   OFFSET   SIZE    DESCRIPTION
53561**      0      16     Header string: "SQLite format 3\000"
53562**     16       2     Page size in bytes.  (1 means 65536)
53563**     18       1     File format write version
53564**     19       1     File format read version
53565**     20       1     Bytes of unused space at the end of each page
53566**     21       1     Max embedded payload fraction (must be 64)
53567**     22       1     Min embedded payload fraction (must be 32)
53568**     23       1     Min leaf payload fraction (must be 32)
53569**     24       4     File change counter
53570**     28       4     Reserved for future use
53571**     32       4     First freelist page
53572**     36       4     Number of freelist pages in the file
53573**     40      60     15 4-byte meta values passed to higher layers
53574**
53575**     40       4     Schema cookie
53576**     44       4     File format of schema layer
53577**     48       4     Size of page cache
53578**     52       4     Largest root-page (auto/incr_vacuum)
53579**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
53580**     60       4     User version
53581**     64       4     Incremental vacuum mode
53582**     68       4     Application-ID
53583**     72      20     unused
53584**     92       4     The version-valid-for number
53585**     96       4     SQLITE_VERSION_NUMBER
53586**
53587** All of the integer values are big-endian (most significant byte first).
53588**
53589** The file change counter is incremented when the database is changed
53590** This counter allows other processes to know when the file has changed
53591** and thus when they need to flush their cache.
53592**
53593** The max embedded payload fraction is the amount of the total usable
53594** space in a page that can be consumed by a single cell for standard
53595** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
53596** is to limit the maximum cell size so that at least 4 cells will fit
53597** on one page.  Thus the default max embedded payload fraction is 64.
53598**
53599** If the payload for a cell is larger than the max payload, then extra
53600** payload is spilled to overflow pages.  Once an overflow page is allocated,
53601** as many bytes as possible are moved into the overflow pages without letting
53602** the cell size drop below the min embedded payload fraction.
53603**
53604** The min leaf payload fraction is like the min embedded payload fraction
53605** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
53606** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
53607** not specified in the header.
53608**
53609** Each btree pages is divided into three sections:  The header, the
53610** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
53611** file header that occurs before the page header.
53612**
53613**      |----------------|
53614**      | file header    |   100 bytes.  Page 1 only.
53615**      |----------------|
53616**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
53617**      |----------------|
53618**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
53619**      | array          |   |  Grows downward
53620**      |                |   v
53621**      |----------------|
53622**      | unallocated    |
53623**      | space          |
53624**      |----------------|   ^  Grows upwards
53625**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
53626**      | area           |   |  and free space fragments.
53627**      |----------------|
53628**
53629** The page headers looks like this:
53630**
53631**   OFFSET   SIZE     DESCRIPTION
53632**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
53633**      1       2      byte offset to the first freeblock
53634**      3       2      number of cells on this page
53635**      5       2      first byte of the cell content area
53636**      7       1      number of fragmented free bytes
53637**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
53638**
53639** The flags define the format of this btree page.  The leaf flag means that
53640** this page has no children.  The zerodata flag means that this page carries
53641** only keys and no data.  The intkey flag means that the key is an integer
53642** which is stored in the key size entry of the cell header rather than in
53643** the payload area.
53644**
53645** The cell pointer array begins on the first byte after the page header.
53646** The cell pointer array contains zero or more 2-byte numbers which are
53647** offsets from the beginning of the page to the cell content in the cell
53648** content area.  The cell pointers occur in sorted order.  The system strives
53649** to keep free space after the last cell pointer so that new cells can
53650** be easily added without having to defragment the page.
53651**
53652** Cell content is stored at the very end of the page and grows toward the
53653** beginning of the page.
53654**
53655** Unused space within the cell content area is collected into a linked list of
53656** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
53657** to the first freeblock is given in the header.  Freeblocks occur in
53658** increasing order.  Because a freeblock must be at least 4 bytes in size,
53659** any group of 3 or fewer unused bytes in the cell content area cannot
53660** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
53661** a fragment.  The total number of bytes in all fragments is recorded.
53662** in the page header at offset 7.
53663**
53664**    SIZE    DESCRIPTION
53665**      2     Byte offset of the next freeblock
53666**      2     Bytes in this freeblock
53667**
53668** Cells are of variable length.  Cells are stored in the cell content area at
53669** the end of the page.  Pointers to the cells are in the cell pointer array
53670** that immediately follows the page header.  Cells is not necessarily
53671** contiguous or in order, but cell pointers are contiguous and in order.
53672**
53673** Cell content makes use of variable length integers.  A variable
53674** length integer is 1 to 9 bytes where the lower 7 bits of each
53675** byte are used.  The integer consists of all bytes that have bit 8 set and
53676** the first byte with bit 8 clear.  The most significant byte of the integer
53677** appears first.  A variable-length integer may not be more than 9 bytes long.
53678** As a special case, all 8 bytes of the 9th byte are used as data.  This
53679** allows a 64-bit integer to be encoded in 9 bytes.
53680**
53681**    0x00                      becomes  0x00000000
53682**    0x7f                      becomes  0x0000007f
53683**    0x81 0x00                 becomes  0x00000080
53684**    0x82 0x00                 becomes  0x00000100
53685**    0x80 0x7f                 becomes  0x0000007f
53686**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
53687**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
53688**
53689** Variable length integers are used for rowids and to hold the number of
53690** bytes of key and data in a btree cell.
53691**
53692** The content of a cell looks like this:
53693**
53694**    SIZE    DESCRIPTION
53695**      4     Page number of the left child. Omitted if leaf flag is set.
53696**     var    Number of bytes of data. Omitted if the zerodata flag is set.
53697**     var    Number of bytes of key. Or the key itself if intkey flag is set.
53698**      *     Payload
53699**      4     First page of the overflow chain.  Omitted if no overflow
53700**
53701** Overflow pages form a linked list.  Each page except the last is completely
53702** filled with data (pagesize - 4 bytes).  The last page can have as little
53703** as 1 byte of data.
53704**
53705**    SIZE    DESCRIPTION
53706**      4     Page number of next overflow page
53707**      *     Data
53708**
53709** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
53710** file header points to the first in a linked list of trunk page.  Each trunk
53711** page points to multiple leaf pages.  The content of a leaf page is
53712** unspecified.  A trunk page looks like this:
53713**
53714**    SIZE    DESCRIPTION
53715**      4     Page number of next trunk page
53716**      4     Number of leaf pointers on this page
53717**      *     zero or more pages numbers of leaves
53718*/
53719/* #include "sqliteInt.h" */
53720
53721
53722/* The following value is the maximum cell size assuming a maximum page
53723** size give above.
53724*/
53725#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
53726
53727/* The maximum number of cells on a single page of the database.  This
53728** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
53729** plus 2 bytes for the index to the cell in the page header).  Such
53730** small cells will be rare, but they are possible.
53731*/
53732#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
53733
53734/* Forward declarations */
53735typedef struct MemPage MemPage;
53736typedef struct BtLock BtLock;
53737typedef struct CellInfo CellInfo;
53738
53739/*
53740** This is a magic string that appears at the beginning of every
53741** SQLite database in order to identify the file as a real database.
53742**
53743** You can change this value at compile-time by specifying a
53744** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
53745** header must be exactly 16 bytes including the zero-terminator so
53746** the string itself should be 15 characters long.  If you change
53747** the header, then your custom library will not be able to read
53748** databases generated by the standard tools and the standard tools
53749** will not be able to read databases created by your custom library.
53750*/
53751#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
53752#  define SQLITE_FILE_HEADER "SQLite format 3"
53753#endif
53754
53755/*
53756** Page type flags.  An ORed combination of these flags appear as the
53757** first byte of on-disk image of every BTree page.
53758*/
53759#define PTF_INTKEY    0x01
53760#define PTF_ZERODATA  0x02
53761#define PTF_LEAFDATA  0x04
53762#define PTF_LEAF      0x08
53763
53764/*
53765** As each page of the file is loaded into memory, an instance of the following
53766** structure is appended and initialized to zero.  This structure stores
53767** information about the page that is decoded from the raw file page.
53768**
53769** The pParent field points back to the parent page.  This allows us to
53770** walk up the BTree from any leaf to the root.  Care must be taken to
53771** unref() the parent page pointer when this page is no longer referenced.
53772** The pageDestructor() routine handles that chore.
53773**
53774** Access to all fields of this structure is controlled by the mutex
53775** stored in MemPage.pBt->mutex.
53776*/
53777struct MemPage {
53778  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
53779  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
53780  u8 intKey;           /* True if table b-trees.  False for index b-trees */
53781  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
53782  u8 noPayload;        /* True if internal intKey page (thus w/o data) */
53783  u8 leaf;             /* True if a leaf page */
53784  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
53785  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
53786  u8 max1bytePayload;  /* min(maxLocal,127) */
53787  u8 bBusy;            /* Prevent endless loops on corrupt database files */
53788  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
53789  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
53790  u16 cellOffset;      /* Index in aData of first cell pointer */
53791  u16 nFree;           /* Number of free bytes on the page */
53792  u16 nCell;           /* Number of cells on this page, local and ovfl */
53793  u16 maskPage;        /* Mask for page offset */
53794  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
53795                       ** non-overflow cell */
53796  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
53797  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
53798  u8 *aData;           /* Pointer to disk image of the page data */
53799  u8 *aDataEnd;        /* One byte past the end of usable data */
53800  u8 *aCellIdx;        /* The cell index area */
53801  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
53802  DbPage *pDbPage;     /* Pager page handle */
53803  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
53804  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
53805  Pgno pgno;           /* Page number for this page */
53806};
53807
53808/*
53809** The in-memory image of a disk page has the auxiliary information appended
53810** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
53811** that extra information.
53812*/
53813#define EXTRA_SIZE sizeof(MemPage)
53814
53815/*
53816** A linked list of the following structures is stored at BtShared.pLock.
53817** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
53818** is opened on the table with root page BtShared.iTable. Locks are removed
53819** from this list when a transaction is committed or rolled back, or when
53820** a btree handle is closed.
53821*/
53822struct BtLock {
53823  Btree *pBtree;        /* Btree handle holding this lock */
53824  Pgno iTable;          /* Root page of table */
53825  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
53826  BtLock *pNext;        /* Next in BtShared.pLock list */
53827};
53828
53829/* Candidate values for BtLock.eLock */
53830#define READ_LOCK     1
53831#define WRITE_LOCK    2
53832
53833/* A Btree handle
53834**
53835** A database connection contains a pointer to an instance of
53836** this object for every database file that it has open.  This structure
53837** is opaque to the database connection.  The database connection cannot
53838** see the internals of this structure and only deals with pointers to
53839** this structure.
53840**
53841** For some database files, the same underlying database cache might be
53842** shared between multiple connections.  In that case, each connection
53843** has it own instance of this object.  But each instance of this object
53844** points to the same BtShared object.  The database cache and the
53845** schema associated with the database file are all contained within
53846** the BtShared object.
53847**
53848** All fields in this structure are accessed under sqlite3.mutex.
53849** The pBt pointer itself may not be changed while there exists cursors
53850** in the referenced BtShared that point back to this Btree since those
53851** cursors have to go through this Btree to find their BtShared and
53852** they often do so without holding sqlite3.mutex.
53853*/
53854struct Btree {
53855  sqlite3 *db;       /* The database connection holding this btree */
53856  BtShared *pBt;     /* Sharable content of this btree */
53857  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
53858  u8 sharable;       /* True if we can share pBt with another db */
53859  u8 locked;         /* True if db currently has pBt locked */
53860  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
53861  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
53862  int nBackup;       /* Number of backup operations reading this btree */
53863  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
53864  Btree *pNext;      /* List of other sharable Btrees from the same db */
53865  Btree *pPrev;      /* Back pointer of the same list */
53866#ifndef SQLITE_OMIT_SHARED_CACHE
53867  BtLock lock;       /* Object used to lock page 1 */
53868#endif
53869};
53870
53871/*
53872** Btree.inTrans may take one of the following values.
53873**
53874** If the shared-data extension is enabled, there may be multiple users
53875** of the Btree structure. At most one of these may open a write transaction,
53876** but any number may have active read transactions.
53877*/
53878#define TRANS_NONE  0
53879#define TRANS_READ  1
53880#define TRANS_WRITE 2
53881
53882/*
53883** An instance of this object represents a single database file.
53884**
53885** A single database file can be in use at the same time by two
53886** or more database connections.  When two or more connections are
53887** sharing the same database file, each connection has it own
53888** private Btree object for the file and each of those Btrees points
53889** to this one BtShared object.  BtShared.nRef is the number of
53890** connections currently sharing this database file.
53891**
53892** Fields in this structure are accessed under the BtShared.mutex
53893** mutex, except for nRef and pNext which are accessed under the
53894** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
53895** may not be modified once it is initially set as long as nRef>0.
53896** The pSchema field may be set once under BtShared.mutex and
53897** thereafter is unchanged as long as nRef>0.
53898**
53899** isPending:
53900**
53901**   If a BtShared client fails to obtain a write-lock on a database
53902**   table (because there exists one or more read-locks on the table),
53903**   the shared-cache enters 'pending-lock' state and isPending is
53904**   set to true.
53905**
53906**   The shared-cache leaves the 'pending lock' state when either of
53907**   the following occur:
53908**
53909**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
53910**     2) The number of locks held by other connections drops to zero.
53911**
53912**   while in the 'pending-lock' state, no connection may start a new
53913**   transaction.
53914**
53915**   This feature is included to help prevent writer-starvation.
53916*/
53917struct BtShared {
53918  Pager *pPager;        /* The page cache */
53919  sqlite3 *db;          /* Database connection currently using this Btree */
53920  BtCursor *pCursor;    /* A list of all open cursors */
53921  MemPage *pPage1;      /* First page of the database */
53922  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
53923#ifndef SQLITE_OMIT_AUTOVACUUM
53924  u8 autoVacuum;        /* True if auto-vacuum is enabled */
53925  u8 incrVacuum;        /* True if incr-vacuum is enabled */
53926  u8 bDoTruncate;       /* True to truncate db on commit */
53927#endif
53928  u8 inTransaction;     /* Transaction state */
53929  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
53930#ifdef SQLITE_HAS_CODEC
53931  u8 optimalReserve;    /* Desired amount of reserved space per page */
53932#endif
53933  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
53934  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
53935  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
53936  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
53937  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
53938  u32 pageSize;         /* Total number of bytes on a page */
53939  u32 usableSize;       /* Number of usable bytes on each page */
53940  int nTransaction;     /* Number of open transactions (read + write) */
53941  u32 nPage;            /* Number of pages in the database */
53942  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
53943  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
53944  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
53945  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
53946#ifndef SQLITE_OMIT_SHARED_CACHE
53947  int nRef;             /* Number of references to this structure */
53948  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
53949  BtLock *pLock;        /* List of locks held on this shared-btree struct */
53950  Btree *pWriter;       /* Btree with currently open write transaction */
53951#endif
53952  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
53953};
53954
53955/*
53956** Allowed values for BtShared.btsFlags
53957*/
53958#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
53959#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
53960#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
53961#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
53962#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
53963#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
53964#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
53965
53966/*
53967** An instance of the following structure is used to hold information
53968** about a cell.  The parseCellPtr() function fills in this structure
53969** based on information extract from the raw disk page.
53970*/
53971struct CellInfo {
53972  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
53973  u8 *pPayload;  /* Pointer to the start of payload */
53974  u32 nPayload;  /* Bytes of payload */
53975  u16 nLocal;    /* Amount of payload held locally, not on overflow */
53976  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
53977  u16 nSize;     /* Size of the cell content on the main b-tree page */
53978};
53979
53980/*
53981** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
53982** this will be declared corrupt. This value is calculated based on a
53983** maximum database size of 2^31 pages a minimum fanout of 2 for a
53984** root-node and 3 for all other internal nodes.
53985**
53986** If a tree that appears to be taller than this is encountered, it is
53987** assumed that the database is corrupt.
53988*/
53989#define BTCURSOR_MAX_DEPTH 20
53990
53991/*
53992** A cursor is a pointer to a particular entry within a particular
53993** b-tree within a database file.
53994**
53995** The entry is identified by its MemPage and the index in
53996** MemPage.aCell[] of the entry.
53997**
53998** A single database file can be shared by two more database connections,
53999** but cursors cannot be shared.  Each cursor is associated with a
54000** particular database connection identified BtCursor.pBtree.db.
54001**
54002** Fields in this structure are accessed under the BtShared.mutex
54003** found at self->pBt->mutex.
54004**
54005** skipNext meaning:
54006**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
54007**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
54008**    eState==FAULT:                   Cursor fault with skipNext as error code.
54009*/
54010struct BtCursor {
54011  Btree *pBtree;            /* The Btree to which this cursor belongs */
54012  BtShared *pBt;            /* The BtShared this cursor points to */
54013  BtCursor *pNext;          /* Forms a linked list of all cursors */
54014  Pgno *aOverflow;          /* Cache of overflow page locations */
54015  CellInfo info;            /* A parse of the cell we are pointing at */
54016  i64 nKey;                 /* Size of pKey, or last integer key */
54017  void *pKey;               /* Saved key that was cursor last known position */
54018  Pgno pgnoRoot;            /* The root page of this tree */
54019  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
54020  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
54021                   ** Error code if eState==CURSOR_FAULT */
54022  u8 curFlags;              /* zero or more BTCF_* flags defined below */
54023  u8 curPagerFlags;         /* Flags to send to sqlite3PagerAcquire() */
54024  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
54025  u8 hints;                 /* As configured by CursorSetHints() */
54026  /* All fields above are zeroed when the cursor is allocated.  See
54027  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
54028  ** initialized. */
54029  i8 iPage;                 /* Index of current page in apPage */
54030  u8 curIntKey;             /* Value of apPage[0]->intKey */
54031  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
54032  void *padding1;           /* Make object size a multiple of 16 */
54033  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
54034  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
54035};
54036
54037/*
54038** Legal values for BtCursor.curFlags
54039*/
54040#define BTCF_WriteFlag    0x01   /* True if a write cursor */
54041#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
54042#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
54043#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
54044#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
54045#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
54046
54047/*
54048** Potential values for BtCursor.eState.
54049**
54050** CURSOR_INVALID:
54051**   Cursor does not point to a valid entry. This can happen (for example)
54052**   because the table is empty or because BtreeCursorFirst() has not been
54053**   called.
54054**
54055** CURSOR_VALID:
54056**   Cursor points to a valid entry. getPayload() etc. may be called.
54057**
54058** CURSOR_SKIPNEXT:
54059**   Cursor is valid except that the Cursor.skipNext field is non-zero
54060**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
54061**   operation should be a no-op.
54062**
54063** CURSOR_REQUIRESEEK:
54064**   The table that this cursor was opened on still exists, but has been
54065**   modified since the cursor was last used. The cursor position is saved
54066**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
54067**   this state, restoreCursorPosition() can be called to attempt to
54068**   seek the cursor to the saved position.
54069**
54070** CURSOR_FAULT:
54071**   An unrecoverable error (an I/O error or a malloc failure) has occurred
54072**   on a different connection that shares the BtShared cache with this
54073**   cursor.  The error has left the cache in an inconsistent state.
54074**   Do nothing else with this cursor.  Any attempt to use the cursor
54075**   should return the error code stored in BtCursor.skipNext
54076*/
54077#define CURSOR_INVALID           0
54078#define CURSOR_VALID             1
54079#define CURSOR_SKIPNEXT          2
54080#define CURSOR_REQUIRESEEK       3
54081#define CURSOR_FAULT             4
54082
54083/*
54084** The database page the PENDING_BYTE occupies. This page is never used.
54085*/
54086# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
54087
54088/*
54089** These macros define the location of the pointer-map entry for a
54090** database page. The first argument to each is the number of usable
54091** bytes on each page of the database (often 1024). The second is the
54092** page number to look up in the pointer map.
54093**
54094** PTRMAP_PAGENO returns the database page number of the pointer-map
54095** page that stores the required pointer. PTRMAP_PTROFFSET returns
54096** the offset of the requested map entry.
54097**
54098** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
54099** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
54100** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
54101** this test.
54102*/
54103#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
54104#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
54105#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
54106
54107/*
54108** The pointer map is a lookup table that identifies the parent page for
54109** each child page in the database file.  The parent page is the page that
54110** contains a pointer to the child.  Every page in the database contains
54111** 0 or 1 parent pages.  (In this context 'database page' refers
54112** to any page that is not part of the pointer map itself.)  Each pointer map
54113** entry consists of a single byte 'type' and a 4 byte parent page number.
54114** The PTRMAP_XXX identifiers below are the valid types.
54115**
54116** The purpose of the pointer map is to facility moving pages from one
54117** position in the file to another as part of autovacuum.  When a page
54118** is moved, the pointer in its parent must be updated to point to the
54119** new location.  The pointer map is used to locate the parent page quickly.
54120**
54121** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
54122**                  used in this case.
54123**
54124** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
54125**                  is not used in this case.
54126**
54127** PTRMAP_OVERFLOW1: The database page is the first page in a list of
54128**                   overflow pages. The page number identifies the page that
54129**                   contains the cell with a pointer to this overflow page.
54130**
54131** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
54132**                   overflow pages. The page-number identifies the previous
54133**                   page in the overflow page list.
54134**
54135** PTRMAP_BTREE: The database page is a non-root btree page. The page number
54136**               identifies the parent page in the btree.
54137*/
54138#define PTRMAP_ROOTPAGE 1
54139#define PTRMAP_FREEPAGE 2
54140#define PTRMAP_OVERFLOW1 3
54141#define PTRMAP_OVERFLOW2 4
54142#define PTRMAP_BTREE 5
54143
54144/* A bunch of assert() statements to check the transaction state variables
54145** of handle p (type Btree*) are internally consistent.
54146*/
54147#define btreeIntegrity(p) \
54148  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
54149  assert( p->pBt->inTransaction>=p->inTrans );
54150
54151
54152/*
54153** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
54154** if the database supports auto-vacuum or not. Because it is used
54155** within an expression that is an argument to another macro
54156** (sqliteMallocRaw), it is not possible to use conditional compilation.
54157** So, this macro is defined instead.
54158*/
54159#ifndef SQLITE_OMIT_AUTOVACUUM
54160#define ISAUTOVACUUM (pBt->autoVacuum)
54161#else
54162#define ISAUTOVACUUM 0
54163#endif
54164
54165
54166/*
54167** This structure is passed around through all the sanity checking routines
54168** in order to keep track of some global state information.
54169**
54170** The aRef[] array is allocated so that there is 1 bit for each page in
54171** the database. As the integrity-check proceeds, for each page used in
54172** the database the corresponding bit is set. This allows integrity-check to
54173** detect pages that are used twice and orphaned pages (both of which
54174** indicate corruption).
54175*/
54176typedef struct IntegrityCk IntegrityCk;
54177struct IntegrityCk {
54178  BtShared *pBt;    /* The tree being checked out */
54179  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
54180  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
54181  Pgno nPage;       /* Number of pages in the database */
54182  int mxErr;        /* Stop accumulating errors when this reaches zero */
54183  int nErr;         /* Number of messages written to zErrMsg so far */
54184  int mallocFailed; /* A memory allocation error has occurred */
54185  const char *zPfx; /* Error message prefix */
54186  int v1, v2;       /* Values for up to two %d fields in zPfx */
54187  StrAccum errMsg;  /* Accumulate the error message text here */
54188  u32 *heap;        /* Min-heap used for analyzing cell coverage */
54189};
54190
54191/*
54192** Routines to read or write a two- and four-byte big-endian integer values.
54193*/
54194#define get2byte(x)   ((x)[0]<<8 | (x)[1])
54195#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
54196#define get4byte sqlite3Get4byte
54197#define put4byte sqlite3Put4byte
54198
54199/*
54200** get2byteAligned(), unlike get2byte(), requires that its argument point to a
54201** two-byte aligned address.  get2bytea() is only used for accessing the
54202** cell addresses in a btree header.
54203*/
54204#if SQLITE_BYTEORDER==4321
54205# define get2byteAligned(x)  (*(u16*)(x))
54206#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
54207    && GCC_VERSION>=4008000
54208# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
54209#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
54210    && defined(_MSC_VER) && _MSC_VER>=1300
54211# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
54212#else
54213# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
54214#endif
54215
54216/************** End of btreeInt.h ********************************************/
54217/************** Continuing where we left off in btmutex.c ********************/
54218#ifndef SQLITE_OMIT_SHARED_CACHE
54219#if SQLITE_THREADSAFE
54220
54221/*
54222** Obtain the BtShared mutex associated with B-Tree handle p. Also,
54223** set BtShared.db to the database handle associated with p and the
54224** p->locked boolean to true.
54225*/
54226static void lockBtreeMutex(Btree *p){
54227  assert( p->locked==0 );
54228  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
54229  assert( sqlite3_mutex_held(p->db->mutex) );
54230
54231  sqlite3_mutex_enter(p->pBt->mutex);
54232  p->pBt->db = p->db;
54233  p->locked = 1;
54234}
54235
54236/*
54237** Release the BtShared mutex associated with B-Tree handle p and
54238** clear the p->locked boolean.
54239*/
54240static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
54241  BtShared *pBt = p->pBt;
54242  assert( p->locked==1 );
54243  assert( sqlite3_mutex_held(pBt->mutex) );
54244  assert( sqlite3_mutex_held(p->db->mutex) );
54245  assert( p->db==pBt->db );
54246
54247  sqlite3_mutex_leave(pBt->mutex);
54248  p->locked = 0;
54249}
54250
54251/* Forward reference */
54252static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
54253
54254/*
54255** Enter a mutex on the given BTree object.
54256**
54257** If the object is not sharable, then no mutex is ever required
54258** and this routine is a no-op.  The underlying mutex is non-recursive.
54259** But we keep a reference count in Btree.wantToLock so the behavior
54260** of this interface is recursive.
54261**
54262** To avoid deadlocks, multiple Btrees are locked in the same order
54263** by all database connections.  The p->pNext is a list of other
54264** Btrees belonging to the same database connection as the p Btree
54265** which need to be locked after p.  If we cannot get a lock on
54266** p, then first unlock all of the others on p->pNext, then wait
54267** for the lock to become available on p, then relock all of the
54268** subsequent Btrees that desire a lock.
54269*/
54270SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
54271  /* Some basic sanity checking on the Btree.  The list of Btrees
54272  ** connected by pNext and pPrev should be in sorted order by
54273  ** Btree.pBt value. All elements of the list should belong to
54274  ** the same connection. Only shared Btrees are on the list. */
54275  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
54276  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
54277  assert( p->pNext==0 || p->pNext->db==p->db );
54278  assert( p->pPrev==0 || p->pPrev->db==p->db );
54279  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
54280
54281  /* Check for locking consistency */
54282  assert( !p->locked || p->wantToLock>0 );
54283  assert( p->sharable || p->wantToLock==0 );
54284
54285  /* We should already hold a lock on the database connection */
54286  assert( sqlite3_mutex_held(p->db->mutex) );
54287
54288  /* Unless the database is sharable and unlocked, then BtShared.db
54289  ** should already be set correctly. */
54290  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
54291
54292  if( !p->sharable ) return;
54293  p->wantToLock++;
54294  if( p->locked ) return;
54295  btreeLockCarefully(p);
54296}
54297
54298/* This is a helper function for sqlite3BtreeLock(). By moving
54299** complex, but seldom used logic, out of sqlite3BtreeLock() and
54300** into this routine, we avoid unnecessary stack pointer changes
54301** and thus help the sqlite3BtreeLock() routine to run much faster
54302** in the common case.
54303*/
54304static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
54305  Btree *pLater;
54306
54307  /* In most cases, we should be able to acquire the lock we
54308  ** want without having to go through the ascending lock
54309  ** procedure that follows.  Just be sure not to block.
54310  */
54311  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
54312    p->pBt->db = p->db;
54313    p->locked = 1;
54314    return;
54315  }
54316
54317  /* To avoid deadlock, first release all locks with a larger
54318  ** BtShared address.  Then acquire our lock.  Then reacquire
54319  ** the other BtShared locks that we used to hold in ascending
54320  ** order.
54321  */
54322  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
54323    assert( pLater->sharable );
54324    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
54325    assert( !pLater->locked || pLater->wantToLock>0 );
54326    if( pLater->locked ){
54327      unlockBtreeMutex(pLater);
54328    }
54329  }
54330  lockBtreeMutex(p);
54331  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
54332    if( pLater->wantToLock ){
54333      lockBtreeMutex(pLater);
54334    }
54335  }
54336}
54337
54338
54339/*
54340** Exit the recursive mutex on a Btree.
54341*/
54342SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
54343  assert( sqlite3_mutex_held(p->db->mutex) );
54344  if( p->sharable ){
54345    assert( p->wantToLock>0 );
54346    p->wantToLock--;
54347    if( p->wantToLock==0 ){
54348      unlockBtreeMutex(p);
54349    }
54350  }
54351}
54352
54353#ifndef NDEBUG
54354/*
54355** Return true if the BtShared mutex is held on the btree, or if the
54356** B-Tree is not marked as sharable.
54357**
54358** This routine is used only from within assert() statements.
54359*/
54360SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
54361  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
54362  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
54363  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
54364  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
54365
54366  return (p->sharable==0 || p->locked);
54367}
54368#endif
54369
54370
54371#ifndef SQLITE_OMIT_INCRBLOB
54372/*
54373** Enter and leave a mutex on a Btree given a cursor owned by that
54374** Btree.  These entry points are used by incremental I/O and can be
54375** omitted if that module is not used.
54376*/
54377SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
54378  sqlite3BtreeEnter(pCur->pBtree);
54379}
54380SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
54381  sqlite3BtreeLeave(pCur->pBtree);
54382}
54383#endif /* SQLITE_OMIT_INCRBLOB */
54384
54385
54386/*
54387** Enter the mutex on every Btree associated with a database
54388** connection.  This is needed (for example) prior to parsing
54389** a statement since we will be comparing table and column names
54390** against all schemas and we do not want those schemas being
54391** reset out from under us.
54392**
54393** There is a corresponding leave-all procedures.
54394**
54395** Enter the mutexes in accending order by BtShared pointer address
54396** to avoid the possibility of deadlock when two threads with
54397** two or more btrees in common both try to lock all their btrees
54398** at the same instant.
54399*/
54400SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
54401  int i;
54402  Btree *p;
54403  assert( sqlite3_mutex_held(db->mutex) );
54404  for(i=0; i<db->nDb; i++){
54405    p = db->aDb[i].pBt;
54406    if( p ) sqlite3BtreeEnter(p);
54407  }
54408}
54409SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
54410  int i;
54411  Btree *p;
54412  assert( sqlite3_mutex_held(db->mutex) );
54413  for(i=0; i<db->nDb; i++){
54414    p = db->aDb[i].pBt;
54415    if( p ) sqlite3BtreeLeave(p);
54416  }
54417}
54418
54419/*
54420** Return true if a particular Btree requires a lock.  Return FALSE if
54421** no lock is ever required since it is not sharable.
54422*/
54423SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
54424  return p->sharable;
54425}
54426
54427#ifndef NDEBUG
54428/*
54429** Return true if the current thread holds the database connection
54430** mutex and all required BtShared mutexes.
54431**
54432** This routine is used inside assert() statements only.
54433*/
54434SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
54435  int i;
54436  if( !sqlite3_mutex_held(db->mutex) ){
54437    return 0;
54438  }
54439  for(i=0; i<db->nDb; i++){
54440    Btree *p;
54441    p = db->aDb[i].pBt;
54442    if( p && p->sharable &&
54443         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
54444      return 0;
54445    }
54446  }
54447  return 1;
54448}
54449#endif /* NDEBUG */
54450
54451#ifndef NDEBUG
54452/*
54453** Return true if the correct mutexes are held for accessing the
54454** db->aDb[iDb].pSchema structure.  The mutexes required for schema
54455** access are:
54456**
54457**   (1) The mutex on db
54458**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
54459**
54460** If pSchema is not NULL, then iDb is computed from pSchema and
54461** db using sqlite3SchemaToIndex().
54462*/
54463SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
54464  Btree *p;
54465  assert( db!=0 );
54466  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
54467  assert( iDb>=0 && iDb<db->nDb );
54468  if( !sqlite3_mutex_held(db->mutex) ) return 0;
54469  if( iDb==1 ) return 1;
54470  p = db->aDb[iDb].pBt;
54471  assert( p!=0 );
54472  return p->sharable==0 || p->locked==1;
54473}
54474#endif /* NDEBUG */
54475
54476#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
54477/*
54478** The following are special cases for mutex enter routines for use
54479** in single threaded applications that use shared cache.  Except for
54480** these two routines, all mutex operations are no-ops in that case and
54481** are null #defines in btree.h.
54482**
54483** If shared cache is disabled, then all btree mutex routines, including
54484** the ones below, are no-ops and are null #defines in btree.h.
54485*/
54486
54487SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
54488  p->pBt->db = p->db;
54489}
54490SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
54491  int i;
54492  for(i=0; i<db->nDb; i++){
54493    Btree *p = db->aDb[i].pBt;
54494    if( p ){
54495      p->pBt->db = p->db;
54496    }
54497  }
54498}
54499#endif /* if SQLITE_THREADSAFE */
54500#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
54501
54502/************** End of btmutex.c *********************************************/
54503/************** Begin file btree.c *******************************************/
54504/*
54505** 2004 April 6
54506**
54507** The author disclaims copyright to this source code.  In place of
54508** a legal notice, here is a blessing:
54509**
54510**    May you do good and not evil.
54511**    May you find forgiveness for yourself and forgive others.
54512**    May you share freely, never taking more than you give.
54513**
54514*************************************************************************
54515** This file implements an external (disk-based) database using BTrees.
54516** See the header comment on "btreeInt.h" for additional information.
54517** Including a description of file format and an overview of operation.
54518*/
54519/* #include "btreeInt.h" */
54520
54521/*
54522** The header string that appears at the beginning of every
54523** SQLite database.
54524*/
54525static const char zMagicHeader[] = SQLITE_FILE_HEADER;
54526
54527/*
54528** Set this global variable to 1 to enable tracing using the TRACE
54529** macro.
54530*/
54531#if 0
54532int sqlite3BtreeTrace=1;  /* True to enable tracing */
54533# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
54534#else
54535# define TRACE(X)
54536#endif
54537
54538/*
54539** Extract a 2-byte big-endian integer from an array of unsigned bytes.
54540** But if the value is zero, make it 65536.
54541**
54542** This routine is used to extract the "offset to cell content area" value
54543** from the header of a btree page.  If the page size is 65536 and the page
54544** is empty, the offset should be 65536, but the 2-byte value stores zero.
54545** This routine makes the necessary adjustment to 65536.
54546*/
54547#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
54548
54549/*
54550** Values passed as the 5th argument to allocateBtreePage()
54551*/
54552#define BTALLOC_ANY   0           /* Allocate any page */
54553#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
54554#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
54555
54556/*
54557** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
54558** defined, or 0 if it is. For example:
54559**
54560**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
54561*/
54562#ifndef SQLITE_OMIT_AUTOVACUUM
54563#define IfNotOmitAV(expr) (expr)
54564#else
54565#define IfNotOmitAV(expr) 0
54566#endif
54567
54568#ifndef SQLITE_OMIT_SHARED_CACHE
54569/*
54570** A list of BtShared objects that are eligible for participation
54571** in shared cache.  This variable has file scope during normal builds,
54572** but the test harness needs to access it so we make it global for
54573** test builds.
54574**
54575** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
54576*/
54577#ifdef SQLITE_TEST
54578SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
54579#else
54580static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
54581#endif
54582#endif /* SQLITE_OMIT_SHARED_CACHE */
54583
54584#ifndef SQLITE_OMIT_SHARED_CACHE
54585/*
54586** Enable or disable the shared pager and schema features.
54587**
54588** This routine has no effect on existing database connections.
54589** The shared cache setting effects only future calls to
54590** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
54591*/
54592SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
54593  sqlite3GlobalConfig.sharedCacheEnabled = enable;
54594  return SQLITE_OK;
54595}
54596#endif
54597
54598
54599
54600#ifdef SQLITE_OMIT_SHARED_CACHE
54601  /*
54602  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
54603  ** and clearAllSharedCacheTableLocks()
54604  ** manipulate entries in the BtShared.pLock linked list used to store
54605  ** shared-cache table level locks. If the library is compiled with the
54606  ** shared-cache feature disabled, then there is only ever one user
54607  ** of each BtShared structure and so this locking is not necessary.
54608  ** So define the lock related functions as no-ops.
54609  */
54610  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
54611  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
54612  #define clearAllSharedCacheTableLocks(a)
54613  #define downgradeAllSharedCacheTableLocks(a)
54614  #define hasSharedCacheTableLock(a,b,c,d) 1
54615  #define hasReadConflicts(a, b) 0
54616#endif
54617
54618#ifndef SQLITE_OMIT_SHARED_CACHE
54619
54620#ifdef SQLITE_DEBUG
54621/*
54622**** This function is only used as part of an assert() statement. ***
54623**
54624** Check to see if pBtree holds the required locks to read or write to the
54625** table with root page iRoot.   Return 1 if it does and 0 if not.
54626**
54627** For example, when writing to a table with root-page iRoot via
54628** Btree connection pBtree:
54629**
54630**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
54631**
54632** When writing to an index that resides in a sharable database, the
54633** caller should have first obtained a lock specifying the root page of
54634** the corresponding table. This makes things a bit more complicated,
54635** as this module treats each table as a separate structure. To determine
54636** the table corresponding to the index being written, this
54637** function has to search through the database schema.
54638**
54639** Instead of a lock on the table/index rooted at page iRoot, the caller may
54640** hold a write-lock on the schema table (root page 1). This is also
54641** acceptable.
54642*/
54643static int hasSharedCacheTableLock(
54644  Btree *pBtree,         /* Handle that must hold lock */
54645  Pgno iRoot,            /* Root page of b-tree */
54646  int isIndex,           /* True if iRoot is the root of an index b-tree */
54647  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
54648){
54649  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
54650  Pgno iTab = 0;
54651  BtLock *pLock;
54652
54653  /* If this database is not shareable, or if the client is reading
54654  ** and has the read-uncommitted flag set, then no lock is required.
54655  ** Return true immediately.
54656  */
54657  if( (pBtree->sharable==0)
54658   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
54659  ){
54660    return 1;
54661  }
54662
54663  /* If the client is reading  or writing an index and the schema is
54664  ** not loaded, then it is too difficult to actually check to see if
54665  ** the correct locks are held.  So do not bother - just return true.
54666  ** This case does not come up very often anyhow.
54667  */
54668  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
54669    return 1;
54670  }
54671
54672  /* Figure out the root-page that the lock should be held on. For table
54673  ** b-trees, this is just the root page of the b-tree being read or
54674  ** written. For index b-trees, it is the root page of the associated
54675  ** table.  */
54676  if( isIndex ){
54677    HashElem *p;
54678    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
54679      Index *pIdx = (Index *)sqliteHashData(p);
54680      if( pIdx->tnum==(int)iRoot ){
54681        if( iTab ){
54682          /* Two or more indexes share the same root page.  There must
54683          ** be imposter tables.  So just return true.  The assert is not
54684          ** useful in that case. */
54685          return 1;
54686        }
54687        iTab = pIdx->pTable->tnum;
54688      }
54689    }
54690  }else{
54691    iTab = iRoot;
54692  }
54693
54694  /* Search for the required lock. Either a write-lock on root-page iTab, a
54695  ** write-lock on the schema table, or (if the client is reading) a
54696  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
54697  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
54698    if( pLock->pBtree==pBtree
54699     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
54700     && pLock->eLock>=eLockType
54701    ){
54702      return 1;
54703    }
54704  }
54705
54706  /* Failed to find the required lock. */
54707  return 0;
54708}
54709#endif /* SQLITE_DEBUG */
54710
54711#ifdef SQLITE_DEBUG
54712/*
54713**** This function may be used as part of assert() statements only. ****
54714**
54715** Return true if it would be illegal for pBtree to write into the
54716** table or index rooted at iRoot because other shared connections are
54717** simultaneously reading that same table or index.
54718**
54719** It is illegal for pBtree to write if some other Btree object that
54720** shares the same BtShared object is currently reading or writing
54721** the iRoot table.  Except, if the other Btree object has the
54722** read-uncommitted flag set, then it is OK for the other object to
54723** have a read cursor.
54724**
54725** For example, before writing to any part of the table or index
54726** rooted at page iRoot, one should call:
54727**
54728**    assert( !hasReadConflicts(pBtree, iRoot) );
54729*/
54730static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
54731  BtCursor *p;
54732  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
54733    if( p->pgnoRoot==iRoot
54734     && p->pBtree!=pBtree
54735     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
54736    ){
54737      return 1;
54738    }
54739  }
54740  return 0;
54741}
54742#endif    /* #ifdef SQLITE_DEBUG */
54743
54744/*
54745** Query to see if Btree handle p may obtain a lock of type eLock
54746** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
54747** SQLITE_OK if the lock may be obtained (by calling
54748** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
54749*/
54750static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
54751  BtShared *pBt = p->pBt;
54752  BtLock *pIter;
54753
54754  assert( sqlite3BtreeHoldsMutex(p) );
54755  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
54756  assert( p->db!=0 );
54757  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
54758
54759  /* If requesting a write-lock, then the Btree must have an open write
54760  ** transaction on this file. And, obviously, for this to be so there
54761  ** must be an open write transaction on the file itself.
54762  */
54763  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
54764  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
54765
54766  /* This routine is a no-op if the shared-cache is not enabled */
54767  if( !p->sharable ){
54768    return SQLITE_OK;
54769  }
54770
54771  /* If some other connection is holding an exclusive lock, the
54772  ** requested lock may not be obtained.
54773  */
54774  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
54775    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
54776    return SQLITE_LOCKED_SHAREDCACHE;
54777  }
54778
54779  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
54780    /* The condition (pIter->eLock!=eLock) in the following if(...)
54781    ** statement is a simplification of:
54782    **
54783    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
54784    **
54785    ** since we know that if eLock==WRITE_LOCK, then no other connection
54786    ** may hold a WRITE_LOCK on any table in this file (since there can
54787    ** only be a single writer).
54788    */
54789    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
54790    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
54791    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
54792      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
54793      if( eLock==WRITE_LOCK ){
54794        assert( p==pBt->pWriter );
54795        pBt->btsFlags |= BTS_PENDING;
54796      }
54797      return SQLITE_LOCKED_SHAREDCACHE;
54798    }
54799  }
54800  return SQLITE_OK;
54801}
54802#endif /* !SQLITE_OMIT_SHARED_CACHE */
54803
54804#ifndef SQLITE_OMIT_SHARED_CACHE
54805/*
54806** Add a lock on the table with root-page iTable to the shared-btree used
54807** by Btree handle p. Parameter eLock must be either READ_LOCK or
54808** WRITE_LOCK.
54809**
54810** This function assumes the following:
54811**
54812**   (a) The specified Btree object p is connected to a sharable
54813**       database (one with the BtShared.sharable flag set), and
54814**
54815**   (b) No other Btree objects hold a lock that conflicts
54816**       with the requested lock (i.e. querySharedCacheTableLock() has
54817**       already been called and returned SQLITE_OK).
54818**
54819** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
54820** is returned if a malloc attempt fails.
54821*/
54822static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
54823  BtShared *pBt = p->pBt;
54824  BtLock *pLock = 0;
54825  BtLock *pIter;
54826
54827  assert( sqlite3BtreeHoldsMutex(p) );
54828  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
54829  assert( p->db!=0 );
54830
54831  /* A connection with the read-uncommitted flag set will never try to
54832  ** obtain a read-lock using this function. The only read-lock obtained
54833  ** by a connection in read-uncommitted mode is on the sqlite_master
54834  ** table, and that lock is obtained in BtreeBeginTrans().  */
54835  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
54836
54837  /* This function should only be called on a sharable b-tree after it
54838  ** has been determined that no other b-tree holds a conflicting lock.  */
54839  assert( p->sharable );
54840  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
54841
54842  /* First search the list for an existing lock on this table. */
54843  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
54844    if( pIter->iTable==iTable && pIter->pBtree==p ){
54845      pLock = pIter;
54846      break;
54847    }
54848  }
54849
54850  /* If the above search did not find a BtLock struct associating Btree p
54851  ** with table iTable, allocate one and link it into the list.
54852  */
54853  if( !pLock ){
54854    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
54855    if( !pLock ){
54856      return SQLITE_NOMEM;
54857    }
54858    pLock->iTable = iTable;
54859    pLock->pBtree = p;
54860    pLock->pNext = pBt->pLock;
54861    pBt->pLock = pLock;
54862  }
54863
54864  /* Set the BtLock.eLock variable to the maximum of the current lock
54865  ** and the requested lock. This means if a write-lock was already held
54866  ** and a read-lock requested, we don't incorrectly downgrade the lock.
54867  */
54868  assert( WRITE_LOCK>READ_LOCK );
54869  if( eLock>pLock->eLock ){
54870    pLock->eLock = eLock;
54871  }
54872
54873  return SQLITE_OK;
54874}
54875#endif /* !SQLITE_OMIT_SHARED_CACHE */
54876
54877#ifndef SQLITE_OMIT_SHARED_CACHE
54878/*
54879** Release all the table locks (locks obtained via calls to
54880** the setSharedCacheTableLock() procedure) held by Btree object p.
54881**
54882** This function assumes that Btree p has an open read or write
54883** transaction. If it does not, then the BTS_PENDING flag
54884** may be incorrectly cleared.
54885*/
54886static void clearAllSharedCacheTableLocks(Btree *p){
54887  BtShared *pBt = p->pBt;
54888  BtLock **ppIter = &pBt->pLock;
54889
54890  assert( sqlite3BtreeHoldsMutex(p) );
54891  assert( p->sharable || 0==*ppIter );
54892  assert( p->inTrans>0 );
54893
54894  while( *ppIter ){
54895    BtLock *pLock = *ppIter;
54896    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
54897    assert( pLock->pBtree->inTrans>=pLock->eLock );
54898    if( pLock->pBtree==p ){
54899      *ppIter = pLock->pNext;
54900      assert( pLock->iTable!=1 || pLock==&p->lock );
54901      if( pLock->iTable!=1 ){
54902        sqlite3_free(pLock);
54903      }
54904    }else{
54905      ppIter = &pLock->pNext;
54906    }
54907  }
54908
54909  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
54910  if( pBt->pWriter==p ){
54911    pBt->pWriter = 0;
54912    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
54913  }else if( pBt->nTransaction==2 ){
54914    /* This function is called when Btree p is concluding its
54915    ** transaction. If there currently exists a writer, and p is not
54916    ** that writer, then the number of locks held by connections other
54917    ** than the writer must be about to drop to zero. In this case
54918    ** set the BTS_PENDING flag to 0.
54919    **
54920    ** If there is not currently a writer, then BTS_PENDING must
54921    ** be zero already. So this next line is harmless in that case.
54922    */
54923    pBt->btsFlags &= ~BTS_PENDING;
54924  }
54925}
54926
54927/*
54928** This function changes all write-locks held by Btree p into read-locks.
54929*/
54930static void downgradeAllSharedCacheTableLocks(Btree *p){
54931  BtShared *pBt = p->pBt;
54932  if( pBt->pWriter==p ){
54933    BtLock *pLock;
54934    pBt->pWriter = 0;
54935    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
54936    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
54937      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
54938      pLock->eLock = READ_LOCK;
54939    }
54940  }
54941}
54942
54943#endif /* SQLITE_OMIT_SHARED_CACHE */
54944
54945static void releasePage(MemPage *pPage);  /* Forward reference */
54946
54947/*
54948***** This routine is used inside of assert() only ****
54949**
54950** Verify that the cursor holds the mutex on its BtShared
54951*/
54952#ifdef SQLITE_DEBUG
54953static int cursorHoldsMutex(BtCursor *p){
54954  return sqlite3_mutex_held(p->pBt->mutex);
54955}
54956#endif
54957
54958/*
54959** Invalidate the overflow cache of the cursor passed as the first argument.
54960** on the shared btree structure pBt.
54961*/
54962#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
54963
54964/*
54965** Invalidate the overflow page-list cache for all cursors opened
54966** on the shared btree structure pBt.
54967*/
54968static void invalidateAllOverflowCache(BtShared *pBt){
54969  BtCursor *p;
54970  assert( sqlite3_mutex_held(pBt->mutex) );
54971  for(p=pBt->pCursor; p; p=p->pNext){
54972    invalidateOverflowCache(p);
54973  }
54974}
54975
54976#ifndef SQLITE_OMIT_INCRBLOB
54977/*
54978** This function is called before modifying the contents of a table
54979** to invalidate any incrblob cursors that are open on the
54980** row or one of the rows being modified.
54981**
54982** If argument isClearTable is true, then the entire contents of the
54983** table is about to be deleted. In this case invalidate all incrblob
54984** cursors open on any row within the table with root-page pgnoRoot.
54985**
54986** Otherwise, if argument isClearTable is false, then the row with
54987** rowid iRow is being replaced or deleted. In this case invalidate
54988** only those incrblob cursors open on that specific row.
54989*/
54990static void invalidateIncrblobCursors(
54991  Btree *pBtree,          /* The database file to check */
54992  i64 iRow,               /* The rowid that might be changing */
54993  int isClearTable        /* True if all rows are being deleted */
54994){
54995  BtCursor *p;
54996  if( pBtree->hasIncrblobCur==0 ) return;
54997  assert( sqlite3BtreeHoldsMutex(pBtree) );
54998  pBtree->hasIncrblobCur = 0;
54999  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
55000    if( (p->curFlags & BTCF_Incrblob)!=0 ){
55001      pBtree->hasIncrblobCur = 1;
55002      if( isClearTable || p->info.nKey==iRow ){
55003        p->eState = CURSOR_INVALID;
55004      }
55005    }
55006  }
55007}
55008
55009#else
55010  /* Stub function when INCRBLOB is omitted */
55011  #define invalidateIncrblobCursors(x,y,z)
55012#endif /* SQLITE_OMIT_INCRBLOB */
55013
55014/*
55015** Set bit pgno of the BtShared.pHasContent bitvec. This is called
55016** when a page that previously contained data becomes a free-list leaf
55017** page.
55018**
55019** The BtShared.pHasContent bitvec exists to work around an obscure
55020** bug caused by the interaction of two useful IO optimizations surrounding
55021** free-list leaf pages:
55022**
55023**   1) When all data is deleted from a page and the page becomes
55024**      a free-list leaf page, the page is not written to the database
55025**      (as free-list leaf pages contain no meaningful data). Sometimes
55026**      such a page is not even journalled (as it will not be modified,
55027**      why bother journalling it?).
55028**
55029**   2) When a free-list leaf page is reused, its content is not read
55030**      from the database or written to the journal file (why should it
55031**      be, if it is not at all meaningful?).
55032**
55033** By themselves, these optimizations work fine and provide a handy
55034** performance boost to bulk delete or insert operations. However, if
55035** a page is moved to the free-list and then reused within the same
55036** transaction, a problem comes up. If the page is not journalled when
55037** it is moved to the free-list and it is also not journalled when it
55038** is extracted from the free-list and reused, then the original data
55039** may be lost. In the event of a rollback, it may not be possible
55040** to restore the database to its original configuration.
55041**
55042** The solution is the BtShared.pHasContent bitvec. Whenever a page is
55043** moved to become a free-list leaf page, the corresponding bit is
55044** set in the bitvec. Whenever a leaf page is extracted from the free-list,
55045** optimization 2 above is omitted if the corresponding bit is already
55046** set in BtShared.pHasContent. The contents of the bitvec are cleared
55047** at the end of every transaction.
55048*/
55049static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
55050  int rc = SQLITE_OK;
55051  if( !pBt->pHasContent ){
55052    assert( pgno<=pBt->nPage );
55053    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
55054    if( !pBt->pHasContent ){
55055      rc = SQLITE_NOMEM;
55056    }
55057  }
55058  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
55059    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
55060  }
55061  return rc;
55062}
55063
55064/*
55065** Query the BtShared.pHasContent vector.
55066**
55067** This function is called when a free-list leaf page is removed from the
55068** free-list for reuse. It returns false if it is safe to retrieve the
55069** page from the pager layer with the 'no-content' flag set. True otherwise.
55070*/
55071static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
55072  Bitvec *p = pBt->pHasContent;
55073  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
55074}
55075
55076/*
55077** Clear (destroy) the BtShared.pHasContent bitvec. This should be
55078** invoked at the conclusion of each write-transaction.
55079*/
55080static void btreeClearHasContent(BtShared *pBt){
55081  sqlite3BitvecDestroy(pBt->pHasContent);
55082  pBt->pHasContent = 0;
55083}
55084
55085/*
55086** Release all of the apPage[] pages for a cursor.
55087*/
55088static void btreeReleaseAllCursorPages(BtCursor *pCur){
55089  int i;
55090  for(i=0; i<=pCur->iPage; i++){
55091    releasePage(pCur->apPage[i]);
55092    pCur->apPage[i] = 0;
55093  }
55094  pCur->iPage = -1;
55095}
55096
55097/*
55098** The cursor passed as the only argument must point to a valid entry
55099** when this function is called (i.e. have eState==CURSOR_VALID). This
55100** function saves the current cursor key in variables pCur->nKey and
55101** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
55102** code otherwise.
55103**
55104** If the cursor is open on an intkey table, then the integer key
55105** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
55106** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
55107** set to point to a malloced buffer pCur->nKey bytes in size containing
55108** the key.
55109*/
55110static int saveCursorKey(BtCursor *pCur){
55111  int rc;
55112  assert( CURSOR_VALID==pCur->eState );
55113  assert( 0==pCur->pKey );
55114  assert( cursorHoldsMutex(pCur) );
55115
55116  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
55117  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
55118
55119  /* If this is an intKey table, then the above call to BtreeKeySize()
55120  ** stores the integer key in pCur->nKey. In this case this value is
55121  ** all that is required. Otherwise, if pCur is not open on an intKey
55122  ** table, then malloc space for and store the pCur->nKey bytes of key
55123  ** data.  */
55124  if( 0==pCur->curIntKey ){
55125    void *pKey = sqlite3Malloc( pCur->nKey );
55126    if( pKey ){
55127      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
55128      if( rc==SQLITE_OK ){
55129        pCur->pKey = pKey;
55130      }else{
55131        sqlite3_free(pKey);
55132      }
55133    }else{
55134      rc = SQLITE_NOMEM;
55135    }
55136  }
55137  assert( !pCur->curIntKey || !pCur->pKey );
55138  return rc;
55139}
55140
55141/*
55142** Save the current cursor position in the variables BtCursor.nKey
55143** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
55144**
55145** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
55146** prior to calling this routine.
55147*/
55148static int saveCursorPosition(BtCursor *pCur){
55149  int rc;
55150
55151  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
55152  assert( 0==pCur->pKey );
55153  assert( cursorHoldsMutex(pCur) );
55154
55155  if( pCur->eState==CURSOR_SKIPNEXT ){
55156    pCur->eState = CURSOR_VALID;
55157  }else{
55158    pCur->skipNext = 0;
55159  }
55160
55161  rc = saveCursorKey(pCur);
55162  if( rc==SQLITE_OK ){
55163    btreeReleaseAllCursorPages(pCur);
55164    pCur->eState = CURSOR_REQUIRESEEK;
55165  }
55166
55167  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
55168  return rc;
55169}
55170
55171/* Forward reference */
55172static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
55173
55174/*
55175** Save the positions of all cursors (except pExcept) that are open on
55176** the table with root-page iRoot.  "Saving the cursor position" means that
55177** the location in the btree is remembered in such a way that it can be
55178** moved back to the same spot after the btree has been modified.  This
55179** routine is called just before cursor pExcept is used to modify the
55180** table, for example in BtreeDelete() or BtreeInsert().
55181**
55182** If there are two or more cursors on the same btree, then all such
55183** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
55184** routine enforces that rule.  This routine only needs to be called in
55185** the uncommon case when pExpect has the BTCF_Multiple flag set.
55186**
55187** If pExpect!=NULL and if no other cursors are found on the same root-page,
55188** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
55189** pointless call to this routine.
55190**
55191** Implementation note:  This routine merely checks to see if any cursors
55192** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
55193** event that cursors are in need to being saved.
55194*/
55195static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
55196  BtCursor *p;
55197  assert( sqlite3_mutex_held(pBt->mutex) );
55198  assert( pExcept==0 || pExcept->pBt==pBt );
55199  for(p=pBt->pCursor; p; p=p->pNext){
55200    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
55201  }
55202  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
55203  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
55204  return SQLITE_OK;
55205}
55206
55207/* This helper routine to saveAllCursors does the actual work of saving
55208** the cursors if and when a cursor is found that actually requires saving.
55209** The common case is that no cursors need to be saved, so this routine is
55210** broken out from its caller to avoid unnecessary stack pointer movement.
55211*/
55212static int SQLITE_NOINLINE saveCursorsOnList(
55213  BtCursor *p,         /* The first cursor that needs saving */
55214  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
55215  BtCursor *pExcept    /* Do not save this cursor */
55216){
55217  do{
55218    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
55219      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
55220        int rc = saveCursorPosition(p);
55221        if( SQLITE_OK!=rc ){
55222          return rc;
55223        }
55224      }else{
55225        testcase( p->iPage>0 );
55226        btreeReleaseAllCursorPages(p);
55227      }
55228    }
55229    p = p->pNext;
55230  }while( p );
55231  return SQLITE_OK;
55232}
55233
55234/*
55235** Clear the current cursor position.
55236*/
55237SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
55238  assert( cursorHoldsMutex(pCur) );
55239  sqlite3_free(pCur->pKey);
55240  pCur->pKey = 0;
55241  pCur->eState = CURSOR_INVALID;
55242}
55243
55244/*
55245** In this version of BtreeMoveto, pKey is a packed index record
55246** such as is generated by the OP_MakeRecord opcode.  Unpack the
55247** record and then call BtreeMovetoUnpacked() to do the work.
55248*/
55249static int btreeMoveto(
55250  BtCursor *pCur,     /* Cursor open on the btree to be searched */
55251  const void *pKey,   /* Packed key if the btree is an index */
55252  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
55253  int bias,           /* Bias search to the high end */
55254  int *pRes           /* Write search results here */
55255){
55256  int rc;                    /* Status code */
55257  UnpackedRecord *pIdxKey;   /* Unpacked index key */
55258  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
55259  char *pFree = 0;
55260
55261  if( pKey ){
55262    assert( nKey==(i64)(int)nKey );
55263    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
55264        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
55265    );
55266    if( pIdxKey==0 ) return SQLITE_NOMEM;
55267    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
55268    if( pIdxKey->nField==0 ){
55269      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
55270      return SQLITE_CORRUPT_BKPT;
55271    }
55272  }else{
55273    pIdxKey = 0;
55274  }
55275  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
55276  if( pFree ){
55277    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
55278  }
55279  return rc;
55280}
55281
55282/*
55283** Restore the cursor to the position it was in (or as close to as possible)
55284** when saveCursorPosition() was called. Note that this call deletes the
55285** saved position info stored by saveCursorPosition(), so there can be
55286** at most one effective restoreCursorPosition() call after each
55287** saveCursorPosition().
55288*/
55289static int btreeRestoreCursorPosition(BtCursor *pCur){
55290  int rc;
55291  int skipNext;
55292  assert( cursorHoldsMutex(pCur) );
55293  assert( pCur->eState>=CURSOR_REQUIRESEEK );
55294  if( pCur->eState==CURSOR_FAULT ){
55295    return pCur->skipNext;
55296  }
55297  pCur->eState = CURSOR_INVALID;
55298  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
55299  if( rc==SQLITE_OK ){
55300    sqlite3_free(pCur->pKey);
55301    pCur->pKey = 0;
55302    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
55303    pCur->skipNext |= skipNext;
55304    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
55305      pCur->eState = CURSOR_SKIPNEXT;
55306    }
55307  }
55308  return rc;
55309}
55310
55311#define restoreCursorPosition(p) \
55312  (p->eState>=CURSOR_REQUIRESEEK ? \
55313         btreeRestoreCursorPosition(p) : \
55314         SQLITE_OK)
55315
55316/*
55317** Determine whether or not a cursor has moved from the position where
55318** it was last placed, or has been invalidated for any other reason.
55319** Cursors can move when the row they are pointing at is deleted out
55320** from under them, for example.  Cursor might also move if a btree
55321** is rebalanced.
55322**
55323** Calling this routine with a NULL cursor pointer returns false.
55324**
55325** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
55326** back to where it ought to be if this routine returns true.
55327*/
55328SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
55329  return pCur->eState!=CURSOR_VALID;
55330}
55331
55332/*
55333** This routine restores a cursor back to its original position after it
55334** has been moved by some outside activity (such as a btree rebalance or
55335** a row having been deleted out from under the cursor).
55336**
55337** On success, the *pDifferentRow parameter is false if the cursor is left
55338** pointing at exactly the same row.  *pDifferntRow is the row the cursor
55339** was pointing to has been deleted, forcing the cursor to point to some
55340** nearby row.
55341**
55342** This routine should only be called for a cursor that just returned
55343** TRUE from sqlite3BtreeCursorHasMoved().
55344*/
55345SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
55346  int rc;
55347
55348  assert( pCur!=0 );
55349  assert( pCur->eState!=CURSOR_VALID );
55350  rc = restoreCursorPosition(pCur);
55351  if( rc ){
55352    *pDifferentRow = 1;
55353    return rc;
55354  }
55355  if( pCur->eState!=CURSOR_VALID ){
55356    *pDifferentRow = 1;
55357  }else{
55358    assert( pCur->skipNext==0 );
55359    *pDifferentRow = 0;
55360  }
55361  return SQLITE_OK;
55362}
55363
55364#ifndef SQLITE_OMIT_AUTOVACUUM
55365/*
55366** Given a page number of a regular database page, return the page
55367** number for the pointer-map page that contains the entry for the
55368** input page number.
55369**
55370** Return 0 (not a valid page) for pgno==1 since there is
55371** no pointer map associated with page 1.  The integrity_check logic
55372** requires that ptrmapPageno(*,1)!=1.
55373*/
55374static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
55375  int nPagesPerMapPage;
55376  Pgno iPtrMap, ret;
55377  assert( sqlite3_mutex_held(pBt->mutex) );
55378  if( pgno<2 ) return 0;
55379  nPagesPerMapPage = (pBt->usableSize/5)+1;
55380  iPtrMap = (pgno-2)/nPagesPerMapPage;
55381  ret = (iPtrMap*nPagesPerMapPage) + 2;
55382  if( ret==PENDING_BYTE_PAGE(pBt) ){
55383    ret++;
55384  }
55385  return ret;
55386}
55387
55388/*
55389** Write an entry into the pointer map.
55390**
55391** This routine updates the pointer map entry for page number 'key'
55392** so that it maps to type 'eType' and parent page number 'pgno'.
55393**
55394** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
55395** a no-op.  If an error occurs, the appropriate error code is written
55396** into *pRC.
55397*/
55398static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
55399  DbPage *pDbPage;  /* The pointer map page */
55400  u8 *pPtrmap;      /* The pointer map data */
55401  Pgno iPtrmap;     /* The pointer map page number */
55402  int offset;       /* Offset in pointer map page */
55403  int rc;           /* Return code from subfunctions */
55404
55405  if( *pRC ) return;
55406
55407  assert( sqlite3_mutex_held(pBt->mutex) );
55408  /* The master-journal page number must never be used as a pointer map page */
55409  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
55410
55411  assert( pBt->autoVacuum );
55412  if( key==0 ){
55413    *pRC = SQLITE_CORRUPT_BKPT;
55414    return;
55415  }
55416  iPtrmap = PTRMAP_PAGENO(pBt, key);
55417  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
55418  if( rc!=SQLITE_OK ){
55419    *pRC = rc;
55420    return;
55421  }
55422  offset = PTRMAP_PTROFFSET(iPtrmap, key);
55423  if( offset<0 ){
55424    *pRC = SQLITE_CORRUPT_BKPT;
55425    goto ptrmap_exit;
55426  }
55427  assert( offset <= (int)pBt->usableSize-5 );
55428  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
55429
55430  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
55431    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
55432    *pRC= rc = sqlite3PagerWrite(pDbPage);
55433    if( rc==SQLITE_OK ){
55434      pPtrmap[offset] = eType;
55435      put4byte(&pPtrmap[offset+1], parent);
55436    }
55437  }
55438
55439ptrmap_exit:
55440  sqlite3PagerUnref(pDbPage);
55441}
55442
55443/*
55444** Read an entry from the pointer map.
55445**
55446** This routine retrieves the pointer map entry for page 'key', writing
55447** the type and parent page number to *pEType and *pPgno respectively.
55448** An error code is returned if something goes wrong, otherwise SQLITE_OK.
55449*/
55450static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
55451  DbPage *pDbPage;   /* The pointer map page */
55452  int iPtrmap;       /* Pointer map page index */
55453  u8 *pPtrmap;       /* Pointer map page data */
55454  int offset;        /* Offset of entry in pointer map */
55455  int rc;
55456
55457  assert( sqlite3_mutex_held(pBt->mutex) );
55458
55459  iPtrmap = PTRMAP_PAGENO(pBt, key);
55460  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
55461  if( rc!=0 ){
55462    return rc;
55463  }
55464  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
55465
55466  offset = PTRMAP_PTROFFSET(iPtrmap, key);
55467  if( offset<0 ){
55468    sqlite3PagerUnref(pDbPage);
55469    return SQLITE_CORRUPT_BKPT;
55470  }
55471  assert( offset <= (int)pBt->usableSize-5 );
55472  assert( pEType!=0 );
55473  *pEType = pPtrmap[offset];
55474  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
55475
55476  sqlite3PagerUnref(pDbPage);
55477  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
55478  return SQLITE_OK;
55479}
55480
55481#else /* if defined SQLITE_OMIT_AUTOVACUUM */
55482  #define ptrmapPut(w,x,y,z,rc)
55483  #define ptrmapGet(w,x,y,z) SQLITE_OK
55484  #define ptrmapPutOvflPtr(x, y, rc)
55485#endif
55486
55487/*
55488** Given a btree page and a cell index (0 means the first cell on
55489** the page, 1 means the second cell, and so forth) return a pointer
55490** to the cell content.
55491**
55492** findCellPastPtr() does the same except it skips past the initial
55493** 4-byte child pointer found on interior pages, if there is one.
55494**
55495** This routine works only for pages that do not contain overflow cells.
55496*/
55497#define findCell(P,I) \
55498  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
55499#define findCellPastPtr(P,I) \
55500  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
55501
55502
55503/*
55504** This is common tail processing for btreeParseCellPtr() and
55505** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
55506** on a single B-tree page.  Make necessary adjustments to the CellInfo
55507** structure.
55508*/
55509static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
55510  MemPage *pPage,         /* Page containing the cell */
55511  u8 *pCell,              /* Pointer to the cell text. */
55512  CellInfo *pInfo         /* Fill in this structure */
55513){
55514  /* If the payload will not fit completely on the local page, we have
55515  ** to decide how much to store locally and how much to spill onto
55516  ** overflow pages.  The strategy is to minimize the amount of unused
55517  ** space on overflow pages while keeping the amount of local storage
55518  ** in between minLocal and maxLocal.
55519  **
55520  ** Warning:  changing the way overflow payload is distributed in any
55521  ** way will result in an incompatible file format.
55522  */
55523  int minLocal;  /* Minimum amount of payload held locally */
55524  int maxLocal;  /* Maximum amount of payload held locally */
55525  int surplus;   /* Overflow payload available for local storage */
55526
55527  minLocal = pPage->minLocal;
55528  maxLocal = pPage->maxLocal;
55529  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
55530  testcase( surplus==maxLocal );
55531  testcase( surplus==maxLocal+1 );
55532  if( surplus <= maxLocal ){
55533    pInfo->nLocal = (u16)surplus;
55534  }else{
55535    pInfo->nLocal = (u16)minLocal;
55536  }
55537  pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
55538  pInfo->nSize = pInfo->iOverflow + 4;
55539}
55540
55541/*
55542** The following routines are implementations of the MemPage.xParseCell()
55543** method.
55544**
55545** Parse a cell content block and fill in the CellInfo structure.
55546**
55547** btreeParseCellPtr()        =>   table btree leaf nodes
55548** btreeParseCellNoPayload()  =>   table btree internal nodes
55549** btreeParseCellPtrIndex()   =>   index btree nodes
55550**
55551** There is also a wrapper function btreeParseCell() that works for
55552** all MemPage types and that references the cell by index rather than
55553** by pointer.
55554*/
55555static void btreeParseCellPtrNoPayload(
55556  MemPage *pPage,         /* Page containing the cell */
55557  u8 *pCell,              /* Pointer to the cell text. */
55558  CellInfo *pInfo         /* Fill in this structure */
55559){
55560  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55561  assert( pPage->leaf==0 );
55562  assert( pPage->noPayload );
55563  assert( pPage->childPtrSize==4 );
55564#ifndef SQLITE_DEBUG
55565  UNUSED_PARAMETER(pPage);
55566#endif
55567  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
55568  pInfo->nPayload = 0;
55569  pInfo->nLocal = 0;
55570  pInfo->iOverflow = 0;
55571  pInfo->pPayload = 0;
55572  return;
55573}
55574static void btreeParseCellPtr(
55575  MemPage *pPage,         /* Page containing the cell */
55576  u8 *pCell,              /* Pointer to the cell text. */
55577  CellInfo *pInfo         /* Fill in this structure */
55578){
55579  u8 *pIter;              /* For scanning through pCell */
55580  u32 nPayload;           /* Number of bytes of cell payload */
55581  u64 iKey;               /* Extracted Key value */
55582
55583  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55584  assert( pPage->leaf==0 || pPage->leaf==1 );
55585  assert( pPage->intKeyLeaf || pPage->noPayload );
55586  assert( pPage->noPayload==0 );
55587  assert( pPage->intKeyLeaf );
55588  assert( pPage->childPtrSize==0 );
55589  pIter = pCell;
55590
55591  /* The next block of code is equivalent to:
55592  **
55593  **     pIter += getVarint32(pIter, nPayload);
55594  **
55595  ** The code is inlined to avoid a function call.
55596  */
55597  nPayload = *pIter;
55598  if( nPayload>=0x80 ){
55599    u8 *pEnd = &pIter[8];
55600    nPayload &= 0x7f;
55601    do{
55602      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
55603    }while( (*pIter)>=0x80 && pIter<pEnd );
55604  }
55605  pIter++;
55606
55607  /* The next block of code is equivalent to:
55608  **
55609  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
55610  **
55611  ** The code is inlined to avoid a function call.
55612  */
55613  iKey = *pIter;
55614  if( iKey>=0x80 ){
55615    u8 *pEnd = &pIter[7];
55616    iKey &= 0x7f;
55617    while(1){
55618      iKey = (iKey<<7) | (*++pIter & 0x7f);
55619      if( (*pIter)<0x80 ) break;
55620      if( pIter>=pEnd ){
55621        iKey = (iKey<<8) | *++pIter;
55622        break;
55623      }
55624    }
55625  }
55626  pIter++;
55627
55628  pInfo->nKey = *(i64*)&iKey;
55629  pInfo->nPayload = nPayload;
55630  pInfo->pPayload = pIter;
55631  testcase( nPayload==pPage->maxLocal );
55632  testcase( nPayload==pPage->maxLocal+1 );
55633  if( nPayload<=pPage->maxLocal ){
55634    /* This is the (easy) common case where the entire payload fits
55635    ** on the local page.  No overflow is required.
55636    */
55637    pInfo->nSize = nPayload + (u16)(pIter - pCell);
55638    if( pInfo->nSize<4 ) pInfo->nSize = 4;
55639    pInfo->nLocal = (u16)nPayload;
55640    pInfo->iOverflow = 0;
55641  }else{
55642    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
55643  }
55644}
55645static void btreeParseCellPtrIndex(
55646  MemPage *pPage,         /* Page containing the cell */
55647  u8 *pCell,              /* Pointer to the cell text. */
55648  CellInfo *pInfo         /* Fill in this structure */
55649){
55650  u8 *pIter;              /* For scanning through pCell */
55651  u32 nPayload;           /* Number of bytes of cell payload */
55652
55653  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55654  assert( pPage->leaf==0 || pPage->leaf==1 );
55655  assert( pPage->intKeyLeaf==0 );
55656  assert( pPage->noPayload==0 );
55657  pIter = pCell + pPage->childPtrSize;
55658  nPayload = *pIter;
55659  if( nPayload>=0x80 ){
55660    u8 *pEnd = &pIter[8];
55661    nPayload &= 0x7f;
55662    do{
55663      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
55664    }while( *(pIter)>=0x80 && pIter<pEnd );
55665  }
55666  pIter++;
55667  pInfo->nKey = nPayload;
55668  pInfo->nPayload = nPayload;
55669  pInfo->pPayload = pIter;
55670  testcase( nPayload==pPage->maxLocal );
55671  testcase( nPayload==pPage->maxLocal+1 );
55672  if( nPayload<=pPage->maxLocal ){
55673    /* This is the (easy) common case where the entire payload fits
55674    ** on the local page.  No overflow is required.
55675    */
55676    pInfo->nSize = nPayload + (u16)(pIter - pCell);
55677    if( pInfo->nSize<4 ) pInfo->nSize = 4;
55678    pInfo->nLocal = (u16)nPayload;
55679    pInfo->iOverflow = 0;
55680  }else{
55681    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
55682  }
55683}
55684static void btreeParseCell(
55685  MemPage *pPage,         /* Page containing the cell */
55686  int iCell,              /* The cell index.  First cell is 0 */
55687  CellInfo *pInfo         /* Fill in this structure */
55688){
55689  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
55690}
55691
55692/*
55693** The following routines are implementations of the MemPage.xCellSize
55694** method.
55695**
55696** Compute the total number of bytes that a Cell needs in the cell
55697** data area of the btree-page.  The return number includes the cell
55698** data header and the local payload, but not any overflow page or
55699** the space used by the cell pointer.
55700**
55701** cellSizePtrNoPayload()    =>   table internal nodes
55702** cellSizePtr()             =>   all index nodes & table leaf nodes
55703*/
55704static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
55705  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
55706  u8 *pEnd;                                /* End mark for a varint */
55707  u32 nSize;                               /* Size value to return */
55708
55709#ifdef SQLITE_DEBUG
55710  /* The value returned by this function should always be the same as
55711  ** the (CellInfo.nSize) value found by doing a full parse of the
55712  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
55713  ** this function verifies that this invariant is not violated. */
55714  CellInfo debuginfo;
55715  pPage->xParseCell(pPage, pCell, &debuginfo);
55716#endif
55717
55718  assert( pPage->noPayload==0 );
55719  nSize = *pIter;
55720  if( nSize>=0x80 ){
55721    pEnd = &pIter[8];
55722    nSize &= 0x7f;
55723    do{
55724      nSize = (nSize<<7) | (*++pIter & 0x7f);
55725    }while( *(pIter)>=0x80 && pIter<pEnd );
55726  }
55727  pIter++;
55728  if( pPage->intKey ){
55729    /* pIter now points at the 64-bit integer key value, a variable length
55730    ** integer. The following block moves pIter to point at the first byte
55731    ** past the end of the key value. */
55732    pEnd = &pIter[9];
55733    while( (*pIter++)&0x80 && pIter<pEnd );
55734  }
55735  testcase( nSize==pPage->maxLocal );
55736  testcase( nSize==pPage->maxLocal+1 );
55737  if( nSize<=pPage->maxLocal ){
55738    nSize += (u32)(pIter - pCell);
55739    if( nSize<4 ) nSize = 4;
55740  }else{
55741    int minLocal = pPage->minLocal;
55742    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
55743    testcase( nSize==pPage->maxLocal );
55744    testcase( nSize==pPage->maxLocal+1 );
55745    if( nSize>pPage->maxLocal ){
55746      nSize = minLocal;
55747    }
55748    nSize += 4 + (u16)(pIter - pCell);
55749  }
55750  assert( nSize==debuginfo.nSize || CORRUPT_DB );
55751  return (u16)nSize;
55752}
55753static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
55754  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
55755  u8 *pEnd;              /* End mark for a varint */
55756
55757#ifdef SQLITE_DEBUG
55758  /* The value returned by this function should always be the same as
55759  ** the (CellInfo.nSize) value found by doing a full parse of the
55760  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
55761  ** this function verifies that this invariant is not violated. */
55762  CellInfo debuginfo;
55763  pPage->xParseCell(pPage, pCell, &debuginfo);
55764#else
55765  UNUSED_PARAMETER(pPage);
55766#endif
55767
55768  assert( pPage->childPtrSize==4 );
55769  pEnd = pIter + 9;
55770  while( (*pIter++)&0x80 && pIter<pEnd );
55771  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
55772  return (u16)(pIter - pCell);
55773}
55774
55775
55776#ifdef SQLITE_DEBUG
55777/* This variation on cellSizePtr() is used inside of assert() statements
55778** only. */
55779static u16 cellSize(MemPage *pPage, int iCell){
55780  return pPage->xCellSize(pPage, findCell(pPage, iCell));
55781}
55782#endif
55783
55784#ifndef SQLITE_OMIT_AUTOVACUUM
55785/*
55786** If the cell pCell, part of page pPage contains a pointer
55787** to an overflow page, insert an entry into the pointer-map
55788** for the overflow page.
55789*/
55790static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
55791  CellInfo info;
55792  if( *pRC ) return;
55793  assert( pCell!=0 );
55794  pPage->xParseCell(pPage, pCell, &info);
55795  if( info.iOverflow ){
55796    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
55797    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
55798  }
55799}
55800#endif
55801
55802
55803/*
55804** Defragment the page given.  All Cells are moved to the
55805** end of the page and all free space is collected into one
55806** big FreeBlk that occurs in between the header and cell
55807** pointer array and the cell content area.
55808**
55809** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
55810** b-tree page so that there are no freeblocks or fragment bytes, all
55811** unused bytes are contained in the unallocated space region, and all
55812** cells are packed tightly at the end of the page.
55813*/
55814static int defragmentPage(MemPage *pPage){
55815  int i;                     /* Loop counter */
55816  int pc;                    /* Address of the i-th cell */
55817  int hdr;                   /* Offset to the page header */
55818  int size;                  /* Size of a cell */
55819  int usableSize;            /* Number of usable bytes on a page */
55820  int cellOffset;            /* Offset to the cell pointer array */
55821  int cbrk;                  /* Offset to the cell content area */
55822  int nCell;                 /* Number of cells on the page */
55823  unsigned char *data;       /* The page data */
55824  unsigned char *temp;       /* Temp area for cell content */
55825  unsigned char *src;        /* Source of content */
55826  int iCellFirst;            /* First allowable cell index */
55827  int iCellLast;             /* Last possible cell index */
55828
55829
55830  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55831  assert( pPage->pBt!=0 );
55832  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
55833  assert( pPage->nOverflow==0 );
55834  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55835  temp = 0;
55836  src = data = pPage->aData;
55837  hdr = pPage->hdrOffset;
55838  cellOffset = pPage->cellOffset;
55839  nCell = pPage->nCell;
55840  assert( nCell==get2byte(&data[hdr+3]) );
55841  usableSize = pPage->pBt->usableSize;
55842  cbrk = usableSize;
55843  iCellFirst = cellOffset + 2*nCell;
55844  iCellLast = usableSize - 4;
55845  for(i=0; i<nCell; i++){
55846    u8 *pAddr;     /* The i-th cell pointer */
55847    pAddr = &data[cellOffset + i*2];
55848    pc = get2byte(pAddr);
55849    testcase( pc==iCellFirst );
55850    testcase( pc==iCellLast );
55851    /* These conditions have already been verified in btreeInitPage()
55852    ** if PRAGMA cell_size_check=ON.
55853    */
55854    if( pc<iCellFirst || pc>iCellLast ){
55855      return SQLITE_CORRUPT_BKPT;
55856    }
55857    assert( pc>=iCellFirst && pc<=iCellLast );
55858    size = pPage->xCellSize(pPage, &src[pc]);
55859    cbrk -= size;
55860    if( cbrk<iCellFirst || pc+size>usableSize ){
55861      return SQLITE_CORRUPT_BKPT;
55862    }
55863    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
55864    testcase( cbrk+size==usableSize );
55865    testcase( pc+size==usableSize );
55866    put2byte(pAddr, cbrk);
55867    if( temp==0 ){
55868      int x;
55869      if( cbrk==pc ) continue;
55870      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
55871      x = get2byte(&data[hdr+5]);
55872      memcpy(&temp[x], &data[x], (cbrk+size) - x);
55873      src = temp;
55874    }
55875    memcpy(&data[cbrk], &src[pc], size);
55876  }
55877  assert( cbrk>=iCellFirst );
55878  put2byte(&data[hdr+5], cbrk);
55879  data[hdr+1] = 0;
55880  data[hdr+2] = 0;
55881  data[hdr+7] = 0;
55882  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
55883  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55884  if( cbrk-iCellFirst!=pPage->nFree ){
55885    return SQLITE_CORRUPT_BKPT;
55886  }
55887  return SQLITE_OK;
55888}
55889
55890/*
55891** Search the free-list on page pPg for space to store a cell nByte bytes in
55892** size. If one can be found, return a pointer to the space and remove it
55893** from the free-list.
55894**
55895** If no suitable space can be found on the free-list, return NULL.
55896**
55897** This function may detect corruption within pPg.  If corruption is
55898** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
55899**
55900** Slots on the free list that are between 1 and 3 bytes larger than nByte
55901** will be ignored if adding the extra space to the fragmentation count
55902** causes the fragmentation count to exceed 60.
55903*/
55904static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
55905  const int hdr = pPg->hdrOffset;
55906  u8 * const aData = pPg->aData;
55907  int iAddr = hdr + 1;
55908  int pc = get2byte(&aData[iAddr]);
55909  int x;
55910  int usableSize = pPg->pBt->usableSize;
55911
55912  assert( pc>0 );
55913  do{
55914    int size;            /* Size of the free slot */
55915    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
55916    ** increasing offset. */
55917    if( pc>usableSize-4 || pc<iAddr+4 ){
55918      *pRc = SQLITE_CORRUPT_BKPT;
55919      return 0;
55920    }
55921    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
55922    ** freeblock form a big-endian integer which is the size of the freeblock
55923    ** in bytes, including the 4-byte header. */
55924    size = get2byte(&aData[pc+2]);
55925    if( (x = size - nByte)>=0 ){
55926      testcase( x==4 );
55927      testcase( x==3 );
55928      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
55929        *pRc = SQLITE_CORRUPT_BKPT;
55930        return 0;
55931      }else if( x<4 ){
55932        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
55933        ** number of bytes in fragments may not exceed 60. */
55934        if( aData[hdr+7]>57 ) return 0;
55935
55936        /* Remove the slot from the free-list. Update the number of
55937        ** fragmented bytes within the page. */
55938        memcpy(&aData[iAddr], &aData[pc], 2);
55939        aData[hdr+7] += (u8)x;
55940      }else{
55941        /* The slot remains on the free-list. Reduce its size to account
55942         ** for the portion used by the new allocation. */
55943        put2byte(&aData[pc+2], x);
55944      }
55945      return &aData[pc + x];
55946    }
55947    iAddr = pc;
55948    pc = get2byte(&aData[pc]);
55949  }while( pc );
55950
55951  return 0;
55952}
55953
55954/*
55955** Allocate nByte bytes of space from within the B-Tree page passed
55956** as the first argument. Write into *pIdx the index into pPage->aData[]
55957** of the first byte of allocated space. Return either SQLITE_OK or
55958** an error code (usually SQLITE_CORRUPT).
55959**
55960** The caller guarantees that there is sufficient space to make the
55961** allocation.  This routine might need to defragment in order to bring
55962** all the space together, however.  This routine will avoid using
55963** the first two bytes past the cell pointer area since presumably this
55964** allocation is being made in order to insert a new cell, so we will
55965** also end up needing a new cell pointer.
55966*/
55967static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
55968  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
55969  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
55970  int top;                             /* First byte of cell content area */
55971  int rc = SQLITE_OK;                  /* Integer return code */
55972  int gap;        /* First byte of gap between cell pointers and cell content */
55973
55974  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55975  assert( pPage->pBt );
55976  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55977  assert( nByte>=0 );  /* Minimum cell size is 4 */
55978  assert( pPage->nFree>=nByte );
55979  assert( pPage->nOverflow==0 );
55980  assert( nByte < (int)(pPage->pBt->usableSize-8) );
55981
55982  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
55983  gap = pPage->cellOffset + 2*pPage->nCell;
55984  assert( gap<=65536 );
55985  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
55986  ** and the reserved space is zero (the usual value for reserved space)
55987  ** then the cell content offset of an empty page wants to be 65536.
55988  ** However, that integer is too large to be stored in a 2-byte unsigned
55989  ** integer, so a value of 0 is used in its place. */
55990  top = get2byte(&data[hdr+5]);
55991  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
55992  if( gap>top ){
55993    if( top==0 && pPage->pBt->usableSize==65536 ){
55994      top = 65536;
55995    }else{
55996      return SQLITE_CORRUPT_BKPT;
55997    }
55998  }
55999
56000  /* If there is enough space between gap and top for one more cell pointer
56001  ** array entry offset, and if the freelist is not empty, then search the
56002  ** freelist looking for a free slot big enough to satisfy the request.
56003  */
56004  testcase( gap+2==top );
56005  testcase( gap+1==top );
56006  testcase( gap==top );
56007  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
56008    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
56009    if( pSpace ){
56010      assert( pSpace>=data && (pSpace - data)<65536 );
56011      *pIdx = (int)(pSpace - data);
56012      return SQLITE_OK;
56013    }else if( rc ){
56014      return rc;
56015    }
56016  }
56017
56018  /* The request could not be fulfilled using a freelist slot.  Check
56019  ** to see if defragmentation is necessary.
56020  */
56021  testcase( gap+2+nByte==top );
56022  if( gap+2+nByte>top ){
56023    assert( pPage->nCell>0 || CORRUPT_DB );
56024    rc = defragmentPage(pPage);
56025    if( rc ) return rc;
56026    top = get2byteNotZero(&data[hdr+5]);
56027    assert( gap+nByte<=top );
56028  }
56029
56030
56031  /* Allocate memory from the gap in between the cell pointer array
56032  ** and the cell content area.  The btreeInitPage() call has already
56033  ** validated the freelist.  Given that the freelist is valid, there
56034  ** is no way that the allocation can extend off the end of the page.
56035  ** The assert() below verifies the previous sentence.
56036  */
56037  top -= nByte;
56038  put2byte(&data[hdr+5], top);
56039  assert( top+nByte <= (int)pPage->pBt->usableSize );
56040  *pIdx = top;
56041  return SQLITE_OK;
56042}
56043
56044/*
56045** Return a section of the pPage->aData to the freelist.
56046** The first byte of the new free block is pPage->aData[iStart]
56047** and the size of the block is iSize bytes.
56048**
56049** Adjacent freeblocks are coalesced.
56050**
56051** Note that even though the freeblock list was checked by btreeInitPage(),
56052** that routine will not detect overlap between cells or freeblocks.  Nor
56053** does it detect cells or freeblocks that encrouch into the reserved bytes
56054** at the end of the page.  So do additional corruption checks inside this
56055** routine and return SQLITE_CORRUPT if any problems are found.
56056*/
56057static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
56058  u16 iPtr;                             /* Address of ptr to next freeblock */
56059  u16 iFreeBlk;                         /* Address of the next freeblock */
56060  u8 hdr;                               /* Page header size.  0 or 100 */
56061  u8 nFrag = 0;                         /* Reduction in fragmentation */
56062  u16 iOrigSize = iSize;                /* Original value of iSize */
56063  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
56064  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
56065  unsigned char *data = pPage->aData;   /* Page content */
56066
56067  assert( pPage->pBt!=0 );
56068  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56069  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
56070  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
56071  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56072  assert( iSize>=4 );   /* Minimum cell size is 4 */
56073  assert( iStart<=iLast );
56074
56075  /* Overwrite deleted information with zeros when the secure_delete
56076  ** option is enabled */
56077  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
56078    memset(&data[iStart], 0, iSize);
56079  }
56080
56081  /* The list of freeblocks must be in ascending order.  Find the
56082  ** spot on the list where iStart should be inserted.
56083  */
56084  hdr = pPage->hdrOffset;
56085  iPtr = hdr + 1;
56086  if( data[iPtr+1]==0 && data[iPtr]==0 ){
56087    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
56088  }else{
56089    while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
56090      if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
56091      iPtr = iFreeBlk;
56092    }
56093    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
56094    assert( iFreeBlk>iPtr || iFreeBlk==0 );
56095
56096    /* At this point:
56097    **    iFreeBlk:   First freeblock after iStart, or zero if none
56098    **    iPtr:       The address of a pointer to iFreeBlk
56099    **
56100    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
56101    */
56102    if( iFreeBlk && iEnd+3>=iFreeBlk ){
56103      nFrag = iFreeBlk - iEnd;
56104      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
56105      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
56106      if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
56107      iSize = iEnd - iStart;
56108      iFreeBlk = get2byte(&data[iFreeBlk]);
56109    }
56110
56111    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
56112    ** pointer in the page header) then check to see if iStart should be
56113    ** coalesced onto the end of iPtr.
56114    */
56115    if( iPtr>hdr+1 ){
56116      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
56117      if( iPtrEnd+3>=iStart ){
56118        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
56119        nFrag += iStart - iPtrEnd;
56120        iSize = iEnd - iPtr;
56121        iStart = iPtr;
56122      }
56123    }
56124    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
56125    data[hdr+7] -= nFrag;
56126  }
56127  if( iStart==get2byte(&data[hdr+5]) ){
56128    /* The new freeblock is at the beginning of the cell content area,
56129    ** so just extend the cell content area rather than create another
56130    ** freelist entry */
56131    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
56132    put2byte(&data[hdr+1], iFreeBlk);
56133    put2byte(&data[hdr+5], iEnd);
56134  }else{
56135    /* Insert the new freeblock into the freelist */
56136    put2byte(&data[iPtr], iStart);
56137    put2byte(&data[iStart], iFreeBlk);
56138    put2byte(&data[iStart+2], iSize);
56139  }
56140  pPage->nFree += iOrigSize;
56141  return SQLITE_OK;
56142}
56143
56144/*
56145** Decode the flags byte (the first byte of the header) for a page
56146** and initialize fields of the MemPage structure accordingly.
56147**
56148** Only the following combinations are supported.  Anything different
56149** indicates a corrupt database files:
56150**
56151**         PTF_ZERODATA
56152**         PTF_ZERODATA | PTF_LEAF
56153**         PTF_LEAFDATA | PTF_INTKEY
56154**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
56155*/
56156static int decodeFlags(MemPage *pPage, int flagByte){
56157  BtShared *pBt;     /* A copy of pPage->pBt */
56158
56159  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
56160  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56161  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
56162  flagByte &= ~PTF_LEAF;
56163  pPage->childPtrSize = 4-4*pPage->leaf;
56164  pPage->xCellSize = cellSizePtr;
56165  pBt = pPage->pBt;
56166  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
56167    /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
56168    ** table b-tree page. */
56169    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
56170    /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
56171    ** table b-tree page. */
56172    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
56173    pPage->intKey = 1;
56174    if( pPage->leaf ){
56175      pPage->intKeyLeaf = 1;
56176      pPage->noPayload = 0;
56177      pPage->xParseCell = btreeParseCellPtr;
56178    }else{
56179      pPage->intKeyLeaf = 0;
56180      pPage->noPayload = 1;
56181      pPage->xCellSize = cellSizePtrNoPayload;
56182      pPage->xParseCell = btreeParseCellPtrNoPayload;
56183    }
56184    pPage->maxLocal = pBt->maxLeaf;
56185    pPage->minLocal = pBt->minLeaf;
56186  }else if( flagByte==PTF_ZERODATA ){
56187    /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
56188    ** index b-tree page. */
56189    assert( (PTF_ZERODATA)==2 );
56190    /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
56191    ** index b-tree page. */
56192    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
56193    pPage->intKey = 0;
56194    pPage->intKeyLeaf = 0;
56195    pPage->noPayload = 0;
56196    pPage->xParseCell = btreeParseCellPtrIndex;
56197    pPage->maxLocal = pBt->maxLocal;
56198    pPage->minLocal = pBt->minLocal;
56199  }else{
56200    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
56201    ** an error. */
56202    return SQLITE_CORRUPT_BKPT;
56203  }
56204  pPage->max1bytePayload = pBt->max1bytePayload;
56205  return SQLITE_OK;
56206}
56207
56208/*
56209** Initialize the auxiliary information for a disk block.
56210**
56211** Return SQLITE_OK on success.  If we see that the page does
56212** not contain a well-formed database page, then return
56213** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
56214** guarantee that the page is well-formed.  It only shows that
56215** we failed to detect any corruption.
56216*/
56217static int btreeInitPage(MemPage *pPage){
56218
56219  assert( pPage->pBt!=0 );
56220  assert( pPage->pBt->db!=0 );
56221  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56222  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
56223  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
56224  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
56225
56226  if( !pPage->isInit ){
56227    u16 pc;            /* Address of a freeblock within pPage->aData[] */
56228    u8 hdr;            /* Offset to beginning of page header */
56229    u8 *data;          /* Equal to pPage->aData */
56230    BtShared *pBt;        /* The main btree structure */
56231    int usableSize;    /* Amount of usable space on each page */
56232    u16 cellOffset;    /* Offset from start of page to first cell pointer */
56233    int nFree;         /* Number of unused bytes on the page */
56234    int top;           /* First byte of the cell content area */
56235    int iCellFirst;    /* First allowable cell or freeblock offset */
56236    int iCellLast;     /* Last possible cell or freeblock offset */
56237
56238    pBt = pPage->pBt;
56239
56240    hdr = pPage->hdrOffset;
56241    data = pPage->aData;
56242    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
56243    ** the b-tree page type. */
56244    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
56245    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
56246    pPage->maskPage = (u16)(pBt->pageSize - 1);
56247    pPage->nOverflow = 0;
56248    usableSize = pBt->usableSize;
56249    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
56250    pPage->aDataEnd = &data[usableSize];
56251    pPage->aCellIdx = &data[cellOffset];
56252    pPage->aDataOfst = &data[pPage->childPtrSize];
56253    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
56254    ** the start of the cell content area. A zero value for this integer is
56255    ** interpreted as 65536. */
56256    top = get2byteNotZero(&data[hdr+5]);
56257    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
56258    ** number of cells on the page. */
56259    pPage->nCell = get2byte(&data[hdr+3]);
56260    if( pPage->nCell>MX_CELL(pBt) ){
56261      /* To many cells for a single page.  The page must be corrupt */
56262      return SQLITE_CORRUPT_BKPT;
56263    }
56264    testcase( pPage->nCell==MX_CELL(pBt) );
56265    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
56266    ** possible for a root page of a table that contains no rows) then the
56267    ** offset to the cell content area will equal the page size minus the
56268    ** bytes of reserved space. */
56269    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
56270
56271    /* A malformed database page might cause us to read past the end
56272    ** of page when parsing a cell.
56273    **
56274    ** The following block of code checks early to see if a cell extends
56275    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
56276    ** returned if it does.
56277    */
56278    iCellFirst = cellOffset + 2*pPage->nCell;
56279    iCellLast = usableSize - 4;
56280    if( pBt->db->flags & SQLITE_CellSizeCk ){
56281      int i;            /* Index into the cell pointer array */
56282      int sz;           /* Size of a cell */
56283
56284      if( !pPage->leaf ) iCellLast--;
56285      for(i=0; i<pPage->nCell; i++){
56286        pc = get2byteAligned(&data[cellOffset+i*2]);
56287        testcase( pc==iCellFirst );
56288        testcase( pc==iCellLast );
56289        if( pc<iCellFirst || pc>iCellLast ){
56290          return SQLITE_CORRUPT_BKPT;
56291        }
56292        sz = pPage->xCellSize(pPage, &data[pc]);
56293        testcase( pc+sz==usableSize );
56294        if( pc+sz>usableSize ){
56295          return SQLITE_CORRUPT_BKPT;
56296        }
56297      }
56298      if( !pPage->leaf ) iCellLast++;
56299    }
56300
56301    /* Compute the total free space on the page
56302    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
56303    ** start of the first freeblock on the page, or is zero if there are no
56304    ** freeblocks. */
56305    pc = get2byte(&data[hdr+1]);
56306    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
56307    while( pc>0 ){
56308      u16 next, size;
56309      if( pc<iCellFirst || pc>iCellLast ){
56310        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
56311        ** always be at least one cell before the first freeblock.
56312        **
56313        ** Or, the freeblock is off the end of the page
56314        */
56315        return SQLITE_CORRUPT_BKPT;
56316      }
56317      next = get2byte(&data[pc]);
56318      size = get2byte(&data[pc+2]);
56319      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
56320        /* Free blocks must be in ascending order. And the last byte of
56321        ** the free-block must lie on the database page.  */
56322        return SQLITE_CORRUPT_BKPT;
56323      }
56324      nFree = nFree + size;
56325      pc = next;
56326    }
56327
56328    /* At this point, nFree contains the sum of the offset to the start
56329    ** of the cell-content area plus the number of free bytes within
56330    ** the cell-content area. If this is greater than the usable-size
56331    ** of the page, then the page must be corrupted. This check also
56332    ** serves to verify that the offset to the start of the cell-content
56333    ** area, according to the page header, lies within the page.
56334    */
56335    if( nFree>usableSize ){
56336      return SQLITE_CORRUPT_BKPT;
56337    }
56338    pPage->nFree = (u16)(nFree - iCellFirst);
56339    pPage->isInit = 1;
56340  }
56341  return SQLITE_OK;
56342}
56343
56344/*
56345** Set up a raw page so that it looks like a database page holding
56346** no entries.
56347*/
56348static void zeroPage(MemPage *pPage, int flags){
56349  unsigned char *data = pPage->aData;
56350  BtShared *pBt = pPage->pBt;
56351  u8 hdr = pPage->hdrOffset;
56352  u16 first;
56353
56354  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
56355  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
56356  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
56357  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56358  assert( sqlite3_mutex_held(pBt->mutex) );
56359  if( pBt->btsFlags & BTS_SECURE_DELETE ){
56360    memset(&data[hdr], 0, pBt->usableSize - hdr);
56361  }
56362  data[hdr] = (char)flags;
56363  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
56364  memset(&data[hdr+1], 0, 4);
56365  data[hdr+7] = 0;
56366  put2byte(&data[hdr+5], pBt->usableSize);
56367  pPage->nFree = (u16)(pBt->usableSize - first);
56368  decodeFlags(pPage, flags);
56369  pPage->cellOffset = first;
56370  pPage->aDataEnd = &data[pBt->usableSize];
56371  pPage->aCellIdx = &data[first];
56372  pPage->aDataOfst = &data[pPage->childPtrSize];
56373  pPage->nOverflow = 0;
56374  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
56375  pPage->maskPage = (u16)(pBt->pageSize - 1);
56376  pPage->nCell = 0;
56377  pPage->isInit = 1;
56378}
56379
56380
56381/*
56382** Convert a DbPage obtained from the pager into a MemPage used by
56383** the btree layer.
56384*/
56385static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
56386  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
56387  pPage->aData = sqlite3PagerGetData(pDbPage);
56388  pPage->pDbPage = pDbPage;
56389  pPage->pBt = pBt;
56390  pPage->pgno = pgno;
56391  pPage->hdrOffset = pgno==1 ? 100 : 0;
56392  return pPage;
56393}
56394
56395/*
56396** Get a page from the pager.  Initialize the MemPage.pBt and
56397** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
56398**
56399** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
56400** about the content of the page at this time.  So do not go to the disk
56401** to fetch the content.  Just fill in the content with zeros for now.
56402** If in the future we call sqlite3PagerWrite() on this page, that
56403** means we have started to be concerned about content and the disk
56404** read should occur at that point.
56405*/
56406static int btreeGetPage(
56407  BtShared *pBt,       /* The btree */
56408  Pgno pgno,           /* Number of the page to fetch */
56409  MemPage **ppPage,    /* Return the page in this parameter */
56410  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
56411){
56412  int rc;
56413  DbPage *pDbPage;
56414
56415  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
56416  assert( sqlite3_mutex_held(pBt->mutex) );
56417  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
56418  if( rc ) return rc;
56419  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
56420  return SQLITE_OK;
56421}
56422
56423/*
56424** Retrieve a page from the pager cache. If the requested page is not
56425** already in the pager cache return NULL. Initialize the MemPage.pBt and
56426** MemPage.aData elements if needed.
56427*/
56428static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
56429  DbPage *pDbPage;
56430  assert( sqlite3_mutex_held(pBt->mutex) );
56431  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
56432  if( pDbPage ){
56433    return btreePageFromDbPage(pDbPage, pgno, pBt);
56434  }
56435  return 0;
56436}
56437
56438/*
56439** Return the size of the database file in pages. If there is any kind of
56440** error, return ((unsigned int)-1).
56441*/
56442static Pgno btreePagecount(BtShared *pBt){
56443  return pBt->nPage;
56444}
56445SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
56446  assert( sqlite3BtreeHoldsMutex(p) );
56447  assert( ((p->pBt->nPage)&0x8000000)==0 );
56448  return btreePagecount(p->pBt);
56449}
56450
56451/*
56452** Get a page from the pager and initialize it.
56453**
56454** If pCur!=0 then the page is being fetched as part of a moveToChild()
56455** call.  Do additional sanity checking on the page in this case.
56456** And if the fetch fails, this routine must decrement pCur->iPage.
56457**
56458** The page is fetched as read-write unless pCur is not NULL and is
56459** a read-only cursor.
56460**
56461** If an error occurs, then *ppPage is undefined. It
56462** may remain unchanged, or it may be set to an invalid value.
56463*/
56464static int getAndInitPage(
56465  BtShared *pBt,                  /* The database file */
56466  Pgno pgno,                      /* Number of the page to get */
56467  MemPage **ppPage,               /* Write the page pointer here */
56468  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
56469  int bReadOnly                   /* True for a read-only page */
56470){
56471  int rc;
56472  DbPage *pDbPage;
56473  assert( sqlite3_mutex_held(pBt->mutex) );
56474  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
56475  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
56476  assert( pCur==0 || pCur->iPage>0 );
56477
56478  if( pgno>btreePagecount(pBt) ){
56479    rc = SQLITE_CORRUPT_BKPT;
56480    goto getAndInitPage_error;
56481  }
56482  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
56483  if( rc ){
56484    goto getAndInitPage_error;
56485  }
56486  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
56487  if( (*ppPage)->isInit==0 ){
56488    rc = btreeInitPage(*ppPage);
56489    if( rc!=SQLITE_OK ){
56490      releasePage(*ppPage);
56491      goto getAndInitPage_error;
56492    }
56493  }
56494
56495  /* If obtaining a child page for a cursor, we must verify that the page is
56496  ** compatible with the root page. */
56497  if( pCur
56498   && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey)
56499  ){
56500    rc = SQLITE_CORRUPT_BKPT;
56501    releasePage(*ppPage);
56502    goto getAndInitPage_error;
56503  }
56504  return SQLITE_OK;
56505
56506getAndInitPage_error:
56507  if( pCur ) pCur->iPage--;
56508  testcase( pgno==0 );
56509  assert( pgno!=0 || rc==SQLITE_CORRUPT );
56510  return rc;
56511}
56512
56513/*
56514** Release a MemPage.  This should be called once for each prior
56515** call to btreeGetPage.
56516*/
56517static void releasePageNotNull(MemPage *pPage){
56518  assert( pPage->aData );
56519  assert( pPage->pBt );
56520  assert( pPage->pDbPage!=0 );
56521  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
56522  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
56523  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56524  sqlite3PagerUnrefNotNull(pPage->pDbPage);
56525}
56526static void releasePage(MemPage *pPage){
56527  if( pPage ) releasePageNotNull(pPage);
56528}
56529
56530/*
56531** Get an unused page.
56532**
56533** This works just like btreeGetPage() with the addition:
56534**
56535**   *  If the page is already in use for some other purpose, immediately
56536**      release it and return an SQLITE_CURRUPT error.
56537**   *  Make sure the isInit flag is clear
56538*/
56539static int btreeGetUnusedPage(
56540  BtShared *pBt,       /* The btree */
56541  Pgno pgno,           /* Number of the page to fetch */
56542  MemPage **ppPage,    /* Return the page in this parameter */
56543  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
56544){
56545  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
56546  if( rc==SQLITE_OK ){
56547    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
56548      releasePage(*ppPage);
56549      *ppPage = 0;
56550      return SQLITE_CORRUPT_BKPT;
56551    }
56552    (*ppPage)->isInit = 0;
56553  }else{
56554    *ppPage = 0;
56555  }
56556  return rc;
56557}
56558
56559
56560/*
56561** During a rollback, when the pager reloads information into the cache
56562** so that the cache is restored to its original state at the start of
56563** the transaction, for each page restored this routine is called.
56564**
56565** This routine needs to reset the extra data section at the end of the
56566** page to agree with the restored data.
56567*/
56568static void pageReinit(DbPage *pData){
56569  MemPage *pPage;
56570  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
56571  assert( sqlite3PagerPageRefcount(pData)>0 );
56572  if( pPage->isInit ){
56573    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56574    pPage->isInit = 0;
56575    if( sqlite3PagerPageRefcount(pData)>1 ){
56576      /* pPage might not be a btree page;  it might be an overflow page
56577      ** or ptrmap page or a free page.  In those cases, the following
56578      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
56579      ** But no harm is done by this.  And it is very important that
56580      ** btreeInitPage() be called on every btree page so we make
56581      ** the call for every page that comes in for re-initing. */
56582      btreeInitPage(pPage);
56583    }
56584  }
56585}
56586
56587/*
56588** Invoke the busy handler for a btree.
56589*/
56590static int btreeInvokeBusyHandler(void *pArg){
56591  BtShared *pBt = (BtShared*)pArg;
56592  assert( pBt->db );
56593  assert( sqlite3_mutex_held(pBt->db->mutex) );
56594  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
56595}
56596
56597/*
56598** Open a database file.
56599**
56600** zFilename is the name of the database file.  If zFilename is NULL
56601** then an ephemeral database is created.  The ephemeral database might
56602** be exclusively in memory, or it might use a disk-based memory cache.
56603** Either way, the ephemeral database will be automatically deleted
56604** when sqlite3BtreeClose() is called.
56605**
56606** If zFilename is ":memory:" then an in-memory database is created
56607** that is automatically destroyed when it is closed.
56608**
56609** The "flags" parameter is a bitmask that might contain bits like
56610** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
56611**
56612** If the database is already opened in the same database connection
56613** and we are in shared cache mode, then the open will fail with an
56614** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
56615** objects in the same database connection since doing so will lead
56616** to problems with locking.
56617*/
56618SQLITE_PRIVATE int sqlite3BtreeOpen(
56619  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
56620  const char *zFilename,  /* Name of the file containing the BTree database */
56621  sqlite3 *db,            /* Associated database handle */
56622  Btree **ppBtree,        /* Pointer to new Btree object written here */
56623  int flags,              /* Options */
56624  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
56625){
56626  BtShared *pBt = 0;             /* Shared part of btree structure */
56627  Btree *p;                      /* Handle to return */
56628  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
56629  int rc = SQLITE_OK;            /* Result code from this function */
56630  u8 nReserve;                   /* Byte of unused space on each page */
56631  unsigned char zDbHeader[100];  /* Database header content */
56632
56633  /* True if opening an ephemeral, temporary database */
56634  const int isTempDb = zFilename==0 || zFilename[0]==0;
56635
56636  /* Set the variable isMemdb to true for an in-memory database, or
56637  ** false for a file-based database.
56638  */
56639#ifdef SQLITE_OMIT_MEMORYDB
56640  const int isMemdb = 0;
56641#else
56642  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
56643                       || (isTempDb && sqlite3TempInMemory(db))
56644                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
56645#endif
56646
56647  assert( db!=0 );
56648  assert( pVfs!=0 );
56649  assert( sqlite3_mutex_held(db->mutex) );
56650  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
56651
56652  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
56653  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
56654
56655  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
56656  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
56657
56658  if( isMemdb ){
56659    flags |= BTREE_MEMORY;
56660  }
56661  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
56662    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
56663  }
56664  p = sqlite3MallocZero(sizeof(Btree));
56665  if( !p ){
56666    return SQLITE_NOMEM;
56667  }
56668  p->inTrans = TRANS_NONE;
56669  p->db = db;
56670#ifndef SQLITE_OMIT_SHARED_CACHE
56671  p->lock.pBtree = p;
56672  p->lock.iTable = 1;
56673#endif
56674
56675#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56676  /*
56677  ** If this Btree is a candidate for shared cache, try to find an
56678  ** existing BtShared object that we can share with
56679  */
56680  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
56681    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
56682      int nFilename = sqlite3Strlen30(zFilename)+1;
56683      int nFullPathname = pVfs->mxPathname+1;
56684      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
56685      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
56686
56687      p->sharable = 1;
56688      if( !zFullPathname ){
56689        sqlite3_free(p);
56690        return SQLITE_NOMEM;
56691      }
56692      if( isMemdb ){
56693        memcpy(zFullPathname, zFilename, nFilename);
56694      }else{
56695        rc = sqlite3OsFullPathname(pVfs, zFilename,
56696                                   nFullPathname, zFullPathname);
56697        if( rc ){
56698          sqlite3_free(zFullPathname);
56699          sqlite3_free(p);
56700          return rc;
56701        }
56702      }
56703#if SQLITE_THREADSAFE
56704      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
56705      sqlite3_mutex_enter(mutexOpen);
56706      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
56707      sqlite3_mutex_enter(mutexShared);
56708#endif
56709      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
56710        assert( pBt->nRef>0 );
56711        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
56712                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
56713          int iDb;
56714          for(iDb=db->nDb-1; iDb>=0; iDb--){
56715            Btree *pExisting = db->aDb[iDb].pBt;
56716            if( pExisting && pExisting->pBt==pBt ){
56717              sqlite3_mutex_leave(mutexShared);
56718              sqlite3_mutex_leave(mutexOpen);
56719              sqlite3_free(zFullPathname);
56720              sqlite3_free(p);
56721              return SQLITE_CONSTRAINT;
56722            }
56723          }
56724          p->pBt = pBt;
56725          pBt->nRef++;
56726          break;
56727        }
56728      }
56729      sqlite3_mutex_leave(mutexShared);
56730      sqlite3_free(zFullPathname);
56731    }
56732#ifdef SQLITE_DEBUG
56733    else{
56734      /* In debug mode, we mark all persistent databases as sharable
56735      ** even when they are not.  This exercises the locking code and
56736      ** gives more opportunity for asserts(sqlite3_mutex_held())
56737      ** statements to find locking problems.
56738      */
56739      p->sharable = 1;
56740    }
56741#endif
56742  }
56743#endif
56744  if( pBt==0 ){
56745    /*
56746    ** The following asserts make sure that structures used by the btree are
56747    ** the right size.  This is to guard against size changes that result
56748    ** when compiling on a different architecture.
56749    */
56750    assert( sizeof(i64)==8 );
56751    assert( sizeof(u64)==8 );
56752    assert( sizeof(u32)==4 );
56753    assert( sizeof(u16)==2 );
56754    assert( sizeof(Pgno)==4 );
56755
56756    pBt = sqlite3MallocZero( sizeof(*pBt) );
56757    if( pBt==0 ){
56758      rc = SQLITE_NOMEM;
56759      goto btree_open_out;
56760    }
56761    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
56762                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
56763    if( rc==SQLITE_OK ){
56764      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
56765      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
56766    }
56767    if( rc!=SQLITE_OK ){
56768      goto btree_open_out;
56769    }
56770    pBt->openFlags = (u8)flags;
56771    pBt->db = db;
56772    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
56773    p->pBt = pBt;
56774
56775    pBt->pCursor = 0;
56776    pBt->pPage1 = 0;
56777    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
56778#ifdef SQLITE_SECURE_DELETE
56779    pBt->btsFlags |= BTS_SECURE_DELETE;
56780#endif
56781    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
56782    ** determined by the 2-byte integer located at an offset of 16 bytes from
56783    ** the beginning of the database file. */
56784    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
56785    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
56786         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
56787      pBt->pageSize = 0;
56788#ifndef SQLITE_OMIT_AUTOVACUUM
56789      /* If the magic name ":memory:" will create an in-memory database, then
56790      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
56791      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
56792      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
56793      ** regular file-name. In this case the auto-vacuum applies as per normal.
56794      */
56795      if( zFilename && !isMemdb ){
56796        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
56797        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
56798      }
56799#endif
56800      nReserve = 0;
56801    }else{
56802      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
56803      ** determined by the one-byte unsigned integer found at an offset of 20
56804      ** into the database file header. */
56805      nReserve = zDbHeader[20];
56806      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
56807#ifndef SQLITE_OMIT_AUTOVACUUM
56808      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
56809      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
56810#endif
56811    }
56812    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
56813    if( rc ) goto btree_open_out;
56814    pBt->usableSize = pBt->pageSize - nReserve;
56815    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
56816
56817#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56818    /* Add the new BtShared object to the linked list sharable BtShareds.
56819    */
56820    if( p->sharable ){
56821      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
56822      pBt->nRef = 1;
56823      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
56824      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
56825        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
56826        if( pBt->mutex==0 ){
56827          rc = SQLITE_NOMEM;
56828          db->mallocFailed = 0;
56829          goto btree_open_out;
56830        }
56831      }
56832      sqlite3_mutex_enter(mutexShared);
56833      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
56834      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
56835      sqlite3_mutex_leave(mutexShared);
56836    }
56837#endif
56838  }
56839
56840#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56841  /* If the new Btree uses a sharable pBtShared, then link the new
56842  ** Btree into the list of all sharable Btrees for the same connection.
56843  ** The list is kept in ascending order by pBt address.
56844  */
56845  if( p->sharable ){
56846    int i;
56847    Btree *pSib;
56848    for(i=0; i<db->nDb; i++){
56849      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
56850        while( pSib->pPrev ){ pSib = pSib->pPrev; }
56851        if( p->pBt<pSib->pBt ){
56852          p->pNext = pSib;
56853          p->pPrev = 0;
56854          pSib->pPrev = p;
56855        }else{
56856          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
56857            pSib = pSib->pNext;
56858          }
56859          p->pNext = pSib->pNext;
56860          p->pPrev = pSib;
56861          if( p->pNext ){
56862            p->pNext->pPrev = p;
56863          }
56864          pSib->pNext = p;
56865        }
56866        break;
56867      }
56868    }
56869  }
56870#endif
56871  *ppBtree = p;
56872
56873btree_open_out:
56874  if( rc!=SQLITE_OK ){
56875    if( pBt && pBt->pPager ){
56876      sqlite3PagerClose(pBt->pPager);
56877    }
56878    sqlite3_free(pBt);
56879    sqlite3_free(p);
56880    *ppBtree = 0;
56881  }else{
56882    /* If the B-Tree was successfully opened, set the pager-cache size to the
56883    ** default value. Except, when opening on an existing shared pager-cache,
56884    ** do not change the pager-cache size.
56885    */
56886    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
56887      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
56888    }
56889  }
56890  if( mutexOpen ){
56891    assert( sqlite3_mutex_held(mutexOpen) );
56892    sqlite3_mutex_leave(mutexOpen);
56893  }
56894  return rc;
56895}
56896
56897/*
56898** Decrement the BtShared.nRef counter.  When it reaches zero,
56899** remove the BtShared structure from the sharing list.  Return
56900** true if the BtShared.nRef counter reaches zero and return
56901** false if it is still positive.
56902*/
56903static int removeFromSharingList(BtShared *pBt){
56904#ifndef SQLITE_OMIT_SHARED_CACHE
56905  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
56906  BtShared *pList;
56907  int removed = 0;
56908
56909  assert( sqlite3_mutex_notheld(pBt->mutex) );
56910  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
56911  sqlite3_mutex_enter(pMaster);
56912  pBt->nRef--;
56913  if( pBt->nRef<=0 ){
56914    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
56915      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
56916    }else{
56917      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
56918      while( ALWAYS(pList) && pList->pNext!=pBt ){
56919        pList=pList->pNext;
56920      }
56921      if( ALWAYS(pList) ){
56922        pList->pNext = pBt->pNext;
56923      }
56924    }
56925    if( SQLITE_THREADSAFE ){
56926      sqlite3_mutex_free(pBt->mutex);
56927    }
56928    removed = 1;
56929  }
56930  sqlite3_mutex_leave(pMaster);
56931  return removed;
56932#else
56933  return 1;
56934#endif
56935}
56936
56937/*
56938** Make sure pBt->pTmpSpace points to an allocation of
56939** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
56940** pointer.
56941*/
56942static void allocateTempSpace(BtShared *pBt){
56943  if( !pBt->pTmpSpace ){
56944    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
56945
56946    /* One of the uses of pBt->pTmpSpace is to format cells before
56947    ** inserting them into a leaf page (function fillInCell()). If
56948    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
56949    ** by the various routines that manipulate binary cells. Which
56950    ** can mean that fillInCell() only initializes the first 2 or 3
56951    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
56952    ** it into a database page. This is not actually a problem, but it
56953    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
56954    ** data is passed to system call write(). So to avoid this error,
56955    ** zero the first 4 bytes of temp space here.
56956    **
56957    ** Also:  Provide four bytes of initialized space before the
56958    ** beginning of pTmpSpace as an area available to prepend the
56959    ** left-child pointer to the beginning of a cell.
56960    */
56961    if( pBt->pTmpSpace ){
56962      memset(pBt->pTmpSpace, 0, 8);
56963      pBt->pTmpSpace += 4;
56964    }
56965  }
56966}
56967
56968/*
56969** Free the pBt->pTmpSpace allocation
56970*/
56971static void freeTempSpace(BtShared *pBt){
56972  if( pBt->pTmpSpace ){
56973    pBt->pTmpSpace -= 4;
56974    sqlite3PageFree(pBt->pTmpSpace);
56975    pBt->pTmpSpace = 0;
56976  }
56977}
56978
56979/*
56980** Close an open database and invalidate all cursors.
56981*/
56982SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
56983  BtShared *pBt = p->pBt;
56984  BtCursor *pCur;
56985
56986  /* Close all cursors opened via this handle.  */
56987  assert( sqlite3_mutex_held(p->db->mutex) );
56988  sqlite3BtreeEnter(p);
56989  pCur = pBt->pCursor;
56990  while( pCur ){
56991    BtCursor *pTmp = pCur;
56992    pCur = pCur->pNext;
56993    if( pTmp->pBtree==p ){
56994      sqlite3BtreeCloseCursor(pTmp);
56995    }
56996  }
56997
56998  /* Rollback any active transaction and free the handle structure.
56999  ** The call to sqlite3BtreeRollback() drops any table-locks held by
57000  ** this handle.
57001  */
57002  sqlite3BtreeRollback(p, SQLITE_OK, 0);
57003  sqlite3BtreeLeave(p);
57004
57005  /* If there are still other outstanding references to the shared-btree
57006  ** structure, return now. The remainder of this procedure cleans
57007  ** up the shared-btree.
57008  */
57009  assert( p->wantToLock==0 && p->locked==0 );
57010  if( !p->sharable || removeFromSharingList(pBt) ){
57011    /* The pBt is no longer on the sharing list, so we can access
57012    ** it without having to hold the mutex.
57013    **
57014    ** Clean out and delete the BtShared object.
57015    */
57016    assert( !pBt->pCursor );
57017    sqlite3PagerClose(pBt->pPager);
57018    if( pBt->xFreeSchema && pBt->pSchema ){
57019      pBt->xFreeSchema(pBt->pSchema);
57020    }
57021    sqlite3DbFree(0, pBt->pSchema);
57022    freeTempSpace(pBt);
57023    sqlite3_free(pBt);
57024  }
57025
57026#ifndef SQLITE_OMIT_SHARED_CACHE
57027  assert( p->wantToLock==0 );
57028  assert( p->locked==0 );
57029  if( p->pPrev ) p->pPrev->pNext = p->pNext;
57030  if( p->pNext ) p->pNext->pPrev = p->pPrev;
57031#endif
57032
57033  sqlite3_free(p);
57034  return SQLITE_OK;
57035}
57036
57037/*
57038** Change the limit on the number of pages allowed in the cache.
57039**
57040** The maximum number of cache pages is set to the absolute
57041** value of mxPage.  If mxPage is negative, the pager will
57042** operate asynchronously - it will not stop to do fsync()s
57043** to insure data is written to the disk surface before
57044** continuing.  Transactions still work if synchronous is off,
57045** and the database cannot be corrupted if this program
57046** crashes.  But if the operating system crashes or there is
57047** an abrupt power failure when synchronous is off, the database
57048** could be left in an inconsistent and unrecoverable state.
57049** Synchronous is on by default so database corruption is not
57050** normally a worry.
57051*/
57052SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
57053  BtShared *pBt = p->pBt;
57054  assert( sqlite3_mutex_held(p->db->mutex) );
57055  sqlite3BtreeEnter(p);
57056  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
57057  sqlite3BtreeLeave(p);
57058  return SQLITE_OK;
57059}
57060
57061#if SQLITE_MAX_MMAP_SIZE>0
57062/*
57063** Change the limit on the amount of the database file that may be
57064** memory mapped.
57065*/
57066SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
57067  BtShared *pBt = p->pBt;
57068  assert( sqlite3_mutex_held(p->db->mutex) );
57069  sqlite3BtreeEnter(p);
57070  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
57071  sqlite3BtreeLeave(p);
57072  return SQLITE_OK;
57073}
57074#endif /* SQLITE_MAX_MMAP_SIZE>0 */
57075
57076/*
57077** Change the way data is synced to disk in order to increase or decrease
57078** how well the database resists damage due to OS crashes and power
57079** failures.  Level 1 is the same as asynchronous (no syncs() occur and
57080** there is a high probability of damage)  Level 2 is the default.  There
57081** is a very low but non-zero probability of damage.  Level 3 reduces the
57082** probability of damage to near zero but with a write performance reduction.
57083*/
57084#ifndef SQLITE_OMIT_PAGER_PRAGMAS
57085SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
57086  Btree *p,              /* The btree to set the safety level on */
57087  unsigned pgFlags       /* Various PAGER_* flags */
57088){
57089  BtShared *pBt = p->pBt;
57090  assert( sqlite3_mutex_held(p->db->mutex) );
57091  sqlite3BtreeEnter(p);
57092  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
57093  sqlite3BtreeLeave(p);
57094  return SQLITE_OK;
57095}
57096#endif
57097
57098/*
57099** Return TRUE if the given btree is set to safety level 1.  In other
57100** words, return TRUE if no sync() occurs on the disk files.
57101*/
57102SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
57103  BtShared *pBt = p->pBt;
57104  int rc;
57105  assert( sqlite3_mutex_held(p->db->mutex) );
57106  sqlite3BtreeEnter(p);
57107  assert( pBt && pBt->pPager );
57108  rc = sqlite3PagerNosync(pBt->pPager);
57109  sqlite3BtreeLeave(p);
57110  return rc;
57111}
57112
57113/*
57114** Change the default pages size and the number of reserved bytes per page.
57115** Or, if the page size has already been fixed, return SQLITE_READONLY
57116** without changing anything.
57117**
57118** The page size must be a power of 2 between 512 and 65536.  If the page
57119** size supplied does not meet this constraint then the page size is not
57120** changed.
57121**
57122** Page sizes are constrained to be a power of two so that the region
57123** of the database file used for locking (beginning at PENDING_BYTE,
57124** the first byte past the 1GB boundary, 0x40000000) needs to occur
57125** at the beginning of a page.
57126**
57127** If parameter nReserve is less than zero, then the number of reserved
57128** bytes per page is left unchanged.
57129**
57130** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
57131** and autovacuum mode can no longer be changed.
57132*/
57133SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
57134  int rc = SQLITE_OK;
57135  BtShared *pBt = p->pBt;
57136  assert( nReserve>=-1 && nReserve<=255 );
57137  sqlite3BtreeEnter(p);
57138#if SQLITE_HAS_CODEC
57139  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
57140#endif
57141  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
57142    sqlite3BtreeLeave(p);
57143    return SQLITE_READONLY;
57144  }
57145  if( nReserve<0 ){
57146    nReserve = pBt->pageSize - pBt->usableSize;
57147  }
57148  assert( nReserve>=0 && nReserve<=255 );
57149  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
57150        ((pageSize-1)&pageSize)==0 ){
57151    assert( (pageSize & 7)==0 );
57152    assert( !pBt->pCursor );
57153    pBt->pageSize = (u32)pageSize;
57154    freeTempSpace(pBt);
57155  }
57156  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
57157  pBt->usableSize = pBt->pageSize - (u16)nReserve;
57158  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
57159  sqlite3BtreeLeave(p);
57160  return rc;
57161}
57162
57163/*
57164** Return the currently defined page size
57165*/
57166SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
57167  return p->pBt->pageSize;
57168}
57169
57170/*
57171** This function is similar to sqlite3BtreeGetReserve(), except that it
57172** may only be called if it is guaranteed that the b-tree mutex is already
57173** held.
57174**
57175** This is useful in one special case in the backup API code where it is
57176** known that the shared b-tree mutex is held, but the mutex on the
57177** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
57178** were to be called, it might collide with some other operation on the
57179** database handle that owns *p, causing undefined behavior.
57180*/
57181SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
57182  int n;
57183  assert( sqlite3_mutex_held(p->pBt->mutex) );
57184  n = p->pBt->pageSize - p->pBt->usableSize;
57185  return n;
57186}
57187
57188/*
57189** Return the number of bytes of space at the end of every page that
57190** are intentually left unused.  This is the "reserved" space that is
57191** sometimes used by extensions.
57192**
57193** If SQLITE_HAS_MUTEX is defined then the number returned is the
57194** greater of the current reserved space and the maximum requested
57195** reserve space.
57196*/
57197SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
57198  int n;
57199  sqlite3BtreeEnter(p);
57200  n = sqlite3BtreeGetReserveNoMutex(p);
57201#ifdef SQLITE_HAS_CODEC
57202  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
57203#endif
57204  sqlite3BtreeLeave(p);
57205  return n;
57206}
57207
57208
57209/*
57210** Set the maximum page count for a database if mxPage is positive.
57211** No changes are made if mxPage is 0 or negative.
57212** Regardless of the value of mxPage, return the maximum page count.
57213*/
57214SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
57215  int n;
57216  sqlite3BtreeEnter(p);
57217  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
57218  sqlite3BtreeLeave(p);
57219  return n;
57220}
57221
57222/*
57223** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
57224** then make no changes.  Always return the value of the BTS_SECURE_DELETE
57225** setting after the change.
57226*/
57227SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
57228  int b;
57229  if( p==0 ) return 0;
57230  sqlite3BtreeEnter(p);
57231  if( newFlag>=0 ){
57232    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
57233    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
57234  }
57235  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
57236  sqlite3BtreeLeave(p);
57237  return b;
57238}
57239
57240/*
57241** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
57242** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
57243** is disabled. The default value for the auto-vacuum property is
57244** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
57245*/
57246SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
57247#ifdef SQLITE_OMIT_AUTOVACUUM
57248  return SQLITE_READONLY;
57249#else
57250  BtShared *pBt = p->pBt;
57251  int rc = SQLITE_OK;
57252  u8 av = (u8)autoVacuum;
57253
57254  sqlite3BtreeEnter(p);
57255  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
57256    rc = SQLITE_READONLY;
57257  }else{
57258    pBt->autoVacuum = av ?1:0;
57259    pBt->incrVacuum = av==2 ?1:0;
57260  }
57261  sqlite3BtreeLeave(p);
57262  return rc;
57263#endif
57264}
57265
57266/*
57267** Return the value of the 'auto-vacuum' property. If auto-vacuum is
57268** enabled 1 is returned. Otherwise 0.
57269*/
57270SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
57271#ifdef SQLITE_OMIT_AUTOVACUUM
57272  return BTREE_AUTOVACUUM_NONE;
57273#else
57274  int rc;
57275  sqlite3BtreeEnter(p);
57276  rc = (
57277    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
57278    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
57279    BTREE_AUTOVACUUM_INCR
57280  );
57281  sqlite3BtreeLeave(p);
57282  return rc;
57283#endif
57284}
57285
57286
57287/*
57288** Get a reference to pPage1 of the database file.  This will
57289** also acquire a readlock on that file.
57290**
57291** SQLITE_OK is returned on success.  If the file is not a
57292** well-formed database file, then SQLITE_CORRUPT is returned.
57293** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
57294** is returned if we run out of memory.
57295*/
57296static int lockBtree(BtShared *pBt){
57297  int rc;              /* Result code from subfunctions */
57298  MemPage *pPage1;     /* Page 1 of the database file */
57299  int nPage;           /* Number of pages in the database */
57300  int nPageFile = 0;   /* Number of pages in the database file */
57301  int nPageHeader;     /* Number of pages in the database according to hdr */
57302
57303  assert( sqlite3_mutex_held(pBt->mutex) );
57304  assert( pBt->pPage1==0 );
57305  rc = sqlite3PagerSharedLock(pBt->pPager);
57306  if( rc!=SQLITE_OK ) return rc;
57307  rc = btreeGetPage(pBt, 1, &pPage1, 0);
57308  if( rc!=SQLITE_OK ) return rc;
57309
57310  /* Do some checking to help insure the file we opened really is
57311  ** a valid database file.
57312  */
57313  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
57314  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
57315  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
57316    nPage = nPageFile;
57317  }
57318  if( nPage>0 ){
57319    u32 pageSize;
57320    u32 usableSize;
57321    u8 *page1 = pPage1->aData;
57322    rc = SQLITE_NOTADB;
57323    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
57324    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
57325    ** 61 74 20 33 00. */
57326    if( memcmp(page1, zMagicHeader, 16)!=0 ){
57327      goto page1_init_failed;
57328    }
57329
57330#ifdef SQLITE_OMIT_WAL
57331    if( page1[18]>1 ){
57332      pBt->btsFlags |= BTS_READ_ONLY;
57333    }
57334    if( page1[19]>1 ){
57335      goto page1_init_failed;
57336    }
57337#else
57338    if( page1[18]>2 ){
57339      pBt->btsFlags |= BTS_READ_ONLY;
57340    }
57341    if( page1[19]>2 ){
57342      goto page1_init_failed;
57343    }
57344
57345    /* If the write version is set to 2, this database should be accessed
57346    ** in WAL mode. If the log is not already open, open it now. Then
57347    ** return SQLITE_OK and return without populating BtShared.pPage1.
57348    ** The caller detects this and calls this function again. This is
57349    ** required as the version of page 1 currently in the page1 buffer
57350    ** may not be the latest version - there may be a newer one in the log
57351    ** file.
57352    */
57353    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
57354      int isOpen = 0;
57355      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
57356      if( rc!=SQLITE_OK ){
57357        goto page1_init_failed;
57358      }else if( isOpen==0 ){
57359        releasePage(pPage1);
57360        return SQLITE_OK;
57361      }
57362      rc = SQLITE_NOTADB;
57363    }
57364#endif
57365
57366    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
57367    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
57368    **
57369    ** The original design allowed these amounts to vary, but as of
57370    ** version 3.6.0, we require them to be fixed.
57371    */
57372    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
57373      goto page1_init_failed;
57374    }
57375    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
57376    ** determined by the 2-byte integer located at an offset of 16 bytes from
57377    ** the beginning of the database file. */
57378    pageSize = (page1[16]<<8) | (page1[17]<<16);
57379    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
57380    ** between 512 and 65536 inclusive. */
57381    if( ((pageSize-1)&pageSize)!=0
57382     || pageSize>SQLITE_MAX_PAGE_SIZE
57383     || pageSize<=256
57384    ){
57385      goto page1_init_failed;
57386    }
57387    assert( (pageSize & 7)==0 );
57388    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
57389    ** integer at offset 20 is the number of bytes of space at the end of
57390    ** each page to reserve for extensions.
57391    **
57392    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
57393    ** determined by the one-byte unsigned integer found at an offset of 20
57394    ** into the database file header. */
57395    usableSize = pageSize - page1[20];
57396    if( (u32)pageSize!=pBt->pageSize ){
57397      /* After reading the first page of the database assuming a page size
57398      ** of BtShared.pageSize, we have discovered that the page-size is
57399      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
57400      ** zero and return SQLITE_OK. The caller will call this function
57401      ** again with the correct page-size.
57402      */
57403      releasePage(pPage1);
57404      pBt->usableSize = usableSize;
57405      pBt->pageSize = pageSize;
57406      freeTempSpace(pBt);
57407      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
57408                                   pageSize-usableSize);
57409      return rc;
57410    }
57411    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
57412      rc = SQLITE_CORRUPT_BKPT;
57413      goto page1_init_failed;
57414    }
57415    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
57416    ** be less than 480. In other words, if the page size is 512, then the
57417    ** reserved space size cannot exceed 32. */
57418    if( usableSize<480 ){
57419      goto page1_init_failed;
57420    }
57421    pBt->pageSize = pageSize;
57422    pBt->usableSize = usableSize;
57423#ifndef SQLITE_OMIT_AUTOVACUUM
57424    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
57425    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
57426#endif
57427  }
57428
57429  /* maxLocal is the maximum amount of payload to store locally for
57430  ** a cell.  Make sure it is small enough so that at least minFanout
57431  ** cells can will fit on one page.  We assume a 10-byte page header.
57432  ** Besides the payload, the cell must store:
57433  **     2-byte pointer to the cell
57434  **     4-byte child pointer
57435  **     9-byte nKey value
57436  **     4-byte nData value
57437  **     4-byte overflow page pointer
57438  ** So a cell consists of a 2-byte pointer, a header which is as much as
57439  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
57440  ** page pointer.
57441  */
57442  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
57443  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
57444  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
57445  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
57446  if( pBt->maxLocal>127 ){
57447    pBt->max1bytePayload = 127;
57448  }else{
57449    pBt->max1bytePayload = (u8)pBt->maxLocal;
57450  }
57451  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
57452  pBt->pPage1 = pPage1;
57453  pBt->nPage = nPage;
57454  return SQLITE_OK;
57455
57456page1_init_failed:
57457  releasePage(pPage1);
57458  pBt->pPage1 = 0;
57459  return rc;
57460}
57461
57462#ifndef NDEBUG
57463/*
57464** Return the number of cursors open on pBt. This is for use
57465** in assert() expressions, so it is only compiled if NDEBUG is not
57466** defined.
57467**
57468** Only write cursors are counted if wrOnly is true.  If wrOnly is
57469** false then all cursors are counted.
57470**
57471** For the purposes of this routine, a cursor is any cursor that
57472** is capable of reading or writing to the database.  Cursors that
57473** have been tripped into the CURSOR_FAULT state are not counted.
57474*/
57475static int countValidCursors(BtShared *pBt, int wrOnly){
57476  BtCursor *pCur;
57477  int r = 0;
57478  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
57479    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
57480     && pCur->eState!=CURSOR_FAULT ) r++;
57481  }
57482  return r;
57483}
57484#endif
57485
57486/*
57487** If there are no outstanding cursors and we are not in the middle
57488** of a transaction but there is a read lock on the database, then
57489** this routine unrefs the first page of the database file which
57490** has the effect of releasing the read lock.
57491**
57492** If there is a transaction in progress, this routine is a no-op.
57493*/
57494static void unlockBtreeIfUnused(BtShared *pBt){
57495  assert( sqlite3_mutex_held(pBt->mutex) );
57496  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
57497  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
57498    MemPage *pPage1 = pBt->pPage1;
57499    assert( pPage1->aData );
57500    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
57501    pBt->pPage1 = 0;
57502    releasePageNotNull(pPage1);
57503  }
57504}
57505
57506/*
57507** If pBt points to an empty file then convert that empty file
57508** into a new empty database by initializing the first page of
57509** the database.
57510*/
57511static int newDatabase(BtShared *pBt){
57512  MemPage *pP1;
57513  unsigned char *data;
57514  int rc;
57515
57516  assert( sqlite3_mutex_held(pBt->mutex) );
57517  if( pBt->nPage>0 ){
57518    return SQLITE_OK;
57519  }
57520  pP1 = pBt->pPage1;
57521  assert( pP1!=0 );
57522  data = pP1->aData;
57523  rc = sqlite3PagerWrite(pP1->pDbPage);
57524  if( rc ) return rc;
57525  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
57526  assert( sizeof(zMagicHeader)==16 );
57527  data[16] = (u8)((pBt->pageSize>>8)&0xff);
57528  data[17] = (u8)((pBt->pageSize>>16)&0xff);
57529  data[18] = 1;
57530  data[19] = 1;
57531  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
57532  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
57533  data[21] = 64;
57534  data[22] = 32;
57535  data[23] = 32;
57536  memset(&data[24], 0, 100-24);
57537  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
57538  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
57539#ifndef SQLITE_OMIT_AUTOVACUUM
57540  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
57541  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
57542  put4byte(&data[36 + 4*4], pBt->autoVacuum);
57543  put4byte(&data[36 + 7*4], pBt->incrVacuum);
57544#endif
57545  pBt->nPage = 1;
57546  data[31] = 1;
57547  return SQLITE_OK;
57548}
57549
57550/*
57551** Initialize the first page of the database file (creating a database
57552** consisting of a single page and no schema objects). Return SQLITE_OK
57553** if successful, or an SQLite error code otherwise.
57554*/
57555SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
57556  int rc;
57557  sqlite3BtreeEnter(p);
57558  p->pBt->nPage = 0;
57559  rc = newDatabase(p->pBt);
57560  sqlite3BtreeLeave(p);
57561  return rc;
57562}
57563
57564/*
57565** Attempt to start a new transaction. A write-transaction
57566** is started if the second argument is nonzero, otherwise a read-
57567** transaction.  If the second argument is 2 or more and exclusive
57568** transaction is started, meaning that no other process is allowed
57569** to access the database.  A preexisting transaction may not be
57570** upgraded to exclusive by calling this routine a second time - the
57571** exclusivity flag only works for a new transaction.
57572**
57573** A write-transaction must be started before attempting any
57574** changes to the database.  None of the following routines
57575** will work unless a transaction is started first:
57576**
57577**      sqlite3BtreeCreateTable()
57578**      sqlite3BtreeCreateIndex()
57579**      sqlite3BtreeClearTable()
57580**      sqlite3BtreeDropTable()
57581**      sqlite3BtreeInsert()
57582**      sqlite3BtreeDelete()
57583**      sqlite3BtreeUpdateMeta()
57584**
57585** If an initial attempt to acquire the lock fails because of lock contention
57586** and the database was previously unlocked, then invoke the busy handler
57587** if there is one.  But if there was previously a read-lock, do not
57588** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
57589** returned when there is already a read-lock in order to avoid a deadlock.
57590**
57591** Suppose there are two processes A and B.  A has a read lock and B has
57592** a reserved lock.  B tries to promote to exclusive but is blocked because
57593** of A's read lock.  A tries to promote to reserved but is blocked by B.
57594** One or the other of the two processes must give way or there can be
57595** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
57596** when A already has a read lock, we encourage A to give up and let B
57597** proceed.
57598*/
57599SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
57600  sqlite3 *pBlock = 0;
57601  BtShared *pBt = p->pBt;
57602  int rc = SQLITE_OK;
57603
57604  sqlite3BtreeEnter(p);
57605  btreeIntegrity(p);
57606
57607  /* If the btree is already in a write-transaction, or it
57608  ** is already in a read-transaction and a read-transaction
57609  ** is requested, this is a no-op.
57610  */
57611  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
57612    goto trans_begun;
57613  }
57614  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
57615
57616  /* Write transactions are not possible on a read-only database */
57617  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
57618    rc = SQLITE_READONLY;
57619    goto trans_begun;
57620  }
57621
57622#ifndef SQLITE_OMIT_SHARED_CACHE
57623  /* If another database handle has already opened a write transaction
57624  ** on this shared-btree structure and a second write transaction is
57625  ** requested, return SQLITE_LOCKED.
57626  */
57627  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
57628   || (pBt->btsFlags & BTS_PENDING)!=0
57629  ){
57630    pBlock = pBt->pWriter->db;
57631  }else if( wrflag>1 ){
57632    BtLock *pIter;
57633    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
57634      if( pIter->pBtree!=p ){
57635        pBlock = pIter->pBtree->db;
57636        break;
57637      }
57638    }
57639  }
57640  if( pBlock ){
57641    sqlite3ConnectionBlocked(p->db, pBlock);
57642    rc = SQLITE_LOCKED_SHAREDCACHE;
57643    goto trans_begun;
57644  }
57645#endif
57646
57647  /* Any read-only or read-write transaction implies a read-lock on
57648  ** page 1. So if some other shared-cache client already has a write-lock
57649  ** on page 1, the transaction cannot be opened. */
57650  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57651  if( SQLITE_OK!=rc ) goto trans_begun;
57652
57653  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
57654  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
57655  do {
57656    /* Call lockBtree() until either pBt->pPage1 is populated or
57657    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
57658    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
57659    ** reading page 1 it discovers that the page-size of the database
57660    ** file is not pBt->pageSize. In this case lockBtree() will update
57661    ** pBt->pageSize to the page-size of the file on disk.
57662    */
57663    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
57664
57665    if( rc==SQLITE_OK && wrflag ){
57666      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
57667        rc = SQLITE_READONLY;
57668      }else{
57669        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
57670        if( rc==SQLITE_OK ){
57671          rc = newDatabase(pBt);
57672        }
57673      }
57674    }
57675
57676    if( rc!=SQLITE_OK ){
57677      unlockBtreeIfUnused(pBt);
57678    }
57679  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
57680          btreeInvokeBusyHandler(pBt) );
57681
57682  if( rc==SQLITE_OK ){
57683    if( p->inTrans==TRANS_NONE ){
57684      pBt->nTransaction++;
57685#ifndef SQLITE_OMIT_SHARED_CACHE
57686      if( p->sharable ){
57687        assert( p->lock.pBtree==p && p->lock.iTable==1 );
57688        p->lock.eLock = READ_LOCK;
57689        p->lock.pNext = pBt->pLock;
57690        pBt->pLock = &p->lock;
57691      }
57692#endif
57693    }
57694    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
57695    if( p->inTrans>pBt->inTransaction ){
57696      pBt->inTransaction = p->inTrans;
57697    }
57698    if( wrflag ){
57699      MemPage *pPage1 = pBt->pPage1;
57700#ifndef SQLITE_OMIT_SHARED_CACHE
57701      assert( !pBt->pWriter );
57702      pBt->pWriter = p;
57703      pBt->btsFlags &= ~BTS_EXCLUSIVE;
57704      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
57705#endif
57706
57707      /* If the db-size header field is incorrect (as it may be if an old
57708      ** client has been writing the database file), update it now. Doing
57709      ** this sooner rather than later means the database size can safely
57710      ** re-read the database size from page 1 if a savepoint or transaction
57711      ** rollback occurs within the transaction.
57712      */
57713      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
57714        rc = sqlite3PagerWrite(pPage1->pDbPage);
57715        if( rc==SQLITE_OK ){
57716          put4byte(&pPage1->aData[28], pBt->nPage);
57717        }
57718      }
57719    }
57720  }
57721
57722
57723trans_begun:
57724  if( rc==SQLITE_OK && wrflag ){
57725    /* This call makes sure that the pager has the correct number of
57726    ** open savepoints. If the second parameter is greater than 0 and
57727    ** the sub-journal is not already open, then it will be opened here.
57728    */
57729    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
57730  }
57731
57732  btreeIntegrity(p);
57733  sqlite3BtreeLeave(p);
57734  return rc;
57735}
57736
57737#ifndef SQLITE_OMIT_AUTOVACUUM
57738
57739/*
57740** Set the pointer-map entries for all children of page pPage. Also, if
57741** pPage contains cells that point to overflow pages, set the pointer
57742** map entries for the overflow pages as well.
57743*/
57744static int setChildPtrmaps(MemPage *pPage){
57745  int i;                             /* Counter variable */
57746  int nCell;                         /* Number of cells in page pPage */
57747  int rc;                            /* Return code */
57748  BtShared *pBt = pPage->pBt;
57749  u8 isInitOrig = pPage->isInit;
57750  Pgno pgno = pPage->pgno;
57751
57752  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57753  rc = btreeInitPage(pPage);
57754  if( rc!=SQLITE_OK ){
57755    goto set_child_ptrmaps_out;
57756  }
57757  nCell = pPage->nCell;
57758
57759  for(i=0; i<nCell; i++){
57760    u8 *pCell = findCell(pPage, i);
57761
57762    ptrmapPutOvflPtr(pPage, pCell, &rc);
57763
57764    if( !pPage->leaf ){
57765      Pgno childPgno = get4byte(pCell);
57766      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
57767    }
57768  }
57769
57770  if( !pPage->leaf ){
57771    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57772    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
57773  }
57774
57775set_child_ptrmaps_out:
57776  pPage->isInit = isInitOrig;
57777  return rc;
57778}
57779
57780/*
57781** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
57782** that it points to iTo. Parameter eType describes the type of pointer to
57783** be modified, as  follows:
57784**
57785** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
57786**                   page of pPage.
57787**
57788** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
57789**                   page pointed to by one of the cells on pPage.
57790**
57791** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
57792**                   overflow page in the list.
57793*/
57794static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
57795  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57796  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
57797  if( eType==PTRMAP_OVERFLOW2 ){
57798    /* The pointer is always the first 4 bytes of the page in this case.  */
57799    if( get4byte(pPage->aData)!=iFrom ){
57800      return SQLITE_CORRUPT_BKPT;
57801    }
57802    put4byte(pPage->aData, iTo);
57803  }else{
57804    u8 isInitOrig = pPage->isInit;
57805    int i;
57806    int nCell;
57807    int rc;
57808
57809    rc = btreeInitPage(pPage);
57810    if( rc ) return rc;
57811    nCell = pPage->nCell;
57812
57813    for(i=0; i<nCell; i++){
57814      u8 *pCell = findCell(pPage, i);
57815      if( eType==PTRMAP_OVERFLOW1 ){
57816        CellInfo info;
57817        pPage->xParseCell(pPage, pCell, &info);
57818        if( info.iOverflow
57819         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
57820         && iFrom==get4byte(&pCell[info.iOverflow])
57821        ){
57822          put4byte(&pCell[info.iOverflow], iTo);
57823          break;
57824        }
57825      }else{
57826        if( get4byte(pCell)==iFrom ){
57827          put4byte(pCell, iTo);
57828          break;
57829        }
57830      }
57831    }
57832
57833    if( i==nCell ){
57834      if( eType!=PTRMAP_BTREE ||
57835          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
57836        return SQLITE_CORRUPT_BKPT;
57837      }
57838      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
57839    }
57840
57841    pPage->isInit = isInitOrig;
57842  }
57843  return SQLITE_OK;
57844}
57845
57846
57847/*
57848** Move the open database page pDbPage to location iFreePage in the
57849** database. The pDbPage reference remains valid.
57850**
57851** The isCommit flag indicates that there is no need to remember that
57852** the journal needs to be sync()ed before database page pDbPage->pgno
57853** can be written to. The caller has already promised not to write to that
57854** page.
57855*/
57856static int relocatePage(
57857  BtShared *pBt,           /* Btree */
57858  MemPage *pDbPage,        /* Open page to move */
57859  u8 eType,                /* Pointer map 'type' entry for pDbPage */
57860  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
57861  Pgno iFreePage,          /* The location to move pDbPage to */
57862  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
57863){
57864  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
57865  Pgno iDbPage = pDbPage->pgno;
57866  Pager *pPager = pBt->pPager;
57867  int rc;
57868
57869  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
57870      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
57871  assert( sqlite3_mutex_held(pBt->mutex) );
57872  assert( pDbPage->pBt==pBt );
57873
57874  /* Move page iDbPage from its current location to page number iFreePage */
57875  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
57876      iDbPage, iFreePage, iPtrPage, eType));
57877  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
57878  if( rc!=SQLITE_OK ){
57879    return rc;
57880  }
57881  pDbPage->pgno = iFreePage;
57882
57883  /* If pDbPage was a btree-page, then it may have child pages and/or cells
57884  ** that point to overflow pages. The pointer map entries for all these
57885  ** pages need to be changed.
57886  **
57887  ** If pDbPage is an overflow page, then the first 4 bytes may store a
57888  ** pointer to a subsequent overflow page. If this is the case, then
57889  ** the pointer map needs to be updated for the subsequent overflow page.
57890  */
57891  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
57892    rc = setChildPtrmaps(pDbPage);
57893    if( rc!=SQLITE_OK ){
57894      return rc;
57895    }
57896  }else{
57897    Pgno nextOvfl = get4byte(pDbPage->aData);
57898    if( nextOvfl!=0 ){
57899      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
57900      if( rc!=SQLITE_OK ){
57901        return rc;
57902      }
57903    }
57904  }
57905
57906  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
57907  ** that it points at iFreePage. Also fix the pointer map entry for
57908  ** iPtrPage.
57909  */
57910  if( eType!=PTRMAP_ROOTPAGE ){
57911    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
57912    if( rc!=SQLITE_OK ){
57913      return rc;
57914    }
57915    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
57916    if( rc!=SQLITE_OK ){
57917      releasePage(pPtrPage);
57918      return rc;
57919    }
57920    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
57921    releasePage(pPtrPage);
57922    if( rc==SQLITE_OK ){
57923      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
57924    }
57925  }
57926  return rc;
57927}
57928
57929/* Forward declaration required by incrVacuumStep(). */
57930static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
57931
57932/*
57933** Perform a single step of an incremental-vacuum. If successful, return
57934** SQLITE_OK. If there is no work to do (and therefore no point in
57935** calling this function again), return SQLITE_DONE. Or, if an error
57936** occurs, return some other error code.
57937**
57938** More specifically, this function attempts to re-organize the database so
57939** that the last page of the file currently in use is no longer in use.
57940**
57941** Parameter nFin is the number of pages that this database would contain
57942** were this function called until it returns SQLITE_DONE.
57943**
57944** If the bCommit parameter is non-zero, this function assumes that the
57945** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
57946** or an error. bCommit is passed true for an auto-vacuum-on-commit
57947** operation, or false for an incremental vacuum.
57948*/
57949static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
57950  Pgno nFreeList;           /* Number of pages still on the free-list */
57951  int rc;
57952
57953  assert( sqlite3_mutex_held(pBt->mutex) );
57954  assert( iLastPg>nFin );
57955
57956  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
57957    u8 eType;
57958    Pgno iPtrPage;
57959
57960    nFreeList = get4byte(&pBt->pPage1->aData[36]);
57961    if( nFreeList==0 ){
57962      return SQLITE_DONE;
57963    }
57964
57965    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
57966    if( rc!=SQLITE_OK ){
57967      return rc;
57968    }
57969    if( eType==PTRMAP_ROOTPAGE ){
57970      return SQLITE_CORRUPT_BKPT;
57971    }
57972
57973    if( eType==PTRMAP_FREEPAGE ){
57974      if( bCommit==0 ){
57975        /* Remove the page from the files free-list. This is not required
57976        ** if bCommit is non-zero. In that case, the free-list will be
57977        ** truncated to zero after this function returns, so it doesn't
57978        ** matter if it still contains some garbage entries.
57979        */
57980        Pgno iFreePg;
57981        MemPage *pFreePg;
57982        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
57983        if( rc!=SQLITE_OK ){
57984          return rc;
57985        }
57986        assert( iFreePg==iLastPg );
57987        releasePage(pFreePg);
57988      }
57989    } else {
57990      Pgno iFreePg;             /* Index of free page to move pLastPg to */
57991      MemPage *pLastPg;
57992      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
57993      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
57994
57995      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
57996      if( rc!=SQLITE_OK ){
57997        return rc;
57998      }
57999
58000      /* If bCommit is zero, this loop runs exactly once and page pLastPg
58001      ** is swapped with the first free page pulled off the free list.
58002      **
58003      ** On the other hand, if bCommit is greater than zero, then keep
58004      ** looping until a free-page located within the first nFin pages
58005      ** of the file is found.
58006      */
58007      if( bCommit==0 ){
58008        eMode = BTALLOC_LE;
58009        iNear = nFin;
58010      }
58011      do {
58012        MemPage *pFreePg;
58013        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
58014        if( rc!=SQLITE_OK ){
58015          releasePage(pLastPg);
58016          return rc;
58017        }
58018        releasePage(pFreePg);
58019      }while( bCommit && iFreePg>nFin );
58020      assert( iFreePg<iLastPg );
58021
58022      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
58023      releasePage(pLastPg);
58024      if( rc!=SQLITE_OK ){
58025        return rc;
58026      }
58027    }
58028  }
58029
58030  if( bCommit==0 ){
58031    do {
58032      iLastPg--;
58033    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
58034    pBt->bDoTruncate = 1;
58035    pBt->nPage = iLastPg;
58036  }
58037  return SQLITE_OK;
58038}
58039
58040/*
58041** The database opened by the first argument is an auto-vacuum database
58042** nOrig pages in size containing nFree free pages. Return the expected
58043** size of the database in pages following an auto-vacuum operation.
58044*/
58045static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
58046  int nEntry;                     /* Number of entries on one ptrmap page */
58047  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
58048  Pgno nFin;                      /* Return value */
58049
58050  nEntry = pBt->usableSize/5;
58051  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
58052  nFin = nOrig - nFree - nPtrmap;
58053  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
58054    nFin--;
58055  }
58056  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
58057    nFin--;
58058  }
58059
58060  return nFin;
58061}
58062
58063/*
58064** A write-transaction must be opened before calling this function.
58065** It performs a single unit of work towards an incremental vacuum.
58066**
58067** If the incremental vacuum is finished after this function has run,
58068** SQLITE_DONE is returned. If it is not finished, but no error occurred,
58069** SQLITE_OK is returned. Otherwise an SQLite error code.
58070*/
58071SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
58072  int rc;
58073  BtShared *pBt = p->pBt;
58074
58075  sqlite3BtreeEnter(p);
58076  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
58077  if( !pBt->autoVacuum ){
58078    rc = SQLITE_DONE;
58079  }else{
58080    Pgno nOrig = btreePagecount(pBt);
58081    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
58082    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
58083
58084    if( nOrig<nFin ){
58085      rc = SQLITE_CORRUPT_BKPT;
58086    }else if( nFree>0 ){
58087      rc = saveAllCursors(pBt, 0, 0);
58088      if( rc==SQLITE_OK ){
58089        invalidateAllOverflowCache(pBt);
58090        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
58091      }
58092      if( rc==SQLITE_OK ){
58093        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58094        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
58095      }
58096    }else{
58097      rc = SQLITE_DONE;
58098    }
58099  }
58100  sqlite3BtreeLeave(p);
58101  return rc;
58102}
58103
58104/*
58105** This routine is called prior to sqlite3PagerCommit when a transaction
58106** is committed for an auto-vacuum database.
58107**
58108** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
58109** the database file should be truncated to during the commit process.
58110** i.e. the database has been reorganized so that only the first *pnTrunc
58111** pages are in use.
58112*/
58113static int autoVacuumCommit(BtShared *pBt){
58114  int rc = SQLITE_OK;
58115  Pager *pPager = pBt->pPager;
58116  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
58117
58118  assert( sqlite3_mutex_held(pBt->mutex) );
58119  invalidateAllOverflowCache(pBt);
58120  assert(pBt->autoVacuum);
58121  if( !pBt->incrVacuum ){
58122    Pgno nFin;         /* Number of pages in database after autovacuuming */
58123    Pgno nFree;        /* Number of pages on the freelist initially */
58124    Pgno iFree;        /* The next page to be freed */
58125    Pgno nOrig;        /* Database size before freeing */
58126
58127    nOrig = btreePagecount(pBt);
58128    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
58129      /* It is not possible to create a database for which the final page
58130      ** is either a pointer-map page or the pending-byte page. If one
58131      ** is encountered, this indicates corruption.
58132      */
58133      return SQLITE_CORRUPT_BKPT;
58134    }
58135
58136    nFree = get4byte(&pBt->pPage1->aData[36]);
58137    nFin = finalDbSize(pBt, nOrig, nFree);
58138    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
58139    if( nFin<nOrig ){
58140      rc = saveAllCursors(pBt, 0, 0);
58141    }
58142    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
58143      rc = incrVacuumStep(pBt, nFin, iFree, 1);
58144    }
58145    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
58146      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58147      put4byte(&pBt->pPage1->aData[32], 0);
58148      put4byte(&pBt->pPage1->aData[36], 0);
58149      put4byte(&pBt->pPage1->aData[28], nFin);
58150      pBt->bDoTruncate = 1;
58151      pBt->nPage = nFin;
58152    }
58153    if( rc!=SQLITE_OK ){
58154      sqlite3PagerRollback(pPager);
58155    }
58156  }
58157
58158  assert( nRef>=sqlite3PagerRefcount(pPager) );
58159  return rc;
58160}
58161
58162#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
58163# define setChildPtrmaps(x) SQLITE_OK
58164#endif
58165
58166/*
58167** This routine does the first phase of a two-phase commit.  This routine
58168** causes a rollback journal to be created (if it does not already exist)
58169** and populated with enough information so that if a power loss occurs
58170** the database can be restored to its original state by playing back
58171** the journal.  Then the contents of the journal are flushed out to
58172** the disk.  After the journal is safely on oxide, the changes to the
58173** database are written into the database file and flushed to oxide.
58174** At the end of this call, the rollback journal still exists on the
58175** disk and we are still holding all locks, so the transaction has not
58176** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
58177** commit process.
58178**
58179** This call is a no-op if no write-transaction is currently active on pBt.
58180**
58181** Otherwise, sync the database file for the btree pBt. zMaster points to
58182** the name of a master journal file that should be written into the
58183** individual journal file, or is NULL, indicating no master journal file
58184** (single database transaction).
58185**
58186** When this is called, the master journal should already have been
58187** created, populated with this journal pointer and synced to disk.
58188**
58189** Once this is routine has returned, the only thing required to commit
58190** the write-transaction for this database file is to delete the journal.
58191*/
58192SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
58193  int rc = SQLITE_OK;
58194  if( p->inTrans==TRANS_WRITE ){
58195    BtShared *pBt = p->pBt;
58196    sqlite3BtreeEnter(p);
58197#ifndef SQLITE_OMIT_AUTOVACUUM
58198    if( pBt->autoVacuum ){
58199      rc = autoVacuumCommit(pBt);
58200      if( rc!=SQLITE_OK ){
58201        sqlite3BtreeLeave(p);
58202        return rc;
58203      }
58204    }
58205    if( pBt->bDoTruncate ){
58206      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
58207    }
58208#endif
58209    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
58210    sqlite3BtreeLeave(p);
58211  }
58212  return rc;
58213}
58214
58215/*
58216** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
58217** at the conclusion of a transaction.
58218*/
58219static void btreeEndTransaction(Btree *p){
58220  BtShared *pBt = p->pBt;
58221  sqlite3 *db = p->db;
58222  assert( sqlite3BtreeHoldsMutex(p) );
58223
58224#ifndef SQLITE_OMIT_AUTOVACUUM
58225  pBt->bDoTruncate = 0;
58226#endif
58227  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
58228    /* If there are other active statements that belong to this database
58229    ** handle, downgrade to a read-only transaction. The other statements
58230    ** may still be reading from the database.  */
58231    downgradeAllSharedCacheTableLocks(p);
58232    p->inTrans = TRANS_READ;
58233  }else{
58234    /* If the handle had any kind of transaction open, decrement the
58235    ** transaction count of the shared btree. If the transaction count
58236    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
58237    ** call below will unlock the pager.  */
58238    if( p->inTrans!=TRANS_NONE ){
58239      clearAllSharedCacheTableLocks(p);
58240      pBt->nTransaction--;
58241      if( 0==pBt->nTransaction ){
58242        pBt->inTransaction = TRANS_NONE;
58243      }
58244    }
58245
58246    /* Set the current transaction state to TRANS_NONE and unlock the
58247    ** pager if this call closed the only read or write transaction.  */
58248    p->inTrans = TRANS_NONE;
58249    unlockBtreeIfUnused(pBt);
58250  }
58251
58252  btreeIntegrity(p);
58253}
58254
58255/*
58256** Commit the transaction currently in progress.
58257**
58258** This routine implements the second phase of a 2-phase commit.  The
58259** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
58260** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
58261** routine did all the work of writing information out to disk and flushing the
58262** contents so that they are written onto the disk platter.  All this
58263** routine has to do is delete or truncate or zero the header in the
58264** the rollback journal (which causes the transaction to commit) and
58265** drop locks.
58266**
58267** Normally, if an error occurs while the pager layer is attempting to
58268** finalize the underlying journal file, this function returns an error and
58269** the upper layer will attempt a rollback. However, if the second argument
58270** is non-zero then this b-tree transaction is part of a multi-file
58271** transaction. In this case, the transaction has already been committed
58272** (by deleting a master journal file) and the caller will ignore this
58273** functions return code. So, even if an error occurs in the pager layer,
58274** reset the b-tree objects internal state to indicate that the write
58275** transaction has been closed. This is quite safe, as the pager will have
58276** transitioned to the error state.
58277**
58278** This will release the write lock on the database file.  If there
58279** are no active cursors, it also releases the read lock.
58280*/
58281SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
58282
58283  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
58284  sqlite3BtreeEnter(p);
58285  btreeIntegrity(p);
58286
58287  /* If the handle has a write-transaction open, commit the shared-btrees
58288  ** transaction and set the shared state to TRANS_READ.
58289  */
58290  if( p->inTrans==TRANS_WRITE ){
58291    int rc;
58292    BtShared *pBt = p->pBt;
58293    assert( pBt->inTransaction==TRANS_WRITE );
58294    assert( pBt->nTransaction>0 );
58295    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
58296    if( rc!=SQLITE_OK && bCleanup==0 ){
58297      sqlite3BtreeLeave(p);
58298      return rc;
58299    }
58300    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
58301    pBt->inTransaction = TRANS_READ;
58302    btreeClearHasContent(pBt);
58303  }
58304
58305  btreeEndTransaction(p);
58306  sqlite3BtreeLeave(p);
58307  return SQLITE_OK;
58308}
58309
58310/*
58311** Do both phases of a commit.
58312*/
58313SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
58314  int rc;
58315  sqlite3BtreeEnter(p);
58316  rc = sqlite3BtreeCommitPhaseOne(p, 0);
58317  if( rc==SQLITE_OK ){
58318    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
58319  }
58320  sqlite3BtreeLeave(p);
58321  return rc;
58322}
58323
58324/*
58325** This routine sets the state to CURSOR_FAULT and the error
58326** code to errCode for every cursor on any BtShared that pBtree
58327** references.  Or if the writeOnly flag is set to 1, then only
58328** trip write cursors and leave read cursors unchanged.
58329**
58330** Every cursor is a candidate to be tripped, including cursors
58331** that belong to other database connections that happen to be
58332** sharing the cache with pBtree.
58333**
58334** This routine gets called when a rollback occurs. If the writeOnly
58335** flag is true, then only write-cursors need be tripped - read-only
58336** cursors save their current positions so that they may continue
58337** following the rollback. Or, if writeOnly is false, all cursors are
58338** tripped. In general, writeOnly is false if the transaction being
58339** rolled back modified the database schema. In this case b-tree root
58340** pages may be moved or deleted from the database altogether, making
58341** it unsafe for read cursors to continue.
58342**
58343** If the writeOnly flag is true and an error is encountered while
58344** saving the current position of a read-only cursor, all cursors,
58345** including all read-cursors are tripped.
58346**
58347** SQLITE_OK is returned if successful, or if an error occurs while
58348** saving a cursor position, an SQLite error code.
58349*/
58350SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
58351  BtCursor *p;
58352  int rc = SQLITE_OK;
58353
58354  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
58355  if( pBtree ){
58356    sqlite3BtreeEnter(pBtree);
58357    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58358      int i;
58359      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
58360        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58361          rc = saveCursorPosition(p);
58362          if( rc!=SQLITE_OK ){
58363            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
58364            break;
58365          }
58366        }
58367      }else{
58368        sqlite3BtreeClearCursor(p);
58369        p->eState = CURSOR_FAULT;
58370        p->skipNext = errCode;
58371      }
58372      for(i=0; i<=p->iPage; i++){
58373        releasePage(p->apPage[i]);
58374        p->apPage[i] = 0;
58375      }
58376    }
58377    sqlite3BtreeLeave(pBtree);
58378  }
58379  return rc;
58380}
58381
58382/*
58383** Rollback the transaction in progress.
58384**
58385** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
58386** Only write cursors are tripped if writeOnly is true but all cursors are
58387** tripped if writeOnly is false.  Any attempt to use
58388** a tripped cursor will result in an error.
58389**
58390** This will release the write lock on the database file.  If there
58391** are no active cursors, it also releases the read lock.
58392*/
58393SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
58394  int rc;
58395  BtShared *pBt = p->pBt;
58396  MemPage *pPage1;
58397
58398  assert( writeOnly==1 || writeOnly==0 );
58399  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
58400  sqlite3BtreeEnter(p);
58401  if( tripCode==SQLITE_OK ){
58402    rc = tripCode = saveAllCursors(pBt, 0, 0);
58403    if( rc ) writeOnly = 0;
58404  }else{
58405    rc = SQLITE_OK;
58406  }
58407  if( tripCode ){
58408    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
58409    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
58410    if( rc2!=SQLITE_OK ) rc = rc2;
58411  }
58412  btreeIntegrity(p);
58413
58414  if( p->inTrans==TRANS_WRITE ){
58415    int rc2;
58416
58417    assert( TRANS_WRITE==pBt->inTransaction );
58418    rc2 = sqlite3PagerRollback(pBt->pPager);
58419    if( rc2!=SQLITE_OK ){
58420      rc = rc2;
58421    }
58422
58423    /* The rollback may have destroyed the pPage1->aData value.  So
58424    ** call btreeGetPage() on page 1 again to make
58425    ** sure pPage1->aData is set correctly. */
58426    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
58427      int nPage = get4byte(28+(u8*)pPage1->aData);
58428      testcase( nPage==0 );
58429      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
58430      testcase( pBt->nPage!=nPage );
58431      pBt->nPage = nPage;
58432      releasePage(pPage1);
58433    }
58434    assert( countValidCursors(pBt, 1)==0 );
58435    pBt->inTransaction = TRANS_READ;
58436    btreeClearHasContent(pBt);
58437  }
58438
58439  btreeEndTransaction(p);
58440  sqlite3BtreeLeave(p);
58441  return rc;
58442}
58443
58444/*
58445** Start a statement subtransaction. The subtransaction can be rolled
58446** back independently of the main transaction. You must start a transaction
58447** before starting a subtransaction. The subtransaction is ended automatically
58448** if the main transaction commits or rolls back.
58449**
58450** Statement subtransactions are used around individual SQL statements
58451** that are contained within a BEGIN...COMMIT block.  If a constraint
58452** error occurs within the statement, the effect of that one statement
58453** can be rolled back without having to rollback the entire transaction.
58454**
58455** A statement sub-transaction is implemented as an anonymous savepoint. The
58456** value passed as the second parameter is the total number of savepoints,
58457** including the new anonymous savepoint, open on the B-Tree. i.e. if there
58458** are no active savepoints and no other statement-transactions open,
58459** iStatement is 1. This anonymous savepoint can be released or rolled back
58460** using the sqlite3BtreeSavepoint() function.
58461*/
58462SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
58463  int rc;
58464  BtShared *pBt = p->pBt;
58465  sqlite3BtreeEnter(p);
58466  assert( p->inTrans==TRANS_WRITE );
58467  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
58468  assert( iStatement>0 );
58469  assert( iStatement>p->db->nSavepoint );
58470  assert( pBt->inTransaction==TRANS_WRITE );
58471  /* At the pager level, a statement transaction is a savepoint with
58472  ** an index greater than all savepoints created explicitly using
58473  ** SQL statements. It is illegal to open, release or rollback any
58474  ** such savepoints while the statement transaction savepoint is active.
58475  */
58476  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
58477  sqlite3BtreeLeave(p);
58478  return rc;
58479}
58480
58481/*
58482** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
58483** or SAVEPOINT_RELEASE. This function either releases or rolls back the
58484** savepoint identified by parameter iSavepoint, depending on the value
58485** of op.
58486**
58487** Normally, iSavepoint is greater than or equal to zero. However, if op is
58488** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
58489** contents of the entire transaction are rolled back. This is different
58490** from a normal transaction rollback, as no locks are released and the
58491** transaction remains open.
58492*/
58493SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
58494  int rc = SQLITE_OK;
58495  if( p && p->inTrans==TRANS_WRITE ){
58496    BtShared *pBt = p->pBt;
58497    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
58498    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
58499    sqlite3BtreeEnter(p);
58500    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
58501    if( rc==SQLITE_OK ){
58502      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
58503        pBt->nPage = 0;
58504      }
58505      rc = newDatabase(pBt);
58506      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
58507
58508      /* The database size was written into the offset 28 of the header
58509      ** when the transaction started, so we know that the value at offset
58510      ** 28 is nonzero. */
58511      assert( pBt->nPage>0 );
58512    }
58513    sqlite3BtreeLeave(p);
58514  }
58515  return rc;
58516}
58517
58518/*
58519** Create a new cursor for the BTree whose root is on the page
58520** iTable. If a read-only cursor is requested, it is assumed that
58521** the caller already has at least a read-only transaction open
58522** on the database already. If a write-cursor is requested, then
58523** the caller is assumed to have an open write transaction.
58524**
58525** If wrFlag==0, then the cursor can only be used for reading.
58526** If wrFlag==1, then the cursor can be used for reading or for
58527** writing if other conditions for writing are also met.  These
58528** are the conditions that must be met in order for writing to
58529** be allowed:
58530**
58531** 1:  The cursor must have been opened with wrFlag==1
58532**
58533** 2:  Other database connections that share the same pager cache
58534**     but which are not in the READ_UNCOMMITTED state may not have
58535**     cursors open with wrFlag==0 on the same table.  Otherwise
58536**     the changes made by this write cursor would be visible to
58537**     the read cursors in the other database connection.
58538**
58539** 3:  The database must be writable (not on read-only media)
58540**
58541** 4:  There must be an active transaction.
58542**
58543** No checking is done to make sure that page iTable really is the
58544** root page of a b-tree.  If it is not, then the cursor acquired
58545** will not work correctly.
58546**
58547** It is assumed that the sqlite3BtreeCursorZero() has been called
58548** on pCur to initialize the memory space prior to invoking this routine.
58549*/
58550static int btreeCursor(
58551  Btree *p,                              /* The btree */
58552  int iTable,                            /* Root page of table to open */
58553  int wrFlag,                            /* 1 to write. 0 read-only */
58554  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
58555  BtCursor *pCur                         /* Space for new cursor */
58556){
58557  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
58558  BtCursor *pX;                          /* Looping over other all cursors */
58559
58560  assert( sqlite3BtreeHoldsMutex(p) );
58561  assert( wrFlag==0 || wrFlag==1 );
58562
58563  /* The following assert statements verify that if this is a sharable
58564  ** b-tree database, the connection is holding the required table locks,
58565  ** and that no other connection has any open cursor that conflicts with
58566  ** this lock.  */
58567  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
58568  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
58569
58570  /* Assert that the caller has opened the required transaction. */
58571  assert( p->inTrans>TRANS_NONE );
58572  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
58573  assert( pBt->pPage1 && pBt->pPage1->aData );
58574  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
58575
58576  if( wrFlag ){
58577    allocateTempSpace(pBt);
58578    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
58579  }
58580  if( iTable==1 && btreePagecount(pBt)==0 ){
58581    assert( wrFlag==0 );
58582    iTable = 0;
58583  }
58584
58585  /* Now that no other errors can occur, finish filling in the BtCursor
58586  ** variables and link the cursor into the BtShared list.  */
58587  pCur->pgnoRoot = (Pgno)iTable;
58588  pCur->iPage = -1;
58589  pCur->pKeyInfo = pKeyInfo;
58590  pCur->pBtree = p;
58591  pCur->pBt = pBt;
58592  assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
58593  pCur->curFlags = wrFlag;
58594  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
58595  /* If there are two or more cursors on the same btree, then all such
58596  ** cursors *must* have the BTCF_Multiple flag set. */
58597  for(pX=pBt->pCursor; pX; pX=pX->pNext){
58598    if( pX->pgnoRoot==(Pgno)iTable ){
58599      pX->curFlags |= BTCF_Multiple;
58600      pCur->curFlags |= BTCF_Multiple;
58601    }
58602  }
58603  pCur->pNext = pBt->pCursor;
58604  pBt->pCursor = pCur;
58605  pCur->eState = CURSOR_INVALID;
58606  return SQLITE_OK;
58607}
58608SQLITE_PRIVATE int sqlite3BtreeCursor(
58609  Btree *p,                                   /* The btree */
58610  int iTable,                                 /* Root page of table to open */
58611  int wrFlag,                                 /* 1 to write. 0 read-only */
58612  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
58613  BtCursor *pCur                              /* Write new cursor here */
58614){
58615  int rc;
58616  if( iTable<1 ){
58617    rc = SQLITE_CORRUPT_BKPT;
58618  }else{
58619    sqlite3BtreeEnter(p);
58620    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
58621    sqlite3BtreeLeave(p);
58622  }
58623  return rc;
58624}
58625
58626/*
58627** Return the size of a BtCursor object in bytes.
58628**
58629** This interfaces is needed so that users of cursors can preallocate
58630** sufficient storage to hold a cursor.  The BtCursor object is opaque
58631** to users so they cannot do the sizeof() themselves - they must call
58632** this routine.
58633*/
58634SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
58635  return ROUND8(sizeof(BtCursor));
58636}
58637
58638/*
58639** Initialize memory that will be converted into a BtCursor object.
58640**
58641** The simple approach here would be to memset() the entire object
58642** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
58643** do not need to be zeroed and they are large, so we can save a lot
58644** of run-time by skipping the initialization of those elements.
58645*/
58646SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
58647  memset(p, 0, offsetof(BtCursor, iPage));
58648}
58649
58650/*
58651** Close a cursor.  The read lock on the database file is released
58652** when the last cursor is closed.
58653*/
58654SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
58655  Btree *pBtree = pCur->pBtree;
58656  if( pBtree ){
58657    int i;
58658    BtShared *pBt = pCur->pBt;
58659    sqlite3BtreeEnter(pBtree);
58660    sqlite3BtreeClearCursor(pCur);
58661    assert( pBt->pCursor!=0 );
58662    if( pBt->pCursor==pCur ){
58663      pBt->pCursor = pCur->pNext;
58664    }else{
58665      BtCursor *pPrev = pBt->pCursor;
58666      do{
58667        if( pPrev->pNext==pCur ){
58668          pPrev->pNext = pCur->pNext;
58669          break;
58670        }
58671        pPrev = pPrev->pNext;
58672      }while( ALWAYS(pPrev) );
58673    }
58674    for(i=0; i<=pCur->iPage; i++){
58675      releasePage(pCur->apPage[i]);
58676    }
58677    unlockBtreeIfUnused(pBt);
58678    sqlite3_free(pCur->aOverflow);
58679    /* sqlite3_free(pCur); */
58680    sqlite3BtreeLeave(pBtree);
58681  }
58682  return SQLITE_OK;
58683}
58684
58685/*
58686** Make sure the BtCursor* given in the argument has a valid
58687** BtCursor.info structure.  If it is not already valid, call
58688** btreeParseCell() to fill it in.
58689**
58690** BtCursor.info is a cache of the information in the current cell.
58691** Using this cache reduces the number of calls to btreeParseCell().
58692*/
58693#ifndef NDEBUG
58694  static void assertCellInfo(BtCursor *pCur){
58695    CellInfo info;
58696    int iPage = pCur->iPage;
58697    memset(&info, 0, sizeof(info));
58698    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
58699    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
58700  }
58701#else
58702  #define assertCellInfo(x)
58703#endif
58704static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
58705  if( pCur->info.nSize==0 ){
58706    int iPage = pCur->iPage;
58707    pCur->curFlags |= BTCF_ValidNKey;
58708    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
58709  }else{
58710    assertCellInfo(pCur);
58711  }
58712}
58713
58714#ifndef NDEBUG  /* The next routine used only within assert() statements */
58715/*
58716** Return true if the given BtCursor is valid.  A valid cursor is one
58717** that is currently pointing to a row in a (non-empty) table.
58718** This is a verification routine is used only within assert() statements.
58719*/
58720SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
58721  return pCur && pCur->eState==CURSOR_VALID;
58722}
58723#endif /* NDEBUG */
58724
58725/*
58726** Set *pSize to the size of the buffer needed to hold the value of
58727** the key for the current entry.  If the cursor is not pointing
58728** to a valid entry, *pSize is set to 0.
58729**
58730** For a table with the INTKEY flag set, this routine returns the key
58731** itself, not the number of bytes in the key.
58732**
58733** The caller must position the cursor prior to invoking this routine.
58734**
58735** This routine cannot fail.  It always returns SQLITE_OK.
58736*/
58737SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
58738  assert( cursorHoldsMutex(pCur) );
58739  assert( pCur->eState==CURSOR_VALID );
58740  getCellInfo(pCur);
58741  *pSize = pCur->info.nKey;
58742  return SQLITE_OK;
58743}
58744
58745/*
58746** Set *pSize to the number of bytes of data in the entry the
58747** cursor currently points to.
58748**
58749** The caller must guarantee that the cursor is pointing to a non-NULL
58750** valid entry.  In other words, the calling procedure must guarantee
58751** that the cursor has Cursor.eState==CURSOR_VALID.
58752**
58753** Failure is not possible.  This function always returns SQLITE_OK.
58754** It might just as well be a procedure (returning void) but we continue
58755** to return an integer result code for historical reasons.
58756*/
58757SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
58758  assert( cursorHoldsMutex(pCur) );
58759  assert( pCur->eState==CURSOR_VALID );
58760  assert( pCur->iPage>=0 );
58761  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
58762  assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
58763  getCellInfo(pCur);
58764  *pSize = pCur->info.nPayload;
58765  return SQLITE_OK;
58766}
58767
58768/*
58769** Given the page number of an overflow page in the database (parameter
58770** ovfl), this function finds the page number of the next page in the
58771** linked list of overflow pages. If possible, it uses the auto-vacuum
58772** pointer-map data instead of reading the content of page ovfl to do so.
58773**
58774** If an error occurs an SQLite error code is returned. Otherwise:
58775**
58776** The page number of the next overflow page in the linked list is
58777** written to *pPgnoNext. If page ovfl is the last page in its linked
58778** list, *pPgnoNext is set to zero.
58779**
58780** If ppPage is not NULL, and a reference to the MemPage object corresponding
58781** to page number pOvfl was obtained, then *ppPage is set to point to that
58782** reference. It is the responsibility of the caller to call releasePage()
58783** on *ppPage to free the reference. In no reference was obtained (because
58784** the pointer-map was used to obtain the value for *pPgnoNext), then
58785** *ppPage is set to zero.
58786*/
58787static int getOverflowPage(
58788  BtShared *pBt,               /* The database file */
58789  Pgno ovfl,                   /* Current overflow page number */
58790  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
58791  Pgno *pPgnoNext              /* OUT: Next overflow page number */
58792){
58793  Pgno next = 0;
58794  MemPage *pPage = 0;
58795  int rc = SQLITE_OK;
58796
58797  assert( sqlite3_mutex_held(pBt->mutex) );
58798  assert(pPgnoNext);
58799
58800#ifndef SQLITE_OMIT_AUTOVACUUM
58801  /* Try to find the next page in the overflow list using the
58802  ** autovacuum pointer-map pages. Guess that the next page in
58803  ** the overflow list is page number (ovfl+1). If that guess turns
58804  ** out to be wrong, fall back to loading the data of page
58805  ** number ovfl to determine the next page number.
58806  */
58807  if( pBt->autoVacuum ){
58808    Pgno pgno;
58809    Pgno iGuess = ovfl+1;
58810    u8 eType;
58811
58812    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
58813      iGuess++;
58814    }
58815
58816    if( iGuess<=btreePagecount(pBt) ){
58817      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
58818      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
58819        next = iGuess;
58820        rc = SQLITE_DONE;
58821      }
58822    }
58823  }
58824#endif
58825
58826  assert( next==0 || rc==SQLITE_DONE );
58827  if( rc==SQLITE_OK ){
58828    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
58829    assert( rc==SQLITE_OK || pPage==0 );
58830    if( rc==SQLITE_OK ){
58831      next = get4byte(pPage->aData);
58832    }
58833  }
58834
58835  *pPgnoNext = next;
58836  if( ppPage ){
58837    *ppPage = pPage;
58838  }else{
58839    releasePage(pPage);
58840  }
58841  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
58842}
58843
58844/*
58845** Copy data from a buffer to a page, or from a page to a buffer.
58846**
58847** pPayload is a pointer to data stored on database page pDbPage.
58848** If argument eOp is false, then nByte bytes of data are copied
58849** from pPayload to the buffer pointed at by pBuf. If eOp is true,
58850** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
58851** of data are copied from the buffer pBuf to pPayload.
58852**
58853** SQLITE_OK is returned on success, otherwise an error code.
58854*/
58855static int copyPayload(
58856  void *pPayload,           /* Pointer to page data */
58857  void *pBuf,               /* Pointer to buffer */
58858  int nByte,                /* Number of bytes to copy */
58859  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
58860  DbPage *pDbPage           /* Page containing pPayload */
58861){
58862  if( eOp ){
58863    /* Copy data from buffer to page (a write operation) */
58864    int rc = sqlite3PagerWrite(pDbPage);
58865    if( rc!=SQLITE_OK ){
58866      return rc;
58867    }
58868    memcpy(pPayload, pBuf, nByte);
58869  }else{
58870    /* Copy data from page to buffer (a read operation) */
58871    memcpy(pBuf, pPayload, nByte);
58872  }
58873  return SQLITE_OK;
58874}
58875
58876/*
58877** This function is used to read or overwrite payload information
58878** for the entry that the pCur cursor is pointing to. The eOp
58879** argument is interpreted as follows:
58880**
58881**   0: The operation is a read. Populate the overflow cache.
58882**   1: The operation is a write. Populate the overflow cache.
58883**   2: The operation is a read. Do not populate the overflow cache.
58884**
58885** A total of "amt" bytes are read or written beginning at "offset".
58886** Data is read to or from the buffer pBuf.
58887**
58888** The content being read or written might appear on the main page
58889** or be scattered out on multiple overflow pages.
58890**
58891** If the current cursor entry uses one or more overflow pages and the
58892** eOp argument is not 2, this function may allocate space for and lazily
58893** populates the overflow page-list cache array (BtCursor.aOverflow).
58894** Subsequent calls use this cache to make seeking to the supplied offset
58895** more efficient.
58896**
58897** Once an overflow page-list cache has been allocated, it may be
58898** invalidated if some other cursor writes to the same table, or if
58899** the cursor is moved to a different row. Additionally, in auto-vacuum
58900** mode, the following events may invalidate an overflow page-list cache.
58901**
58902**   * An incremental vacuum,
58903**   * A commit in auto_vacuum="full" mode,
58904**   * Creating a table (may require moving an overflow page).
58905*/
58906static int accessPayload(
58907  BtCursor *pCur,      /* Cursor pointing to entry to read from */
58908  u32 offset,          /* Begin reading this far into payload */
58909  u32 amt,             /* Read this many bytes */
58910  unsigned char *pBuf, /* Write the bytes into this buffer */
58911  int eOp              /* zero to read. non-zero to write. */
58912){
58913  unsigned char *aPayload;
58914  int rc = SQLITE_OK;
58915  int iIdx = 0;
58916  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
58917  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
58918#ifdef SQLITE_DIRECT_OVERFLOW_READ
58919  unsigned char * const pBufStart = pBuf;
58920  int bEnd;                                 /* True if reading to end of data */
58921#endif
58922
58923  assert( pPage );
58924  assert( pCur->eState==CURSOR_VALID );
58925  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
58926  assert( cursorHoldsMutex(pCur) );
58927  assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
58928
58929  getCellInfo(pCur);
58930  aPayload = pCur->info.pPayload;
58931#ifdef SQLITE_DIRECT_OVERFLOW_READ
58932  bEnd = offset+amt==pCur->info.nPayload;
58933#endif
58934  assert( offset+amt <= pCur->info.nPayload );
58935
58936  if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
58937    /* Trying to read or write past the end of the data is an error */
58938    return SQLITE_CORRUPT_BKPT;
58939  }
58940
58941  /* Check if data must be read/written to/from the btree page itself. */
58942  if( offset<pCur->info.nLocal ){
58943    int a = amt;
58944    if( a+offset>pCur->info.nLocal ){
58945      a = pCur->info.nLocal - offset;
58946    }
58947    rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
58948    offset = 0;
58949    pBuf += a;
58950    amt -= a;
58951  }else{
58952    offset -= pCur->info.nLocal;
58953  }
58954
58955
58956  if( rc==SQLITE_OK && amt>0 ){
58957    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
58958    Pgno nextPage;
58959
58960    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
58961
58962    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
58963    ** Except, do not allocate aOverflow[] for eOp==2.
58964    **
58965    ** The aOverflow[] array is sized at one entry for each overflow page
58966    ** in the overflow chain. The page number of the first overflow page is
58967    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
58968    ** means "not yet known" (the cache is lazily populated).
58969    */
58970    if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
58971      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
58972      if( nOvfl>pCur->nOvflAlloc ){
58973        Pgno *aNew = (Pgno*)sqlite3Realloc(
58974            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
58975        );
58976        if( aNew==0 ){
58977          rc = SQLITE_NOMEM;
58978        }else{
58979          pCur->nOvflAlloc = nOvfl*2;
58980          pCur->aOverflow = aNew;
58981        }
58982      }
58983      if( rc==SQLITE_OK ){
58984        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
58985        pCur->curFlags |= BTCF_ValidOvfl;
58986      }
58987    }
58988
58989    /* If the overflow page-list cache has been allocated and the
58990    ** entry for the first required overflow page is valid, skip
58991    ** directly to it.
58992    */
58993    if( (pCur->curFlags & BTCF_ValidOvfl)!=0
58994     && pCur->aOverflow[offset/ovflSize]
58995    ){
58996      iIdx = (offset/ovflSize);
58997      nextPage = pCur->aOverflow[iIdx];
58998      offset = (offset%ovflSize);
58999    }
59000
59001    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
59002
59003      /* If required, populate the overflow page-list cache. */
59004      if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
59005        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
59006        pCur->aOverflow[iIdx] = nextPage;
59007      }
59008
59009      if( offset>=ovflSize ){
59010        /* The only reason to read this page is to obtain the page
59011        ** number for the next page in the overflow chain. The page
59012        ** data is not required. So first try to lookup the overflow
59013        ** page-list cache, if any, then fall back to the getOverflowPage()
59014        ** function.
59015        **
59016        ** Note that the aOverflow[] array must be allocated because eOp!=2
59017        ** here.  If eOp==2, then offset==0 and this branch is never taken.
59018        */
59019        assert( eOp!=2 );
59020        assert( pCur->curFlags & BTCF_ValidOvfl );
59021        assert( pCur->pBtree->db==pBt->db );
59022        if( pCur->aOverflow[iIdx+1] ){
59023          nextPage = pCur->aOverflow[iIdx+1];
59024        }else{
59025          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
59026        }
59027        offset -= ovflSize;
59028      }else{
59029        /* Need to read this page properly. It contains some of the
59030        ** range of data that is being read (eOp==0) or written (eOp!=0).
59031        */
59032#ifdef SQLITE_DIRECT_OVERFLOW_READ
59033        sqlite3_file *fd;
59034#endif
59035        int a = amt;
59036        if( a + offset > ovflSize ){
59037          a = ovflSize - offset;
59038        }
59039
59040#ifdef SQLITE_DIRECT_OVERFLOW_READ
59041        /* If all the following are true:
59042        **
59043        **   1) this is a read operation, and
59044        **   2) data is required from the start of this overflow page, and
59045        **   3) the database is file-backed, and
59046        **   4) there is no open write-transaction, and
59047        **   5) the database is not a WAL database,
59048        **   6) all data from the page is being read.
59049        **   7) at least 4 bytes have already been read into the output buffer
59050        **
59051        ** then data can be read directly from the database file into the
59052        ** output buffer, bypassing the page-cache altogether. This speeds
59053        ** up loading large records that span many overflow pages.
59054        */
59055        if( (eOp&0x01)==0                                      /* (1) */
59056         && offset==0                                          /* (2) */
59057         && (bEnd || a==ovflSize)                              /* (6) */
59058         && pBt->inTransaction==TRANS_READ                     /* (4) */
59059         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
59060         && pBt->pPage1->aData[19]==0x01                       /* (5) */
59061         && &pBuf[-4]>=pBufStart                               /* (7) */
59062        ){
59063          u8 aSave[4];
59064          u8 *aWrite = &pBuf[-4];
59065          assert( aWrite>=pBufStart );                         /* hence (7) */
59066          memcpy(aSave, aWrite, 4);
59067          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
59068          nextPage = get4byte(aWrite);
59069          memcpy(aWrite, aSave, 4);
59070        }else
59071#endif
59072
59073        {
59074          DbPage *pDbPage;
59075          rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
59076              ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
59077          );
59078          if( rc==SQLITE_OK ){
59079            aPayload = sqlite3PagerGetData(pDbPage);
59080            nextPage = get4byte(aPayload);
59081            rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
59082            sqlite3PagerUnref(pDbPage);
59083            offset = 0;
59084          }
59085        }
59086        amt -= a;
59087        pBuf += a;
59088      }
59089    }
59090  }
59091
59092  if( rc==SQLITE_OK && amt>0 ){
59093    return SQLITE_CORRUPT_BKPT;
59094  }
59095  return rc;
59096}
59097
59098/*
59099** Read part of the key associated with cursor pCur.  Exactly
59100** "amt" bytes will be transferred into pBuf[].  The transfer
59101** begins at "offset".
59102**
59103** The caller must ensure that pCur is pointing to a valid row
59104** in the table.
59105**
59106** Return SQLITE_OK on success or an error code if anything goes
59107** wrong.  An error is returned if "offset+amt" is larger than
59108** the available payload.
59109*/
59110SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
59111  assert( cursorHoldsMutex(pCur) );
59112  assert( pCur->eState==CURSOR_VALID );
59113  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
59114  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59115  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
59116}
59117
59118/*
59119** Read part of the data associated with cursor pCur.  Exactly
59120** "amt" bytes will be transfered into pBuf[].  The transfer
59121** begins at "offset".
59122**
59123** Return SQLITE_OK on success or an error code if anything goes
59124** wrong.  An error is returned if "offset+amt" is larger than
59125** the available payload.
59126*/
59127SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
59128  int rc;
59129
59130#ifndef SQLITE_OMIT_INCRBLOB
59131  if ( pCur->eState==CURSOR_INVALID ){
59132    return SQLITE_ABORT;
59133  }
59134#endif
59135
59136  assert( cursorHoldsMutex(pCur) );
59137  rc = restoreCursorPosition(pCur);
59138  if( rc==SQLITE_OK ){
59139    assert( pCur->eState==CURSOR_VALID );
59140    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
59141    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59142    rc = accessPayload(pCur, offset, amt, pBuf, 0);
59143  }
59144  return rc;
59145}
59146
59147/*
59148** Return a pointer to payload information from the entry that the
59149** pCur cursor is pointing to.  The pointer is to the beginning of
59150** the key if index btrees (pPage->intKey==0) and is the data for
59151** table btrees (pPage->intKey==1). The number of bytes of available
59152** key/data is written into *pAmt.  If *pAmt==0, then the value
59153** returned will not be a valid pointer.
59154**
59155** This routine is an optimization.  It is common for the entire key
59156** and data to fit on the local page and for there to be no overflow
59157** pages.  When that is so, this routine can be used to access the
59158** key and data without making a copy.  If the key and/or data spills
59159** onto overflow pages, then accessPayload() must be used to reassemble
59160** the key/data and copy it into a preallocated buffer.
59161**
59162** The pointer returned by this routine looks directly into the cached
59163** page of the database.  The data might change or move the next time
59164** any btree routine is called.
59165*/
59166static const void *fetchPayload(
59167  BtCursor *pCur,      /* Cursor pointing to entry to read from */
59168  u32 *pAmt            /* Write the number of available bytes here */
59169){
59170  u32 amt;
59171  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
59172  assert( pCur->eState==CURSOR_VALID );
59173  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59174  assert( cursorHoldsMutex(pCur) );
59175  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59176  assert( pCur->info.nSize>0 );
59177  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
59178  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
59179  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
59180  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
59181  *pAmt = amt;
59182  return (void*)pCur->info.pPayload;
59183}
59184
59185
59186/*
59187** For the entry that cursor pCur is point to, return as
59188** many bytes of the key or data as are available on the local
59189** b-tree page.  Write the number of available bytes into *pAmt.
59190**
59191** The pointer returned is ephemeral.  The key/data may move
59192** or be destroyed on the next call to any Btree routine,
59193** including calls from other threads against the same cache.
59194** Hence, a mutex on the BtShared should be held prior to calling
59195** this routine.
59196**
59197** These routines is used to get quick access to key and data
59198** in the common case where no overflow pages are used.
59199*/
59200SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
59201  return fetchPayload(pCur, pAmt);
59202}
59203SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
59204  return fetchPayload(pCur, pAmt);
59205}
59206
59207
59208/*
59209** Move the cursor down to a new child page.  The newPgno argument is the
59210** page number of the child page to move to.
59211**
59212** This function returns SQLITE_CORRUPT if the page-header flags field of
59213** the new child page does not match the flags field of the parent (i.e.
59214** if an intkey page appears to be the parent of a non-intkey page, or
59215** vice-versa).
59216*/
59217static int moveToChild(BtCursor *pCur, u32 newPgno){
59218  BtShared *pBt = pCur->pBt;
59219
59220  assert( cursorHoldsMutex(pCur) );
59221  assert( pCur->eState==CURSOR_VALID );
59222  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
59223  assert( pCur->iPage>=0 );
59224  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
59225    return SQLITE_CORRUPT_BKPT;
59226  }
59227  pCur->info.nSize = 0;
59228  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59229  pCur->iPage++;
59230  pCur->aiIdx[pCur->iPage] = 0;
59231  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
59232                        pCur, pCur->curPagerFlags);
59233}
59234
59235#if SQLITE_DEBUG
59236/*
59237** Page pParent is an internal (non-leaf) tree page. This function
59238** asserts that page number iChild is the left-child if the iIdx'th
59239** cell in page pParent. Or, if iIdx is equal to the total number of
59240** cells in pParent, that page number iChild is the right-child of
59241** the page.
59242*/
59243static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
59244  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
59245                            ** in a corrupt database */
59246  assert( iIdx<=pParent->nCell );
59247  if( iIdx==pParent->nCell ){
59248    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
59249  }else{
59250    assert( get4byte(findCell(pParent, iIdx))==iChild );
59251  }
59252}
59253#else
59254#  define assertParentIndex(x,y,z)
59255#endif
59256
59257/*
59258** Move the cursor up to the parent page.
59259**
59260** pCur->idx is set to the cell index that contains the pointer
59261** to the page we are coming from.  If we are coming from the
59262** right-most child page then pCur->idx is set to one more than
59263** the largest cell index.
59264*/
59265static void moveToParent(BtCursor *pCur){
59266  assert( cursorHoldsMutex(pCur) );
59267  assert( pCur->eState==CURSOR_VALID );
59268  assert( pCur->iPage>0 );
59269  assert( pCur->apPage[pCur->iPage] );
59270  assertParentIndex(
59271    pCur->apPage[pCur->iPage-1],
59272    pCur->aiIdx[pCur->iPage-1],
59273    pCur->apPage[pCur->iPage]->pgno
59274  );
59275  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
59276  pCur->info.nSize = 0;
59277  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59278  releasePageNotNull(pCur->apPage[pCur->iPage--]);
59279}
59280
59281/*
59282** Move the cursor to point to the root page of its b-tree structure.
59283**
59284** If the table has a virtual root page, then the cursor is moved to point
59285** to the virtual root page instead of the actual root page. A table has a
59286** virtual root page when the actual root page contains no cells and a
59287** single child page. This can only happen with the table rooted at page 1.
59288**
59289** If the b-tree structure is empty, the cursor state is set to
59290** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
59291** cell located on the root (or virtual root) page and the cursor state
59292** is set to CURSOR_VALID.
59293**
59294** If this function returns successfully, it may be assumed that the
59295** page-header flags indicate that the [virtual] root-page is the expected
59296** kind of b-tree page (i.e. if when opening the cursor the caller did not
59297** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
59298** indicating a table b-tree, or if the caller did specify a KeyInfo
59299** structure the flags byte is set to 0x02 or 0x0A, indicating an index
59300** b-tree).
59301*/
59302static int moveToRoot(BtCursor *pCur){
59303  MemPage *pRoot;
59304  int rc = SQLITE_OK;
59305
59306  assert( cursorHoldsMutex(pCur) );
59307  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
59308  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
59309  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
59310  if( pCur->eState>=CURSOR_REQUIRESEEK ){
59311    if( pCur->eState==CURSOR_FAULT ){
59312      assert( pCur->skipNext!=SQLITE_OK );
59313      return pCur->skipNext;
59314    }
59315    sqlite3BtreeClearCursor(pCur);
59316  }
59317
59318  if( pCur->iPage>=0 ){
59319    while( pCur->iPage ){
59320      assert( pCur->apPage[pCur->iPage]!=0 );
59321      releasePageNotNull(pCur->apPage[pCur->iPage--]);
59322    }
59323  }else if( pCur->pgnoRoot==0 ){
59324    pCur->eState = CURSOR_INVALID;
59325    return SQLITE_OK;
59326  }else{
59327    assert( pCur->iPage==(-1) );
59328    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
59329                        0, pCur->curPagerFlags);
59330    if( rc!=SQLITE_OK ){
59331      pCur->eState = CURSOR_INVALID;
59332      return rc;
59333    }
59334    pCur->iPage = 0;
59335    pCur->curIntKey = pCur->apPage[0]->intKey;
59336  }
59337  pRoot = pCur->apPage[0];
59338  assert( pRoot->pgno==pCur->pgnoRoot );
59339
59340  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
59341  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
59342  ** NULL, the caller expects a table b-tree. If this is not the case,
59343  ** return an SQLITE_CORRUPT error.
59344  **
59345  ** Earlier versions of SQLite assumed that this test could not fail
59346  ** if the root page was already loaded when this function was called (i.e.
59347  ** if pCur->iPage>=0). But this is not so if the database is corrupted
59348  ** in such a way that page pRoot is linked into a second b-tree table
59349  ** (or the freelist).  */
59350  assert( pRoot->intKey==1 || pRoot->intKey==0 );
59351  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
59352    return SQLITE_CORRUPT_BKPT;
59353  }
59354
59355  pCur->aiIdx[0] = 0;
59356  pCur->info.nSize = 0;
59357  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
59358
59359  if( pRoot->nCell>0 ){
59360    pCur->eState = CURSOR_VALID;
59361  }else if( !pRoot->leaf ){
59362    Pgno subpage;
59363    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
59364    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
59365    pCur->eState = CURSOR_VALID;
59366    rc = moveToChild(pCur, subpage);
59367  }else{
59368    pCur->eState = CURSOR_INVALID;
59369  }
59370  return rc;
59371}
59372
59373/*
59374** Move the cursor down to the left-most leaf entry beneath the
59375** entry to which it is currently pointing.
59376**
59377** The left-most leaf is the one with the smallest key - the first
59378** in ascending order.
59379*/
59380static int moveToLeftmost(BtCursor *pCur){
59381  Pgno pgno;
59382  int rc = SQLITE_OK;
59383  MemPage *pPage;
59384
59385  assert( cursorHoldsMutex(pCur) );
59386  assert( pCur->eState==CURSOR_VALID );
59387  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
59388    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
59389    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
59390    rc = moveToChild(pCur, pgno);
59391  }
59392  return rc;
59393}
59394
59395/*
59396** Move the cursor down to the right-most leaf entry beneath the
59397** page to which it is currently pointing.  Notice the difference
59398** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
59399** finds the left-most entry beneath the *entry* whereas moveToRightmost()
59400** finds the right-most entry beneath the *page*.
59401**
59402** The right-most entry is the one with the largest key - the last
59403** key in ascending order.
59404*/
59405static int moveToRightmost(BtCursor *pCur){
59406  Pgno pgno;
59407  int rc = SQLITE_OK;
59408  MemPage *pPage = 0;
59409
59410  assert( cursorHoldsMutex(pCur) );
59411  assert( pCur->eState==CURSOR_VALID );
59412  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
59413    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59414    pCur->aiIdx[pCur->iPage] = pPage->nCell;
59415    rc = moveToChild(pCur, pgno);
59416    if( rc ) return rc;
59417  }
59418  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
59419  assert( pCur->info.nSize==0 );
59420  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
59421  return SQLITE_OK;
59422}
59423
59424/* Move the cursor to the first entry in the table.  Return SQLITE_OK
59425** on success.  Set *pRes to 0 if the cursor actually points to something
59426** or set *pRes to 1 if the table is empty.
59427*/
59428SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
59429  int rc;
59430
59431  assert( cursorHoldsMutex(pCur) );
59432  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59433  rc = moveToRoot(pCur);
59434  if( rc==SQLITE_OK ){
59435    if( pCur->eState==CURSOR_INVALID ){
59436      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59437      *pRes = 1;
59438    }else{
59439      assert( pCur->apPage[pCur->iPage]->nCell>0 );
59440      *pRes = 0;
59441      rc = moveToLeftmost(pCur);
59442    }
59443  }
59444  return rc;
59445}
59446
59447/* Move the cursor to the last entry in the table.  Return SQLITE_OK
59448** on success.  Set *pRes to 0 if the cursor actually points to something
59449** or set *pRes to 1 if the table is empty.
59450*/
59451SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
59452  int rc;
59453
59454  assert( cursorHoldsMutex(pCur) );
59455  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59456
59457  /* If the cursor already points to the last entry, this is a no-op. */
59458  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
59459#ifdef SQLITE_DEBUG
59460    /* This block serves to assert() that the cursor really does point
59461    ** to the last entry in the b-tree. */
59462    int ii;
59463    for(ii=0; ii<pCur->iPage; ii++){
59464      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
59465    }
59466    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
59467    assert( pCur->apPage[pCur->iPage]->leaf );
59468#endif
59469    return SQLITE_OK;
59470  }
59471
59472  rc = moveToRoot(pCur);
59473  if( rc==SQLITE_OK ){
59474    if( CURSOR_INVALID==pCur->eState ){
59475      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59476      *pRes = 1;
59477    }else{
59478      assert( pCur->eState==CURSOR_VALID );
59479      *pRes = 0;
59480      rc = moveToRightmost(pCur);
59481      if( rc==SQLITE_OK ){
59482        pCur->curFlags |= BTCF_AtLast;
59483      }else{
59484        pCur->curFlags &= ~BTCF_AtLast;
59485      }
59486
59487    }
59488  }
59489  return rc;
59490}
59491
59492/* Move the cursor so that it points to an entry near the key
59493** specified by pIdxKey or intKey.   Return a success code.
59494**
59495** For INTKEY tables, the intKey parameter is used.  pIdxKey
59496** must be NULL.  For index tables, pIdxKey is used and intKey
59497** is ignored.
59498**
59499** If an exact match is not found, then the cursor is always
59500** left pointing at a leaf page which would hold the entry if it
59501** were present.  The cursor might point to an entry that comes
59502** before or after the key.
59503**
59504** An integer is written into *pRes which is the result of
59505** comparing the key with the entry to which the cursor is
59506** pointing.  The meaning of the integer written into
59507** *pRes is as follows:
59508**
59509**     *pRes<0      The cursor is left pointing at an entry that
59510**                  is smaller than intKey/pIdxKey or if the table is empty
59511**                  and the cursor is therefore left point to nothing.
59512**
59513**     *pRes==0     The cursor is left pointing at an entry that
59514**                  exactly matches intKey/pIdxKey.
59515**
59516**     *pRes>0      The cursor is left pointing at an entry that
59517**                  is larger than intKey/pIdxKey.
59518**
59519*/
59520SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
59521  BtCursor *pCur,          /* The cursor to be moved */
59522  UnpackedRecord *pIdxKey, /* Unpacked index key */
59523  i64 intKey,              /* The table key */
59524  int biasRight,           /* If true, bias the search to the high end */
59525  int *pRes                /* Write search results here */
59526){
59527  int rc;
59528  RecordCompare xRecordCompare;
59529
59530  assert( cursorHoldsMutex(pCur) );
59531  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59532  assert( pRes );
59533  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
59534
59535  /* If the cursor is already positioned at the point we are trying
59536  ** to move to, then just return without doing any work */
59537  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
59538   && pCur->curIntKey
59539  ){
59540    if( pCur->info.nKey==intKey ){
59541      *pRes = 0;
59542      return SQLITE_OK;
59543    }
59544    if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
59545      *pRes = -1;
59546      return SQLITE_OK;
59547    }
59548  }
59549
59550  if( pIdxKey ){
59551    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
59552    pIdxKey->errCode = 0;
59553    assert( pIdxKey->default_rc==1
59554         || pIdxKey->default_rc==0
59555         || pIdxKey->default_rc==-1
59556    );
59557  }else{
59558    xRecordCompare = 0; /* All keys are integers */
59559  }
59560
59561  rc = moveToRoot(pCur);
59562  if( rc ){
59563    return rc;
59564  }
59565  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
59566  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
59567  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
59568  if( pCur->eState==CURSOR_INVALID ){
59569    *pRes = -1;
59570    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59571    return SQLITE_OK;
59572  }
59573  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
59574  assert( pCur->curIntKey || pIdxKey );
59575  for(;;){
59576    int lwr, upr, idx, c;
59577    Pgno chldPg;
59578    MemPage *pPage = pCur->apPage[pCur->iPage];
59579    u8 *pCell;                          /* Pointer to current cell in pPage */
59580
59581    /* pPage->nCell must be greater than zero. If this is the root-page
59582    ** the cursor would have been INVALID above and this for(;;) loop
59583    ** not run. If this is not the root-page, then the moveToChild() routine
59584    ** would have already detected db corruption. Similarly, pPage must
59585    ** be the right kind (index or table) of b-tree page. Otherwise
59586    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
59587    assert( pPage->nCell>0 );
59588    assert( pPage->intKey==(pIdxKey==0) );
59589    lwr = 0;
59590    upr = pPage->nCell-1;
59591    assert( biasRight==0 || biasRight==1 );
59592    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
59593    pCur->aiIdx[pCur->iPage] = (u16)idx;
59594    if( xRecordCompare==0 ){
59595      for(;;){
59596        i64 nCellKey;
59597        pCell = findCellPastPtr(pPage, idx);
59598        if( pPage->intKeyLeaf ){
59599          while( 0x80 <= *(pCell++) ){
59600            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
59601          }
59602        }
59603        getVarint(pCell, (u64*)&nCellKey);
59604        if( nCellKey<intKey ){
59605          lwr = idx+1;
59606          if( lwr>upr ){ c = -1; break; }
59607        }else if( nCellKey>intKey ){
59608          upr = idx-1;
59609          if( lwr>upr ){ c = +1; break; }
59610        }else{
59611          assert( nCellKey==intKey );
59612          pCur->curFlags |= BTCF_ValidNKey;
59613          pCur->info.nKey = nCellKey;
59614          pCur->aiIdx[pCur->iPage] = (u16)idx;
59615          if( !pPage->leaf ){
59616            lwr = idx;
59617            goto moveto_next_layer;
59618          }else{
59619            *pRes = 0;
59620            rc = SQLITE_OK;
59621            goto moveto_finish;
59622          }
59623        }
59624        assert( lwr+upr>=0 );
59625        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
59626      }
59627    }else{
59628      for(;;){
59629        int nCell;  /* Size of the pCell cell in bytes */
59630        pCell = findCellPastPtr(pPage, idx);
59631
59632        /* The maximum supported page-size is 65536 bytes. This means that
59633        ** the maximum number of record bytes stored on an index B-Tree
59634        ** page is less than 16384 bytes and may be stored as a 2-byte
59635        ** varint. This information is used to attempt to avoid parsing
59636        ** the entire cell by checking for the cases where the record is
59637        ** stored entirely within the b-tree page by inspecting the first
59638        ** 2 bytes of the cell.
59639        */
59640        nCell = pCell[0];
59641        if( nCell<=pPage->max1bytePayload ){
59642          /* This branch runs if the record-size field of the cell is a
59643          ** single byte varint and the record fits entirely on the main
59644          ** b-tree page.  */
59645          testcase( pCell+nCell+1==pPage->aDataEnd );
59646          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
59647        }else if( !(pCell[1] & 0x80)
59648          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
59649        ){
59650          /* The record-size field is a 2 byte varint and the record
59651          ** fits entirely on the main b-tree page.  */
59652          testcase( pCell+nCell+2==pPage->aDataEnd );
59653          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
59654        }else{
59655          /* The record flows over onto one or more overflow pages. In
59656          ** this case the whole cell needs to be parsed, a buffer allocated
59657          ** and accessPayload() used to retrieve the record into the
59658          ** buffer before VdbeRecordCompare() can be called.
59659          **
59660          ** If the record is corrupt, the xRecordCompare routine may read
59661          ** up to two varints past the end of the buffer. An extra 18
59662          ** bytes of padding is allocated at the end of the buffer in
59663          ** case this happens.  */
59664          void *pCellKey;
59665          u8 * const pCellBody = pCell - pPage->childPtrSize;
59666          pPage->xParseCell(pPage, pCellBody, &pCur->info);
59667          nCell = (int)pCur->info.nKey;
59668          testcase( nCell<0 );   /* True if key size is 2^32 or more */
59669          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
59670          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
59671          testcase( nCell==2 );  /* Minimum legal index key size */
59672          if( nCell<2 ){
59673            rc = SQLITE_CORRUPT_BKPT;
59674            goto moveto_finish;
59675          }
59676          pCellKey = sqlite3Malloc( nCell+18 );
59677          if( pCellKey==0 ){
59678            rc = SQLITE_NOMEM;
59679            goto moveto_finish;
59680          }
59681          pCur->aiIdx[pCur->iPage] = (u16)idx;
59682          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
59683          if( rc ){
59684            sqlite3_free(pCellKey);
59685            goto moveto_finish;
59686          }
59687          c = xRecordCompare(nCell, pCellKey, pIdxKey);
59688          sqlite3_free(pCellKey);
59689        }
59690        assert(
59691            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
59692         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
59693        );
59694        if( c<0 ){
59695          lwr = idx+1;
59696        }else if( c>0 ){
59697          upr = idx-1;
59698        }else{
59699          assert( c==0 );
59700          *pRes = 0;
59701          rc = SQLITE_OK;
59702          pCur->aiIdx[pCur->iPage] = (u16)idx;
59703          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
59704          goto moveto_finish;
59705        }
59706        if( lwr>upr ) break;
59707        assert( lwr+upr>=0 );
59708        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
59709      }
59710    }
59711    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
59712    assert( pPage->isInit );
59713    if( pPage->leaf ){
59714      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59715      pCur->aiIdx[pCur->iPage] = (u16)idx;
59716      *pRes = c;
59717      rc = SQLITE_OK;
59718      goto moveto_finish;
59719    }
59720moveto_next_layer:
59721    if( lwr>=pPage->nCell ){
59722      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59723    }else{
59724      chldPg = get4byte(findCell(pPage, lwr));
59725    }
59726    pCur->aiIdx[pCur->iPage] = (u16)lwr;
59727    rc = moveToChild(pCur, chldPg);
59728    if( rc ) break;
59729  }
59730moveto_finish:
59731  pCur->info.nSize = 0;
59732  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59733  return rc;
59734}
59735
59736
59737/*
59738** Return TRUE if the cursor is not pointing at an entry of the table.
59739**
59740** TRUE will be returned after a call to sqlite3BtreeNext() moves
59741** past the last entry in the table or sqlite3BtreePrev() moves past
59742** the first entry.  TRUE is also returned if the table is empty.
59743*/
59744SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
59745  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
59746  ** have been deleted? This API will need to change to return an error code
59747  ** as well as the boolean result value.
59748  */
59749  return (CURSOR_VALID!=pCur->eState);
59750}
59751
59752/*
59753** Advance the cursor to the next entry in the database.  If
59754** successful then set *pRes=0.  If the cursor
59755** was already pointing to the last entry in the database before
59756** this routine was called, then set *pRes=1.
59757**
59758** The main entry point is sqlite3BtreeNext().  That routine is optimized
59759** for the common case of merely incrementing the cell counter BtCursor.aiIdx
59760** to the next cell on the current page.  The (slower) btreeNext() helper
59761** routine is called when it is necessary to move to a different page or
59762** to restore the cursor.
59763**
59764** The calling function will set *pRes to 0 or 1.  The initial *pRes value
59765** will be 1 if the cursor being stepped corresponds to an SQL index and
59766** if this routine could have been skipped if that SQL index had been
59767** a unique index.  Otherwise the caller will have set *pRes to zero.
59768** Zero is the common case. The btree implementation is free to use the
59769** initial *pRes value as a hint to improve performance, but the current
59770** SQLite btree implementation does not. (Note that the comdb2 btree
59771** implementation does use this hint, however.)
59772*/
59773static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
59774  int rc;
59775  int idx;
59776  MemPage *pPage;
59777
59778  assert( cursorHoldsMutex(pCur) );
59779  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59780  assert( *pRes==0 );
59781  if( pCur->eState!=CURSOR_VALID ){
59782    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
59783    rc = restoreCursorPosition(pCur);
59784    if( rc!=SQLITE_OK ){
59785      return rc;
59786    }
59787    if( CURSOR_INVALID==pCur->eState ){
59788      *pRes = 1;
59789      return SQLITE_OK;
59790    }
59791    if( pCur->skipNext ){
59792      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
59793      pCur->eState = CURSOR_VALID;
59794      if( pCur->skipNext>0 ){
59795        pCur->skipNext = 0;
59796        return SQLITE_OK;
59797      }
59798      pCur->skipNext = 0;
59799    }
59800  }
59801
59802  pPage = pCur->apPage[pCur->iPage];
59803  idx = ++pCur->aiIdx[pCur->iPage];
59804  assert( pPage->isInit );
59805
59806  /* If the database file is corrupt, it is possible for the value of idx
59807  ** to be invalid here. This can only occur if a second cursor modifies
59808  ** the page while cursor pCur is holding a reference to it. Which can
59809  ** only happen if the database is corrupt in such a way as to link the
59810  ** page into more than one b-tree structure. */
59811  testcase( idx>pPage->nCell );
59812
59813  if( idx>=pPage->nCell ){
59814    if( !pPage->leaf ){
59815      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
59816      if( rc ) return rc;
59817      return moveToLeftmost(pCur);
59818    }
59819    do{
59820      if( pCur->iPage==0 ){
59821        *pRes = 1;
59822        pCur->eState = CURSOR_INVALID;
59823        return SQLITE_OK;
59824      }
59825      moveToParent(pCur);
59826      pPage = pCur->apPage[pCur->iPage];
59827    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
59828    if( pPage->intKey ){
59829      return sqlite3BtreeNext(pCur, pRes);
59830    }else{
59831      return SQLITE_OK;
59832    }
59833  }
59834  if( pPage->leaf ){
59835    return SQLITE_OK;
59836  }else{
59837    return moveToLeftmost(pCur);
59838  }
59839}
59840SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
59841  MemPage *pPage;
59842  assert( cursorHoldsMutex(pCur) );
59843  assert( pRes!=0 );
59844  assert( *pRes==0 || *pRes==1 );
59845  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59846  pCur->info.nSize = 0;
59847  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59848  *pRes = 0;
59849  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
59850  pPage = pCur->apPage[pCur->iPage];
59851  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
59852    pCur->aiIdx[pCur->iPage]--;
59853    return btreeNext(pCur, pRes);
59854  }
59855  if( pPage->leaf ){
59856    return SQLITE_OK;
59857  }else{
59858    return moveToLeftmost(pCur);
59859  }
59860}
59861
59862/*
59863** Step the cursor to the back to the previous entry in the database.  If
59864** successful then set *pRes=0.  If the cursor
59865** was already pointing to the first entry in the database before
59866** this routine was called, then set *pRes=1.
59867**
59868** The main entry point is sqlite3BtreePrevious().  That routine is optimized
59869** for the common case of merely decrementing the cell counter BtCursor.aiIdx
59870** to the previous cell on the current page.  The (slower) btreePrevious()
59871** helper routine is called when it is necessary to move to a different page
59872** or to restore the cursor.
59873**
59874** The calling function will set *pRes to 0 or 1.  The initial *pRes value
59875** will be 1 if the cursor being stepped corresponds to an SQL index and
59876** if this routine could have been skipped if that SQL index had been
59877** a unique index.  Otherwise the caller will have set *pRes to zero.
59878** Zero is the common case. The btree implementation is free to use the
59879** initial *pRes value as a hint to improve performance, but the current
59880** SQLite btree implementation does not. (Note that the comdb2 btree
59881** implementation does use this hint, however.)
59882*/
59883static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
59884  int rc;
59885  MemPage *pPage;
59886
59887  assert( cursorHoldsMutex(pCur) );
59888  assert( pRes!=0 );
59889  assert( *pRes==0 );
59890  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59891  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
59892  assert( pCur->info.nSize==0 );
59893  if( pCur->eState!=CURSOR_VALID ){
59894    rc = restoreCursorPosition(pCur);
59895    if( rc!=SQLITE_OK ){
59896      return rc;
59897    }
59898    if( CURSOR_INVALID==pCur->eState ){
59899      *pRes = 1;
59900      return SQLITE_OK;
59901    }
59902    if( pCur->skipNext ){
59903      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
59904      pCur->eState = CURSOR_VALID;
59905      if( pCur->skipNext<0 ){
59906        pCur->skipNext = 0;
59907        return SQLITE_OK;
59908      }
59909      pCur->skipNext = 0;
59910    }
59911  }
59912
59913  pPage = pCur->apPage[pCur->iPage];
59914  assert( pPage->isInit );
59915  if( !pPage->leaf ){
59916    int idx = pCur->aiIdx[pCur->iPage];
59917    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
59918    if( rc ) return rc;
59919    rc = moveToRightmost(pCur);
59920  }else{
59921    while( pCur->aiIdx[pCur->iPage]==0 ){
59922      if( pCur->iPage==0 ){
59923        pCur->eState = CURSOR_INVALID;
59924        *pRes = 1;
59925        return SQLITE_OK;
59926      }
59927      moveToParent(pCur);
59928    }
59929    assert( pCur->info.nSize==0 );
59930    assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
59931
59932    pCur->aiIdx[pCur->iPage]--;
59933    pPage = pCur->apPage[pCur->iPage];
59934    if( pPage->intKey && !pPage->leaf ){
59935      rc = sqlite3BtreePrevious(pCur, pRes);
59936    }else{
59937      rc = SQLITE_OK;
59938    }
59939  }
59940  return rc;
59941}
59942SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
59943  assert( cursorHoldsMutex(pCur) );
59944  assert( pRes!=0 );
59945  assert( *pRes==0 || *pRes==1 );
59946  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59947  *pRes = 0;
59948  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
59949  pCur->info.nSize = 0;
59950  if( pCur->eState!=CURSOR_VALID
59951   || pCur->aiIdx[pCur->iPage]==0
59952   || pCur->apPage[pCur->iPage]->leaf==0
59953  ){
59954    return btreePrevious(pCur, pRes);
59955  }
59956  pCur->aiIdx[pCur->iPage]--;
59957  return SQLITE_OK;
59958}
59959
59960/*
59961** Allocate a new page from the database file.
59962**
59963** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
59964** has already been called on the new page.)  The new page has also
59965** been referenced and the calling routine is responsible for calling
59966** sqlite3PagerUnref() on the new page when it is done.
59967**
59968** SQLITE_OK is returned on success.  Any other return value indicates
59969** an error.  *ppPage is set to NULL in the event of an error.
59970**
59971** If the "nearby" parameter is not 0, then an effort is made to
59972** locate a page close to the page number "nearby".  This can be used in an
59973** attempt to keep related pages close to each other in the database file,
59974** which in turn can make database access faster.
59975**
59976** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
59977** anywhere on the free-list, then it is guaranteed to be returned.  If
59978** eMode is BTALLOC_LT then the page returned will be less than or equal
59979** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
59980** are no restrictions on which page is returned.
59981*/
59982static int allocateBtreePage(
59983  BtShared *pBt,         /* The btree */
59984  MemPage **ppPage,      /* Store pointer to the allocated page here */
59985  Pgno *pPgno,           /* Store the page number here */
59986  Pgno nearby,           /* Search for a page near this one */
59987  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
59988){
59989  MemPage *pPage1;
59990  int rc;
59991  u32 n;     /* Number of pages on the freelist */
59992  u32 k;     /* Number of leaves on the trunk of the freelist */
59993  MemPage *pTrunk = 0;
59994  MemPage *pPrevTrunk = 0;
59995  Pgno mxPage;     /* Total size of the database file */
59996
59997  assert( sqlite3_mutex_held(pBt->mutex) );
59998  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
59999  pPage1 = pBt->pPage1;
60000  mxPage = btreePagecount(pBt);
60001  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
60002  ** stores stores the total number of pages on the freelist. */
60003  n = get4byte(&pPage1->aData[36]);
60004  testcase( n==mxPage-1 );
60005  if( n>=mxPage ){
60006    return SQLITE_CORRUPT_BKPT;
60007  }
60008  if( n>0 ){
60009    /* There are pages on the freelist.  Reuse one of those pages. */
60010    Pgno iTrunk;
60011    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
60012    u32 nSearch = 0;   /* Count of the number of search attempts */
60013
60014    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
60015    ** shows that the page 'nearby' is somewhere on the free-list, then
60016    ** the entire-list will be searched for that page.
60017    */
60018#ifndef SQLITE_OMIT_AUTOVACUUM
60019    if( eMode==BTALLOC_EXACT ){
60020      if( nearby<=mxPage ){
60021        u8 eType;
60022        assert( nearby>0 );
60023        assert( pBt->autoVacuum );
60024        rc = ptrmapGet(pBt, nearby, &eType, 0);
60025        if( rc ) return rc;
60026        if( eType==PTRMAP_FREEPAGE ){
60027          searchList = 1;
60028        }
60029      }
60030    }else if( eMode==BTALLOC_LE ){
60031      searchList = 1;
60032    }
60033#endif
60034
60035    /* Decrement the free-list count by 1. Set iTrunk to the index of the
60036    ** first free-list trunk page. iPrevTrunk is initially 1.
60037    */
60038    rc = sqlite3PagerWrite(pPage1->pDbPage);
60039    if( rc ) return rc;
60040    put4byte(&pPage1->aData[36], n-1);
60041
60042    /* The code within this loop is run only once if the 'searchList' variable
60043    ** is not true. Otherwise, it runs once for each trunk-page on the
60044    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
60045    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
60046    */
60047    do {
60048      pPrevTrunk = pTrunk;
60049      if( pPrevTrunk ){
60050        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
60051        ** is the page number of the next freelist trunk page in the list or
60052        ** zero if this is the last freelist trunk page. */
60053        iTrunk = get4byte(&pPrevTrunk->aData[0]);
60054      }else{
60055        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
60056        ** stores the page number of the first page of the freelist, or zero if
60057        ** the freelist is empty. */
60058        iTrunk = get4byte(&pPage1->aData[32]);
60059      }
60060      testcase( iTrunk==mxPage );
60061      if( iTrunk>mxPage || nSearch++ > n ){
60062        rc = SQLITE_CORRUPT_BKPT;
60063      }else{
60064        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
60065      }
60066      if( rc ){
60067        pTrunk = 0;
60068        goto end_allocate_page;
60069      }
60070      assert( pTrunk!=0 );
60071      assert( pTrunk->aData!=0 );
60072      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
60073      ** is the number of leaf page pointers to follow. */
60074      k = get4byte(&pTrunk->aData[4]);
60075      if( k==0 && !searchList ){
60076        /* The trunk has no leaves and the list is not being searched.
60077        ** So extract the trunk page itself and use it as the newly
60078        ** allocated page */
60079        assert( pPrevTrunk==0 );
60080        rc = sqlite3PagerWrite(pTrunk->pDbPage);
60081        if( rc ){
60082          goto end_allocate_page;
60083        }
60084        *pPgno = iTrunk;
60085        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
60086        *ppPage = pTrunk;
60087        pTrunk = 0;
60088        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
60089      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
60090        /* Value of k is out of range.  Database corruption */
60091        rc = SQLITE_CORRUPT_BKPT;
60092        goto end_allocate_page;
60093#ifndef SQLITE_OMIT_AUTOVACUUM
60094      }else if( searchList
60095            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
60096      ){
60097        /* The list is being searched and this trunk page is the page
60098        ** to allocate, regardless of whether it has leaves.
60099        */
60100        *pPgno = iTrunk;
60101        *ppPage = pTrunk;
60102        searchList = 0;
60103        rc = sqlite3PagerWrite(pTrunk->pDbPage);
60104        if( rc ){
60105          goto end_allocate_page;
60106        }
60107        if( k==0 ){
60108          if( !pPrevTrunk ){
60109            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
60110          }else{
60111            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
60112            if( rc!=SQLITE_OK ){
60113              goto end_allocate_page;
60114            }
60115            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
60116          }
60117        }else{
60118          /* The trunk page is required by the caller but it contains
60119          ** pointers to free-list leaves. The first leaf becomes a trunk
60120          ** page in this case.
60121          */
60122          MemPage *pNewTrunk;
60123          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
60124          if( iNewTrunk>mxPage ){
60125            rc = SQLITE_CORRUPT_BKPT;
60126            goto end_allocate_page;
60127          }
60128          testcase( iNewTrunk==mxPage );
60129          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
60130          if( rc!=SQLITE_OK ){
60131            goto end_allocate_page;
60132          }
60133          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
60134          if( rc!=SQLITE_OK ){
60135            releasePage(pNewTrunk);
60136            goto end_allocate_page;
60137          }
60138          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
60139          put4byte(&pNewTrunk->aData[4], k-1);
60140          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
60141          releasePage(pNewTrunk);
60142          if( !pPrevTrunk ){
60143            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
60144            put4byte(&pPage1->aData[32], iNewTrunk);
60145          }else{
60146            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
60147            if( rc ){
60148              goto end_allocate_page;
60149            }
60150            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
60151          }
60152        }
60153        pTrunk = 0;
60154        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
60155#endif
60156      }else if( k>0 ){
60157        /* Extract a leaf from the trunk */
60158        u32 closest;
60159        Pgno iPage;
60160        unsigned char *aData = pTrunk->aData;
60161        if( nearby>0 ){
60162          u32 i;
60163          closest = 0;
60164          if( eMode==BTALLOC_LE ){
60165            for(i=0; i<k; i++){
60166              iPage = get4byte(&aData[8+i*4]);
60167              if( iPage<=nearby ){
60168                closest = i;
60169                break;
60170              }
60171            }
60172          }else{
60173            int dist;
60174            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
60175            for(i=1; i<k; i++){
60176              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
60177              if( d2<dist ){
60178                closest = i;
60179                dist = d2;
60180              }
60181            }
60182          }
60183        }else{
60184          closest = 0;
60185        }
60186
60187        iPage = get4byte(&aData[8+closest*4]);
60188        testcase( iPage==mxPage );
60189        if( iPage>mxPage ){
60190          rc = SQLITE_CORRUPT_BKPT;
60191          goto end_allocate_page;
60192        }
60193        testcase( iPage==mxPage );
60194        if( !searchList
60195         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
60196        ){
60197          int noContent;
60198          *pPgno = iPage;
60199          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
60200                 ": %d more free pages\n",
60201                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
60202          rc = sqlite3PagerWrite(pTrunk->pDbPage);
60203          if( rc ) goto end_allocate_page;
60204          if( closest<k-1 ){
60205            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
60206          }
60207          put4byte(&aData[4], k-1);
60208          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
60209          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
60210          if( rc==SQLITE_OK ){
60211            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
60212            if( rc!=SQLITE_OK ){
60213              releasePage(*ppPage);
60214              *ppPage = 0;
60215            }
60216          }
60217          searchList = 0;
60218        }
60219      }
60220      releasePage(pPrevTrunk);
60221      pPrevTrunk = 0;
60222    }while( searchList );
60223  }else{
60224    /* There are no pages on the freelist, so append a new page to the
60225    ** database image.
60226    **
60227    ** Normally, new pages allocated by this block can be requested from the
60228    ** pager layer with the 'no-content' flag set. This prevents the pager
60229    ** from trying to read the pages content from disk. However, if the
60230    ** current transaction has already run one or more incremental-vacuum
60231    ** steps, then the page we are about to allocate may contain content
60232    ** that is required in the event of a rollback. In this case, do
60233    ** not set the no-content flag. This causes the pager to load and journal
60234    ** the current page content before overwriting it.
60235    **
60236    ** Note that the pager will not actually attempt to load or journal
60237    ** content for any page that really does lie past the end of the database
60238    ** file on disk. So the effects of disabling the no-content optimization
60239    ** here are confined to those pages that lie between the end of the
60240    ** database image and the end of the database file.
60241    */
60242    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
60243
60244    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60245    if( rc ) return rc;
60246    pBt->nPage++;
60247    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
60248
60249#ifndef SQLITE_OMIT_AUTOVACUUM
60250    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
60251      /* If *pPgno refers to a pointer-map page, allocate two new pages
60252      ** at the end of the file instead of one. The first allocated page
60253      ** becomes a new pointer-map page, the second is used by the caller.
60254      */
60255      MemPage *pPg = 0;
60256      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
60257      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
60258      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
60259      if( rc==SQLITE_OK ){
60260        rc = sqlite3PagerWrite(pPg->pDbPage);
60261        releasePage(pPg);
60262      }
60263      if( rc ) return rc;
60264      pBt->nPage++;
60265      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
60266    }
60267#endif
60268    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
60269    *pPgno = pBt->nPage;
60270
60271    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
60272    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
60273    if( rc ) return rc;
60274    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
60275    if( rc!=SQLITE_OK ){
60276      releasePage(*ppPage);
60277      *ppPage = 0;
60278    }
60279    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
60280  }
60281
60282  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
60283
60284end_allocate_page:
60285  releasePage(pTrunk);
60286  releasePage(pPrevTrunk);
60287  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
60288  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
60289  return rc;
60290}
60291
60292/*
60293** This function is used to add page iPage to the database file free-list.
60294** It is assumed that the page is not already a part of the free-list.
60295**
60296** The value passed as the second argument to this function is optional.
60297** If the caller happens to have a pointer to the MemPage object
60298** corresponding to page iPage handy, it may pass it as the second value.
60299** Otherwise, it may pass NULL.
60300**
60301** If a pointer to a MemPage object is passed as the second argument,
60302** its reference count is not altered by this function.
60303*/
60304static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
60305  MemPage *pTrunk = 0;                /* Free-list trunk page */
60306  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
60307  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
60308  MemPage *pPage;                     /* Page being freed. May be NULL. */
60309  int rc;                             /* Return Code */
60310  int nFree;                          /* Initial number of pages on free-list */
60311
60312  assert( sqlite3_mutex_held(pBt->mutex) );
60313  assert( CORRUPT_DB || iPage>1 );
60314  assert( !pMemPage || pMemPage->pgno==iPage );
60315
60316  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
60317  if( pMemPage ){
60318    pPage = pMemPage;
60319    sqlite3PagerRef(pPage->pDbPage);
60320  }else{
60321    pPage = btreePageLookup(pBt, iPage);
60322  }
60323
60324  /* Increment the free page count on pPage1 */
60325  rc = sqlite3PagerWrite(pPage1->pDbPage);
60326  if( rc ) goto freepage_out;
60327  nFree = get4byte(&pPage1->aData[36]);
60328  put4byte(&pPage1->aData[36], nFree+1);
60329
60330  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60331    /* If the secure_delete option is enabled, then
60332    ** always fully overwrite deleted information with zeros.
60333    */
60334    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
60335     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
60336    ){
60337      goto freepage_out;
60338    }
60339    memset(pPage->aData, 0, pPage->pBt->pageSize);
60340  }
60341
60342  /* If the database supports auto-vacuum, write an entry in the pointer-map
60343  ** to indicate that the page is free.
60344  */
60345  if( ISAUTOVACUUM ){
60346    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
60347    if( rc ) goto freepage_out;
60348  }
60349
60350  /* Now manipulate the actual database free-list structure. There are two
60351  ** possibilities. If the free-list is currently empty, or if the first
60352  ** trunk page in the free-list is full, then this page will become a
60353  ** new free-list trunk page. Otherwise, it will become a leaf of the
60354  ** first trunk page in the current free-list. This block tests if it
60355  ** is possible to add the page as a new free-list leaf.
60356  */
60357  if( nFree!=0 ){
60358    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
60359
60360    iTrunk = get4byte(&pPage1->aData[32]);
60361    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
60362    if( rc!=SQLITE_OK ){
60363      goto freepage_out;
60364    }
60365
60366    nLeaf = get4byte(&pTrunk->aData[4]);
60367    assert( pBt->usableSize>32 );
60368    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
60369      rc = SQLITE_CORRUPT_BKPT;
60370      goto freepage_out;
60371    }
60372    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
60373      /* In this case there is room on the trunk page to insert the page
60374      ** being freed as a new leaf.
60375      **
60376      ** Note that the trunk page is not really full until it contains
60377      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
60378      ** coded.  But due to a coding error in versions of SQLite prior to
60379      ** 3.6.0, databases with freelist trunk pages holding more than
60380      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
60381      ** to maintain backwards compatibility with older versions of SQLite,
60382      ** we will continue to restrict the number of entries to usableSize/4 - 8
60383      ** for now.  At some point in the future (once everyone has upgraded
60384      ** to 3.6.0 or later) we should consider fixing the conditional above
60385      ** to read "usableSize/4-2" instead of "usableSize/4-8".
60386      **
60387      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
60388      ** avoid using the last six entries in the freelist trunk page array in
60389      ** order that database files created by newer versions of SQLite can be
60390      ** read by older versions of SQLite.
60391      */
60392      rc = sqlite3PagerWrite(pTrunk->pDbPage);
60393      if( rc==SQLITE_OK ){
60394        put4byte(&pTrunk->aData[4], nLeaf+1);
60395        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
60396        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
60397          sqlite3PagerDontWrite(pPage->pDbPage);
60398        }
60399        rc = btreeSetHasContent(pBt, iPage);
60400      }
60401      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
60402      goto freepage_out;
60403    }
60404  }
60405
60406  /* If control flows to this point, then it was not possible to add the
60407  ** the page being freed as a leaf page of the first trunk in the free-list.
60408  ** Possibly because the free-list is empty, or possibly because the
60409  ** first trunk in the free-list is full. Either way, the page being freed
60410  ** will become the new first trunk page in the free-list.
60411  */
60412  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
60413    goto freepage_out;
60414  }
60415  rc = sqlite3PagerWrite(pPage->pDbPage);
60416  if( rc!=SQLITE_OK ){
60417    goto freepage_out;
60418  }
60419  put4byte(pPage->aData, iTrunk);
60420  put4byte(&pPage->aData[4], 0);
60421  put4byte(&pPage1->aData[32], iPage);
60422  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
60423
60424freepage_out:
60425  if( pPage ){
60426    pPage->isInit = 0;
60427  }
60428  releasePage(pPage);
60429  releasePage(pTrunk);
60430  return rc;
60431}
60432static void freePage(MemPage *pPage, int *pRC){
60433  if( (*pRC)==SQLITE_OK ){
60434    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
60435  }
60436}
60437
60438/*
60439** Free any overflow pages associated with the given Cell.  Write the
60440** local Cell size (the number of bytes on the original page, omitting
60441** overflow) into *pnSize.
60442*/
60443static int clearCell(
60444  MemPage *pPage,          /* The page that contains the Cell */
60445  unsigned char *pCell,    /* First byte of the Cell */
60446  u16 *pnSize              /* Write the size of the Cell here */
60447){
60448  BtShared *pBt = pPage->pBt;
60449  CellInfo info;
60450  Pgno ovflPgno;
60451  int rc;
60452  int nOvfl;
60453  u32 ovflPageSize;
60454
60455  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60456  pPage->xParseCell(pPage, pCell, &info);
60457  *pnSize = info.nSize;
60458  if( info.iOverflow==0 ){
60459    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
60460  }
60461  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
60462    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
60463  }
60464  ovflPgno = get4byte(&pCell[info.iOverflow]);
60465  assert( pBt->usableSize > 4 );
60466  ovflPageSize = pBt->usableSize - 4;
60467  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
60468  assert( nOvfl>0 ||
60469    (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
60470  );
60471  while( nOvfl-- ){
60472    Pgno iNext = 0;
60473    MemPage *pOvfl = 0;
60474    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
60475      /* 0 is not a legal page number and page 1 cannot be an
60476      ** overflow page. Therefore if ovflPgno<2 or past the end of the
60477      ** file the database must be corrupt. */
60478      return SQLITE_CORRUPT_BKPT;
60479    }
60480    if( nOvfl ){
60481      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
60482      if( rc ) return rc;
60483    }
60484
60485    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
60486     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
60487    ){
60488      /* There is no reason any cursor should have an outstanding reference
60489      ** to an overflow page belonging to a cell that is being deleted/updated.
60490      ** So if there exists more than one reference to this page, then it
60491      ** must not really be an overflow page and the database must be corrupt.
60492      ** It is helpful to detect this before calling freePage2(), as
60493      ** freePage2() may zero the page contents if secure-delete mode is
60494      ** enabled. If this 'overflow' page happens to be a page that the
60495      ** caller is iterating through or using in some other way, this
60496      ** can be problematic.
60497      */
60498      rc = SQLITE_CORRUPT_BKPT;
60499    }else{
60500      rc = freePage2(pBt, pOvfl, ovflPgno);
60501    }
60502
60503    if( pOvfl ){
60504      sqlite3PagerUnref(pOvfl->pDbPage);
60505    }
60506    if( rc ) return rc;
60507    ovflPgno = iNext;
60508  }
60509  return SQLITE_OK;
60510}
60511
60512/*
60513** Create the byte sequence used to represent a cell on page pPage
60514** and write that byte sequence into pCell[].  Overflow pages are
60515** allocated and filled in as necessary.  The calling procedure
60516** is responsible for making sure sufficient space has been allocated
60517** for pCell[].
60518**
60519** Note that pCell does not necessary need to point to the pPage->aData
60520** area.  pCell might point to some temporary storage.  The cell will
60521** be constructed in this temporary area then copied into pPage->aData
60522** later.
60523*/
60524static int fillInCell(
60525  MemPage *pPage,                /* The page that contains the cell */
60526  unsigned char *pCell,          /* Complete text of the cell */
60527  const void *pKey, i64 nKey,    /* The key */
60528  const void *pData,int nData,   /* The data */
60529  int nZero,                     /* Extra zero bytes to append to pData */
60530  int *pnSize                    /* Write cell size here */
60531){
60532  int nPayload;
60533  const u8 *pSrc;
60534  int nSrc, n, rc;
60535  int spaceLeft;
60536  MemPage *pOvfl = 0;
60537  MemPage *pToRelease = 0;
60538  unsigned char *pPrior;
60539  unsigned char *pPayload;
60540  BtShared *pBt = pPage->pBt;
60541  Pgno pgnoOvfl = 0;
60542  int nHeader;
60543
60544  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60545
60546  /* pPage is not necessarily writeable since pCell might be auxiliary
60547  ** buffer space that is separate from the pPage buffer area */
60548  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
60549            || sqlite3PagerIswriteable(pPage->pDbPage) );
60550
60551  /* Fill in the header. */
60552  nHeader = pPage->childPtrSize;
60553  nPayload = nData + nZero;
60554  if( pPage->intKeyLeaf ){
60555    nHeader += putVarint32(&pCell[nHeader], nPayload);
60556  }else{
60557    assert( nData==0 );
60558    assert( nZero==0 );
60559  }
60560  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
60561
60562  /* Fill in the payload size */
60563  if( pPage->intKey ){
60564    pSrc = pData;
60565    nSrc = nData;
60566    nData = 0;
60567  }else{
60568    assert( nKey<=0x7fffffff && pKey!=0 );
60569    nPayload = (int)nKey;
60570    pSrc = pKey;
60571    nSrc = (int)nKey;
60572  }
60573  if( nPayload<=pPage->maxLocal ){
60574    n = nHeader + nPayload;
60575    testcase( n==3 );
60576    testcase( n==4 );
60577    if( n<4 ) n = 4;
60578    *pnSize = n;
60579    spaceLeft = nPayload;
60580    pPrior = pCell;
60581  }else{
60582    int mn = pPage->minLocal;
60583    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
60584    testcase( n==pPage->maxLocal );
60585    testcase( n==pPage->maxLocal+1 );
60586    if( n > pPage->maxLocal ) n = mn;
60587    spaceLeft = n;
60588    *pnSize = n + nHeader + 4;
60589    pPrior = &pCell[nHeader+n];
60590  }
60591  pPayload = &pCell[nHeader];
60592
60593  /* At this point variables should be set as follows:
60594  **
60595  **   nPayload           Total payload size in bytes
60596  **   pPayload           Begin writing payload here
60597  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
60598  **                      that means content must spill into overflow pages.
60599  **   *pnSize            Size of the local cell (not counting overflow pages)
60600  **   pPrior             Where to write the pgno of the first overflow page
60601  **
60602  ** Use a call to btreeParseCellPtr() to verify that the values above
60603  ** were computed correctly.
60604  */
60605#if SQLITE_DEBUG
60606  {
60607    CellInfo info;
60608    pPage->xParseCell(pPage, pCell, &info);
60609    assert( nHeader=(int)(info.pPayload - pCell) );
60610    assert( info.nKey==nKey );
60611    assert( *pnSize == info.nSize );
60612    assert( spaceLeft == info.nLocal );
60613    assert( pPrior == &pCell[info.iOverflow] );
60614  }
60615#endif
60616
60617  /* Write the payload into the local Cell and any extra into overflow pages */
60618  while( nPayload>0 ){
60619    if( spaceLeft==0 ){
60620#ifndef SQLITE_OMIT_AUTOVACUUM
60621      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
60622      if( pBt->autoVacuum ){
60623        do{
60624          pgnoOvfl++;
60625        } while(
60626          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
60627        );
60628      }
60629#endif
60630      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
60631#ifndef SQLITE_OMIT_AUTOVACUUM
60632      /* If the database supports auto-vacuum, and the second or subsequent
60633      ** overflow page is being allocated, add an entry to the pointer-map
60634      ** for that page now.
60635      **
60636      ** If this is the first overflow page, then write a partial entry
60637      ** to the pointer-map. If we write nothing to this pointer-map slot,
60638      ** then the optimistic overflow chain processing in clearCell()
60639      ** may misinterpret the uninitialized values and delete the
60640      ** wrong pages from the database.
60641      */
60642      if( pBt->autoVacuum && rc==SQLITE_OK ){
60643        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
60644        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
60645        if( rc ){
60646          releasePage(pOvfl);
60647        }
60648      }
60649#endif
60650      if( rc ){
60651        releasePage(pToRelease);
60652        return rc;
60653      }
60654
60655      /* If pToRelease is not zero than pPrior points into the data area
60656      ** of pToRelease.  Make sure pToRelease is still writeable. */
60657      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
60658
60659      /* If pPrior is part of the data area of pPage, then make sure pPage
60660      ** is still writeable */
60661      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
60662            || sqlite3PagerIswriteable(pPage->pDbPage) );
60663
60664      put4byte(pPrior, pgnoOvfl);
60665      releasePage(pToRelease);
60666      pToRelease = pOvfl;
60667      pPrior = pOvfl->aData;
60668      put4byte(pPrior, 0);
60669      pPayload = &pOvfl->aData[4];
60670      spaceLeft = pBt->usableSize - 4;
60671    }
60672    n = nPayload;
60673    if( n>spaceLeft ) n = spaceLeft;
60674
60675    /* If pToRelease is not zero than pPayload points into the data area
60676    ** of pToRelease.  Make sure pToRelease is still writeable. */
60677    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
60678
60679    /* If pPayload is part of the data area of pPage, then make sure pPage
60680    ** is still writeable */
60681    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
60682            || sqlite3PagerIswriteable(pPage->pDbPage) );
60683
60684    if( nSrc>0 ){
60685      if( n>nSrc ) n = nSrc;
60686      assert( pSrc );
60687      memcpy(pPayload, pSrc, n);
60688    }else{
60689      memset(pPayload, 0, n);
60690    }
60691    nPayload -= n;
60692    pPayload += n;
60693    pSrc += n;
60694    nSrc -= n;
60695    spaceLeft -= n;
60696    if( nSrc==0 ){
60697      nSrc = nData;
60698      pSrc = pData;
60699    }
60700  }
60701  releasePage(pToRelease);
60702  return SQLITE_OK;
60703}
60704
60705/*
60706** Remove the i-th cell from pPage.  This routine effects pPage only.
60707** The cell content is not freed or deallocated.  It is assumed that
60708** the cell content has been copied someplace else.  This routine just
60709** removes the reference to the cell from pPage.
60710**
60711** "sz" must be the number of bytes in the cell.
60712*/
60713static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
60714  u32 pc;         /* Offset to cell content of cell being deleted */
60715  u8 *data;       /* pPage->aData */
60716  u8 *ptr;        /* Used to move bytes around within data[] */
60717  int rc;         /* The return code */
60718  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
60719
60720  if( *pRC ) return;
60721
60722  assert( idx>=0 && idx<pPage->nCell );
60723  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
60724  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60725  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60726  data = pPage->aData;
60727  ptr = &pPage->aCellIdx[2*idx];
60728  pc = get2byte(ptr);
60729  hdr = pPage->hdrOffset;
60730  testcase( pc==get2byte(&data[hdr+5]) );
60731  testcase( pc+sz==pPage->pBt->usableSize );
60732  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
60733    *pRC = SQLITE_CORRUPT_BKPT;
60734    return;
60735  }
60736  rc = freeSpace(pPage, pc, sz);
60737  if( rc ){
60738    *pRC = rc;
60739    return;
60740  }
60741  pPage->nCell--;
60742  if( pPage->nCell==0 ){
60743    memset(&data[hdr+1], 0, 4);
60744    data[hdr+7] = 0;
60745    put2byte(&data[hdr+5], pPage->pBt->usableSize);
60746    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
60747                       - pPage->childPtrSize - 8;
60748  }else{
60749    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
60750    put2byte(&data[hdr+3], pPage->nCell);
60751    pPage->nFree += 2;
60752  }
60753}
60754
60755/*
60756** Insert a new cell on pPage at cell index "i".  pCell points to the
60757** content of the cell.
60758**
60759** If the cell content will fit on the page, then put it there.  If it
60760** will not fit, then make a copy of the cell content into pTemp if
60761** pTemp is not null.  Regardless of pTemp, allocate a new entry
60762** in pPage->apOvfl[] and make it point to the cell content (either
60763** in pTemp or the original pCell) and also record its index.
60764** Allocating a new entry in pPage->aCell[] implies that
60765** pPage->nOverflow is incremented.
60766*/
60767static void insertCell(
60768  MemPage *pPage,   /* Page into which we are copying */
60769  int i,            /* New cell becomes the i-th cell of the page */
60770  u8 *pCell,        /* Content of the new cell */
60771  int sz,           /* Bytes of content in pCell */
60772  u8 *pTemp,        /* Temp storage space for pCell, if needed */
60773  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
60774  int *pRC          /* Read and write return code from here */
60775){
60776  int idx = 0;      /* Where to write new cell content in data[] */
60777  int j;            /* Loop counter */
60778  u8 *data;         /* The content of the whole page */
60779  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
60780
60781  if( *pRC ) return;
60782
60783  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
60784  assert( MX_CELL(pPage->pBt)<=10921 );
60785  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
60786  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
60787  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
60788  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60789  /* The cell should normally be sized correctly.  However, when moving a
60790  ** malformed cell from a leaf page to an interior page, if the cell size
60791  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
60792  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
60793  ** the term after the || in the following assert(). */
60794  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
60795  if( pPage->nOverflow || sz+2>pPage->nFree ){
60796    if( pTemp ){
60797      memcpy(pTemp, pCell, sz);
60798      pCell = pTemp;
60799    }
60800    if( iChild ){
60801      put4byte(pCell, iChild);
60802    }
60803    j = pPage->nOverflow++;
60804    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
60805    pPage->apOvfl[j] = pCell;
60806    pPage->aiOvfl[j] = (u16)i;
60807
60808    /* When multiple overflows occur, they are always sequential and in
60809    ** sorted order.  This invariants arise because multiple overflows can
60810    ** only occur when inserting divider cells into the parent page during
60811    ** balancing, and the dividers are adjacent and sorted.
60812    */
60813    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
60814    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
60815  }else{
60816    int rc = sqlite3PagerWrite(pPage->pDbPage);
60817    if( rc!=SQLITE_OK ){
60818      *pRC = rc;
60819      return;
60820    }
60821    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60822    data = pPage->aData;
60823    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
60824    rc = allocateSpace(pPage, sz, &idx);
60825    if( rc ){ *pRC = rc; return; }
60826    /* The allocateSpace() routine guarantees the following properties
60827    ** if it returns successfully */
60828    assert( idx >= 0 );
60829    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
60830    assert( idx+sz <= (int)pPage->pBt->usableSize );
60831    pPage->nFree -= (u16)(2 + sz);
60832    memcpy(&data[idx], pCell, sz);
60833    if( iChild ){
60834      put4byte(&data[idx], iChild);
60835    }
60836    pIns = pPage->aCellIdx + i*2;
60837    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
60838    put2byte(pIns, idx);
60839    pPage->nCell++;
60840    /* increment the cell count */
60841    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
60842    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
60843#ifndef SQLITE_OMIT_AUTOVACUUM
60844    if( pPage->pBt->autoVacuum ){
60845      /* The cell may contain a pointer to an overflow page. If so, write
60846      ** the entry for the overflow page into the pointer map.
60847      */
60848      ptrmapPutOvflPtr(pPage, pCell, pRC);
60849    }
60850#endif
60851  }
60852}
60853
60854/*
60855** A CellArray object contains a cache of pointers and sizes for a
60856** consecutive sequence of cells that might be held multiple pages.
60857*/
60858typedef struct CellArray CellArray;
60859struct CellArray {
60860  int nCell;              /* Number of cells in apCell[] */
60861  MemPage *pRef;          /* Reference page */
60862  u8 **apCell;            /* All cells begin balanced */
60863  u16 *szCell;            /* Local size of all cells in apCell[] */
60864};
60865
60866/*
60867** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
60868** computed.
60869*/
60870static void populateCellCache(CellArray *p, int idx, int N){
60871  assert( idx>=0 && idx+N<=p->nCell );
60872  while( N>0 ){
60873    assert( p->apCell[idx]!=0 );
60874    if( p->szCell[idx]==0 ){
60875      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
60876    }else{
60877      assert( CORRUPT_DB ||
60878              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
60879    }
60880    idx++;
60881    N--;
60882  }
60883}
60884
60885/*
60886** Return the size of the Nth element of the cell array
60887*/
60888static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
60889  assert( N>=0 && N<p->nCell );
60890  assert( p->szCell[N]==0 );
60891  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
60892  return p->szCell[N];
60893}
60894static u16 cachedCellSize(CellArray *p, int N){
60895  assert( N>=0 && N<p->nCell );
60896  if( p->szCell[N] ) return p->szCell[N];
60897  return computeCellSize(p, N);
60898}
60899
60900/*
60901** Array apCell[] contains pointers to nCell b-tree page cells. The
60902** szCell[] array contains the size in bytes of each cell. This function
60903** replaces the current contents of page pPg with the contents of the cell
60904** array.
60905**
60906** Some of the cells in apCell[] may currently be stored in pPg. This
60907** function works around problems caused by this by making a copy of any
60908** such cells before overwriting the page data.
60909**
60910** The MemPage.nFree field is invalidated by this function. It is the
60911** responsibility of the caller to set it correctly.
60912*/
60913static int rebuildPage(
60914  MemPage *pPg,                   /* Edit this page */
60915  int nCell,                      /* Final number of cells on page */
60916  u8 **apCell,                    /* Array of cells */
60917  u16 *szCell                     /* Array of cell sizes */
60918){
60919  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
60920  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
60921  const int usableSize = pPg->pBt->usableSize;
60922  u8 * const pEnd = &aData[usableSize];
60923  int i;
60924  u8 *pCellptr = pPg->aCellIdx;
60925  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
60926  u8 *pData;
60927
60928  i = get2byte(&aData[hdr+5]);
60929  memcpy(&pTmp[i], &aData[i], usableSize - i);
60930
60931  pData = pEnd;
60932  for(i=0; i<nCell; i++){
60933    u8 *pCell = apCell[i];
60934    if( pCell>aData && pCell<pEnd ){
60935      pCell = &pTmp[pCell - aData];
60936    }
60937    pData -= szCell[i];
60938    put2byte(pCellptr, (pData - aData));
60939    pCellptr += 2;
60940    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
60941    memcpy(pData, pCell, szCell[i]);
60942    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
60943    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
60944  }
60945
60946  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
60947  pPg->nCell = nCell;
60948  pPg->nOverflow = 0;
60949
60950  put2byte(&aData[hdr+1], 0);
60951  put2byte(&aData[hdr+3], pPg->nCell);
60952  put2byte(&aData[hdr+5], pData - aData);
60953  aData[hdr+7] = 0x00;
60954  return SQLITE_OK;
60955}
60956
60957/*
60958** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
60959** contains the size in bytes of each such cell. This function attempts to
60960** add the cells stored in the array to page pPg. If it cannot (because
60961** the page needs to be defragmented before the cells will fit), non-zero
60962** is returned. Otherwise, if the cells are added successfully, zero is
60963** returned.
60964**
60965** Argument pCellptr points to the first entry in the cell-pointer array
60966** (part of page pPg) to populate. After cell apCell[0] is written to the
60967** page body, a 16-bit offset is written to pCellptr. And so on, for each
60968** cell in the array. It is the responsibility of the caller to ensure
60969** that it is safe to overwrite this part of the cell-pointer array.
60970**
60971** When this function is called, *ppData points to the start of the
60972** content area on page pPg. If the size of the content area is extended,
60973** *ppData is updated to point to the new start of the content area
60974** before returning.
60975**
60976** Finally, argument pBegin points to the byte immediately following the
60977** end of the space required by this page for the cell-pointer area (for
60978** all cells - not just those inserted by the current call). If the content
60979** area must be extended to before this point in order to accomodate all
60980** cells in apCell[], then the cells do not fit and non-zero is returned.
60981*/
60982static int pageInsertArray(
60983  MemPage *pPg,                   /* Page to add cells to */
60984  u8 *pBegin,                     /* End of cell-pointer array */
60985  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
60986  u8 *pCellptr,                   /* Pointer to cell-pointer area */
60987  int iFirst,                     /* Index of first cell to add */
60988  int nCell,                      /* Number of cells to add to pPg */
60989  CellArray *pCArray              /* Array of cells */
60990){
60991  int i;
60992  u8 *aData = pPg->aData;
60993  u8 *pData = *ppData;
60994  int iEnd = iFirst + nCell;
60995  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
60996  for(i=iFirst; i<iEnd; i++){
60997    int sz, rc;
60998    u8 *pSlot;
60999    sz = cachedCellSize(pCArray, i);
61000    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
61001      pData -= sz;
61002      if( pData<pBegin ) return 1;
61003      pSlot = pData;
61004    }
61005    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
61006    ** database.  But they might for a corrupt database.  Hence use memmove()
61007    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
61008    assert( (pSlot+sz)<=pCArray->apCell[i]
61009         || pSlot>=(pCArray->apCell[i]+sz)
61010         || CORRUPT_DB );
61011    memmove(pSlot, pCArray->apCell[i], sz);
61012    put2byte(pCellptr, (pSlot - aData));
61013    pCellptr += 2;
61014  }
61015  *ppData = pData;
61016  return 0;
61017}
61018
61019/*
61020** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
61021** contains the size in bytes of each such cell. This function adds the
61022** space associated with each cell in the array that is currently stored
61023** within the body of pPg to the pPg free-list. The cell-pointers and other
61024** fields of the page are not updated.
61025**
61026** This function returns the total number of cells added to the free-list.
61027*/
61028static int pageFreeArray(
61029  MemPage *pPg,                   /* Page to edit */
61030  int iFirst,                     /* First cell to delete */
61031  int nCell,                      /* Cells to delete */
61032  CellArray *pCArray              /* Array of cells */
61033){
61034  u8 * const aData = pPg->aData;
61035  u8 * const pEnd = &aData[pPg->pBt->usableSize];
61036  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
61037  int nRet = 0;
61038  int i;
61039  int iEnd = iFirst + nCell;
61040  u8 *pFree = 0;
61041  int szFree = 0;
61042
61043  for(i=iFirst; i<iEnd; i++){
61044    u8 *pCell = pCArray->apCell[i];
61045    if( pCell>=pStart && pCell<pEnd ){
61046      int sz;
61047      /* No need to use cachedCellSize() here.  The sizes of all cells that
61048      ** are to be freed have already been computing while deciding which
61049      ** cells need freeing */
61050      sz = pCArray->szCell[i];  assert( sz>0 );
61051      if( pFree!=(pCell + sz) ){
61052        if( pFree ){
61053          assert( pFree>aData && (pFree - aData)<65536 );
61054          freeSpace(pPg, (u16)(pFree - aData), szFree);
61055        }
61056        pFree = pCell;
61057        szFree = sz;
61058        if( pFree+sz>pEnd ) return 0;
61059      }else{
61060        pFree = pCell;
61061        szFree += sz;
61062      }
61063      nRet++;
61064    }
61065  }
61066  if( pFree ){
61067    assert( pFree>aData && (pFree - aData)<65536 );
61068    freeSpace(pPg, (u16)(pFree - aData), szFree);
61069  }
61070  return nRet;
61071}
61072
61073/*
61074** apCell[] and szCell[] contains pointers to and sizes of all cells in the
61075** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
61076** with apCell[iOld].  After balancing, this page should hold nNew cells
61077** starting at apCell[iNew].
61078**
61079** This routine makes the necessary adjustments to pPg so that it contains
61080** the correct cells after being balanced.
61081**
61082** The pPg->nFree field is invalid when this function returns. It is the
61083** responsibility of the caller to set it correctly.
61084*/
61085static int editPage(
61086  MemPage *pPg,                   /* Edit this page */
61087  int iOld,                       /* Index of first cell currently on page */
61088  int iNew,                       /* Index of new first cell on page */
61089  int nNew,                       /* Final number of cells on page */
61090  CellArray *pCArray              /* Array of cells and sizes */
61091){
61092  u8 * const aData = pPg->aData;
61093  const int hdr = pPg->hdrOffset;
61094  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
61095  int nCell = pPg->nCell;       /* Cells stored on pPg */
61096  u8 *pData;
61097  u8 *pCellptr;
61098  int i;
61099  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
61100  int iNewEnd = iNew + nNew;
61101
61102#ifdef SQLITE_DEBUG
61103  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
61104  memcpy(pTmp, aData, pPg->pBt->usableSize);
61105#endif
61106
61107  /* Remove cells from the start and end of the page */
61108  if( iOld<iNew ){
61109    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
61110    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
61111    nCell -= nShift;
61112  }
61113  if( iNewEnd < iOldEnd ){
61114    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
61115  }
61116
61117  pData = &aData[get2byteNotZero(&aData[hdr+5])];
61118  if( pData<pBegin ) goto editpage_fail;
61119
61120  /* Add cells to the start of the page */
61121  if( iNew<iOld ){
61122    int nAdd = MIN(nNew,iOld-iNew);
61123    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
61124    pCellptr = pPg->aCellIdx;
61125    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
61126    if( pageInsertArray(
61127          pPg, pBegin, &pData, pCellptr,
61128          iNew, nAdd, pCArray
61129    ) ) goto editpage_fail;
61130    nCell += nAdd;
61131  }
61132
61133  /* Add any overflow cells */
61134  for(i=0; i<pPg->nOverflow; i++){
61135    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
61136    if( iCell>=0 && iCell<nNew ){
61137      pCellptr = &pPg->aCellIdx[iCell * 2];
61138      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
61139      nCell++;
61140      if( pageInsertArray(
61141            pPg, pBegin, &pData, pCellptr,
61142            iCell+iNew, 1, pCArray
61143      ) ) goto editpage_fail;
61144    }
61145  }
61146
61147  /* Append cells to the end of the page */
61148  pCellptr = &pPg->aCellIdx[nCell*2];
61149  if( pageInsertArray(
61150        pPg, pBegin, &pData, pCellptr,
61151        iNew+nCell, nNew-nCell, pCArray
61152  ) ) goto editpage_fail;
61153
61154  pPg->nCell = nNew;
61155  pPg->nOverflow = 0;
61156
61157  put2byte(&aData[hdr+3], pPg->nCell);
61158  put2byte(&aData[hdr+5], pData - aData);
61159
61160#ifdef SQLITE_DEBUG
61161  for(i=0; i<nNew && !CORRUPT_DB; i++){
61162    u8 *pCell = pCArray->apCell[i+iNew];
61163    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
61164    if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
61165      pCell = &pTmp[pCell - aData];
61166    }
61167    assert( 0==memcmp(pCell, &aData[iOff],
61168            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
61169  }
61170#endif
61171
61172  return SQLITE_OK;
61173 editpage_fail:
61174  /* Unable to edit this page. Rebuild it from scratch instead. */
61175  populateCellCache(pCArray, iNew, nNew);
61176  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
61177}
61178
61179/*
61180** The following parameters determine how many adjacent pages get involved
61181** in a balancing operation.  NN is the number of neighbors on either side
61182** of the page that participate in the balancing operation.  NB is the
61183** total number of pages that participate, including the target page and
61184** NN neighbors on either side.
61185**
61186** The minimum value of NN is 1 (of course).  Increasing NN above 1
61187** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
61188** in exchange for a larger degradation in INSERT and UPDATE performance.
61189** The value of NN appears to give the best results overall.
61190*/
61191#define NN 1             /* Number of neighbors on either side of pPage */
61192#define NB (NN*2+1)      /* Total pages involved in the balance */
61193
61194
61195#ifndef SQLITE_OMIT_QUICKBALANCE
61196/*
61197** This version of balance() handles the common special case where
61198** a new entry is being inserted on the extreme right-end of the
61199** tree, in other words, when the new entry will become the largest
61200** entry in the tree.
61201**
61202** Instead of trying to balance the 3 right-most leaf pages, just add
61203** a new page to the right-hand side and put the one new entry in
61204** that page.  This leaves the right side of the tree somewhat
61205** unbalanced.  But odds are that we will be inserting new entries
61206** at the end soon afterwards so the nearly empty page will quickly
61207** fill up.  On average.
61208**
61209** pPage is the leaf page which is the right-most page in the tree.
61210** pParent is its parent.  pPage must have a single overflow entry
61211** which is also the right-most entry on the page.
61212**
61213** The pSpace buffer is used to store a temporary copy of the divider
61214** cell that will be inserted into pParent. Such a cell consists of a 4
61215** byte page number followed by a variable length integer. In other
61216** words, at most 13 bytes. Hence the pSpace buffer must be at
61217** least 13 bytes in size.
61218*/
61219static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
61220  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
61221  MemPage *pNew;                       /* Newly allocated page */
61222  int rc;                              /* Return Code */
61223  Pgno pgnoNew;                        /* Page number of pNew */
61224
61225  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61226  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61227  assert( pPage->nOverflow==1 );
61228
61229  /* This error condition is now caught prior to reaching this function */
61230  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
61231
61232  /* Allocate a new page. This page will become the right-sibling of
61233  ** pPage. Make the parent page writable, so that the new divider cell
61234  ** may be inserted. If both these operations are successful, proceed.
61235  */
61236  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
61237
61238  if( rc==SQLITE_OK ){
61239
61240    u8 *pOut = &pSpace[4];
61241    u8 *pCell = pPage->apOvfl[0];
61242    u16 szCell = pPage->xCellSize(pPage, pCell);
61243    u8 *pStop;
61244
61245    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
61246    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
61247    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
61248    rc = rebuildPage(pNew, 1, &pCell, &szCell);
61249    if( NEVER(rc) ) return rc;
61250    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
61251
61252    /* If this is an auto-vacuum database, update the pointer map
61253    ** with entries for the new page, and any pointer from the
61254    ** cell on the page to an overflow page. If either of these
61255    ** operations fails, the return code is set, but the contents
61256    ** of the parent page are still manipulated by thh code below.
61257    ** That is Ok, at this point the parent page is guaranteed to
61258    ** be marked as dirty. Returning an error code will cause a
61259    ** rollback, undoing any changes made to the parent page.
61260    */
61261    if( ISAUTOVACUUM ){
61262      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
61263      if( szCell>pNew->minLocal ){
61264        ptrmapPutOvflPtr(pNew, pCell, &rc);
61265      }
61266    }
61267
61268    /* Create a divider cell to insert into pParent. The divider cell
61269    ** consists of a 4-byte page number (the page number of pPage) and
61270    ** a variable length key value (which must be the same value as the
61271    ** largest key on pPage).
61272    **
61273    ** To find the largest key value on pPage, first find the right-most
61274    ** cell on pPage. The first two fields of this cell are the
61275    ** record-length (a variable length integer at most 32-bits in size)
61276    ** and the key value (a variable length integer, may have any value).
61277    ** The first of the while(...) loops below skips over the record-length
61278    ** field. The second while(...) loop copies the key value from the
61279    ** cell on pPage into the pSpace buffer.
61280    */
61281    pCell = findCell(pPage, pPage->nCell-1);
61282    pStop = &pCell[9];
61283    while( (*(pCell++)&0x80) && pCell<pStop );
61284    pStop = &pCell[9];
61285    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
61286
61287    /* Insert the new divider cell into pParent. */
61288    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
61289               0, pPage->pgno, &rc);
61290
61291    /* Set the right-child pointer of pParent to point to the new page. */
61292    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
61293
61294    /* Release the reference to the new page. */
61295    releasePage(pNew);
61296  }
61297
61298  return rc;
61299}
61300#endif /* SQLITE_OMIT_QUICKBALANCE */
61301
61302#if 0
61303/*
61304** This function does not contribute anything to the operation of SQLite.
61305** it is sometimes activated temporarily while debugging code responsible
61306** for setting pointer-map entries.
61307*/
61308static int ptrmapCheckPages(MemPage **apPage, int nPage){
61309  int i, j;
61310  for(i=0; i<nPage; i++){
61311    Pgno n;
61312    u8 e;
61313    MemPage *pPage = apPage[i];
61314    BtShared *pBt = pPage->pBt;
61315    assert( pPage->isInit );
61316
61317    for(j=0; j<pPage->nCell; j++){
61318      CellInfo info;
61319      u8 *z;
61320
61321      z = findCell(pPage, j);
61322      pPage->xParseCell(pPage, z, &info);
61323      if( info.iOverflow ){
61324        Pgno ovfl = get4byte(&z[info.iOverflow]);
61325        ptrmapGet(pBt, ovfl, &e, &n);
61326        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
61327      }
61328      if( !pPage->leaf ){
61329        Pgno child = get4byte(z);
61330        ptrmapGet(pBt, child, &e, &n);
61331        assert( n==pPage->pgno && e==PTRMAP_BTREE );
61332      }
61333    }
61334    if( !pPage->leaf ){
61335      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61336      ptrmapGet(pBt, child, &e, &n);
61337      assert( n==pPage->pgno && e==PTRMAP_BTREE );
61338    }
61339  }
61340  return 1;
61341}
61342#endif
61343
61344/*
61345** This function is used to copy the contents of the b-tree node stored
61346** on page pFrom to page pTo. If page pFrom was not a leaf page, then
61347** the pointer-map entries for each child page are updated so that the
61348** parent page stored in the pointer map is page pTo. If pFrom contained
61349** any cells with overflow page pointers, then the corresponding pointer
61350** map entries are also updated so that the parent page is page pTo.
61351**
61352** If pFrom is currently carrying any overflow cells (entries in the
61353** MemPage.apOvfl[] array), they are not copied to pTo.
61354**
61355** Before returning, page pTo is reinitialized using btreeInitPage().
61356**
61357** The performance of this function is not critical. It is only used by
61358** the balance_shallower() and balance_deeper() procedures, neither of
61359** which are called often under normal circumstances.
61360*/
61361static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
61362  if( (*pRC)==SQLITE_OK ){
61363    BtShared * const pBt = pFrom->pBt;
61364    u8 * const aFrom = pFrom->aData;
61365    u8 * const aTo = pTo->aData;
61366    int const iFromHdr = pFrom->hdrOffset;
61367    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
61368    int rc;
61369    int iData;
61370
61371
61372    assert( pFrom->isInit );
61373    assert( pFrom->nFree>=iToHdr );
61374    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
61375
61376    /* Copy the b-tree node content from page pFrom to page pTo. */
61377    iData = get2byte(&aFrom[iFromHdr+5]);
61378    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
61379    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
61380
61381    /* Reinitialize page pTo so that the contents of the MemPage structure
61382    ** match the new data. The initialization of pTo can actually fail under
61383    ** fairly obscure circumstances, even though it is a copy of initialized
61384    ** page pFrom.
61385    */
61386    pTo->isInit = 0;
61387    rc = btreeInitPage(pTo);
61388    if( rc!=SQLITE_OK ){
61389      *pRC = rc;
61390      return;
61391    }
61392
61393    /* If this is an auto-vacuum database, update the pointer-map entries
61394    ** for any b-tree or overflow pages that pTo now contains the pointers to.
61395    */
61396    if( ISAUTOVACUUM ){
61397      *pRC = setChildPtrmaps(pTo);
61398    }
61399  }
61400}
61401
61402/*
61403** This routine redistributes cells on the iParentIdx'th child of pParent
61404** (hereafter "the page") and up to 2 siblings so that all pages have about the
61405** same amount of free space. Usually a single sibling on either side of the
61406** page are used in the balancing, though both siblings might come from one
61407** side if the page is the first or last child of its parent. If the page
61408** has fewer than 2 siblings (something which can only happen if the page
61409** is a root page or a child of a root page) then all available siblings
61410** participate in the balancing.
61411**
61412** The number of siblings of the page might be increased or decreased by
61413** one or two in an effort to keep pages nearly full but not over full.
61414**
61415** Note that when this routine is called, some of the cells on the page
61416** might not actually be stored in MemPage.aData[]. This can happen
61417** if the page is overfull. This routine ensures that all cells allocated
61418** to the page and its siblings fit into MemPage.aData[] before returning.
61419**
61420** In the course of balancing the page and its siblings, cells may be
61421** inserted into or removed from the parent page (pParent). Doing so
61422** may cause the parent page to become overfull or underfull. If this
61423** happens, it is the responsibility of the caller to invoke the correct
61424** balancing routine to fix this problem (see the balance() routine).
61425**
61426** If this routine fails for any reason, it might leave the database
61427** in a corrupted state. So if this routine fails, the database should
61428** be rolled back.
61429**
61430** The third argument to this function, aOvflSpace, is a pointer to a
61431** buffer big enough to hold one page. If while inserting cells into the parent
61432** page (pParent) the parent page becomes overfull, this buffer is
61433** used to store the parent's overflow cells. Because this function inserts
61434** a maximum of four divider cells into the parent page, and the maximum
61435** size of a cell stored within an internal node is always less than 1/4
61436** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
61437** enough for all overflow cells.
61438**
61439** If aOvflSpace is set to a null pointer, this function returns
61440** SQLITE_NOMEM.
61441*/
61442#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
61443#pragma optimize("", off)
61444#endif
61445static int balance_nonroot(
61446  MemPage *pParent,               /* Parent page of siblings being balanced */
61447  int iParentIdx,                 /* Index of "the page" in pParent */
61448  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
61449  int isRoot,                     /* True if pParent is a root-page */
61450  int bBulk                       /* True if this call is part of a bulk load */
61451){
61452  BtShared *pBt;               /* The whole database */
61453  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
61454  int nNew = 0;                /* Number of pages in apNew[] */
61455  int nOld;                    /* Number of pages in apOld[] */
61456  int i, j, k;                 /* Loop counters */
61457  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
61458  int rc = SQLITE_OK;          /* The return code */
61459  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
61460  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
61461  int usableSpace;             /* Bytes in pPage beyond the header */
61462  int pageFlags;               /* Value of pPage->aData[0] */
61463  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
61464  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
61465  int szScratch;               /* Size of scratch memory requested */
61466  MemPage *apOld[NB];          /* pPage and up to two siblings */
61467  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
61468  u8 *pRight;                  /* Location in parent of right-sibling pointer */
61469  u8 *apDiv[NB-1];             /* Divider cells in pParent */
61470  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
61471  int cntOld[NB+2];            /* Old index in b.apCell[] */
61472  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
61473  u8 *aSpace1;                 /* Space for copies of dividers cells */
61474  Pgno pgno;                   /* Temp var to store a page number in */
61475  u8 abDone[NB+2];             /* True after i'th new page is populated */
61476  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
61477  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
61478  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
61479  CellArray b;                  /* Parsed information on cells being balanced */
61480
61481  memset(abDone, 0, sizeof(abDone));
61482  b.nCell = 0;
61483  b.apCell = 0;
61484  pBt = pParent->pBt;
61485  assert( sqlite3_mutex_held(pBt->mutex) );
61486  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61487
61488#if 0
61489  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
61490#endif
61491
61492  /* At this point pParent may have at most one overflow cell. And if
61493  ** this overflow cell is present, it must be the cell with
61494  ** index iParentIdx. This scenario comes about when this function
61495  ** is called (indirectly) from sqlite3BtreeDelete().
61496  */
61497  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
61498  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
61499
61500  if( !aOvflSpace ){
61501    return SQLITE_NOMEM;
61502  }
61503
61504  /* Find the sibling pages to balance. Also locate the cells in pParent
61505  ** that divide the siblings. An attempt is made to find NN siblings on
61506  ** either side of pPage. More siblings are taken from one side, however,
61507  ** if there are fewer than NN siblings on the other side. If pParent
61508  ** has NB or fewer children then all children of pParent are taken.
61509  **
61510  ** This loop also drops the divider cells from the parent page. This
61511  ** way, the remainder of the function does not have to deal with any
61512  ** overflow cells in the parent page, since if any existed they will
61513  ** have already been removed.
61514  */
61515  i = pParent->nOverflow + pParent->nCell;
61516  if( i<2 ){
61517    nxDiv = 0;
61518  }else{
61519    assert( bBulk==0 || bBulk==1 );
61520    if( iParentIdx==0 ){
61521      nxDiv = 0;
61522    }else if( iParentIdx==i ){
61523      nxDiv = i-2+bBulk;
61524    }else{
61525      nxDiv = iParentIdx-1;
61526    }
61527    i = 2-bBulk;
61528  }
61529  nOld = i+1;
61530  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
61531    pRight = &pParent->aData[pParent->hdrOffset+8];
61532  }else{
61533    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
61534  }
61535  pgno = get4byte(pRight);
61536  while( 1 ){
61537    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
61538    if( rc ){
61539      memset(apOld, 0, (i+1)*sizeof(MemPage*));
61540      goto balance_cleanup;
61541    }
61542    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
61543    if( (i--)==0 ) break;
61544
61545    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
61546      apDiv[i] = pParent->apOvfl[0];
61547      pgno = get4byte(apDiv[i]);
61548      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
61549      pParent->nOverflow = 0;
61550    }else{
61551      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
61552      pgno = get4byte(apDiv[i]);
61553      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
61554
61555      /* Drop the cell from the parent page. apDiv[i] still points to
61556      ** the cell within the parent, even though it has been dropped.
61557      ** This is safe because dropping a cell only overwrites the first
61558      ** four bytes of it, and this function does not need the first
61559      ** four bytes of the divider cell. So the pointer is safe to use
61560      ** later on.
61561      **
61562      ** But not if we are in secure-delete mode. In secure-delete mode,
61563      ** the dropCell() routine will overwrite the entire cell with zeroes.
61564      ** In this case, temporarily copy the cell into the aOvflSpace[]
61565      ** buffer. It will be copied out again as soon as the aSpace[] buffer
61566      ** is allocated.  */
61567      if( pBt->btsFlags & BTS_SECURE_DELETE ){
61568        int iOff;
61569
61570        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
61571        if( (iOff+szNew[i])>(int)pBt->usableSize ){
61572          rc = SQLITE_CORRUPT_BKPT;
61573          memset(apOld, 0, (i+1)*sizeof(MemPage*));
61574          goto balance_cleanup;
61575        }else{
61576          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
61577          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
61578        }
61579      }
61580      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
61581    }
61582  }
61583
61584  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
61585  ** alignment */
61586  nMaxCells = (nMaxCells + 3)&~3;
61587
61588  /*
61589  ** Allocate space for memory structures
61590  */
61591  szScratch =
61592       nMaxCells*sizeof(u8*)                       /* b.apCell */
61593     + nMaxCells*sizeof(u16)                       /* b.szCell */
61594     + pBt->pageSize;                              /* aSpace1 */
61595
61596  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
61597  ** that is more than 6 times the database page size. */
61598  assert( szScratch<=6*(int)pBt->pageSize );
61599  b.apCell = sqlite3ScratchMalloc( szScratch );
61600  if( b.apCell==0 ){
61601    rc = SQLITE_NOMEM;
61602    goto balance_cleanup;
61603  }
61604  b.szCell = (u16*)&b.apCell[nMaxCells];
61605  aSpace1 = (u8*)&b.szCell[nMaxCells];
61606  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
61607
61608  /*
61609  ** Load pointers to all cells on sibling pages and the divider cells
61610  ** into the local b.apCell[] array.  Make copies of the divider cells
61611  ** into space obtained from aSpace1[]. The divider cells have already
61612  ** been removed from pParent.
61613  **
61614  ** If the siblings are on leaf pages, then the child pointers of the
61615  ** divider cells are stripped from the cells before they are copied
61616  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
61617  ** child pointers.  If siblings are not leaves, then all cell in
61618  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
61619  ** are alike.
61620  **
61621  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
61622  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
61623  */
61624  b.pRef = apOld[0];
61625  leafCorrection = b.pRef->leaf*4;
61626  leafData = b.pRef->intKeyLeaf;
61627  for(i=0; i<nOld; i++){
61628    MemPage *pOld = apOld[i];
61629    int limit = pOld->nCell;
61630    u8 *aData = pOld->aData;
61631    u16 maskPage = pOld->maskPage;
61632    u8 *piCell = aData + pOld->cellOffset;
61633    u8 *piEnd;
61634
61635    /* Verify that all sibling pages are of the same "type" (table-leaf,
61636    ** table-interior, index-leaf, or index-interior).
61637    */
61638    if( pOld->aData[0]!=apOld[0]->aData[0] ){
61639      rc = SQLITE_CORRUPT_BKPT;
61640      goto balance_cleanup;
61641    }
61642
61643    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
61644    ** constains overflow cells, include them in the b.apCell[] array
61645    ** in the correct spot.
61646    **
61647    ** Note that when there are multiple overflow cells, it is always the
61648    ** case that they are sequential and adjacent.  This invariant arises
61649    ** because multiple overflows can only occurs when inserting divider
61650    ** cells into a parent on a prior balance, and divider cells are always
61651    ** adjacent and are inserted in order.  There is an assert() tagged
61652    ** with "NOTE 1" in the overflow cell insertion loop to prove this
61653    ** invariant.
61654    **
61655    ** This must be done in advance.  Once the balance starts, the cell
61656    ** offset section of the btree page will be overwritten and we will no
61657    ** long be able to find the cells if a pointer to each cell is not saved
61658    ** first.
61659    */
61660    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit);
61661    if( pOld->nOverflow>0 ){
61662      memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow);
61663      limit = pOld->aiOvfl[0];
61664      for(j=0; j<limit; j++){
61665        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
61666        piCell += 2;
61667        b.nCell++;
61668      }
61669      for(k=0; k<pOld->nOverflow; k++){
61670        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
61671        b.apCell[b.nCell] = pOld->apOvfl[k];
61672        b.nCell++;
61673      }
61674    }
61675    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
61676    while( piCell<piEnd ){
61677      assert( b.nCell<nMaxCells );
61678      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
61679      piCell += 2;
61680      b.nCell++;
61681    }
61682
61683    cntOld[i] = b.nCell;
61684    if( i<nOld-1 && !leafData){
61685      u16 sz = (u16)szNew[i];
61686      u8 *pTemp;
61687      assert( b.nCell<nMaxCells );
61688      b.szCell[b.nCell] = sz;
61689      pTemp = &aSpace1[iSpace1];
61690      iSpace1 += sz;
61691      assert( sz<=pBt->maxLocal+23 );
61692      assert( iSpace1 <= (int)pBt->pageSize );
61693      memcpy(pTemp, apDiv[i], sz);
61694      b.apCell[b.nCell] = pTemp+leafCorrection;
61695      assert( leafCorrection==0 || leafCorrection==4 );
61696      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
61697      if( !pOld->leaf ){
61698        assert( leafCorrection==0 );
61699        assert( pOld->hdrOffset==0 );
61700        /* The right pointer of the child page pOld becomes the left
61701        ** pointer of the divider cell */
61702        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
61703      }else{
61704        assert( leafCorrection==4 );
61705        while( b.szCell[b.nCell]<4 ){
61706          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
61707          ** does exist, pad it with 0x00 bytes. */
61708          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
61709          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
61710          aSpace1[iSpace1++] = 0x00;
61711          b.szCell[b.nCell]++;
61712        }
61713      }
61714      b.nCell++;
61715    }
61716  }
61717
61718  /*
61719  ** Figure out the number of pages needed to hold all b.nCell cells.
61720  ** Store this number in "k".  Also compute szNew[] which is the total
61721  ** size of all cells on the i-th page and cntNew[] which is the index
61722  ** in b.apCell[] of the cell that divides page i from page i+1.
61723  ** cntNew[k] should equal b.nCell.
61724  **
61725  ** Values computed by this block:
61726  **
61727  **           k: The total number of sibling pages
61728  **    szNew[i]: Spaced used on the i-th sibling page.
61729  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
61730  **              the right of the i-th sibling page.
61731  ** usableSpace: Number of bytes of space available on each sibling.
61732  **
61733  */
61734  usableSpace = pBt->usableSize - 12 + leafCorrection;
61735  for(i=0; i<nOld; i++){
61736    MemPage *p = apOld[i];
61737    szNew[i] = usableSpace - p->nFree;
61738    if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
61739    for(j=0; j<p->nOverflow; j++){
61740      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
61741    }
61742    cntNew[i] = cntOld[i];
61743  }
61744  k = nOld;
61745  for(i=0; i<k; i++){
61746    int sz;
61747    while( szNew[i]>usableSpace ){
61748      if( i+1>=k ){
61749        k = i+2;
61750        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
61751        szNew[k-1] = 0;
61752        cntNew[k-1] = b.nCell;
61753      }
61754      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
61755      szNew[i] -= sz;
61756      if( !leafData ){
61757        if( cntNew[i]<b.nCell ){
61758          sz = 2 + cachedCellSize(&b, cntNew[i]);
61759        }else{
61760          sz = 0;
61761        }
61762      }
61763      szNew[i+1] += sz;
61764      cntNew[i]--;
61765    }
61766    while( cntNew[i]<b.nCell ){
61767      sz = 2 + cachedCellSize(&b, cntNew[i]);
61768      if( szNew[i]+sz>usableSpace ) break;
61769      szNew[i] += sz;
61770      cntNew[i]++;
61771      if( !leafData ){
61772        if( cntNew[i]<b.nCell ){
61773          sz = 2 + cachedCellSize(&b, cntNew[i]);
61774        }else{
61775          sz = 0;
61776        }
61777      }
61778      szNew[i+1] -= sz;
61779    }
61780    if( cntNew[i]>=b.nCell ){
61781      k = i+1;
61782    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
61783      rc = SQLITE_CORRUPT_BKPT;
61784      goto balance_cleanup;
61785    }
61786  }
61787
61788  /*
61789  ** The packing computed by the previous block is biased toward the siblings
61790  ** on the left side (siblings with smaller keys). The left siblings are
61791  ** always nearly full, while the right-most sibling might be nearly empty.
61792  ** The next block of code attempts to adjust the packing of siblings to
61793  ** get a better balance.
61794  **
61795  ** This adjustment is more than an optimization.  The packing above might
61796  ** be so out of balance as to be illegal.  For example, the right-most
61797  ** sibling might be completely empty.  This adjustment is not optional.
61798  */
61799  for(i=k-1; i>0; i--){
61800    int szRight = szNew[i];  /* Size of sibling on the right */
61801    int szLeft = szNew[i-1]; /* Size of sibling on the left */
61802    int r;              /* Index of right-most cell in left sibling */
61803    int d;              /* Index of first cell to the left of right sibling */
61804
61805    r = cntNew[i-1] - 1;
61806    d = r + 1 - leafData;
61807    (void)cachedCellSize(&b, d);
61808    do{
61809      assert( d<nMaxCells );
61810      assert( r<nMaxCells );
61811      (void)cachedCellSize(&b, r);
61812      if( szRight!=0
61813       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
61814        break;
61815      }
61816      szRight += b.szCell[d] + 2;
61817      szLeft -= b.szCell[r] + 2;
61818      cntNew[i-1] = r;
61819      r--;
61820      d--;
61821    }while( r>=0 );
61822    szNew[i] = szRight;
61823    szNew[i-1] = szLeft;
61824    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
61825      rc = SQLITE_CORRUPT_BKPT;
61826      goto balance_cleanup;
61827    }
61828  }
61829
61830  /* Sanity check:  For a non-corrupt database file one of the follwing
61831  ** must be true:
61832  **    (1) We found one or more cells (cntNew[0])>0), or
61833  **    (2) pPage is a virtual root page.  A virtual root page is when
61834  **        the real root page is page 1 and we are the only child of
61835  **        that page.
61836  */
61837  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
61838  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
61839    apOld[0]->pgno, apOld[0]->nCell,
61840    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
61841    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
61842  ));
61843
61844  /*
61845  ** Allocate k new pages.  Reuse old pages where possible.
61846  */
61847  pageFlags = apOld[0]->aData[0];
61848  for(i=0; i<k; i++){
61849    MemPage *pNew;
61850    if( i<nOld ){
61851      pNew = apNew[i] = apOld[i];
61852      apOld[i] = 0;
61853      rc = sqlite3PagerWrite(pNew->pDbPage);
61854      nNew++;
61855      if( rc ) goto balance_cleanup;
61856    }else{
61857      assert( i>0 );
61858      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
61859      if( rc ) goto balance_cleanup;
61860      zeroPage(pNew, pageFlags);
61861      apNew[i] = pNew;
61862      nNew++;
61863      cntOld[i] = b.nCell;
61864
61865      /* Set the pointer-map entry for the new sibling page. */
61866      if( ISAUTOVACUUM ){
61867        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
61868        if( rc!=SQLITE_OK ){
61869          goto balance_cleanup;
61870        }
61871      }
61872    }
61873  }
61874
61875  /*
61876  ** Reassign page numbers so that the new pages are in ascending order.
61877  ** This helps to keep entries in the disk file in order so that a scan
61878  ** of the table is closer to a linear scan through the file. That in turn
61879  ** helps the operating system to deliver pages from the disk more rapidly.
61880  **
61881  ** An O(n^2) insertion sort algorithm is used, but since n is never more
61882  ** than (NB+2) (a small constant), that should not be a problem.
61883  **
61884  ** When NB==3, this one optimization makes the database about 25% faster
61885  ** for large insertions and deletions.
61886  */
61887  for(i=0; i<nNew; i++){
61888    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
61889    aPgFlags[i] = apNew[i]->pDbPage->flags;
61890    for(j=0; j<i; j++){
61891      if( aPgno[j]==aPgno[i] ){
61892        /* This branch is taken if the set of sibling pages somehow contains
61893        ** duplicate entries. This can happen if the database is corrupt.
61894        ** It would be simpler to detect this as part of the loop below, but
61895        ** we do the detection here in order to avoid populating the pager
61896        ** cache with two separate objects associated with the same
61897        ** page number.  */
61898        assert( CORRUPT_DB );
61899        rc = SQLITE_CORRUPT_BKPT;
61900        goto balance_cleanup;
61901      }
61902    }
61903  }
61904  for(i=0; i<nNew; i++){
61905    int iBest = 0;                /* aPgno[] index of page number to use */
61906    for(j=1; j<nNew; j++){
61907      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
61908    }
61909    pgno = aPgOrder[iBest];
61910    aPgOrder[iBest] = 0xffffffff;
61911    if( iBest!=i ){
61912      if( iBest>i ){
61913        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
61914      }
61915      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
61916      apNew[i]->pgno = pgno;
61917    }
61918  }
61919
61920  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
61921         "%d(%d nc=%d) %d(%d nc=%d)\n",
61922    apNew[0]->pgno, szNew[0], cntNew[0],
61923    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
61924    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
61925    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
61926    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
61927    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
61928    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
61929    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
61930    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
61931  ));
61932
61933  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61934  put4byte(pRight, apNew[nNew-1]->pgno);
61935
61936  /* If the sibling pages are not leaves, ensure that the right-child pointer
61937  ** of the right-most new sibling page is set to the value that was
61938  ** originally in the same field of the right-most old sibling page. */
61939  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
61940    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
61941    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
61942  }
61943
61944  /* Make any required updates to pointer map entries associated with
61945  ** cells stored on sibling pages following the balance operation. Pointer
61946  ** map entries associated with divider cells are set by the insertCell()
61947  ** routine. The associated pointer map entries are:
61948  **
61949  **   a) if the cell contains a reference to an overflow chain, the
61950  **      entry associated with the first page in the overflow chain, and
61951  **
61952  **   b) if the sibling pages are not leaves, the child page associated
61953  **      with the cell.
61954  **
61955  ** If the sibling pages are not leaves, then the pointer map entry
61956  ** associated with the right-child of each sibling may also need to be
61957  ** updated. This happens below, after the sibling pages have been
61958  ** populated, not here.
61959  */
61960  if( ISAUTOVACUUM ){
61961    MemPage *pNew = apNew[0];
61962    u8 *aOld = pNew->aData;
61963    int cntOldNext = pNew->nCell + pNew->nOverflow;
61964    int usableSize = pBt->usableSize;
61965    int iNew = 0;
61966    int iOld = 0;
61967
61968    for(i=0; i<b.nCell; i++){
61969      u8 *pCell = b.apCell[i];
61970      if( i==cntOldNext ){
61971        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
61972        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
61973        aOld = pOld->aData;
61974      }
61975      if( i==cntNew[iNew] ){
61976        pNew = apNew[++iNew];
61977        if( !leafData ) continue;
61978      }
61979
61980      /* Cell pCell is destined for new sibling page pNew. Originally, it
61981      ** was either part of sibling page iOld (possibly an overflow cell),
61982      ** or else the divider cell to the left of sibling page iOld. So,
61983      ** if sibling page iOld had the same page number as pNew, and if
61984      ** pCell really was a part of sibling page iOld (not a divider or
61985      ** overflow cell), we can skip updating the pointer map entries.  */
61986      if( iOld>=nNew
61987       || pNew->pgno!=aPgno[iOld]
61988       || pCell<aOld
61989       || pCell>=&aOld[usableSize]
61990      ){
61991        if( !leafCorrection ){
61992          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
61993        }
61994        if( cachedCellSize(&b,i)>pNew->minLocal ){
61995          ptrmapPutOvflPtr(pNew, pCell, &rc);
61996        }
61997        if( rc ) goto balance_cleanup;
61998      }
61999    }
62000  }
62001
62002  /* Insert new divider cells into pParent. */
62003  for(i=0; i<nNew-1; i++){
62004    u8 *pCell;
62005    u8 *pTemp;
62006    int sz;
62007    MemPage *pNew = apNew[i];
62008    j = cntNew[i];
62009
62010    assert( j<nMaxCells );
62011    assert( b.apCell[j]!=0 );
62012    pCell = b.apCell[j];
62013    sz = b.szCell[j] + leafCorrection;
62014    pTemp = &aOvflSpace[iOvflSpace];
62015    if( !pNew->leaf ){
62016      memcpy(&pNew->aData[8], pCell, 4);
62017    }else if( leafData ){
62018      /* If the tree is a leaf-data tree, and the siblings are leaves,
62019      ** then there is no divider cell in b.apCell[]. Instead, the divider
62020      ** cell consists of the integer key for the right-most cell of
62021      ** the sibling-page assembled above only.
62022      */
62023      CellInfo info;
62024      j--;
62025      pNew->xParseCell(pNew, b.apCell[j], &info);
62026      pCell = pTemp;
62027      sz = 4 + putVarint(&pCell[4], info.nKey);
62028      pTemp = 0;
62029    }else{
62030      pCell -= 4;
62031      /* Obscure case for non-leaf-data trees: If the cell at pCell was
62032      ** previously stored on a leaf node, and its reported size was 4
62033      ** bytes, then it may actually be smaller than this
62034      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
62035      ** any cell). But it is important to pass the correct size to
62036      ** insertCell(), so reparse the cell now.
62037      **
62038      ** Note that this can never happen in an SQLite data file, as all
62039      ** cells are at least 4 bytes. It only happens in b-trees used
62040      ** to evaluate "IN (SELECT ...)" and similar clauses.
62041      */
62042      if( b.szCell[j]==4 ){
62043        assert(leafCorrection==4);
62044        sz = pParent->xCellSize(pParent, pCell);
62045      }
62046    }
62047    iOvflSpace += sz;
62048    assert( sz<=pBt->maxLocal+23 );
62049    assert( iOvflSpace <= (int)pBt->pageSize );
62050    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
62051    if( rc!=SQLITE_OK ) goto balance_cleanup;
62052    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
62053  }
62054
62055  /* Now update the actual sibling pages. The order in which they are updated
62056  ** is important, as this code needs to avoid disrupting any page from which
62057  ** cells may still to be read. In practice, this means:
62058  **
62059  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
62060  **      then it is not safe to update page apNew[iPg] until after
62061  **      the left-hand sibling apNew[iPg-1] has been updated.
62062  **
62063  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
62064  **      then it is not safe to update page apNew[iPg] until after
62065  **      the right-hand sibling apNew[iPg+1] has been updated.
62066  **
62067  ** If neither of the above apply, the page is safe to update.
62068  **
62069  ** The iPg value in the following loop starts at nNew-1 goes down
62070  ** to 0, then back up to nNew-1 again, thus making two passes over
62071  ** the pages.  On the initial downward pass, only condition (1) above
62072  ** needs to be tested because (2) will always be true from the previous
62073  ** step.  On the upward pass, both conditions are always true, so the
62074  ** upwards pass simply processes pages that were missed on the downward
62075  ** pass.
62076  */
62077  for(i=1-nNew; i<nNew; i++){
62078    int iPg = i<0 ? -i : i;
62079    assert( iPg>=0 && iPg<nNew );
62080    if( abDone[iPg] ) continue;         /* Skip pages already processed */
62081    if( i>=0                            /* On the upwards pass, or... */
62082     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
62083    ){
62084      int iNew;
62085      int iOld;
62086      int nNewCell;
62087
62088      /* Verify condition (1):  If cells are moving left, update iPg
62089      ** only after iPg-1 has already been updated. */
62090      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
62091
62092      /* Verify condition (2):  If cells are moving right, update iPg
62093      ** only after iPg+1 has already been updated. */
62094      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
62095
62096      if( iPg==0 ){
62097        iNew = iOld = 0;
62098        nNewCell = cntNew[0];
62099      }else{
62100        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
62101        iNew = cntNew[iPg-1] + !leafData;
62102        nNewCell = cntNew[iPg] - iNew;
62103      }
62104
62105      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
62106      if( rc ) goto balance_cleanup;
62107      abDone[iPg]++;
62108      apNew[iPg]->nFree = usableSpace-szNew[iPg];
62109      assert( apNew[iPg]->nOverflow==0 );
62110      assert( apNew[iPg]->nCell==nNewCell );
62111    }
62112  }
62113
62114  /* All pages have been processed exactly once */
62115  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
62116
62117  assert( nOld>0 );
62118  assert( nNew>0 );
62119
62120  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
62121    /* The root page of the b-tree now contains no cells. The only sibling
62122    ** page is the right-child of the parent. Copy the contents of the
62123    ** child page into the parent, decreasing the overall height of the
62124    ** b-tree structure by one. This is described as the "balance-shallower"
62125    ** sub-algorithm in some documentation.
62126    **
62127    ** If this is an auto-vacuum database, the call to copyNodeContent()
62128    ** sets all pointer-map entries corresponding to database image pages
62129    ** for which the pointer is stored within the content being copied.
62130    **
62131    ** It is critical that the child page be defragmented before being
62132    ** copied into the parent, because if the parent is page 1 then it will
62133    ** by smaller than the child due to the database header, and so all the
62134    ** free space needs to be up front.
62135    */
62136    assert( nNew==1 || CORRUPT_DB );
62137    rc = defragmentPage(apNew[0]);
62138    testcase( rc!=SQLITE_OK );
62139    assert( apNew[0]->nFree ==
62140        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
62141      || rc!=SQLITE_OK
62142    );
62143    copyNodeContent(apNew[0], pParent, &rc);
62144    freePage(apNew[0], &rc);
62145  }else if( ISAUTOVACUUM && !leafCorrection ){
62146    /* Fix the pointer map entries associated with the right-child of each
62147    ** sibling page. All other pointer map entries have already been taken
62148    ** care of.  */
62149    for(i=0; i<nNew; i++){
62150      u32 key = get4byte(&apNew[i]->aData[8]);
62151      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
62152    }
62153  }
62154
62155  assert( pParent->isInit );
62156  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
62157          nOld, nNew, b.nCell));
62158
62159  /* Free any old pages that were not reused as new pages.
62160  */
62161  for(i=nNew; i<nOld; i++){
62162    freePage(apOld[i], &rc);
62163  }
62164
62165#if 0
62166  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
62167    /* The ptrmapCheckPages() contains assert() statements that verify that
62168    ** all pointer map pages are set correctly. This is helpful while
62169    ** debugging. This is usually disabled because a corrupt database may
62170    ** cause an assert() statement to fail.  */
62171    ptrmapCheckPages(apNew, nNew);
62172    ptrmapCheckPages(&pParent, 1);
62173  }
62174#endif
62175
62176  /*
62177  ** Cleanup before returning.
62178  */
62179balance_cleanup:
62180  sqlite3ScratchFree(b.apCell);
62181  for(i=0; i<nOld; i++){
62182    releasePage(apOld[i]);
62183  }
62184  for(i=0; i<nNew; i++){
62185    releasePage(apNew[i]);
62186  }
62187
62188  return rc;
62189}
62190#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
62191#pragma optimize("", on)
62192#endif
62193
62194
62195/*
62196** This function is called when the root page of a b-tree structure is
62197** overfull (has one or more overflow pages).
62198**
62199** A new child page is allocated and the contents of the current root
62200** page, including overflow cells, are copied into the child. The root
62201** page is then overwritten to make it an empty page with the right-child
62202** pointer pointing to the new page.
62203**
62204** Before returning, all pointer-map entries corresponding to pages
62205** that the new child-page now contains pointers to are updated. The
62206** entry corresponding to the new right-child pointer of the root
62207** page is also updated.
62208**
62209** If successful, *ppChild is set to contain a reference to the child
62210** page and SQLITE_OK is returned. In this case the caller is required
62211** to call releasePage() on *ppChild exactly once. If an error occurs,
62212** an error code is returned and *ppChild is set to 0.
62213*/
62214static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
62215  int rc;                        /* Return value from subprocedures */
62216  MemPage *pChild = 0;           /* Pointer to a new child page */
62217  Pgno pgnoChild = 0;            /* Page number of the new child page */
62218  BtShared *pBt = pRoot->pBt;    /* The BTree */
62219
62220  assert( pRoot->nOverflow>0 );
62221  assert( sqlite3_mutex_held(pBt->mutex) );
62222
62223  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
62224  ** page that will become the new right-child of pPage. Copy the contents
62225  ** of the node stored on pRoot into the new child page.
62226  */
62227  rc = sqlite3PagerWrite(pRoot->pDbPage);
62228  if( rc==SQLITE_OK ){
62229    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
62230    copyNodeContent(pRoot, pChild, &rc);
62231    if( ISAUTOVACUUM ){
62232      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
62233    }
62234  }
62235  if( rc ){
62236    *ppChild = 0;
62237    releasePage(pChild);
62238    return rc;
62239  }
62240  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
62241  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
62242  assert( pChild->nCell==pRoot->nCell );
62243
62244  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
62245
62246  /* Copy the overflow cells from pRoot to pChild */
62247  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
62248         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
62249  memcpy(pChild->apOvfl, pRoot->apOvfl,
62250         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
62251  pChild->nOverflow = pRoot->nOverflow;
62252
62253  /* Zero the contents of pRoot. Then install pChild as the right-child. */
62254  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
62255  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
62256
62257  *ppChild = pChild;
62258  return SQLITE_OK;
62259}
62260
62261/*
62262** The page that pCur currently points to has just been modified in
62263** some way. This function figures out if this modification means the
62264** tree needs to be balanced, and if so calls the appropriate balancing
62265** routine. Balancing routines are:
62266**
62267**   balance_quick()
62268**   balance_deeper()
62269**   balance_nonroot()
62270*/
62271static int balance(BtCursor *pCur){
62272  int rc = SQLITE_OK;
62273  const int nMin = pCur->pBt->usableSize * 2 / 3;
62274  u8 aBalanceQuickSpace[13];
62275  u8 *pFree = 0;
62276
62277  TESTONLY( int balance_quick_called = 0 );
62278  TESTONLY( int balance_deeper_called = 0 );
62279
62280  do {
62281    int iPage = pCur->iPage;
62282    MemPage *pPage = pCur->apPage[iPage];
62283
62284    if( iPage==0 ){
62285      if( pPage->nOverflow ){
62286        /* The root page of the b-tree is overfull. In this case call the
62287        ** balance_deeper() function to create a new child for the root-page
62288        ** and copy the current contents of the root-page to it. The
62289        ** next iteration of the do-loop will balance the child page.
62290        */
62291        assert( (balance_deeper_called++)==0 );
62292        rc = balance_deeper(pPage, &pCur->apPage[1]);
62293        if( rc==SQLITE_OK ){
62294          pCur->iPage = 1;
62295          pCur->aiIdx[0] = 0;
62296          pCur->aiIdx[1] = 0;
62297          assert( pCur->apPage[1]->nOverflow );
62298        }
62299      }else{
62300        break;
62301      }
62302    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
62303      break;
62304    }else{
62305      MemPage * const pParent = pCur->apPage[iPage-1];
62306      int const iIdx = pCur->aiIdx[iPage-1];
62307
62308      rc = sqlite3PagerWrite(pParent->pDbPage);
62309      if( rc==SQLITE_OK ){
62310#ifndef SQLITE_OMIT_QUICKBALANCE
62311        if( pPage->intKeyLeaf
62312         && pPage->nOverflow==1
62313         && pPage->aiOvfl[0]==pPage->nCell
62314         && pParent->pgno!=1
62315         && pParent->nCell==iIdx
62316        ){
62317          /* Call balance_quick() to create a new sibling of pPage on which
62318          ** to store the overflow cell. balance_quick() inserts a new cell
62319          ** into pParent, which may cause pParent overflow. If this
62320          ** happens, the next iteration of the do-loop will balance pParent
62321          ** use either balance_nonroot() or balance_deeper(). Until this
62322          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
62323          ** buffer.
62324          **
62325          ** The purpose of the following assert() is to check that only a
62326          ** single call to balance_quick() is made for each call to this
62327          ** function. If this were not verified, a subtle bug involving reuse
62328          ** of the aBalanceQuickSpace[] might sneak in.
62329          */
62330          assert( (balance_quick_called++)==0 );
62331          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
62332        }else
62333#endif
62334        {
62335          /* In this case, call balance_nonroot() to redistribute cells
62336          ** between pPage and up to 2 of its sibling pages. This involves
62337          ** modifying the contents of pParent, which may cause pParent to
62338          ** become overfull or underfull. The next iteration of the do-loop
62339          ** will balance the parent page to correct this.
62340          **
62341          ** If the parent page becomes overfull, the overflow cell or cells
62342          ** are stored in the pSpace buffer allocated immediately below.
62343          ** A subsequent iteration of the do-loop will deal with this by
62344          ** calling balance_nonroot() (balance_deeper() may be called first,
62345          ** but it doesn't deal with overflow cells - just moves them to a
62346          ** different page). Once this subsequent call to balance_nonroot()
62347          ** has completed, it is safe to release the pSpace buffer used by
62348          ** the previous call, as the overflow cell data will have been
62349          ** copied either into the body of a database page or into the new
62350          ** pSpace buffer passed to the latter call to balance_nonroot().
62351          */
62352          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
62353          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
62354                               pCur->hints&BTREE_BULKLOAD);
62355          if( pFree ){
62356            /* If pFree is not NULL, it points to the pSpace buffer used
62357            ** by a previous call to balance_nonroot(). Its contents are
62358            ** now stored either on real database pages or within the
62359            ** new pSpace buffer, so it may be safely freed here. */
62360            sqlite3PageFree(pFree);
62361          }
62362
62363          /* The pSpace buffer will be freed after the next call to
62364          ** balance_nonroot(), or just before this function returns, whichever
62365          ** comes first. */
62366          pFree = pSpace;
62367        }
62368      }
62369
62370      pPage->nOverflow = 0;
62371
62372      /* The next iteration of the do-loop balances the parent page. */
62373      releasePage(pPage);
62374      pCur->iPage--;
62375      assert( pCur->iPage>=0 );
62376    }
62377  }while( rc==SQLITE_OK );
62378
62379  if( pFree ){
62380    sqlite3PageFree(pFree);
62381  }
62382  return rc;
62383}
62384
62385
62386/*
62387** Insert a new record into the BTree.  The key is given by (pKey,nKey)
62388** and the data is given by (pData,nData).  The cursor is used only to
62389** define what table the record should be inserted into.  The cursor
62390** is left pointing at a random location.
62391**
62392** For an INTKEY table, only the nKey value of the key is used.  pKey is
62393** ignored.  For a ZERODATA table, the pData and nData are both ignored.
62394**
62395** If the seekResult parameter is non-zero, then a successful call to
62396** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
62397** been performed. seekResult is the search result returned (a negative
62398** number if pCur points at an entry that is smaller than (pKey, nKey), or
62399** a positive value if pCur points at an entry that is larger than
62400** (pKey, nKey)).
62401**
62402** If the seekResult parameter is non-zero, then the caller guarantees that
62403** cursor pCur is pointing at the existing copy of a row that is to be
62404** overwritten.  If the seekResult parameter is 0, then cursor pCur may
62405** point to any entry or to no entry at all and so this function has to seek
62406** the cursor before the new key can be inserted.
62407*/
62408SQLITE_PRIVATE int sqlite3BtreeInsert(
62409  BtCursor *pCur,                /* Insert data into the table of this cursor */
62410  const void *pKey, i64 nKey,    /* The key of the new record */
62411  const void *pData, int nData,  /* The data of the new record */
62412  int nZero,                     /* Number of extra 0 bytes to append to data */
62413  int appendBias,                /* True if this is likely an append */
62414  int seekResult                 /* Result of prior MovetoUnpacked() call */
62415){
62416  int rc;
62417  int loc = seekResult;          /* -1: before desired location  +1: after */
62418  int szNew = 0;
62419  int idx;
62420  MemPage *pPage;
62421  Btree *p = pCur->pBtree;
62422  BtShared *pBt = p->pBt;
62423  unsigned char *oldCell;
62424  unsigned char *newCell = 0;
62425
62426  if( pCur->eState==CURSOR_FAULT ){
62427    assert( pCur->skipNext!=SQLITE_OK );
62428    return pCur->skipNext;
62429  }
62430
62431  assert( cursorHoldsMutex(pCur) );
62432  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
62433              && pBt->inTransaction==TRANS_WRITE
62434              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
62435  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
62436
62437  /* Assert that the caller has been consistent. If this cursor was opened
62438  ** expecting an index b-tree, then the caller should be inserting blob
62439  ** keys with no associated data. If the cursor was opened expecting an
62440  ** intkey table, the caller should be inserting integer keys with a
62441  ** blob of associated data.  */
62442  assert( (pKey==0)==(pCur->pKeyInfo==0) );
62443
62444  /* Save the positions of any other cursors open on this table.
62445  **
62446  ** In some cases, the call to btreeMoveto() below is a no-op. For
62447  ** example, when inserting data into a table with auto-generated integer
62448  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
62449  ** integer key to use. It then calls this function to actually insert the
62450  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
62451  ** that the cursor is already where it needs to be and returns without
62452  ** doing any work. To avoid thwarting these optimizations, it is important
62453  ** not to clear the cursor here.
62454  */
62455  if( pCur->curFlags & BTCF_Multiple ){
62456    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
62457    if( rc ) return rc;
62458  }
62459
62460  if( pCur->pKeyInfo==0 ){
62461    assert( pKey==0 );
62462    /* If this is an insert into a table b-tree, invalidate any incrblob
62463    ** cursors open on the row being replaced */
62464    invalidateIncrblobCursors(p, nKey, 0);
62465
62466    /* If the cursor is currently on the last row and we are appending a
62467    ** new row onto the end, set the "loc" to avoid an unnecessary
62468    ** btreeMoveto() call */
62469    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
62470      && pCur->info.nKey==nKey-1 ){
62471       loc = -1;
62472    }else if( loc==0 ){
62473      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
62474      if( rc ) return rc;
62475    }
62476  }else if( loc==0 ){
62477    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
62478    if( rc ) return rc;
62479  }
62480  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
62481
62482  pPage = pCur->apPage[pCur->iPage];
62483  assert( pPage->intKey || nKey>=0 );
62484  assert( pPage->leaf || !pPage->intKey );
62485
62486  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
62487          pCur->pgnoRoot, nKey, nData, pPage->pgno,
62488          loc==0 ? "overwrite" : "new entry"));
62489  assert( pPage->isInit );
62490  newCell = pBt->pTmpSpace;
62491  assert( newCell!=0 );
62492  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
62493  if( rc ) goto end_insert;
62494  assert( szNew==pPage->xCellSize(pPage, newCell) );
62495  assert( szNew <= MX_CELL_SIZE(pBt) );
62496  idx = pCur->aiIdx[pCur->iPage];
62497  if( loc==0 ){
62498    u16 szOld;
62499    assert( idx<pPage->nCell );
62500    rc = sqlite3PagerWrite(pPage->pDbPage);
62501    if( rc ){
62502      goto end_insert;
62503    }
62504    oldCell = findCell(pPage, idx);
62505    if( !pPage->leaf ){
62506      memcpy(newCell, oldCell, 4);
62507    }
62508    rc = clearCell(pPage, oldCell, &szOld);
62509    dropCell(pPage, idx, szOld, &rc);
62510    if( rc ) goto end_insert;
62511  }else if( loc<0 && pPage->nCell>0 ){
62512    assert( pPage->leaf );
62513    idx = ++pCur->aiIdx[pCur->iPage];
62514  }else{
62515    assert( pPage->leaf );
62516  }
62517  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
62518  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
62519
62520  /* If no error has occurred and pPage has an overflow cell, call balance()
62521  ** to redistribute the cells within the tree. Since balance() may move
62522  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
62523  ** variables.
62524  **
62525  ** Previous versions of SQLite called moveToRoot() to move the cursor
62526  ** back to the root page as balance() used to invalidate the contents
62527  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
62528  ** set the cursor state to "invalid". This makes common insert operations
62529  ** slightly faster.
62530  **
62531  ** There is a subtle but important optimization here too. When inserting
62532  ** multiple records into an intkey b-tree using a single cursor (as can
62533  ** happen while processing an "INSERT INTO ... SELECT" statement), it
62534  ** is advantageous to leave the cursor pointing to the last entry in
62535  ** the b-tree if possible. If the cursor is left pointing to the last
62536  ** entry in the table, and the next row inserted has an integer key
62537  ** larger than the largest existing key, it is possible to insert the
62538  ** row without seeking the cursor. This can be a big performance boost.
62539  */
62540  pCur->info.nSize = 0;
62541  if( rc==SQLITE_OK && pPage->nOverflow ){
62542    pCur->curFlags &= ~(BTCF_ValidNKey);
62543    rc = balance(pCur);
62544
62545    /* Must make sure nOverflow is reset to zero even if the balance()
62546    ** fails. Internal data structure corruption will result otherwise.
62547    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
62548    ** from trying to save the current position of the cursor.  */
62549    pCur->apPage[pCur->iPage]->nOverflow = 0;
62550    pCur->eState = CURSOR_INVALID;
62551  }
62552  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
62553
62554end_insert:
62555  return rc;
62556}
62557
62558/*
62559** Delete the entry that the cursor is pointing to.
62560**
62561** If the second parameter is zero, then the cursor is left pointing at an
62562** arbitrary location after the delete. If it is non-zero, then the cursor
62563** is left in a state such that the next call to BtreeNext() or BtreePrev()
62564** moves it to the same row as it would if the call to BtreeDelete() had
62565** been omitted.
62566*/
62567SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, int bPreserve){
62568  Btree *p = pCur->pBtree;
62569  BtShared *pBt = p->pBt;
62570  int rc;                              /* Return code */
62571  MemPage *pPage;                      /* Page to delete cell from */
62572  unsigned char *pCell;                /* Pointer to cell to delete */
62573  int iCellIdx;                        /* Index of cell to delete */
62574  int iCellDepth;                      /* Depth of node containing pCell */
62575  u16 szCell;                          /* Size of the cell being deleted */
62576  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
62577
62578  assert( cursorHoldsMutex(pCur) );
62579  assert( pBt->inTransaction==TRANS_WRITE );
62580  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62581  assert( pCur->curFlags & BTCF_WriteFlag );
62582  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
62583  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
62584  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62585  assert( pCur->eState==CURSOR_VALID );
62586
62587  iCellDepth = pCur->iPage;
62588  iCellIdx = pCur->aiIdx[iCellDepth];
62589  pPage = pCur->apPage[iCellDepth];
62590  pCell = findCell(pPage, iCellIdx);
62591
62592  /* If the page containing the entry to delete is not a leaf page, move
62593  ** the cursor to the largest entry in the tree that is smaller than
62594  ** the entry being deleted. This cell will replace the cell being deleted
62595  ** from the internal node. The 'previous' entry is used for this instead
62596  ** of the 'next' entry, as the previous entry is always a part of the
62597  ** sub-tree headed by the child page of the cell being deleted. This makes
62598  ** balancing the tree following the delete operation easier.  */
62599  if( !pPage->leaf ){
62600    int notUsed = 0;
62601    rc = sqlite3BtreePrevious(pCur, &notUsed);
62602    if( rc ) return rc;
62603  }
62604
62605  /* Save the positions of any other cursors open on this table before
62606  ** making any modifications.  */
62607  if( pCur->curFlags & BTCF_Multiple ){
62608    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
62609    if( rc ) return rc;
62610  }
62611
62612  /* If this is a delete operation to remove a row from a table b-tree,
62613  ** invalidate any incrblob cursors open on the row being deleted.  */
62614  if( pCur->pKeyInfo==0 ){
62615    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
62616  }
62617
62618  /* If the bPreserve flag is set to true, then the cursor position must
62619  ** be preserved following this delete operation. If the current delete
62620  ** will cause a b-tree rebalance, then this is done by saving the cursor
62621  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
62622  ** returning.
62623  **
62624  ** Or, if the current delete will not cause a rebalance, then the cursor
62625  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
62626  ** before or after the deleted entry. In this case set bSkipnext to true.  */
62627  if( bPreserve ){
62628    if( !pPage->leaf
62629     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
62630    ){
62631      /* A b-tree rebalance will be required after deleting this entry.
62632      ** Save the cursor key.  */
62633      rc = saveCursorKey(pCur);
62634      if( rc ) return rc;
62635    }else{
62636      bSkipnext = 1;
62637    }
62638  }
62639
62640  /* Make the page containing the entry to be deleted writable. Then free any
62641  ** overflow pages associated with the entry and finally remove the cell
62642  ** itself from within the page.  */
62643  rc = sqlite3PagerWrite(pPage->pDbPage);
62644  if( rc ) return rc;
62645  rc = clearCell(pPage, pCell, &szCell);
62646  dropCell(pPage, iCellIdx, szCell, &rc);
62647  if( rc ) return rc;
62648
62649  /* If the cell deleted was not located on a leaf page, then the cursor
62650  ** is currently pointing to the largest entry in the sub-tree headed
62651  ** by the child-page of the cell that was just deleted from an internal
62652  ** node. The cell from the leaf node needs to be moved to the internal
62653  ** node to replace the deleted cell.  */
62654  if( !pPage->leaf ){
62655    MemPage *pLeaf = pCur->apPage[pCur->iPage];
62656    int nCell;
62657    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
62658    unsigned char *pTmp;
62659
62660    pCell = findCell(pLeaf, pLeaf->nCell-1);
62661    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
62662    nCell = pLeaf->xCellSize(pLeaf, pCell);
62663    assert( MX_CELL_SIZE(pBt) >= nCell );
62664    pTmp = pBt->pTmpSpace;
62665    assert( pTmp!=0 );
62666    rc = sqlite3PagerWrite(pLeaf->pDbPage);
62667    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
62668    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
62669    if( rc ) return rc;
62670  }
62671
62672  /* Balance the tree. If the entry deleted was located on a leaf page,
62673  ** then the cursor still points to that page. In this case the first
62674  ** call to balance() repairs the tree, and the if(...) condition is
62675  ** never true.
62676  **
62677  ** Otherwise, if the entry deleted was on an internal node page, then
62678  ** pCur is pointing to the leaf page from which a cell was removed to
62679  ** replace the cell deleted from the internal node. This is slightly
62680  ** tricky as the leaf node may be underfull, and the internal node may
62681  ** be either under or overfull. In this case run the balancing algorithm
62682  ** on the leaf node first. If the balance proceeds far enough up the
62683  ** tree that we can be sure that any problem in the internal node has
62684  ** been corrected, so be it. Otherwise, after balancing the leaf node,
62685  ** walk the cursor up the tree to the internal node and balance it as
62686  ** well.  */
62687  rc = balance(pCur);
62688  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
62689    while( pCur->iPage>iCellDepth ){
62690      releasePage(pCur->apPage[pCur->iPage--]);
62691    }
62692    rc = balance(pCur);
62693  }
62694
62695  if( rc==SQLITE_OK ){
62696    if( bSkipnext ){
62697      assert( bPreserve && pCur->iPage==iCellDepth );
62698      assert( pPage==pCur->apPage[pCur->iPage] );
62699      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
62700      pCur->eState = CURSOR_SKIPNEXT;
62701      if( iCellIdx>=pPage->nCell ){
62702        pCur->skipNext = -1;
62703        pCur->aiIdx[iCellDepth] = pPage->nCell-1;
62704      }else{
62705        pCur->skipNext = 1;
62706      }
62707    }else{
62708      rc = moveToRoot(pCur);
62709      if( bPreserve ){
62710        pCur->eState = CURSOR_REQUIRESEEK;
62711      }
62712    }
62713  }
62714  return rc;
62715}
62716
62717/*
62718** Create a new BTree table.  Write into *piTable the page
62719** number for the root page of the new table.
62720**
62721** The type of type is determined by the flags parameter.  Only the
62722** following values of flags are currently in use.  Other values for
62723** flags might not work:
62724**
62725**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
62726**     BTREE_ZERODATA                  Used for SQL indices
62727*/
62728static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
62729  BtShared *pBt = p->pBt;
62730  MemPage *pRoot;
62731  Pgno pgnoRoot;
62732  int rc;
62733  int ptfFlags;          /* Page-type flage for the root page of new table */
62734
62735  assert( sqlite3BtreeHoldsMutex(p) );
62736  assert( pBt->inTransaction==TRANS_WRITE );
62737  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62738
62739#ifdef SQLITE_OMIT_AUTOVACUUM
62740  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
62741  if( rc ){
62742    return rc;
62743  }
62744#else
62745  if( pBt->autoVacuum ){
62746    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
62747    MemPage *pPageMove; /* The page to move to. */
62748
62749    /* Creating a new table may probably require moving an existing database
62750    ** to make room for the new tables root page. In case this page turns
62751    ** out to be an overflow page, delete all overflow page-map caches
62752    ** held by open cursors.
62753    */
62754    invalidateAllOverflowCache(pBt);
62755
62756    /* Read the value of meta[3] from the database to determine where the
62757    ** root page of the new table should go. meta[3] is the largest root-page
62758    ** created so far, so the new root-page is (meta[3]+1).
62759    */
62760    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
62761    pgnoRoot++;
62762
62763    /* The new root-page may not be allocated on a pointer-map page, or the
62764    ** PENDING_BYTE page.
62765    */
62766    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
62767        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
62768      pgnoRoot++;
62769    }
62770    assert( pgnoRoot>=3 || CORRUPT_DB );
62771    testcase( pgnoRoot<3 );
62772
62773    /* Allocate a page. The page that currently resides at pgnoRoot will
62774    ** be moved to the allocated page (unless the allocated page happens
62775    ** to reside at pgnoRoot).
62776    */
62777    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
62778    if( rc!=SQLITE_OK ){
62779      return rc;
62780    }
62781
62782    if( pgnoMove!=pgnoRoot ){
62783      /* pgnoRoot is the page that will be used for the root-page of
62784      ** the new table (assuming an error did not occur). But we were
62785      ** allocated pgnoMove. If required (i.e. if it was not allocated
62786      ** by extending the file), the current page at position pgnoMove
62787      ** is already journaled.
62788      */
62789      u8 eType = 0;
62790      Pgno iPtrPage = 0;
62791
62792      /* Save the positions of any open cursors. This is required in
62793      ** case they are holding a reference to an xFetch reference
62794      ** corresponding to page pgnoRoot.  */
62795      rc = saveAllCursors(pBt, 0, 0);
62796      releasePage(pPageMove);
62797      if( rc!=SQLITE_OK ){
62798        return rc;
62799      }
62800
62801      /* Move the page currently at pgnoRoot to pgnoMove. */
62802      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
62803      if( rc!=SQLITE_OK ){
62804        return rc;
62805      }
62806      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
62807      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
62808        rc = SQLITE_CORRUPT_BKPT;
62809      }
62810      if( rc!=SQLITE_OK ){
62811        releasePage(pRoot);
62812        return rc;
62813      }
62814      assert( eType!=PTRMAP_ROOTPAGE );
62815      assert( eType!=PTRMAP_FREEPAGE );
62816      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
62817      releasePage(pRoot);
62818
62819      /* Obtain the page at pgnoRoot */
62820      if( rc!=SQLITE_OK ){
62821        return rc;
62822      }
62823      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
62824      if( rc!=SQLITE_OK ){
62825        return rc;
62826      }
62827      rc = sqlite3PagerWrite(pRoot->pDbPage);
62828      if( rc!=SQLITE_OK ){
62829        releasePage(pRoot);
62830        return rc;
62831      }
62832    }else{
62833      pRoot = pPageMove;
62834    }
62835
62836    /* Update the pointer-map and meta-data with the new root-page number. */
62837    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
62838    if( rc ){
62839      releasePage(pRoot);
62840      return rc;
62841    }
62842
62843    /* When the new root page was allocated, page 1 was made writable in
62844    ** order either to increase the database filesize, or to decrement the
62845    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
62846    */
62847    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
62848    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
62849    if( NEVER(rc) ){
62850      releasePage(pRoot);
62851      return rc;
62852    }
62853
62854  }else{
62855    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
62856    if( rc ) return rc;
62857  }
62858#endif
62859  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
62860  if( createTabFlags & BTREE_INTKEY ){
62861    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
62862  }else{
62863    ptfFlags = PTF_ZERODATA | PTF_LEAF;
62864  }
62865  zeroPage(pRoot, ptfFlags);
62866  sqlite3PagerUnref(pRoot->pDbPage);
62867  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
62868  *piTable = (int)pgnoRoot;
62869  return SQLITE_OK;
62870}
62871SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
62872  int rc;
62873  sqlite3BtreeEnter(p);
62874  rc = btreeCreateTable(p, piTable, flags);
62875  sqlite3BtreeLeave(p);
62876  return rc;
62877}
62878
62879/*
62880** Erase the given database page and all its children.  Return
62881** the page to the freelist.
62882*/
62883static int clearDatabasePage(
62884  BtShared *pBt,           /* The BTree that contains the table */
62885  Pgno pgno,               /* Page number to clear */
62886  int freePageFlag,        /* Deallocate page if true */
62887  int *pnChange            /* Add number of Cells freed to this counter */
62888){
62889  MemPage *pPage;
62890  int rc;
62891  unsigned char *pCell;
62892  int i;
62893  int hdr;
62894  u16 szCell;
62895
62896  assert( sqlite3_mutex_held(pBt->mutex) );
62897  if( pgno>btreePagecount(pBt) ){
62898    return SQLITE_CORRUPT_BKPT;
62899  }
62900  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
62901  if( rc ) return rc;
62902  if( pPage->bBusy ){
62903    rc = SQLITE_CORRUPT_BKPT;
62904    goto cleardatabasepage_out;
62905  }
62906  pPage->bBusy = 1;
62907  hdr = pPage->hdrOffset;
62908  for(i=0; i<pPage->nCell; i++){
62909    pCell = findCell(pPage, i);
62910    if( !pPage->leaf ){
62911      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
62912      if( rc ) goto cleardatabasepage_out;
62913    }
62914    rc = clearCell(pPage, pCell, &szCell);
62915    if( rc ) goto cleardatabasepage_out;
62916  }
62917  if( !pPage->leaf ){
62918    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
62919    if( rc ) goto cleardatabasepage_out;
62920  }else if( pnChange ){
62921    assert( pPage->intKey || CORRUPT_DB );
62922    testcase( !pPage->intKey );
62923    *pnChange += pPage->nCell;
62924  }
62925  if( freePageFlag ){
62926    freePage(pPage, &rc);
62927  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
62928    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
62929  }
62930
62931cleardatabasepage_out:
62932  pPage->bBusy = 0;
62933  releasePage(pPage);
62934  return rc;
62935}
62936
62937/*
62938** Delete all information from a single table in the database.  iTable is
62939** the page number of the root of the table.  After this routine returns,
62940** the root page is empty, but still exists.
62941**
62942** This routine will fail with SQLITE_LOCKED if there are any open
62943** read cursors on the table.  Open write cursors are moved to the
62944** root of the table.
62945**
62946** If pnChange is not NULL, then table iTable must be an intkey table. The
62947** integer value pointed to by pnChange is incremented by the number of
62948** entries in the table.
62949*/
62950SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
62951  int rc;
62952  BtShared *pBt = p->pBt;
62953  sqlite3BtreeEnter(p);
62954  assert( p->inTrans==TRANS_WRITE );
62955
62956  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
62957
62958  if( SQLITE_OK==rc ){
62959    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
62960    ** is the root of a table b-tree - if it is not, the following call is
62961    ** a no-op).  */
62962    invalidateIncrblobCursors(p, 0, 1);
62963    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
62964  }
62965  sqlite3BtreeLeave(p);
62966  return rc;
62967}
62968
62969/*
62970** Delete all information from the single table that pCur is open on.
62971**
62972** This routine only work for pCur on an ephemeral table.
62973*/
62974SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
62975  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
62976}
62977
62978/*
62979** Erase all information in a table and add the root of the table to
62980** the freelist.  Except, the root of the principle table (the one on
62981** page 1) is never added to the freelist.
62982**
62983** This routine will fail with SQLITE_LOCKED if there are any open
62984** cursors on the table.
62985**
62986** If AUTOVACUUM is enabled and the page at iTable is not the last
62987** root page in the database file, then the last root page
62988** in the database file is moved into the slot formerly occupied by
62989** iTable and that last slot formerly occupied by the last root page
62990** is added to the freelist instead of iTable.  In this say, all
62991** root pages are kept at the beginning of the database file, which
62992** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
62993** page number that used to be the last root page in the file before
62994** the move.  If no page gets moved, *piMoved is set to 0.
62995** The last root page is recorded in meta[3] and the value of
62996** meta[3] is updated by this procedure.
62997*/
62998static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
62999  int rc;
63000  MemPage *pPage = 0;
63001  BtShared *pBt = p->pBt;
63002
63003  assert( sqlite3BtreeHoldsMutex(p) );
63004  assert( p->inTrans==TRANS_WRITE );
63005
63006  /* It is illegal to drop a table if any cursors are open on the
63007  ** database. This is because in auto-vacuum mode the backend may
63008  ** need to move another root-page to fill a gap left by the deleted
63009  ** root page. If an open cursor was using this page a problem would
63010  ** occur.
63011  **
63012  ** This error is caught long before control reaches this point.
63013  */
63014  if( NEVER(pBt->pCursor) ){
63015    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
63016    return SQLITE_LOCKED_SHAREDCACHE;
63017  }
63018
63019  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
63020  if( rc ) return rc;
63021  rc = sqlite3BtreeClearTable(p, iTable, 0);
63022  if( rc ){
63023    releasePage(pPage);
63024    return rc;
63025  }
63026
63027  *piMoved = 0;
63028
63029  if( iTable>1 ){
63030#ifdef SQLITE_OMIT_AUTOVACUUM
63031    freePage(pPage, &rc);
63032    releasePage(pPage);
63033#else
63034    if( pBt->autoVacuum ){
63035      Pgno maxRootPgno;
63036      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
63037
63038      if( iTable==maxRootPgno ){
63039        /* If the table being dropped is the table with the largest root-page
63040        ** number in the database, put the root page on the free list.
63041        */
63042        freePage(pPage, &rc);
63043        releasePage(pPage);
63044        if( rc!=SQLITE_OK ){
63045          return rc;
63046        }
63047      }else{
63048        /* The table being dropped does not have the largest root-page
63049        ** number in the database. So move the page that does into the
63050        ** gap left by the deleted root-page.
63051        */
63052        MemPage *pMove;
63053        releasePage(pPage);
63054        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
63055        if( rc!=SQLITE_OK ){
63056          return rc;
63057        }
63058        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
63059        releasePage(pMove);
63060        if( rc!=SQLITE_OK ){
63061          return rc;
63062        }
63063        pMove = 0;
63064        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
63065        freePage(pMove, &rc);
63066        releasePage(pMove);
63067        if( rc!=SQLITE_OK ){
63068          return rc;
63069        }
63070        *piMoved = maxRootPgno;
63071      }
63072
63073      /* Set the new 'max-root-page' value in the database header. This
63074      ** is the old value less one, less one more if that happens to
63075      ** be a root-page number, less one again if that is the
63076      ** PENDING_BYTE_PAGE.
63077      */
63078      maxRootPgno--;
63079      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
63080             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
63081        maxRootPgno--;
63082      }
63083      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
63084
63085      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
63086    }else{
63087      freePage(pPage, &rc);
63088      releasePage(pPage);
63089    }
63090#endif
63091  }else{
63092    /* If sqlite3BtreeDropTable was called on page 1.
63093    ** This really never should happen except in a corrupt
63094    ** database.
63095    */
63096    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
63097    releasePage(pPage);
63098  }
63099  return rc;
63100}
63101SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
63102  int rc;
63103  sqlite3BtreeEnter(p);
63104  rc = btreeDropTable(p, iTable, piMoved);
63105  sqlite3BtreeLeave(p);
63106  return rc;
63107}
63108
63109
63110/*
63111** This function may only be called if the b-tree connection already
63112** has a read or write transaction open on the database.
63113**
63114** Read the meta-information out of a database file.  Meta[0]
63115** is the number of free pages currently in the database.  Meta[1]
63116** through meta[15] are available for use by higher layers.  Meta[0]
63117** is read-only, the others are read/write.
63118**
63119** The schema layer numbers meta values differently.  At the schema
63120** layer (and the SetCookie and ReadCookie opcodes) the number of
63121** free pages is not visible.  So Cookie[0] is the same as Meta[1].
63122**
63123** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
63124** of reading the value out of the header, it instead loads the "DataVersion"
63125** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
63126** database file.  It is a number computed by the pager.  But its access
63127** pattern is the same as header meta values, and so it is convenient to
63128** read it from this routine.
63129*/
63130SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
63131  BtShared *pBt = p->pBt;
63132
63133  sqlite3BtreeEnter(p);
63134  assert( p->inTrans>TRANS_NONE );
63135  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
63136  assert( pBt->pPage1 );
63137  assert( idx>=0 && idx<=15 );
63138
63139  if( idx==BTREE_DATA_VERSION ){
63140    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
63141  }else{
63142    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
63143  }
63144
63145  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
63146  ** database, mark the database as read-only.  */
63147#ifdef SQLITE_OMIT_AUTOVACUUM
63148  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
63149    pBt->btsFlags |= BTS_READ_ONLY;
63150  }
63151#endif
63152
63153  sqlite3BtreeLeave(p);
63154}
63155
63156/*
63157** Write meta-information back into the database.  Meta[0] is
63158** read-only and may not be written.
63159*/
63160SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
63161  BtShared *pBt = p->pBt;
63162  unsigned char *pP1;
63163  int rc;
63164  assert( idx>=1 && idx<=15 );
63165  sqlite3BtreeEnter(p);
63166  assert( p->inTrans==TRANS_WRITE );
63167  assert( pBt->pPage1!=0 );
63168  pP1 = pBt->pPage1->aData;
63169  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63170  if( rc==SQLITE_OK ){
63171    put4byte(&pP1[36 + idx*4], iMeta);
63172#ifndef SQLITE_OMIT_AUTOVACUUM
63173    if( idx==BTREE_INCR_VACUUM ){
63174      assert( pBt->autoVacuum || iMeta==0 );
63175      assert( iMeta==0 || iMeta==1 );
63176      pBt->incrVacuum = (u8)iMeta;
63177    }
63178#endif
63179  }
63180  sqlite3BtreeLeave(p);
63181  return rc;
63182}
63183
63184#ifndef SQLITE_OMIT_BTREECOUNT
63185/*
63186** The first argument, pCur, is a cursor opened on some b-tree. Count the
63187** number of entries in the b-tree and write the result to *pnEntry.
63188**
63189** SQLITE_OK is returned if the operation is successfully executed.
63190** Otherwise, if an error is encountered (i.e. an IO error or database
63191** corruption) an SQLite error code is returned.
63192*/
63193SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
63194  i64 nEntry = 0;                      /* Value to return in *pnEntry */
63195  int rc;                              /* Return code */
63196
63197  if( pCur->pgnoRoot==0 ){
63198    *pnEntry = 0;
63199    return SQLITE_OK;
63200  }
63201  rc = moveToRoot(pCur);
63202
63203  /* Unless an error occurs, the following loop runs one iteration for each
63204  ** page in the B-Tree structure (not including overflow pages).
63205  */
63206  while( rc==SQLITE_OK ){
63207    int iIdx;                          /* Index of child node in parent */
63208    MemPage *pPage;                    /* Current page of the b-tree */
63209
63210    /* If this is a leaf page or the tree is not an int-key tree, then
63211    ** this page contains countable entries. Increment the entry counter
63212    ** accordingly.
63213    */
63214    pPage = pCur->apPage[pCur->iPage];
63215    if( pPage->leaf || !pPage->intKey ){
63216      nEntry += pPage->nCell;
63217    }
63218
63219    /* pPage is a leaf node. This loop navigates the cursor so that it
63220    ** points to the first interior cell that it points to the parent of
63221    ** the next page in the tree that has not yet been visited. The
63222    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
63223    ** of the page, or to the number of cells in the page if the next page
63224    ** to visit is the right-child of its parent.
63225    **
63226    ** If all pages in the tree have been visited, return SQLITE_OK to the
63227    ** caller.
63228    */
63229    if( pPage->leaf ){
63230      do {
63231        if( pCur->iPage==0 ){
63232          /* All pages of the b-tree have been visited. Return successfully. */
63233          *pnEntry = nEntry;
63234          return moveToRoot(pCur);
63235        }
63236        moveToParent(pCur);
63237      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
63238
63239      pCur->aiIdx[pCur->iPage]++;
63240      pPage = pCur->apPage[pCur->iPage];
63241    }
63242
63243    /* Descend to the child node of the cell that the cursor currently
63244    ** points at. This is the right-child if (iIdx==pPage->nCell).
63245    */
63246    iIdx = pCur->aiIdx[pCur->iPage];
63247    if( iIdx==pPage->nCell ){
63248      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63249    }else{
63250      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
63251    }
63252  }
63253
63254  /* An error has occurred. Return an error code. */
63255  return rc;
63256}
63257#endif
63258
63259/*
63260** Return the pager associated with a BTree.  This routine is used for
63261** testing and debugging only.
63262*/
63263SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
63264  return p->pBt->pPager;
63265}
63266
63267#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63268/*
63269** Append a message to the error message string.
63270*/
63271static void checkAppendMsg(
63272  IntegrityCk *pCheck,
63273  const char *zFormat,
63274  ...
63275){
63276  va_list ap;
63277  if( !pCheck->mxErr ) return;
63278  pCheck->mxErr--;
63279  pCheck->nErr++;
63280  va_start(ap, zFormat);
63281  if( pCheck->errMsg.nChar ){
63282    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
63283  }
63284  if( pCheck->zPfx ){
63285    sqlite3XPrintf(&pCheck->errMsg, 0, pCheck->zPfx, pCheck->v1, pCheck->v2);
63286  }
63287  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
63288  va_end(ap);
63289  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
63290    pCheck->mallocFailed = 1;
63291  }
63292}
63293#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63294
63295#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63296
63297/*
63298** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
63299** corresponds to page iPg is already set.
63300*/
63301static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
63302  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
63303  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
63304}
63305
63306/*
63307** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
63308*/
63309static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
63310  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
63311  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
63312}
63313
63314
63315/*
63316** Add 1 to the reference count for page iPage.  If this is the second
63317** reference to the page, add an error message to pCheck->zErrMsg.
63318** Return 1 if there are 2 or more references to the page and 0 if
63319** if this is the first reference to the page.
63320**
63321** Also check that the page number is in bounds.
63322*/
63323static int checkRef(IntegrityCk *pCheck, Pgno iPage){
63324  if( iPage==0 ) return 1;
63325  if( iPage>pCheck->nPage ){
63326    checkAppendMsg(pCheck, "invalid page number %d", iPage);
63327    return 1;
63328  }
63329  if( getPageReferenced(pCheck, iPage) ){
63330    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
63331    return 1;
63332  }
63333  setPageReferenced(pCheck, iPage);
63334  return 0;
63335}
63336
63337#ifndef SQLITE_OMIT_AUTOVACUUM
63338/*
63339** Check that the entry in the pointer-map for page iChild maps to
63340** page iParent, pointer type ptrType. If not, append an error message
63341** to pCheck.
63342*/
63343static void checkPtrmap(
63344  IntegrityCk *pCheck,   /* Integrity check context */
63345  Pgno iChild,           /* Child page number */
63346  u8 eType,              /* Expected pointer map type */
63347  Pgno iParent           /* Expected pointer map parent page number */
63348){
63349  int rc;
63350  u8 ePtrmapType;
63351  Pgno iPtrmapParent;
63352
63353  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
63354  if( rc!=SQLITE_OK ){
63355    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
63356    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
63357    return;
63358  }
63359
63360  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
63361    checkAppendMsg(pCheck,
63362      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
63363      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
63364  }
63365}
63366#endif
63367
63368/*
63369** Check the integrity of the freelist or of an overflow page list.
63370** Verify that the number of pages on the list is N.
63371*/
63372static void checkList(
63373  IntegrityCk *pCheck,  /* Integrity checking context */
63374  int isFreeList,       /* True for a freelist.  False for overflow page list */
63375  int iPage,            /* Page number for first page in the list */
63376  int N                 /* Expected number of pages in the list */
63377){
63378  int i;
63379  int expected = N;
63380  int iFirst = iPage;
63381  while( N-- > 0 && pCheck->mxErr ){
63382    DbPage *pOvflPage;
63383    unsigned char *pOvflData;
63384    if( iPage<1 ){
63385      checkAppendMsg(pCheck,
63386         "%d of %d pages missing from overflow list starting at %d",
63387          N+1, expected, iFirst);
63388      break;
63389    }
63390    if( checkRef(pCheck, iPage) ) break;
63391    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
63392      checkAppendMsg(pCheck, "failed to get page %d", iPage);
63393      break;
63394    }
63395    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
63396    if( isFreeList ){
63397      int n = get4byte(&pOvflData[4]);
63398#ifndef SQLITE_OMIT_AUTOVACUUM
63399      if( pCheck->pBt->autoVacuum ){
63400        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
63401      }
63402#endif
63403      if( n>(int)pCheck->pBt->usableSize/4-2 ){
63404        checkAppendMsg(pCheck,
63405           "freelist leaf count too big on page %d", iPage);
63406        N--;
63407      }else{
63408        for(i=0; i<n; i++){
63409          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
63410#ifndef SQLITE_OMIT_AUTOVACUUM
63411          if( pCheck->pBt->autoVacuum ){
63412            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
63413          }
63414#endif
63415          checkRef(pCheck, iFreePage);
63416        }
63417        N -= n;
63418      }
63419    }
63420#ifndef SQLITE_OMIT_AUTOVACUUM
63421    else{
63422      /* If this database supports auto-vacuum and iPage is not the last
63423      ** page in this overflow list, check that the pointer-map entry for
63424      ** the following page matches iPage.
63425      */
63426      if( pCheck->pBt->autoVacuum && N>0 ){
63427        i = get4byte(pOvflData);
63428        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
63429      }
63430    }
63431#endif
63432    iPage = get4byte(pOvflData);
63433    sqlite3PagerUnref(pOvflPage);
63434
63435    if( isFreeList && N<(iPage!=0) ){
63436      checkAppendMsg(pCheck, "free-page count in header is too small");
63437    }
63438  }
63439}
63440#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63441
63442/*
63443** An implementation of a min-heap.
63444**
63445** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
63446** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
63447** and aHeap[N*2+1].
63448**
63449** The heap property is this:  Every node is less than or equal to both
63450** of its daughter nodes.  A consequence of the heap property is that the
63451** root node aHeap[1] is always the minimum value currently in the heap.
63452**
63453** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
63454** the heap, preserving the heap property.  The btreeHeapPull() routine
63455** removes the root element from the heap (the minimum value in the heap)
63456** and then moves other nodes around as necessary to preserve the heap
63457** property.
63458**
63459** This heap is used for cell overlap and coverage testing.  Each u32
63460** entry represents the span of a cell or freeblock on a btree page.
63461** The upper 16 bits are the index of the first byte of a range and the
63462** lower 16 bits are the index of the last byte of that range.
63463*/
63464static void btreeHeapInsert(u32 *aHeap, u32 x){
63465  u32 j, i = ++aHeap[0];
63466  aHeap[i] = x;
63467  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
63468    x = aHeap[j];
63469    aHeap[j] = aHeap[i];
63470    aHeap[i] = x;
63471    i = j;
63472  }
63473}
63474static int btreeHeapPull(u32 *aHeap, u32 *pOut){
63475  u32 j, i, x;
63476  if( (x = aHeap[0])==0 ) return 0;
63477  *pOut = aHeap[1];
63478  aHeap[1] = aHeap[x];
63479  aHeap[x] = 0xffffffff;
63480  aHeap[0]--;
63481  i = 1;
63482  while( (j = i*2)<=aHeap[0] ){
63483    if( aHeap[j]>aHeap[j+1] ) j++;
63484    if( aHeap[i]<aHeap[j] ) break;
63485    x = aHeap[i];
63486    aHeap[i] = aHeap[j];
63487    aHeap[j] = x;
63488    i = j;
63489  }
63490  return 1;
63491}
63492
63493#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63494/*
63495** Do various sanity checks on a single page of a tree.  Return
63496** the tree depth.  Root pages return 0.  Parents of root pages
63497** return 1, and so forth.
63498**
63499** These checks are done:
63500**
63501**      1.  Make sure that cells and freeblocks do not overlap
63502**          but combine to completely cover the page.
63503**      2.  Make sure integer cell keys are in order.
63504**      3.  Check the integrity of overflow pages.
63505**      4.  Recursively call checkTreePage on all children.
63506**      5.  Verify that the depth of all children is the same.
63507*/
63508static int checkTreePage(
63509  IntegrityCk *pCheck,  /* Context for the sanity check */
63510  int iPage,            /* Page number of the page to check */
63511  i64 *piMinKey,        /* Write minimum integer primary key here */
63512  i64 maxKey            /* Error if integer primary key greater than this */
63513){
63514  MemPage *pPage = 0;      /* The page being analyzed */
63515  int i;                   /* Loop counter */
63516  int rc;                  /* Result code from subroutine call */
63517  int depth = -1, d2;      /* Depth of a subtree */
63518  int pgno;                /* Page number */
63519  int nFrag;               /* Number of fragmented bytes on the page */
63520  int hdr;                 /* Offset to the page header */
63521  int cellStart;           /* Offset to the start of the cell pointer array */
63522  int nCell;               /* Number of cells */
63523  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
63524  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
63525                           ** False if IPK must be strictly less than maxKey */
63526  u8 *data;                /* Page content */
63527  u8 *pCell;               /* Cell content */
63528  u8 *pCellIdx;            /* Next element of the cell pointer array */
63529  BtShared *pBt;           /* The BtShared object that owns pPage */
63530  u32 pc;                  /* Address of a cell */
63531  u32 usableSize;          /* Usable size of the page */
63532  u32 contentOffset;       /* Offset to the start of the cell content area */
63533  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
63534  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
63535  const char *saved_zPfx = pCheck->zPfx;
63536  int saved_v1 = pCheck->v1;
63537  int saved_v2 = pCheck->v2;
63538  u8 savedIsInit = 0;
63539
63540  /* Check that the page exists
63541  */
63542  pBt = pCheck->pBt;
63543  usableSize = pBt->usableSize;
63544  if( iPage==0 ) return 0;
63545  if( checkRef(pCheck, iPage) ) return 0;
63546  pCheck->zPfx = "Page %d: ";
63547  pCheck->v1 = iPage;
63548  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
63549    checkAppendMsg(pCheck,
63550       "unable to get the page. error code=%d", rc);
63551    goto end_of_check;
63552  }
63553
63554  /* Clear MemPage.isInit to make sure the corruption detection code in
63555  ** btreeInitPage() is executed.  */
63556  savedIsInit = pPage->isInit;
63557  pPage->isInit = 0;
63558  if( (rc = btreeInitPage(pPage))!=0 ){
63559    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
63560    checkAppendMsg(pCheck,
63561                   "btreeInitPage() returns error code %d", rc);
63562    goto end_of_check;
63563  }
63564  data = pPage->aData;
63565  hdr = pPage->hdrOffset;
63566
63567  /* Set up for cell analysis */
63568  pCheck->zPfx = "On tree page %d cell %d: ";
63569  contentOffset = get2byteNotZero(&data[hdr+5]);
63570  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
63571
63572  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
63573  ** number of cells on the page. */
63574  nCell = get2byte(&data[hdr+3]);
63575  assert( pPage->nCell==nCell );
63576
63577  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
63578  ** immediately follows the b-tree page header. */
63579  cellStart = hdr + 12 - 4*pPage->leaf;
63580  assert( pPage->aCellIdx==&data[cellStart] );
63581  pCellIdx = &data[cellStart + 2*(nCell-1)];
63582
63583  if( !pPage->leaf ){
63584    /* Analyze the right-child page of internal pages */
63585    pgno = get4byte(&data[hdr+8]);
63586#ifndef SQLITE_OMIT_AUTOVACUUM
63587    if( pBt->autoVacuum ){
63588      pCheck->zPfx = "On page %d at right child: ";
63589      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
63590    }
63591#endif
63592    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
63593    keyCanBeEqual = 0;
63594  }else{
63595    /* For leaf pages, the coverage check will occur in the same loop
63596    ** as the other cell checks, so initialize the heap.  */
63597    heap = pCheck->heap;
63598    heap[0] = 0;
63599  }
63600
63601  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
63602  ** integer offsets to the cell contents. */
63603  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
63604    CellInfo info;
63605
63606    /* Check cell size */
63607    pCheck->v2 = i;
63608    assert( pCellIdx==&data[cellStart + i*2] );
63609    pc = get2byteAligned(pCellIdx);
63610    pCellIdx -= 2;
63611    if( pc<contentOffset || pc>usableSize-4 ){
63612      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
63613                             pc, contentOffset, usableSize-4);
63614      doCoverageCheck = 0;
63615      continue;
63616    }
63617    pCell = &data[pc];
63618    pPage->xParseCell(pPage, pCell, &info);
63619    if( pc+info.nSize>usableSize ){
63620      checkAppendMsg(pCheck, "Extends off end of page");
63621      doCoverageCheck = 0;
63622      continue;
63623    }
63624
63625    /* Check for integer primary key out of range */
63626    if( pPage->intKey ){
63627      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
63628        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
63629      }
63630      maxKey = info.nKey;
63631    }
63632
63633    /* Check the content overflow list */
63634    if( info.nPayload>info.nLocal ){
63635      int nPage;       /* Number of pages on the overflow chain */
63636      Pgno pgnoOvfl;   /* First page of the overflow chain */
63637      assert( pc + info.iOverflow <= usableSize );
63638      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
63639      pgnoOvfl = get4byte(&pCell[info.iOverflow]);
63640#ifndef SQLITE_OMIT_AUTOVACUUM
63641      if( pBt->autoVacuum ){
63642        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
63643      }
63644#endif
63645      checkList(pCheck, 0, pgnoOvfl, nPage);
63646    }
63647
63648    if( !pPage->leaf ){
63649      /* Check sanity of left child page for internal pages */
63650      pgno = get4byte(pCell);
63651#ifndef SQLITE_OMIT_AUTOVACUUM
63652      if( pBt->autoVacuum ){
63653        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
63654      }
63655#endif
63656      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
63657      keyCanBeEqual = 0;
63658      if( d2!=depth ){
63659        checkAppendMsg(pCheck, "Child page depth differs");
63660        depth = d2;
63661      }
63662    }else{
63663      /* Populate the coverage-checking heap for leaf pages */
63664      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
63665    }
63666  }
63667  *piMinKey = maxKey;
63668
63669  /* Check for complete coverage of the page
63670  */
63671  pCheck->zPfx = 0;
63672  if( doCoverageCheck && pCheck->mxErr>0 ){
63673    /* For leaf pages, the min-heap has already been initialized and the
63674    ** cells have already been inserted.  But for internal pages, that has
63675    ** not yet been done, so do it now */
63676    if( !pPage->leaf ){
63677      heap = pCheck->heap;
63678      heap[0] = 0;
63679      for(i=nCell-1; i>=0; i--){
63680        u32 size;
63681        pc = get2byteAligned(&data[cellStart+i*2]);
63682        size = pPage->xCellSize(pPage, &data[pc]);
63683        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
63684      }
63685    }
63686    /* Add the freeblocks to the min-heap
63687    **
63688    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
63689    ** is the offset of the first freeblock, or zero if there are no
63690    ** freeblocks on the page.
63691    */
63692    i = get2byte(&data[hdr+1]);
63693    while( i>0 ){
63694      int size, j;
63695      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
63696      size = get2byte(&data[i+2]);
63697      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
63698      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
63699      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
63700      ** big-endian integer which is the offset in the b-tree page of the next
63701      ** freeblock in the chain, or zero if the freeblock is the last on the
63702      ** chain. */
63703      j = get2byte(&data[i]);
63704      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
63705      ** increasing offset. */
63706      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
63707      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
63708      i = j;
63709    }
63710    /* Analyze the min-heap looking for overlap between cells and/or
63711    ** freeblocks, and counting the number of untracked bytes in nFrag.
63712    **
63713    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
63714    ** There is an implied first entry the covers the page header, the cell
63715    ** pointer index, and the gap between the cell pointer index and the start
63716    ** of cell content.
63717    **
63718    ** The loop below pulls entries from the min-heap in order and compares
63719    ** the start_address against the previous end_address.  If there is an
63720    ** overlap, that means bytes are used multiple times.  If there is a gap,
63721    ** that gap is added to the fragmentation count.
63722    */
63723    nFrag = 0;
63724    prev = contentOffset - 1;   /* Implied first min-heap entry */
63725    while( btreeHeapPull(heap,&x) ){
63726      if( (prev&0xffff)>=(x>>16) ){
63727        checkAppendMsg(pCheck,
63728          "Multiple uses for byte %u of page %d", x>>16, iPage);
63729        break;
63730      }else{
63731        nFrag += (x>>16) - (prev&0xffff) - 1;
63732        prev = x;
63733      }
63734    }
63735    nFrag += usableSize - (prev&0xffff) - 1;
63736    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
63737    ** is stored in the fifth field of the b-tree page header.
63738    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
63739    ** number of fragmented free bytes within the cell content area.
63740    */
63741    if( heap[0]==0 && nFrag!=data[hdr+7] ){
63742      checkAppendMsg(pCheck,
63743          "Fragmentation of %d bytes reported as %d on page %d",
63744          nFrag, data[hdr+7], iPage);
63745    }
63746  }
63747
63748end_of_check:
63749  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
63750  releasePage(pPage);
63751  pCheck->zPfx = saved_zPfx;
63752  pCheck->v1 = saved_v1;
63753  pCheck->v2 = saved_v2;
63754  return depth+1;
63755}
63756#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63757
63758#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63759/*
63760** This routine does a complete check of the given BTree file.  aRoot[] is
63761** an array of pages numbers were each page number is the root page of
63762** a table.  nRoot is the number of entries in aRoot.
63763**
63764** A read-only or read-write transaction must be opened before calling
63765** this function.
63766**
63767** Write the number of error seen in *pnErr.  Except for some memory
63768** allocation errors,  an error message held in memory obtained from
63769** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
63770** returned.  If a memory allocation error occurs, NULL is returned.
63771*/
63772SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
63773  Btree *p,     /* The btree to be checked */
63774  int *aRoot,   /* An array of root pages numbers for individual trees */
63775  int nRoot,    /* Number of entries in aRoot[] */
63776  int mxErr,    /* Stop reporting errors after this many */
63777  int *pnErr    /* Write number of errors seen to this variable */
63778){
63779  Pgno i;
63780  IntegrityCk sCheck;
63781  BtShared *pBt = p->pBt;
63782  int savedDbFlags = pBt->db->flags;
63783  char zErr[100];
63784  VVA_ONLY( int nRef );
63785
63786  sqlite3BtreeEnter(p);
63787  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
63788  assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 );
63789  sCheck.pBt = pBt;
63790  sCheck.pPager = pBt->pPager;
63791  sCheck.nPage = btreePagecount(sCheck.pBt);
63792  sCheck.mxErr = mxErr;
63793  sCheck.nErr = 0;
63794  sCheck.mallocFailed = 0;
63795  sCheck.zPfx = 0;
63796  sCheck.v1 = 0;
63797  sCheck.v2 = 0;
63798  sCheck.aPgRef = 0;
63799  sCheck.heap = 0;
63800  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
63801  if( sCheck.nPage==0 ){
63802    goto integrity_ck_cleanup;
63803  }
63804
63805  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
63806  if( !sCheck.aPgRef ){
63807    sCheck.mallocFailed = 1;
63808    goto integrity_ck_cleanup;
63809  }
63810  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
63811  if( sCheck.heap==0 ){
63812    sCheck.mallocFailed = 1;
63813    goto integrity_ck_cleanup;
63814  }
63815
63816  i = PENDING_BYTE_PAGE(pBt);
63817  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
63818
63819  /* Check the integrity of the freelist
63820  */
63821  sCheck.zPfx = "Main freelist: ";
63822  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
63823            get4byte(&pBt->pPage1->aData[36]));
63824  sCheck.zPfx = 0;
63825
63826  /* Check all the tables.
63827  */
63828  testcase( pBt->db->flags & SQLITE_CellSizeCk );
63829  pBt->db->flags &= ~SQLITE_CellSizeCk;
63830  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
63831    i64 notUsed;
63832    if( aRoot[i]==0 ) continue;
63833#ifndef SQLITE_OMIT_AUTOVACUUM
63834    if( pBt->autoVacuum && aRoot[i]>1 ){
63835      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
63836    }
63837#endif
63838    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
63839  }
63840  pBt->db->flags = savedDbFlags;
63841
63842  /* Make sure every page in the file is referenced
63843  */
63844  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
63845#ifdef SQLITE_OMIT_AUTOVACUUM
63846    if( getPageReferenced(&sCheck, i)==0 ){
63847      checkAppendMsg(&sCheck, "Page %d is never used", i);
63848    }
63849#else
63850    /* If the database supports auto-vacuum, make sure no tables contain
63851    ** references to pointer-map pages.
63852    */
63853    if( getPageReferenced(&sCheck, i)==0 &&
63854       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
63855      checkAppendMsg(&sCheck, "Page %d is never used", i);
63856    }
63857    if( getPageReferenced(&sCheck, i)!=0 &&
63858       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
63859      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
63860    }
63861#endif
63862  }
63863
63864  /* Clean  up and report errors.
63865  */
63866integrity_ck_cleanup:
63867  sqlite3PageFree(sCheck.heap);
63868  sqlite3_free(sCheck.aPgRef);
63869  if( sCheck.mallocFailed ){
63870    sqlite3StrAccumReset(&sCheck.errMsg);
63871    sCheck.nErr++;
63872  }
63873  *pnErr = sCheck.nErr;
63874  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
63875  /* Make sure this analysis did not leave any unref() pages. */
63876  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
63877  sqlite3BtreeLeave(p);
63878  return sqlite3StrAccumFinish(&sCheck.errMsg);
63879}
63880#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63881
63882/*
63883** Return the full pathname of the underlying database file.  Return
63884** an empty string if the database is in-memory or a TEMP database.
63885**
63886** The pager filename is invariant as long as the pager is
63887** open so it is safe to access without the BtShared mutex.
63888*/
63889SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
63890  assert( p->pBt->pPager!=0 );
63891  return sqlite3PagerFilename(p->pBt->pPager, 1);
63892}
63893
63894/*
63895** Return the pathname of the journal file for this database. The return
63896** value of this routine is the same regardless of whether the journal file
63897** has been created or not.
63898**
63899** The pager journal filename is invariant as long as the pager is
63900** open so it is safe to access without the BtShared mutex.
63901*/
63902SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
63903  assert( p->pBt->pPager!=0 );
63904  return sqlite3PagerJournalname(p->pBt->pPager);
63905}
63906
63907/*
63908** Return non-zero if a transaction is active.
63909*/
63910SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
63911  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
63912  return (p && (p->inTrans==TRANS_WRITE));
63913}
63914
63915#ifndef SQLITE_OMIT_WAL
63916/*
63917** Run a checkpoint on the Btree passed as the first argument.
63918**
63919** Return SQLITE_LOCKED if this or any other connection has an open
63920** transaction on the shared-cache the argument Btree is connected to.
63921**
63922** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
63923*/
63924SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
63925  int rc = SQLITE_OK;
63926  if( p ){
63927    BtShared *pBt = p->pBt;
63928    sqlite3BtreeEnter(p);
63929    if( pBt->inTransaction!=TRANS_NONE ){
63930      rc = SQLITE_LOCKED;
63931    }else{
63932      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
63933    }
63934    sqlite3BtreeLeave(p);
63935  }
63936  return rc;
63937}
63938#endif
63939
63940/*
63941** Return non-zero if a read (or write) transaction is active.
63942*/
63943SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
63944  assert( p );
63945  assert( sqlite3_mutex_held(p->db->mutex) );
63946  return p->inTrans!=TRANS_NONE;
63947}
63948
63949SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
63950  assert( p );
63951  assert( sqlite3_mutex_held(p->db->mutex) );
63952  return p->nBackup!=0;
63953}
63954
63955/*
63956** This function returns a pointer to a blob of memory associated with
63957** a single shared-btree. The memory is used by client code for its own
63958** purposes (for example, to store a high-level schema associated with
63959** the shared-btree). The btree layer manages reference counting issues.
63960**
63961** The first time this is called on a shared-btree, nBytes bytes of memory
63962** are allocated, zeroed, and returned to the caller. For each subsequent
63963** call the nBytes parameter is ignored and a pointer to the same blob
63964** of memory returned.
63965**
63966** If the nBytes parameter is 0 and the blob of memory has not yet been
63967** allocated, a null pointer is returned. If the blob has already been
63968** allocated, it is returned as normal.
63969**
63970** Just before the shared-btree is closed, the function passed as the
63971** xFree argument when the memory allocation was made is invoked on the
63972** blob of allocated memory. The xFree function should not call sqlite3_free()
63973** on the memory, the btree layer does that.
63974*/
63975SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
63976  BtShared *pBt = p->pBt;
63977  sqlite3BtreeEnter(p);
63978  if( !pBt->pSchema && nBytes ){
63979    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
63980    pBt->xFreeSchema = xFree;
63981  }
63982  sqlite3BtreeLeave(p);
63983  return pBt->pSchema;
63984}
63985
63986/*
63987** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
63988** btree as the argument handle holds an exclusive lock on the
63989** sqlite_master table. Otherwise SQLITE_OK.
63990*/
63991SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
63992  int rc;
63993  assert( sqlite3_mutex_held(p->db->mutex) );
63994  sqlite3BtreeEnter(p);
63995  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
63996  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
63997  sqlite3BtreeLeave(p);
63998  return rc;
63999}
64000
64001
64002#ifndef SQLITE_OMIT_SHARED_CACHE
64003/*
64004** Obtain a lock on the table whose root page is iTab.  The
64005** lock is a write lock if isWritelock is true or a read lock
64006** if it is false.
64007*/
64008SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
64009  int rc = SQLITE_OK;
64010  assert( p->inTrans!=TRANS_NONE );
64011  if( p->sharable ){
64012    u8 lockType = READ_LOCK + isWriteLock;
64013    assert( READ_LOCK+1==WRITE_LOCK );
64014    assert( isWriteLock==0 || isWriteLock==1 );
64015
64016    sqlite3BtreeEnter(p);
64017    rc = querySharedCacheTableLock(p, iTab, lockType);
64018    if( rc==SQLITE_OK ){
64019      rc = setSharedCacheTableLock(p, iTab, lockType);
64020    }
64021    sqlite3BtreeLeave(p);
64022  }
64023  return rc;
64024}
64025#endif
64026
64027#ifndef SQLITE_OMIT_INCRBLOB
64028/*
64029** Argument pCsr must be a cursor opened for writing on an
64030** INTKEY table currently pointing at a valid table entry.
64031** This function modifies the data stored as part of that entry.
64032**
64033** Only the data content may only be modified, it is not possible to
64034** change the length of the data stored. If this function is called with
64035** parameters that attempt to write past the end of the existing data,
64036** no modifications are made and SQLITE_CORRUPT is returned.
64037*/
64038SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
64039  int rc;
64040  assert( cursorHoldsMutex(pCsr) );
64041  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
64042  assert( pCsr->curFlags & BTCF_Incrblob );
64043
64044  rc = restoreCursorPosition(pCsr);
64045  if( rc!=SQLITE_OK ){
64046    return rc;
64047  }
64048  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
64049  if( pCsr->eState!=CURSOR_VALID ){
64050    return SQLITE_ABORT;
64051  }
64052
64053  /* Save the positions of all other cursors open on this table. This is
64054  ** required in case any of them are holding references to an xFetch
64055  ** version of the b-tree page modified by the accessPayload call below.
64056  **
64057  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
64058  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
64059  ** saveAllCursors can only return SQLITE_OK.
64060  */
64061  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
64062  assert( rc==SQLITE_OK );
64063
64064  /* Check some assumptions:
64065  **   (a) the cursor is open for writing,
64066  **   (b) there is a read/write transaction open,
64067  **   (c) the connection holds a write-lock on the table (if required),
64068  **   (d) there are no conflicting read-locks, and
64069  **   (e) the cursor points at a valid row of an intKey table.
64070  */
64071  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
64072    return SQLITE_READONLY;
64073  }
64074  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
64075              && pCsr->pBt->inTransaction==TRANS_WRITE );
64076  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
64077  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
64078  assert( pCsr->apPage[pCsr->iPage]->intKey );
64079
64080  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
64081}
64082
64083/*
64084** Mark this cursor as an incremental blob cursor.
64085*/
64086SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
64087  pCur->curFlags |= BTCF_Incrblob;
64088  pCur->pBtree->hasIncrblobCur = 1;
64089}
64090#endif
64091
64092/*
64093** Set both the "read version" (single byte at byte offset 18) and
64094** "write version" (single byte at byte offset 19) fields in the database
64095** header to iVersion.
64096*/
64097SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
64098  BtShared *pBt = pBtree->pBt;
64099  int rc;                         /* Return code */
64100
64101  assert( iVersion==1 || iVersion==2 );
64102
64103  /* If setting the version fields to 1, do not automatically open the
64104  ** WAL connection, even if the version fields are currently set to 2.
64105  */
64106  pBt->btsFlags &= ~BTS_NO_WAL;
64107  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
64108
64109  rc = sqlite3BtreeBeginTrans(pBtree, 0);
64110  if( rc==SQLITE_OK ){
64111    u8 *aData = pBt->pPage1->aData;
64112    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
64113      rc = sqlite3BtreeBeginTrans(pBtree, 2);
64114      if( rc==SQLITE_OK ){
64115        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
64116        if( rc==SQLITE_OK ){
64117          aData[18] = (u8)iVersion;
64118          aData[19] = (u8)iVersion;
64119        }
64120      }
64121    }
64122  }
64123
64124  pBt->btsFlags &= ~BTS_NO_WAL;
64125  return rc;
64126}
64127
64128/*
64129** set the mask of hint flags for cursor pCsr.
64130*/
64131SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
64132  assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
64133  pCsr->hints = mask;
64134}
64135
64136#ifdef SQLITE_DEBUG
64137/*
64138** Return true if the cursor has a hint specified.  This routine is
64139** only used from within assert() statements
64140*/
64141SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
64142  return (pCsr->hints & mask)!=0;
64143}
64144#endif
64145
64146/*
64147** Return true if the given Btree is read-only.
64148*/
64149SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
64150  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
64151}
64152
64153/*
64154** Return the size of the header added to each page by this module.
64155*/
64156SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
64157
64158/************** End of btree.c ***********************************************/
64159/************** Begin file backup.c ******************************************/
64160/*
64161** 2009 January 28
64162**
64163** The author disclaims copyright to this source code.  In place of
64164** a legal notice, here is a blessing:
64165**
64166**    May you do good and not evil.
64167**    May you find forgiveness for yourself and forgive others.
64168**    May you share freely, never taking more than you give.
64169**
64170*************************************************************************
64171** This file contains the implementation of the sqlite3_backup_XXX()
64172** API functions and the related features.
64173*/
64174/* #include "sqliteInt.h" */
64175/* #include "btreeInt.h" */
64176
64177/*
64178** Structure allocated for each backup operation.
64179*/
64180struct sqlite3_backup {
64181  sqlite3* pDestDb;        /* Destination database handle */
64182  Btree *pDest;            /* Destination b-tree file */
64183  u32 iDestSchema;         /* Original schema cookie in destination */
64184  int bDestLocked;         /* True once a write-transaction is open on pDest */
64185
64186  Pgno iNext;              /* Page number of the next source page to copy */
64187  sqlite3* pSrcDb;         /* Source database handle */
64188  Btree *pSrc;             /* Source b-tree file */
64189
64190  int rc;                  /* Backup process error code */
64191
64192  /* These two variables are set by every call to backup_step(). They are
64193  ** read by calls to backup_remaining() and backup_pagecount().
64194  */
64195  Pgno nRemaining;         /* Number of pages left to copy */
64196  Pgno nPagecount;         /* Total number of pages to copy */
64197
64198  int isAttached;          /* True once backup has been registered with pager */
64199  sqlite3_backup *pNext;   /* Next backup associated with source pager */
64200};
64201
64202/*
64203** THREAD SAFETY NOTES:
64204**
64205**   Once it has been created using backup_init(), a single sqlite3_backup
64206**   structure may be accessed via two groups of thread-safe entry points:
64207**
64208**     * Via the sqlite3_backup_XXX() API function backup_step() and
64209**       backup_finish(). Both these functions obtain the source database
64210**       handle mutex and the mutex associated with the source BtShared
64211**       structure, in that order.
64212**
64213**     * Via the BackupUpdate() and BackupRestart() functions, which are
64214**       invoked by the pager layer to report various state changes in
64215**       the page cache associated with the source database. The mutex
64216**       associated with the source database BtShared structure will always
64217**       be held when either of these functions are invoked.
64218**
64219**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
64220**   backup_pagecount() are not thread-safe functions. If they are called
64221**   while some other thread is calling backup_step() or backup_finish(),
64222**   the values returned may be invalid. There is no way for a call to
64223**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
64224**   or backup_pagecount().
64225**
64226**   Depending on the SQLite configuration, the database handles and/or
64227**   the Btree objects may have their own mutexes that require locking.
64228**   Non-sharable Btrees (in-memory databases for example), do not have
64229**   associated mutexes.
64230*/
64231
64232/*
64233** Return a pointer corresponding to database zDb (i.e. "main", "temp")
64234** in connection handle pDb. If such a database cannot be found, return
64235** a NULL pointer and write an error message to pErrorDb.
64236**
64237** If the "temp" database is requested, it may need to be opened by this
64238** function. If an error occurs while doing so, return 0 and write an
64239** error message to pErrorDb.
64240*/
64241static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
64242  int i = sqlite3FindDbName(pDb, zDb);
64243
64244  if( i==1 ){
64245    Parse *pParse;
64246    int rc = 0;
64247    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
64248    if( pParse==0 ){
64249      sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
64250      rc = SQLITE_NOMEM;
64251    }else{
64252      pParse->db = pDb;
64253      if( sqlite3OpenTempDatabase(pParse) ){
64254        sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
64255        rc = SQLITE_ERROR;
64256      }
64257      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
64258      sqlite3ParserReset(pParse);
64259      sqlite3StackFree(pErrorDb, pParse);
64260    }
64261    if( rc ){
64262      return 0;
64263    }
64264  }
64265
64266  if( i<0 ){
64267    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
64268    return 0;
64269  }
64270
64271  return pDb->aDb[i].pBt;
64272}
64273
64274/*
64275** Attempt to set the page size of the destination to match the page size
64276** of the source.
64277*/
64278static int setDestPgsz(sqlite3_backup *p){
64279  int rc;
64280  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
64281  return rc;
64282}
64283
64284/*
64285** Check that there is no open read-transaction on the b-tree passed as the
64286** second argument. If there is not, return SQLITE_OK. Otherwise, if there
64287** is an open read-transaction, return SQLITE_ERROR and leave an error
64288** message in database handle db.
64289*/
64290static int checkReadTransaction(sqlite3 *db, Btree *p){
64291  if( sqlite3BtreeIsInReadTrans(p) ){
64292    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
64293    return SQLITE_ERROR;
64294  }
64295  return SQLITE_OK;
64296}
64297
64298/*
64299** Create an sqlite3_backup process to copy the contents of zSrcDb from
64300** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
64301** a pointer to the new sqlite3_backup object.
64302**
64303** If an error occurs, NULL is returned and an error code and error message
64304** stored in database handle pDestDb.
64305*/
64306SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
64307  sqlite3* pDestDb,                     /* Database to write to */
64308  const char *zDestDb,                  /* Name of database within pDestDb */
64309  sqlite3* pSrcDb,                      /* Database connection to read from */
64310  const char *zSrcDb                    /* Name of database within pSrcDb */
64311){
64312  sqlite3_backup *p;                    /* Value to return */
64313
64314#ifdef SQLITE_ENABLE_API_ARMOR
64315  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
64316    (void)SQLITE_MISUSE_BKPT;
64317    return 0;
64318  }
64319#endif
64320
64321  /* Lock the source database handle. The destination database
64322  ** handle is not locked in this routine, but it is locked in
64323  ** sqlite3_backup_step(). The user is required to ensure that no
64324  ** other thread accesses the destination handle for the duration
64325  ** of the backup operation.  Any attempt to use the destination
64326  ** database connection while a backup is in progress may cause
64327  ** a malfunction or a deadlock.
64328  */
64329  sqlite3_mutex_enter(pSrcDb->mutex);
64330  sqlite3_mutex_enter(pDestDb->mutex);
64331
64332  if( pSrcDb==pDestDb ){
64333    sqlite3ErrorWithMsg(
64334        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
64335    );
64336    p = 0;
64337  }else {
64338    /* Allocate space for a new sqlite3_backup object...
64339    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
64340    ** call to sqlite3_backup_init() and is destroyed by a call to
64341    ** sqlite3_backup_finish(). */
64342    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
64343    if( !p ){
64344      sqlite3Error(pDestDb, SQLITE_NOMEM);
64345    }
64346  }
64347
64348  /* If the allocation succeeded, populate the new object. */
64349  if( p ){
64350    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
64351    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
64352    p->pDestDb = pDestDb;
64353    p->pSrcDb = pSrcDb;
64354    p->iNext = 1;
64355    p->isAttached = 0;
64356
64357    if( 0==p->pSrc || 0==p->pDest
64358     || setDestPgsz(p)==SQLITE_NOMEM
64359     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
64360     ){
64361      /* One (or both) of the named databases did not exist or an OOM
64362      ** error was hit. Or there is a transaction open on the destination
64363      ** database. The error has already been written into the pDestDb
64364      ** handle. All that is left to do here is free the sqlite3_backup
64365      ** structure.  */
64366      sqlite3_free(p);
64367      p = 0;
64368    }
64369  }
64370  if( p ){
64371    p->pSrc->nBackup++;
64372  }
64373
64374  sqlite3_mutex_leave(pDestDb->mutex);
64375  sqlite3_mutex_leave(pSrcDb->mutex);
64376  return p;
64377}
64378
64379/*
64380** Argument rc is an SQLite error code. Return true if this error is
64381** considered fatal if encountered during a backup operation. All errors
64382** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
64383*/
64384static int isFatalError(int rc){
64385  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
64386}
64387
64388/*
64389** Parameter zSrcData points to a buffer containing the data for
64390** page iSrcPg from the source database. Copy this data into the
64391** destination database.
64392*/
64393static int backupOnePage(
64394  sqlite3_backup *p,              /* Backup handle */
64395  Pgno iSrcPg,                    /* Source database page to backup */
64396  const u8 *zSrcData,             /* Source database page data */
64397  int bUpdate                     /* True for an update, false otherwise */
64398){
64399  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
64400  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
64401  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
64402  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
64403  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
64404#ifdef SQLITE_HAS_CODEC
64405  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
64406  ** guaranteed that the shared-mutex is held by this thread, handle
64407  ** p->pSrc may not actually be the owner.  */
64408  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
64409  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
64410#endif
64411  int rc = SQLITE_OK;
64412  i64 iOff;
64413
64414  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
64415  assert( p->bDestLocked );
64416  assert( !isFatalError(p->rc) );
64417  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
64418  assert( zSrcData );
64419
64420  /* Catch the case where the destination is an in-memory database and the
64421  ** page sizes of the source and destination differ.
64422  */
64423  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
64424    rc = SQLITE_READONLY;
64425  }
64426
64427#ifdef SQLITE_HAS_CODEC
64428  /* Backup is not possible if the page size of the destination is changing
64429  ** and a codec is in use.
64430  */
64431  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
64432    rc = SQLITE_READONLY;
64433  }
64434
64435  /* Backup is not possible if the number of bytes of reserve space differ
64436  ** between source and destination.  If there is a difference, try to
64437  ** fix the destination to agree with the source.  If that is not possible,
64438  ** then the backup cannot proceed.
64439  */
64440  if( nSrcReserve!=nDestReserve ){
64441    u32 newPgsz = nSrcPgsz;
64442    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
64443    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
64444  }
64445#endif
64446
64447  /* This loop runs once for each destination page spanned by the source
64448  ** page. For each iteration, variable iOff is set to the byte offset
64449  ** of the destination page.
64450  */
64451  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
64452    DbPage *pDestPg = 0;
64453    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
64454    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
64455    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
64456     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
64457    ){
64458      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
64459      u8 *zDestData = sqlite3PagerGetData(pDestPg);
64460      u8 *zOut = &zDestData[iOff%nDestPgsz];
64461
64462      /* Copy the data from the source page into the destination page.
64463      ** Then clear the Btree layer MemPage.isInit flag. Both this module
64464      ** and the pager code use this trick (clearing the first byte
64465      ** of the page 'extra' space to invalidate the Btree layers
64466      ** cached parse of the page). MemPage.isInit is marked
64467      ** "MUST BE FIRST" for this purpose.
64468      */
64469      memcpy(zOut, zIn, nCopy);
64470      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
64471      if( iOff==0 && bUpdate==0 ){
64472        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
64473      }
64474    }
64475    sqlite3PagerUnref(pDestPg);
64476  }
64477
64478  return rc;
64479}
64480
64481/*
64482** If pFile is currently larger than iSize bytes, then truncate it to
64483** exactly iSize bytes. If pFile is not larger than iSize bytes, then
64484** this function is a no-op.
64485**
64486** Return SQLITE_OK if everything is successful, or an SQLite error
64487** code if an error occurs.
64488*/
64489static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
64490  i64 iCurrent;
64491  int rc = sqlite3OsFileSize(pFile, &iCurrent);
64492  if( rc==SQLITE_OK && iCurrent>iSize ){
64493    rc = sqlite3OsTruncate(pFile, iSize);
64494  }
64495  return rc;
64496}
64497
64498/*
64499** Register this backup object with the associated source pager for
64500** callbacks when pages are changed or the cache invalidated.
64501*/
64502static void attachBackupObject(sqlite3_backup *p){
64503  sqlite3_backup **pp;
64504  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
64505  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
64506  p->pNext = *pp;
64507  *pp = p;
64508  p->isAttached = 1;
64509}
64510
64511/*
64512** Copy nPage pages from the source b-tree to the destination.
64513*/
64514SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
64515  int rc;
64516  int destMode;       /* Destination journal mode */
64517  int pgszSrc = 0;    /* Source page size */
64518  int pgszDest = 0;   /* Destination page size */
64519
64520#ifdef SQLITE_ENABLE_API_ARMOR
64521  if( p==0 ) return SQLITE_MISUSE_BKPT;
64522#endif
64523  sqlite3_mutex_enter(p->pSrcDb->mutex);
64524  sqlite3BtreeEnter(p->pSrc);
64525  if( p->pDestDb ){
64526    sqlite3_mutex_enter(p->pDestDb->mutex);
64527  }
64528
64529  rc = p->rc;
64530  if( !isFatalError(rc) ){
64531    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
64532    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
64533    int ii;                            /* Iterator variable */
64534    int nSrcPage = -1;                 /* Size of source db in pages */
64535    int bCloseTrans = 0;               /* True if src db requires unlocking */
64536
64537    /* If the source pager is currently in a write-transaction, return
64538    ** SQLITE_BUSY immediately.
64539    */
64540    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
64541      rc = SQLITE_BUSY;
64542    }else{
64543      rc = SQLITE_OK;
64544    }
64545
64546    /* Lock the destination database, if it is not locked already. */
64547    if( SQLITE_OK==rc && p->bDestLocked==0
64548     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
64549    ){
64550      p->bDestLocked = 1;
64551      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
64552    }
64553
64554    /* If there is no open read-transaction on the source database, open
64555    ** one now. If a transaction is opened here, then it will be closed
64556    ** before this function exits.
64557    */
64558    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
64559      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
64560      bCloseTrans = 1;
64561    }
64562
64563    /* Do not allow backup if the destination database is in WAL mode
64564    ** and the page sizes are different between source and destination */
64565    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
64566    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
64567    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
64568    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
64569      rc = SQLITE_READONLY;
64570    }
64571
64572    /* Now that there is a read-lock on the source database, query the
64573    ** source pager for the number of pages in the database.
64574    */
64575    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
64576    assert( nSrcPage>=0 );
64577    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
64578      const Pgno iSrcPg = p->iNext;                 /* Source page number */
64579      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
64580        DbPage *pSrcPg;                             /* Source page object */
64581        rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
64582                                 PAGER_GET_READONLY);
64583        if( rc==SQLITE_OK ){
64584          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
64585          sqlite3PagerUnref(pSrcPg);
64586        }
64587      }
64588      p->iNext++;
64589    }
64590    if( rc==SQLITE_OK ){
64591      p->nPagecount = nSrcPage;
64592      p->nRemaining = nSrcPage+1-p->iNext;
64593      if( p->iNext>(Pgno)nSrcPage ){
64594        rc = SQLITE_DONE;
64595      }else if( !p->isAttached ){
64596        attachBackupObject(p);
64597      }
64598    }
64599
64600    /* Update the schema version field in the destination database. This
64601    ** is to make sure that the schema-version really does change in
64602    ** the case where the source and destination databases have the
64603    ** same schema version.
64604    */
64605    if( rc==SQLITE_DONE ){
64606      if( nSrcPage==0 ){
64607        rc = sqlite3BtreeNewDb(p->pDest);
64608        nSrcPage = 1;
64609      }
64610      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
64611        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
64612      }
64613      if( rc==SQLITE_OK ){
64614        if( p->pDestDb ){
64615          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
64616        }
64617        if( destMode==PAGER_JOURNALMODE_WAL ){
64618          rc = sqlite3BtreeSetVersion(p->pDest, 2);
64619        }
64620      }
64621      if( rc==SQLITE_OK ){
64622        int nDestTruncate;
64623        /* Set nDestTruncate to the final number of pages in the destination
64624        ** database. The complication here is that the destination page
64625        ** size may be different to the source page size.
64626        **
64627        ** If the source page size is smaller than the destination page size,
64628        ** round up. In this case the call to sqlite3OsTruncate() below will
64629        ** fix the size of the file. However it is important to call
64630        ** sqlite3PagerTruncateImage() here so that any pages in the
64631        ** destination file that lie beyond the nDestTruncate page mark are
64632        ** journalled by PagerCommitPhaseOne() before they are destroyed
64633        ** by the file truncation.
64634        */
64635        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
64636        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
64637        if( pgszSrc<pgszDest ){
64638          int ratio = pgszDest/pgszSrc;
64639          nDestTruncate = (nSrcPage+ratio-1)/ratio;
64640          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
64641            nDestTruncate--;
64642          }
64643        }else{
64644          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
64645        }
64646        assert( nDestTruncate>0 );
64647
64648        if( pgszSrc<pgszDest ){
64649          /* If the source page-size is smaller than the destination page-size,
64650          ** two extra things may need to happen:
64651          **
64652          **   * The destination may need to be truncated, and
64653          **
64654          **   * Data stored on the pages immediately following the
64655          **     pending-byte page in the source database may need to be
64656          **     copied into the destination database.
64657          */
64658          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
64659          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
64660          Pgno iPg;
64661          int nDstPage;
64662          i64 iOff;
64663          i64 iEnd;
64664
64665          assert( pFile );
64666          assert( nDestTruncate==0
64667              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
64668                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
64669             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
64670          ));
64671
64672          /* This block ensures that all data required to recreate the original
64673          ** database has been stored in the journal for pDestPager and the
64674          ** journal synced to disk. So at this point we may safely modify
64675          ** the database file in any way, knowing that if a power failure
64676          ** occurs, the original database will be reconstructed from the
64677          ** journal file.  */
64678          sqlite3PagerPagecount(pDestPager, &nDstPage);
64679          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
64680            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
64681              DbPage *pPg;
64682              rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
64683              if( rc==SQLITE_OK ){
64684                rc = sqlite3PagerWrite(pPg);
64685                sqlite3PagerUnref(pPg);
64686              }
64687            }
64688          }
64689          if( rc==SQLITE_OK ){
64690            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
64691          }
64692
64693          /* Write the extra pages and truncate the database file as required */
64694          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
64695          for(
64696            iOff=PENDING_BYTE+pgszSrc;
64697            rc==SQLITE_OK && iOff<iEnd;
64698            iOff+=pgszSrc
64699          ){
64700            PgHdr *pSrcPg = 0;
64701            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
64702            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
64703            if( rc==SQLITE_OK ){
64704              u8 *zData = sqlite3PagerGetData(pSrcPg);
64705              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
64706            }
64707            sqlite3PagerUnref(pSrcPg);
64708          }
64709          if( rc==SQLITE_OK ){
64710            rc = backupTruncateFile(pFile, iSize);
64711          }
64712
64713          /* Sync the database file to disk. */
64714          if( rc==SQLITE_OK ){
64715            rc = sqlite3PagerSync(pDestPager, 0);
64716          }
64717        }else{
64718          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
64719          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
64720        }
64721
64722        /* Finish committing the transaction to the destination database. */
64723        if( SQLITE_OK==rc
64724         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
64725        ){
64726          rc = SQLITE_DONE;
64727        }
64728      }
64729    }
64730
64731    /* If bCloseTrans is true, then this function opened a read transaction
64732    ** on the source database. Close the read transaction here. There is
64733    ** no need to check the return values of the btree methods here, as
64734    ** "committing" a read-only transaction cannot fail.
64735    */
64736    if( bCloseTrans ){
64737      TESTONLY( int rc2 );
64738      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
64739      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
64740      assert( rc2==SQLITE_OK );
64741    }
64742
64743    if( rc==SQLITE_IOERR_NOMEM ){
64744      rc = SQLITE_NOMEM;
64745    }
64746    p->rc = rc;
64747  }
64748  if( p->pDestDb ){
64749    sqlite3_mutex_leave(p->pDestDb->mutex);
64750  }
64751  sqlite3BtreeLeave(p->pSrc);
64752  sqlite3_mutex_leave(p->pSrcDb->mutex);
64753  return rc;
64754}
64755
64756/*
64757** Release all resources associated with an sqlite3_backup* handle.
64758*/
64759SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
64760  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
64761  sqlite3 *pSrcDb;                     /* Source database connection */
64762  int rc;                              /* Value to return */
64763
64764  /* Enter the mutexes */
64765  if( p==0 ) return SQLITE_OK;
64766  pSrcDb = p->pSrcDb;
64767  sqlite3_mutex_enter(pSrcDb->mutex);
64768  sqlite3BtreeEnter(p->pSrc);
64769  if( p->pDestDb ){
64770    sqlite3_mutex_enter(p->pDestDb->mutex);
64771  }
64772
64773  /* Detach this backup from the source pager. */
64774  if( p->pDestDb ){
64775    p->pSrc->nBackup--;
64776  }
64777  if( p->isAttached ){
64778    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
64779    while( *pp!=p ){
64780      pp = &(*pp)->pNext;
64781    }
64782    *pp = p->pNext;
64783  }
64784
64785  /* If a transaction is still open on the Btree, roll it back. */
64786  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
64787
64788  /* Set the error code of the destination database handle. */
64789  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
64790  if( p->pDestDb ){
64791    sqlite3Error(p->pDestDb, rc);
64792
64793    /* Exit the mutexes and free the backup context structure. */
64794    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
64795  }
64796  sqlite3BtreeLeave(p->pSrc);
64797  if( p->pDestDb ){
64798    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
64799    ** call to sqlite3_backup_init() and is destroyed by a call to
64800    ** sqlite3_backup_finish(). */
64801    sqlite3_free(p);
64802  }
64803  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
64804  return rc;
64805}
64806
64807/*
64808** Return the number of pages still to be backed up as of the most recent
64809** call to sqlite3_backup_step().
64810*/
64811SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
64812#ifdef SQLITE_ENABLE_API_ARMOR
64813  if( p==0 ){
64814    (void)SQLITE_MISUSE_BKPT;
64815    return 0;
64816  }
64817#endif
64818  return p->nRemaining;
64819}
64820
64821/*
64822** Return the total number of pages in the source database as of the most
64823** recent call to sqlite3_backup_step().
64824*/
64825SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
64826#ifdef SQLITE_ENABLE_API_ARMOR
64827  if( p==0 ){
64828    (void)SQLITE_MISUSE_BKPT;
64829    return 0;
64830  }
64831#endif
64832  return p->nPagecount;
64833}
64834
64835/*
64836** This function is called after the contents of page iPage of the
64837** source database have been modified. If page iPage has already been
64838** copied into the destination database, then the data written to the
64839** destination is now invalidated. The destination copy of iPage needs
64840** to be updated with the new data before the backup operation is
64841** complete.
64842**
64843** It is assumed that the mutex associated with the BtShared object
64844** corresponding to the source database is held when this function is
64845** called.
64846*/
64847static SQLITE_NOINLINE void backupUpdate(
64848  sqlite3_backup *p,
64849  Pgno iPage,
64850  const u8 *aData
64851){
64852  assert( p!=0 );
64853  do{
64854    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
64855    if( !isFatalError(p->rc) && iPage<p->iNext ){
64856      /* The backup process p has already copied page iPage. But now it
64857      ** has been modified by a transaction on the source pager. Copy
64858      ** the new data into the backup.
64859      */
64860      int rc;
64861      assert( p->pDestDb );
64862      sqlite3_mutex_enter(p->pDestDb->mutex);
64863      rc = backupOnePage(p, iPage, aData, 1);
64864      sqlite3_mutex_leave(p->pDestDb->mutex);
64865      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
64866      if( rc!=SQLITE_OK ){
64867        p->rc = rc;
64868      }
64869    }
64870  }while( (p = p->pNext)!=0 );
64871}
64872SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
64873  if( pBackup ) backupUpdate(pBackup, iPage, aData);
64874}
64875
64876/*
64877** Restart the backup process. This is called when the pager layer
64878** detects that the database has been modified by an external database
64879** connection. In this case there is no way of knowing which of the
64880** pages that have been copied into the destination database are still
64881** valid and which are not, so the entire process needs to be restarted.
64882**
64883** It is assumed that the mutex associated with the BtShared object
64884** corresponding to the source database is held when this function is
64885** called.
64886*/
64887SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
64888  sqlite3_backup *p;                   /* Iterator variable */
64889  for(p=pBackup; p; p=p->pNext){
64890    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
64891    p->iNext = 1;
64892  }
64893}
64894
64895#ifndef SQLITE_OMIT_VACUUM
64896/*
64897** Copy the complete content of pBtFrom into pBtTo.  A transaction
64898** must be active for both files.
64899**
64900** The size of file pTo may be reduced by this operation. If anything
64901** goes wrong, the transaction on pTo is rolled back. If successful, the
64902** transaction is committed before returning.
64903*/
64904SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
64905  int rc;
64906  sqlite3_file *pFd;              /* File descriptor for database pTo */
64907  sqlite3_backup b;
64908  sqlite3BtreeEnter(pTo);
64909  sqlite3BtreeEnter(pFrom);
64910
64911  assert( sqlite3BtreeIsInTrans(pTo) );
64912  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
64913  if( pFd->pMethods ){
64914    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
64915    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
64916    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
64917    if( rc ) goto copy_finished;
64918  }
64919
64920  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
64921  ** to 0. This is used by the implementations of sqlite3_backup_step()
64922  ** and sqlite3_backup_finish() to detect that they are being called
64923  ** from this function, not directly by the user.
64924  */
64925  memset(&b, 0, sizeof(b));
64926  b.pSrcDb = pFrom->db;
64927  b.pSrc = pFrom;
64928  b.pDest = pTo;
64929  b.iNext = 1;
64930
64931#ifdef SQLITE_HAS_CODEC
64932  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
64933#endif
64934
64935  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
64936  ** file. By passing this as the number of pages to copy to
64937  ** sqlite3_backup_step(), we can guarantee that the copy finishes
64938  ** within a single call (unless an error occurs). The assert() statement
64939  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
64940  ** or an error code.
64941  */
64942  sqlite3_backup_step(&b, 0x7FFFFFFF);
64943  assert( b.rc!=SQLITE_OK );
64944  rc = sqlite3_backup_finish(&b);
64945  if( rc==SQLITE_OK ){
64946    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
64947  }else{
64948    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
64949  }
64950
64951  assert( sqlite3BtreeIsInTrans(pTo)==0 );
64952copy_finished:
64953  sqlite3BtreeLeave(pFrom);
64954  sqlite3BtreeLeave(pTo);
64955  return rc;
64956}
64957#endif /* SQLITE_OMIT_VACUUM */
64958
64959/************** End of backup.c **********************************************/
64960/************** Begin file vdbemem.c *****************************************/
64961/*
64962** 2004 May 26
64963**
64964** The author disclaims copyright to this source code.  In place of
64965** a legal notice, here is a blessing:
64966**
64967**    May you do good and not evil.
64968**    May you find forgiveness for yourself and forgive others.
64969**    May you share freely, never taking more than you give.
64970**
64971*************************************************************************
64972**
64973** This file contains code use to manipulate "Mem" structure.  A "Mem"
64974** stores a single value in the VDBE.  Mem is an opaque structure visible
64975** only within the VDBE.  Interface routines refer to a Mem using the
64976** name sqlite_value
64977*/
64978/* #include "sqliteInt.h" */
64979/* #include "vdbeInt.h" */
64980
64981#ifdef SQLITE_DEBUG
64982/*
64983** Check invariants on a Mem object.
64984**
64985** This routine is intended for use inside of assert() statements, like
64986** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
64987*/
64988SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
64989  /* If MEM_Dyn is set then Mem.xDel!=0.
64990  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
64991  */
64992  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
64993
64994  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
64995  ** ensure that if Mem.szMalloc>0 then it is safe to do
64996  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
64997  ** That saves a few cycles in inner loops. */
64998  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
64999
65000  /* Cannot be both MEM_Int and MEM_Real at the same time */
65001  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
65002
65003  /* The szMalloc field holds the correct memory allocation size */
65004  assert( p->szMalloc==0
65005       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
65006
65007  /* If p holds a string or blob, the Mem.z must point to exactly
65008  ** one of the following:
65009  **
65010  **   (1) Memory in Mem.zMalloc and managed by the Mem object
65011  **   (2) Memory to be freed using Mem.xDel
65012  **   (3) An ephemeral string or blob
65013  **   (4) A static string or blob
65014  */
65015  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
65016    assert(
65017      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
65018      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
65019      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
65020      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
65021    );
65022  }
65023  return 1;
65024}
65025#endif
65026
65027
65028/*
65029** If pMem is an object with a valid string representation, this routine
65030** ensures the internal encoding for the string representation is
65031** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
65032**
65033** If pMem is not a string object, or the encoding of the string
65034** representation is already stored using the requested encoding, then this
65035** routine is a no-op.
65036**
65037** SQLITE_OK is returned if the conversion is successful (or not required).
65038** SQLITE_NOMEM may be returned if a malloc() fails during conversion
65039** between formats.
65040*/
65041SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
65042#ifndef SQLITE_OMIT_UTF16
65043  int rc;
65044#endif
65045  assert( (pMem->flags&MEM_RowSet)==0 );
65046  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
65047           || desiredEnc==SQLITE_UTF16BE );
65048  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
65049    return SQLITE_OK;
65050  }
65051  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65052#ifdef SQLITE_OMIT_UTF16
65053  return SQLITE_ERROR;
65054#else
65055
65056  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
65057  ** then the encoding of the value may not have changed.
65058  */
65059  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
65060  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
65061  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
65062  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
65063  return rc;
65064#endif
65065}
65066
65067/*
65068** Make sure pMem->z points to a writable allocation of at least
65069** min(n,32) bytes.
65070**
65071** If the bPreserve argument is true, then copy of the content of
65072** pMem->z into the new allocation.  pMem must be either a string or
65073** blob if bPreserve is true.  If bPreserve is false, any prior content
65074** in pMem->z is discarded.
65075*/
65076SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
65077  assert( sqlite3VdbeCheckMemInvariants(pMem) );
65078  assert( (pMem->flags&MEM_RowSet)==0 );
65079
65080  /* If the bPreserve flag is set to true, then the memory cell must already
65081  ** contain a valid string or blob value.  */
65082  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
65083  testcase( bPreserve && pMem->z==0 );
65084
65085  assert( pMem->szMalloc==0
65086       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
65087  if( pMem->szMalloc<n ){
65088    if( n<32 ) n = 32;
65089    if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
65090      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
65091      bPreserve = 0;
65092    }else{
65093      if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
65094      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
65095    }
65096    if( pMem->zMalloc==0 ){
65097      sqlite3VdbeMemSetNull(pMem);
65098      pMem->z = 0;
65099      pMem->szMalloc = 0;
65100      return SQLITE_NOMEM;
65101    }else{
65102      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
65103    }
65104  }
65105
65106  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
65107    memcpy(pMem->zMalloc, pMem->z, pMem->n);
65108  }
65109  if( (pMem->flags&MEM_Dyn)!=0 ){
65110    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
65111    pMem->xDel((void *)(pMem->z));
65112  }
65113
65114  pMem->z = pMem->zMalloc;
65115  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
65116  return SQLITE_OK;
65117}
65118
65119/*
65120** Change the pMem->zMalloc allocation to be at least szNew bytes.
65121** If pMem->zMalloc already meets or exceeds the requested size, this
65122** routine is a no-op.
65123**
65124** Any prior string or blob content in the pMem object may be discarded.
65125** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
65126** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
65127** values are preserved.
65128**
65129** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
65130** if unable to complete the resizing.
65131*/
65132SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
65133  assert( szNew>0 );
65134  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
65135  if( pMem->szMalloc<szNew ){
65136    return sqlite3VdbeMemGrow(pMem, szNew, 0);
65137  }
65138  assert( (pMem->flags & MEM_Dyn)==0 );
65139  pMem->z = pMem->zMalloc;
65140  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
65141  return SQLITE_OK;
65142}
65143
65144/*
65145** Change pMem so that its MEM_Str or MEM_Blob value is stored in
65146** MEM.zMalloc, where it can be safely written.
65147**
65148** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
65149*/
65150SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
65151  int f;
65152  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65153  assert( (pMem->flags&MEM_RowSet)==0 );
65154  ExpandBlob(pMem);
65155  f = pMem->flags;
65156  if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
65157    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
65158      return SQLITE_NOMEM;
65159    }
65160    pMem->z[pMem->n] = 0;
65161    pMem->z[pMem->n+1] = 0;
65162    pMem->flags |= MEM_Term;
65163  }
65164  pMem->flags &= ~MEM_Ephem;
65165#ifdef SQLITE_DEBUG
65166  pMem->pScopyFrom = 0;
65167#endif
65168
65169  return SQLITE_OK;
65170}
65171
65172/*
65173** If the given Mem* has a zero-filled tail, turn it into an ordinary
65174** blob stored in dynamically allocated space.
65175*/
65176#ifndef SQLITE_OMIT_INCRBLOB
65177SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
65178  if( pMem->flags & MEM_Zero ){
65179    int nByte;
65180    assert( pMem->flags&MEM_Blob );
65181    assert( (pMem->flags&MEM_RowSet)==0 );
65182    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65183
65184    /* Set nByte to the number of bytes required to store the expanded blob. */
65185    nByte = pMem->n + pMem->u.nZero;
65186    if( nByte<=0 ){
65187      nByte = 1;
65188    }
65189    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
65190      return SQLITE_NOMEM;
65191    }
65192
65193    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
65194    pMem->n += pMem->u.nZero;
65195    pMem->flags &= ~(MEM_Zero|MEM_Term);
65196  }
65197  return SQLITE_OK;
65198}
65199#endif
65200
65201/*
65202** It is already known that pMem contains an unterminated string.
65203** Add the zero terminator.
65204*/
65205static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
65206  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
65207    return SQLITE_NOMEM;
65208  }
65209  pMem->z[pMem->n] = 0;
65210  pMem->z[pMem->n+1] = 0;
65211  pMem->flags |= MEM_Term;
65212  return SQLITE_OK;
65213}
65214
65215/*
65216** Make sure the given Mem is \u0000 terminated.
65217*/
65218SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
65219  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65220  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
65221  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
65222  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
65223    return SQLITE_OK;   /* Nothing to do */
65224  }else{
65225    return vdbeMemAddTerminator(pMem);
65226  }
65227}
65228
65229/*
65230** Add MEM_Str to the set of representations for the given Mem.  Numbers
65231** are converted using sqlite3_snprintf().  Converting a BLOB to a string
65232** is a no-op.
65233**
65234** Existing representations MEM_Int and MEM_Real are invalidated if
65235** bForce is true but are retained if bForce is false.
65236**
65237** A MEM_Null value will never be passed to this function. This function is
65238** used for converting values to text for returning to the user (i.e. via
65239** sqlite3_value_text()), or for ensuring that values to be used as btree
65240** keys are strings. In the former case a NULL pointer is returned the
65241** user and the latter is an internal programming error.
65242*/
65243SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
65244  int fg = pMem->flags;
65245  const int nByte = 32;
65246
65247  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65248  assert( !(fg&MEM_Zero) );
65249  assert( !(fg&(MEM_Str|MEM_Blob)) );
65250  assert( fg&(MEM_Int|MEM_Real) );
65251  assert( (pMem->flags&MEM_RowSet)==0 );
65252  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65253
65254
65255  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
65256    return SQLITE_NOMEM;
65257  }
65258
65259  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
65260  ** string representation of the value. Then, if the required encoding
65261  ** is UTF-16le or UTF-16be do a translation.
65262  **
65263  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
65264  */
65265  if( fg & MEM_Int ){
65266    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
65267  }else{
65268    assert( fg & MEM_Real );
65269    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
65270  }
65271  pMem->n = sqlite3Strlen30(pMem->z);
65272  pMem->enc = SQLITE_UTF8;
65273  pMem->flags |= MEM_Str|MEM_Term;
65274  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
65275  sqlite3VdbeChangeEncoding(pMem, enc);
65276  return SQLITE_OK;
65277}
65278
65279/*
65280** Memory cell pMem contains the context of an aggregate function.
65281** This routine calls the finalize method for that function.  The
65282** result of the aggregate is stored back into pMem.
65283**
65284** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
65285** otherwise.
65286*/
65287SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
65288  int rc = SQLITE_OK;
65289  if( ALWAYS(pFunc && pFunc->xFinalize) ){
65290    sqlite3_context ctx;
65291    Mem t;
65292    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
65293    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65294    memset(&ctx, 0, sizeof(ctx));
65295    memset(&t, 0, sizeof(t));
65296    t.flags = MEM_Null;
65297    t.db = pMem->db;
65298    ctx.pOut = &t;
65299    ctx.pMem = pMem;
65300    ctx.pFunc = pFunc;
65301    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
65302    assert( (pMem->flags & MEM_Dyn)==0 );
65303    if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
65304    memcpy(pMem, &t, sizeof(t));
65305    rc = ctx.isError;
65306  }
65307  return rc;
65308}
65309
65310/*
65311** If the memory cell contains a value that must be freed by
65312** invoking the external callback in Mem.xDel, then this routine
65313** will free that value.  It also sets Mem.flags to MEM_Null.
65314**
65315** This is a helper routine for sqlite3VdbeMemSetNull() and
65316** for sqlite3VdbeMemRelease().  Use those other routines as the
65317** entry point for releasing Mem resources.
65318*/
65319static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
65320  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
65321  assert( VdbeMemDynamic(p) );
65322  if( p->flags&MEM_Agg ){
65323    sqlite3VdbeMemFinalize(p, p->u.pDef);
65324    assert( (p->flags & MEM_Agg)==0 );
65325    testcase( p->flags & MEM_Dyn );
65326  }
65327  if( p->flags&MEM_Dyn ){
65328    assert( (p->flags&MEM_RowSet)==0 );
65329    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
65330    p->xDel((void *)p->z);
65331  }else if( p->flags&MEM_RowSet ){
65332    sqlite3RowSetClear(p->u.pRowSet);
65333  }else if( p->flags&MEM_Frame ){
65334    VdbeFrame *pFrame = p->u.pFrame;
65335    pFrame->pParent = pFrame->v->pDelFrame;
65336    pFrame->v->pDelFrame = pFrame;
65337  }
65338  p->flags = MEM_Null;
65339}
65340
65341/*
65342** Release memory held by the Mem p, both external memory cleared
65343** by p->xDel and memory in p->zMalloc.
65344**
65345** This is a helper routine invoked by sqlite3VdbeMemRelease() in
65346** the unusual case where there really is memory in p that needs
65347** to be freed.
65348*/
65349static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
65350  if( VdbeMemDynamic(p) ){
65351    vdbeMemClearExternAndSetNull(p);
65352  }
65353  if( p->szMalloc ){
65354    sqlite3DbFree(p->db, p->zMalloc);
65355    p->szMalloc = 0;
65356  }
65357  p->z = 0;
65358}
65359
65360/*
65361** Release any memory resources held by the Mem.  Both the memory that is
65362** free by Mem.xDel and the Mem.zMalloc allocation are freed.
65363**
65364** Use this routine prior to clean up prior to abandoning a Mem, or to
65365** reset a Mem back to its minimum memory utilization.
65366**
65367** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
65368** prior to inserting new content into the Mem.
65369*/
65370SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
65371  assert( sqlite3VdbeCheckMemInvariants(p) );
65372  if( VdbeMemDynamic(p) || p->szMalloc ){
65373    vdbeMemClear(p);
65374  }
65375}
65376
65377/*
65378** Convert a 64-bit IEEE double into a 64-bit signed integer.
65379** If the double is out of range of a 64-bit signed integer then
65380** return the closest available 64-bit signed integer.
65381*/
65382static i64 doubleToInt64(double r){
65383#ifdef SQLITE_OMIT_FLOATING_POINT
65384  /* When floating-point is omitted, double and int64 are the same thing */
65385  return r;
65386#else
65387  /*
65388  ** Many compilers we encounter do not define constants for the
65389  ** minimum and maximum 64-bit integers, or they define them
65390  ** inconsistently.  And many do not understand the "LL" notation.
65391  ** So we define our own static constants here using nothing
65392  ** larger than a 32-bit integer constant.
65393  */
65394  static const i64 maxInt = LARGEST_INT64;
65395  static const i64 minInt = SMALLEST_INT64;
65396
65397  if( r<=(double)minInt ){
65398    return minInt;
65399  }else if( r>=(double)maxInt ){
65400    return maxInt;
65401  }else{
65402    return (i64)r;
65403  }
65404#endif
65405}
65406
65407/*
65408** Return some kind of integer value which is the best we can do
65409** at representing the value that *pMem describes as an integer.
65410** If pMem is an integer, then the value is exact.  If pMem is
65411** a floating-point then the value returned is the integer part.
65412** If pMem is a string or blob, then we make an attempt to convert
65413** it into an integer and return that.  If pMem represents an
65414** an SQL-NULL value, return 0.
65415**
65416** If pMem represents a string value, its encoding might be changed.
65417*/
65418SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
65419  int flags;
65420  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65421  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65422  flags = pMem->flags;
65423  if( flags & MEM_Int ){
65424    return pMem->u.i;
65425  }else if( flags & MEM_Real ){
65426    return doubleToInt64(pMem->u.r);
65427  }else if( flags & (MEM_Str|MEM_Blob) ){
65428    i64 value = 0;
65429    assert( pMem->z || pMem->n==0 );
65430    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
65431    return value;
65432  }else{
65433    return 0;
65434  }
65435}
65436
65437/*
65438** Return the best representation of pMem that we can get into a
65439** double.  If pMem is already a double or an integer, return its
65440** value.  If it is a string or blob, try to convert it to a double.
65441** If it is a NULL, return 0.0.
65442*/
65443SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
65444  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65445  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65446  if( pMem->flags & MEM_Real ){
65447    return pMem->u.r;
65448  }else if( pMem->flags & MEM_Int ){
65449    return (double)pMem->u.i;
65450  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
65451    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65452    double val = (double)0;
65453    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
65454    return val;
65455  }else{
65456    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65457    return (double)0;
65458  }
65459}
65460
65461/*
65462** The MEM structure is already a MEM_Real.  Try to also make it a
65463** MEM_Int if we can.
65464*/
65465SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
65466  i64 ix;
65467  assert( pMem->flags & MEM_Real );
65468  assert( (pMem->flags & MEM_RowSet)==0 );
65469  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65470  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65471
65472  ix = doubleToInt64(pMem->u.r);
65473
65474  /* Only mark the value as an integer if
65475  **
65476  **    (1) the round-trip conversion real->int->real is a no-op, and
65477  **    (2) The integer is neither the largest nor the smallest
65478  **        possible integer (ticket #3922)
65479  **
65480  ** The second and third terms in the following conditional enforces
65481  ** the second condition under the assumption that addition overflow causes
65482  ** values to wrap around.
65483  */
65484  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
65485    pMem->u.i = ix;
65486    MemSetTypeFlag(pMem, MEM_Int);
65487  }
65488}
65489
65490/*
65491** Convert pMem to type integer.  Invalidate any prior representations.
65492*/
65493SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
65494  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65495  assert( (pMem->flags & MEM_RowSet)==0 );
65496  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65497
65498  pMem->u.i = sqlite3VdbeIntValue(pMem);
65499  MemSetTypeFlag(pMem, MEM_Int);
65500  return SQLITE_OK;
65501}
65502
65503/*
65504** Convert pMem so that it is of type MEM_Real.
65505** Invalidate any prior representations.
65506*/
65507SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
65508  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65509  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65510
65511  pMem->u.r = sqlite3VdbeRealValue(pMem);
65512  MemSetTypeFlag(pMem, MEM_Real);
65513  return SQLITE_OK;
65514}
65515
65516/*
65517** Convert pMem so that it has types MEM_Real or MEM_Int or both.
65518** Invalidate any prior representations.
65519**
65520** Every effort is made to force the conversion, even if the input
65521** is a string that does not look completely like a number.  Convert
65522** as much of the string as we can and ignore the rest.
65523*/
65524SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
65525  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
65526    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
65527    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65528    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
65529      MemSetTypeFlag(pMem, MEM_Int);
65530    }else{
65531      pMem->u.r = sqlite3VdbeRealValue(pMem);
65532      MemSetTypeFlag(pMem, MEM_Real);
65533      sqlite3VdbeIntegerAffinity(pMem);
65534    }
65535  }
65536  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
65537  pMem->flags &= ~(MEM_Str|MEM_Blob);
65538  return SQLITE_OK;
65539}
65540
65541/*
65542** Cast the datatype of the value in pMem according to the affinity
65543** "aff".  Casting is different from applying affinity in that a cast
65544** is forced.  In other words, the value is converted into the desired
65545** affinity even if that results in loss of data.  This routine is
65546** used (for example) to implement the SQL "cast()" operator.
65547*/
65548SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
65549  if( pMem->flags & MEM_Null ) return;
65550  switch( aff ){
65551    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
65552      if( (pMem->flags & MEM_Blob)==0 ){
65553        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
65554        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
65555        MemSetTypeFlag(pMem, MEM_Blob);
65556      }else{
65557        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
65558      }
65559      break;
65560    }
65561    case SQLITE_AFF_NUMERIC: {
65562      sqlite3VdbeMemNumerify(pMem);
65563      break;
65564    }
65565    case SQLITE_AFF_INTEGER: {
65566      sqlite3VdbeMemIntegerify(pMem);
65567      break;
65568    }
65569    case SQLITE_AFF_REAL: {
65570      sqlite3VdbeMemRealify(pMem);
65571      break;
65572    }
65573    default: {
65574      assert( aff==SQLITE_AFF_TEXT );
65575      assert( MEM_Str==(MEM_Blob>>3) );
65576      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
65577      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
65578      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
65579      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65580      break;
65581    }
65582  }
65583}
65584
65585/*
65586** Initialize bulk memory to be a consistent Mem object.
65587**
65588** The minimum amount of initialization feasible is performed.
65589*/
65590SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
65591  assert( (flags & ~MEM_TypeMask)==0 );
65592  pMem->flags = flags;
65593  pMem->db = db;
65594  pMem->szMalloc = 0;
65595}
65596
65597
65598/*
65599** Delete any previous value and set the value stored in *pMem to NULL.
65600**
65601** This routine calls the Mem.xDel destructor to dispose of values that
65602** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
65603** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
65604** routine to invoke the destructor and deallocates Mem.zMalloc.
65605**
65606** Use this routine to reset the Mem prior to insert a new value.
65607**
65608** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
65609*/
65610SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
65611  if( VdbeMemDynamic(pMem) ){
65612    vdbeMemClearExternAndSetNull(pMem);
65613  }else{
65614    pMem->flags = MEM_Null;
65615  }
65616}
65617SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
65618  sqlite3VdbeMemSetNull((Mem*)p);
65619}
65620
65621/*
65622** Delete any previous value and set the value to be a BLOB of length
65623** n containing all zeros.
65624*/
65625SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
65626  sqlite3VdbeMemRelease(pMem);
65627  pMem->flags = MEM_Blob|MEM_Zero;
65628  pMem->n = 0;
65629  if( n<0 ) n = 0;
65630  pMem->u.nZero = n;
65631  pMem->enc = SQLITE_UTF8;
65632  pMem->z = 0;
65633}
65634
65635/*
65636** The pMem is known to contain content that needs to be destroyed prior
65637** to a value change.  So invoke the destructor, then set the value to
65638** a 64-bit integer.
65639*/
65640static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
65641  sqlite3VdbeMemSetNull(pMem);
65642  pMem->u.i = val;
65643  pMem->flags = MEM_Int;
65644}
65645
65646/*
65647** Delete any previous value and set the value stored in *pMem to val,
65648** manifest type INTEGER.
65649*/
65650SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
65651  if( VdbeMemDynamic(pMem) ){
65652    vdbeReleaseAndSetInt64(pMem, val);
65653  }else{
65654    pMem->u.i = val;
65655    pMem->flags = MEM_Int;
65656  }
65657}
65658
65659#ifndef SQLITE_OMIT_FLOATING_POINT
65660/*
65661** Delete any previous value and set the value stored in *pMem to val,
65662** manifest type REAL.
65663*/
65664SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
65665  sqlite3VdbeMemSetNull(pMem);
65666  if( !sqlite3IsNaN(val) ){
65667    pMem->u.r = val;
65668    pMem->flags = MEM_Real;
65669  }
65670}
65671#endif
65672
65673/*
65674** Delete any previous value and set the value of pMem to be an
65675** empty boolean index.
65676*/
65677SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
65678  sqlite3 *db = pMem->db;
65679  assert( db!=0 );
65680  assert( (pMem->flags & MEM_RowSet)==0 );
65681  sqlite3VdbeMemRelease(pMem);
65682  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
65683  if( db->mallocFailed ){
65684    pMem->flags = MEM_Null;
65685    pMem->szMalloc = 0;
65686  }else{
65687    assert( pMem->zMalloc );
65688    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
65689    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
65690    assert( pMem->u.pRowSet!=0 );
65691    pMem->flags = MEM_RowSet;
65692  }
65693}
65694
65695/*
65696** Return true if the Mem object contains a TEXT or BLOB that is
65697** too large - whose size exceeds SQLITE_MAX_LENGTH.
65698*/
65699SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
65700  assert( p->db!=0 );
65701  if( p->flags & (MEM_Str|MEM_Blob) ){
65702    int n = p->n;
65703    if( p->flags & MEM_Zero ){
65704      n += p->u.nZero;
65705    }
65706    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
65707  }
65708  return 0;
65709}
65710
65711#ifdef SQLITE_DEBUG
65712/*
65713** This routine prepares a memory cell for modification by breaking
65714** its link to a shallow copy and by marking any current shallow
65715** copies of this cell as invalid.
65716**
65717** This is used for testing and debugging only - to make sure shallow
65718** copies are not misused.
65719*/
65720SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
65721  int i;
65722  Mem *pX;
65723  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
65724    if( pX->pScopyFrom==pMem ){
65725      pX->flags |= MEM_Undefined;
65726      pX->pScopyFrom = 0;
65727    }
65728  }
65729  pMem->pScopyFrom = 0;
65730}
65731#endif /* SQLITE_DEBUG */
65732
65733
65734/*
65735** Make an shallow copy of pFrom into pTo.  Prior contents of
65736** pTo are freed.  The pFrom->z field is not duplicated.  If
65737** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
65738** and flags gets srcType (either MEM_Ephem or MEM_Static).
65739*/
65740static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
65741  vdbeMemClearExternAndSetNull(pTo);
65742  assert( !VdbeMemDynamic(pTo) );
65743  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
65744}
65745SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
65746  assert( (pFrom->flags & MEM_RowSet)==0 );
65747  assert( pTo->db==pFrom->db );
65748  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
65749  memcpy(pTo, pFrom, MEMCELLSIZE);
65750  if( (pFrom->flags&MEM_Static)==0 ){
65751    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
65752    assert( srcType==MEM_Ephem || srcType==MEM_Static );
65753    pTo->flags |= srcType;
65754  }
65755}
65756
65757/*
65758** Make a full copy of pFrom into pTo.  Prior contents of pTo are
65759** freed before the copy is made.
65760*/
65761SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
65762  int rc = SQLITE_OK;
65763
65764  /* The pFrom==0 case in the following assert() is when an sqlite3_value
65765  ** from sqlite3_value_dup() is used as the argument
65766  ** to sqlite3_result_value(). */
65767  assert( pTo->db==pFrom->db || pFrom->db==0 );
65768  assert( (pFrom->flags & MEM_RowSet)==0 );
65769  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
65770  memcpy(pTo, pFrom, MEMCELLSIZE);
65771  pTo->flags &= ~MEM_Dyn;
65772  if( pTo->flags&(MEM_Str|MEM_Blob) ){
65773    if( 0==(pFrom->flags&MEM_Static) ){
65774      pTo->flags |= MEM_Ephem;
65775      rc = sqlite3VdbeMemMakeWriteable(pTo);
65776    }
65777  }
65778
65779  return rc;
65780}
65781
65782/*
65783** Transfer the contents of pFrom to pTo. Any existing value in pTo is
65784** freed. If pFrom contains ephemeral data, a copy is made.
65785**
65786** pFrom contains an SQL NULL when this routine returns.
65787*/
65788SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
65789  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
65790  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
65791  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
65792
65793  sqlite3VdbeMemRelease(pTo);
65794  memcpy(pTo, pFrom, sizeof(Mem));
65795  pFrom->flags = MEM_Null;
65796  pFrom->szMalloc = 0;
65797}
65798
65799/*
65800** Change the value of a Mem to be a string or a BLOB.
65801**
65802** The memory management strategy depends on the value of the xDel
65803** parameter. If the value passed is SQLITE_TRANSIENT, then the
65804** string is copied into a (possibly existing) buffer managed by the
65805** Mem structure. Otherwise, any existing buffer is freed and the
65806** pointer copied.
65807**
65808** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
65809** size limit) then no memory allocation occurs.  If the string can be
65810** stored without allocating memory, then it is.  If a memory allocation
65811** is required to store the string, then value of pMem is unchanged.  In
65812** either case, SQLITE_TOOBIG is returned.
65813*/
65814SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
65815  Mem *pMem,          /* Memory cell to set to string value */
65816  const char *z,      /* String pointer */
65817  int n,              /* Bytes in string, or negative */
65818  u8 enc,             /* Encoding of z.  0 for BLOBs */
65819  void (*xDel)(void*) /* Destructor function */
65820){
65821  int nByte = n;      /* New value for pMem->n */
65822  int iLimit;         /* Maximum allowed string or blob size */
65823  u16 flags = 0;      /* New value for pMem->flags */
65824
65825  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65826  assert( (pMem->flags & MEM_RowSet)==0 );
65827
65828  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
65829  if( !z ){
65830    sqlite3VdbeMemSetNull(pMem);
65831    return SQLITE_OK;
65832  }
65833
65834  if( pMem->db ){
65835    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
65836  }else{
65837    iLimit = SQLITE_MAX_LENGTH;
65838  }
65839  flags = (enc==0?MEM_Blob:MEM_Str);
65840  if( nByte<0 ){
65841    assert( enc!=0 );
65842    if( enc==SQLITE_UTF8 ){
65843      nByte = sqlite3Strlen30(z);
65844      if( nByte>iLimit ) nByte = iLimit+1;
65845    }else{
65846      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
65847    }
65848    flags |= MEM_Term;
65849  }
65850
65851  /* The following block sets the new values of Mem.z and Mem.xDel. It
65852  ** also sets a flag in local variable "flags" to indicate the memory
65853  ** management (one of MEM_Dyn or MEM_Static).
65854  */
65855  if( xDel==SQLITE_TRANSIENT ){
65856    int nAlloc = nByte;
65857    if( flags&MEM_Term ){
65858      nAlloc += (enc==SQLITE_UTF8?1:2);
65859    }
65860    if( nByte>iLimit ){
65861      return SQLITE_TOOBIG;
65862    }
65863    testcase( nAlloc==0 );
65864    testcase( nAlloc==31 );
65865    testcase( nAlloc==32 );
65866    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
65867      return SQLITE_NOMEM;
65868    }
65869    memcpy(pMem->z, z, nAlloc);
65870  }else if( xDel==SQLITE_DYNAMIC ){
65871    sqlite3VdbeMemRelease(pMem);
65872    pMem->zMalloc = pMem->z = (char *)z;
65873    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
65874  }else{
65875    sqlite3VdbeMemRelease(pMem);
65876    pMem->z = (char *)z;
65877    pMem->xDel = xDel;
65878    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
65879  }
65880
65881  pMem->n = nByte;
65882  pMem->flags = flags;
65883  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
65884
65885#ifndef SQLITE_OMIT_UTF16
65886  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
65887    return SQLITE_NOMEM;
65888  }
65889#endif
65890
65891  if( nByte>iLimit ){
65892    return SQLITE_TOOBIG;
65893  }
65894
65895  return SQLITE_OK;
65896}
65897
65898/*
65899** Move data out of a btree key or data field and into a Mem structure.
65900** The data or key is taken from the entry that pCur is currently pointing
65901** to.  offset and amt determine what portion of the data or key to retrieve.
65902** key is true to get the key or false to get data.  The result is written
65903** into the pMem element.
65904**
65905** The pMem object must have been initialized.  This routine will use
65906** pMem->zMalloc to hold the content from the btree, if possible.  New
65907** pMem->zMalloc space will be allocated if necessary.  The calling routine
65908** is responsible for making sure that the pMem object is eventually
65909** destroyed.
65910**
65911** If this routine fails for any reason (malloc returns NULL or unable
65912** to read from the disk) then the pMem is left in an inconsistent state.
65913*/
65914static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
65915  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
65916  u32 offset,       /* Offset from the start of data to return bytes from. */
65917  u32 amt,          /* Number of bytes to return. */
65918  int key,          /* If true, retrieve from the btree key, not data. */
65919  Mem *pMem         /* OUT: Return data in this Mem structure. */
65920){
65921  int rc;
65922  pMem->flags = MEM_Null;
65923  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
65924    if( key ){
65925      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
65926    }else{
65927      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
65928    }
65929    if( rc==SQLITE_OK ){
65930      pMem->z[amt] = 0;
65931      pMem->z[amt+1] = 0;
65932      pMem->flags = MEM_Blob|MEM_Term;
65933      pMem->n = (int)amt;
65934    }else{
65935      sqlite3VdbeMemRelease(pMem);
65936    }
65937  }
65938  return rc;
65939}
65940SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
65941  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
65942  u32 offset,       /* Offset from the start of data to return bytes from. */
65943  u32 amt,          /* Number of bytes to return. */
65944  int key,          /* If true, retrieve from the btree key, not data. */
65945  Mem *pMem         /* OUT: Return data in this Mem structure. */
65946){
65947  char *zData;        /* Data from the btree layer */
65948  u32 available = 0;  /* Number of bytes available on the local btree page */
65949  int rc = SQLITE_OK; /* Return code */
65950
65951  assert( sqlite3BtreeCursorIsValid(pCur) );
65952  assert( !VdbeMemDynamic(pMem) );
65953
65954  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
65955  ** that both the BtShared and database handle mutexes are held. */
65956  assert( (pMem->flags & MEM_RowSet)==0 );
65957  if( key ){
65958    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
65959  }else{
65960    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
65961  }
65962  assert( zData!=0 );
65963
65964  if( offset+amt<=available ){
65965    pMem->z = &zData[offset];
65966    pMem->flags = MEM_Blob|MEM_Ephem;
65967    pMem->n = (int)amt;
65968  }else{
65969    rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
65970  }
65971
65972  return rc;
65973}
65974
65975/*
65976** The pVal argument is known to be a value other than NULL.
65977** Convert it into a string with encoding enc and return a pointer
65978** to a zero-terminated version of that string.
65979*/
65980static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
65981  assert( pVal!=0 );
65982  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
65983  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
65984  assert( (pVal->flags & MEM_RowSet)==0 );
65985  assert( (pVal->flags & (MEM_Null))==0 );
65986  if( pVal->flags & (MEM_Blob|MEM_Str) ){
65987    pVal->flags |= MEM_Str;
65988    if( pVal->flags & MEM_Zero ){
65989      sqlite3VdbeMemExpandBlob(pVal);
65990    }
65991    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
65992      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
65993    }
65994    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
65995      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
65996      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
65997        return 0;
65998      }
65999    }
66000    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
66001  }else{
66002    sqlite3VdbeMemStringify(pVal, enc, 0);
66003    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
66004  }
66005  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
66006              || pVal->db->mallocFailed );
66007  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
66008    return pVal->z;
66009  }else{
66010    return 0;
66011  }
66012}
66013
66014/* This function is only available internally, it is not part of the
66015** external API. It works in a similar way to sqlite3_value_text(),
66016** except the data returned is in the encoding specified by the second
66017** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
66018** SQLITE_UTF8.
66019**
66020** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
66021** If that is the case, then the result must be aligned on an even byte
66022** boundary.
66023*/
66024SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
66025  if( !pVal ) return 0;
66026  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
66027  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
66028  assert( (pVal->flags & MEM_RowSet)==0 );
66029  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
66030    return pVal->z;
66031  }
66032  if( pVal->flags&MEM_Null ){
66033    return 0;
66034  }
66035  return valueToText(pVal, enc);
66036}
66037
66038/*
66039** Create a new sqlite3_value object.
66040*/
66041SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
66042  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
66043  if( p ){
66044    p->flags = MEM_Null;
66045    p->db = db;
66046  }
66047  return p;
66048}
66049
66050/*
66051** Context object passed by sqlite3Stat4ProbeSetValue() through to
66052** valueNew(). See comments above valueNew() for details.
66053*/
66054struct ValueNewStat4Ctx {
66055  Parse *pParse;
66056  Index *pIdx;
66057  UnpackedRecord **ppRec;
66058  int iVal;
66059};
66060
66061/*
66062** Allocate and return a pointer to a new sqlite3_value object. If
66063** the second argument to this function is NULL, the object is allocated
66064** by calling sqlite3ValueNew().
66065**
66066** Otherwise, if the second argument is non-zero, then this function is
66067** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
66068** already been allocated, allocate the UnpackedRecord structure that
66069** that function will return to its caller here. Then return a pointer to
66070** an sqlite3_value within the UnpackedRecord.a[] array.
66071*/
66072static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
66073#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66074  if( p ){
66075    UnpackedRecord *pRec = p->ppRec[0];
66076
66077    if( pRec==0 ){
66078      Index *pIdx = p->pIdx;      /* Index being probed */
66079      int nByte;                  /* Bytes of space to allocate */
66080      int i;                      /* Counter variable */
66081      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
66082
66083      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
66084      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
66085      if( pRec ){
66086        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
66087        if( pRec->pKeyInfo ){
66088          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
66089          assert( pRec->pKeyInfo->enc==ENC(db) );
66090          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
66091          for(i=0; i<nCol; i++){
66092            pRec->aMem[i].flags = MEM_Null;
66093            pRec->aMem[i].db = db;
66094          }
66095        }else{
66096          sqlite3DbFree(db, pRec);
66097          pRec = 0;
66098        }
66099      }
66100      if( pRec==0 ) return 0;
66101      p->ppRec[0] = pRec;
66102    }
66103
66104    pRec->nField = p->iVal+1;
66105    return &pRec->aMem[p->iVal];
66106  }
66107#else
66108  UNUSED_PARAMETER(p);
66109#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
66110  return sqlite3ValueNew(db);
66111}
66112
66113/*
66114** The expression object indicated by the second argument is guaranteed
66115** to be a scalar SQL function. If
66116**
66117**   * all function arguments are SQL literals,
66118**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
66119**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
66120**
66121** then this routine attempts to invoke the SQL function. Assuming no
66122** error occurs, output parameter (*ppVal) is set to point to a value
66123** object containing the result before returning SQLITE_OK.
66124**
66125** Affinity aff is applied to the result of the function before returning.
66126** If the result is a text value, the sqlite3_value object uses encoding
66127** enc.
66128**
66129** If the conditions above are not met, this function returns SQLITE_OK
66130** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
66131** NULL and an SQLite error code returned.
66132*/
66133#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66134static int valueFromFunction(
66135  sqlite3 *db,                    /* The database connection */
66136  Expr *p,                        /* The expression to evaluate */
66137  u8 enc,                         /* Encoding to use */
66138  u8 aff,                         /* Affinity to use */
66139  sqlite3_value **ppVal,          /* Write the new value here */
66140  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
66141){
66142  sqlite3_context ctx;            /* Context object for function invocation */
66143  sqlite3_value **apVal = 0;      /* Function arguments */
66144  int nVal = 0;                   /* Size of apVal[] array */
66145  FuncDef *pFunc = 0;             /* Function definition */
66146  sqlite3_value *pVal = 0;        /* New value */
66147  int rc = SQLITE_OK;             /* Return code */
66148  int nName;                      /* Size of function name in bytes */
66149  ExprList *pList = 0;            /* Function arguments */
66150  int i;                          /* Iterator variable */
66151
66152  assert( pCtx!=0 );
66153  assert( (p->flags & EP_TokenOnly)==0 );
66154  pList = p->x.pList;
66155  if( pList ) nVal = pList->nExpr;
66156  nName = sqlite3Strlen30(p->u.zToken);
66157  pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
66158  assert( pFunc );
66159  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
66160   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
66161  ){
66162    return SQLITE_OK;
66163  }
66164
66165  if( pList ){
66166    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
66167    if( apVal==0 ){
66168      rc = SQLITE_NOMEM;
66169      goto value_from_function_out;
66170    }
66171    for(i=0; i<nVal; i++){
66172      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
66173      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
66174    }
66175  }
66176
66177  pVal = valueNew(db, pCtx);
66178  if( pVal==0 ){
66179    rc = SQLITE_NOMEM;
66180    goto value_from_function_out;
66181  }
66182
66183  assert( pCtx->pParse->rc==SQLITE_OK );
66184  memset(&ctx, 0, sizeof(ctx));
66185  ctx.pOut = pVal;
66186  ctx.pFunc = pFunc;
66187  pFunc->xFunc(&ctx, nVal, apVal);
66188  if( ctx.isError ){
66189    rc = ctx.isError;
66190    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
66191  }else{
66192    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
66193    assert( rc==SQLITE_OK );
66194    rc = sqlite3VdbeChangeEncoding(pVal, enc);
66195    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
66196      rc = SQLITE_TOOBIG;
66197      pCtx->pParse->nErr++;
66198    }
66199  }
66200  pCtx->pParse->rc = rc;
66201
66202 value_from_function_out:
66203  if( rc!=SQLITE_OK ){
66204    pVal = 0;
66205  }
66206  if( apVal ){
66207    for(i=0; i<nVal; i++){
66208      sqlite3ValueFree(apVal[i]);
66209    }
66210    sqlite3DbFree(db, apVal);
66211  }
66212
66213  *ppVal = pVal;
66214  return rc;
66215}
66216#else
66217# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
66218#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
66219
66220/*
66221** Extract a value from the supplied expression in the manner described
66222** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
66223** using valueNew().
66224**
66225** If pCtx is NULL and an error occurs after the sqlite3_value object
66226** has been allocated, it is freed before returning. Or, if pCtx is not
66227** NULL, it is assumed that the caller will free any allocated object
66228** in all cases.
66229*/
66230static int valueFromExpr(
66231  sqlite3 *db,                    /* The database connection */
66232  Expr *pExpr,                    /* The expression to evaluate */
66233  u8 enc,                         /* Encoding to use */
66234  u8 affinity,                    /* Affinity to use */
66235  sqlite3_value **ppVal,          /* Write the new value here */
66236  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
66237){
66238  int op;
66239  char *zVal = 0;
66240  sqlite3_value *pVal = 0;
66241  int negInt = 1;
66242  const char *zNeg = "";
66243  int rc = SQLITE_OK;
66244
66245  if( !pExpr ){
66246    *ppVal = 0;
66247    return SQLITE_OK;
66248  }
66249  while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
66250  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
66251
66252  /* Compressed expressions only appear when parsing the DEFAULT clause
66253  ** on a table column definition, and hence only when pCtx==0.  This
66254  ** check ensures that an EP_TokenOnly expression is never passed down
66255  ** into valueFromFunction(). */
66256  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
66257
66258  if( op==TK_CAST ){
66259    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
66260    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
66261    testcase( rc!=SQLITE_OK );
66262    if( *ppVal ){
66263      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
66264      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
66265    }
66266    return rc;
66267  }
66268
66269  /* Handle negative integers in a single step.  This is needed in the
66270  ** case when the value is -9223372036854775808.
66271  */
66272  if( op==TK_UMINUS
66273   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
66274    pExpr = pExpr->pLeft;
66275    op = pExpr->op;
66276    negInt = -1;
66277    zNeg = "-";
66278  }
66279
66280  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
66281    pVal = valueNew(db, pCtx);
66282    if( pVal==0 ) goto no_mem;
66283    if( ExprHasProperty(pExpr, EP_IntValue) ){
66284      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
66285    }else{
66286      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
66287      if( zVal==0 ) goto no_mem;
66288      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
66289    }
66290    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
66291      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
66292    }else{
66293      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
66294    }
66295    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
66296    if( enc!=SQLITE_UTF8 ){
66297      rc = sqlite3VdbeChangeEncoding(pVal, enc);
66298    }
66299  }else if( op==TK_UMINUS ) {
66300    /* This branch happens for multiple negative signs.  Ex: -(-5) */
66301    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
66302     && pVal!=0
66303    ){
66304      sqlite3VdbeMemNumerify(pVal);
66305      if( pVal->flags & MEM_Real ){
66306        pVal->u.r = -pVal->u.r;
66307      }else if( pVal->u.i==SMALLEST_INT64 ){
66308        pVal->u.r = -(double)SMALLEST_INT64;
66309        MemSetTypeFlag(pVal, MEM_Real);
66310      }else{
66311        pVal->u.i = -pVal->u.i;
66312      }
66313      sqlite3ValueApplyAffinity(pVal, affinity, enc);
66314    }
66315  }else if( op==TK_NULL ){
66316    pVal = valueNew(db, pCtx);
66317    if( pVal==0 ) goto no_mem;
66318  }
66319#ifndef SQLITE_OMIT_BLOB_LITERAL
66320  else if( op==TK_BLOB ){
66321    int nVal;
66322    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
66323    assert( pExpr->u.zToken[1]=='\'' );
66324    pVal = valueNew(db, pCtx);
66325    if( !pVal ) goto no_mem;
66326    zVal = &pExpr->u.zToken[2];
66327    nVal = sqlite3Strlen30(zVal)-1;
66328    assert( zVal[nVal]=='\'' );
66329    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
66330                         0, SQLITE_DYNAMIC);
66331  }
66332#endif
66333
66334#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66335  else if( op==TK_FUNCTION && pCtx!=0 ){
66336    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
66337  }
66338#endif
66339
66340  *ppVal = pVal;
66341  return rc;
66342
66343no_mem:
66344  db->mallocFailed = 1;
66345  sqlite3DbFree(db, zVal);
66346  assert( *ppVal==0 );
66347#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66348  if( pCtx==0 ) sqlite3ValueFree(pVal);
66349#else
66350  assert( pCtx==0 ); sqlite3ValueFree(pVal);
66351#endif
66352  return SQLITE_NOMEM;
66353}
66354
66355/*
66356** Create a new sqlite3_value object, containing the value of pExpr.
66357**
66358** This only works for very simple expressions that consist of one constant
66359** token (i.e. "5", "5.1", "'a string'"). If the expression can
66360** be converted directly into a value, then the value is allocated and
66361** a pointer written to *ppVal. The caller is responsible for deallocating
66362** the value by passing it to sqlite3ValueFree() later on. If the expression
66363** cannot be converted to a value, then *ppVal is set to NULL.
66364*/
66365SQLITE_PRIVATE int sqlite3ValueFromExpr(
66366  sqlite3 *db,              /* The database connection */
66367  Expr *pExpr,              /* The expression to evaluate */
66368  u8 enc,                   /* Encoding to use */
66369  u8 affinity,              /* Affinity to use */
66370  sqlite3_value **ppVal     /* Write the new value here */
66371){
66372  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
66373}
66374
66375#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66376/*
66377** The implementation of the sqlite_record() function. This function accepts
66378** a single argument of any type. The return value is a formatted database
66379** record (a blob) containing the argument value.
66380**
66381** This is used to convert the value stored in the 'sample' column of the
66382** sqlite_stat3 table to the record format SQLite uses internally.
66383*/
66384static void recordFunc(
66385  sqlite3_context *context,
66386  int argc,
66387  sqlite3_value **argv
66388){
66389  const int file_format = 1;
66390  int iSerial;                    /* Serial type */
66391  int nSerial;                    /* Bytes of space for iSerial as varint */
66392  int nVal;                       /* Bytes of space required for argv[0] */
66393  int nRet;
66394  sqlite3 *db;
66395  u8 *aRet;
66396
66397  UNUSED_PARAMETER( argc );
66398  iSerial = sqlite3VdbeSerialType(argv[0], file_format);
66399  nSerial = sqlite3VarintLen(iSerial);
66400  nVal = sqlite3VdbeSerialTypeLen(iSerial);
66401  db = sqlite3_context_db_handle(context);
66402
66403  nRet = 1 + nSerial + nVal;
66404  aRet = sqlite3DbMallocRaw(db, nRet);
66405  if( aRet==0 ){
66406    sqlite3_result_error_nomem(context);
66407  }else{
66408    aRet[0] = nSerial+1;
66409    putVarint32(&aRet[1], iSerial);
66410    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
66411    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
66412    sqlite3DbFree(db, aRet);
66413  }
66414}
66415
66416/*
66417** Register built-in functions used to help read ANALYZE data.
66418*/
66419SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
66420  static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
66421    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
66422  };
66423  int i;
66424  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
66425  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
66426  for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
66427    sqlite3FuncDefInsert(pHash, &aFunc[i]);
66428  }
66429}
66430
66431/*
66432** Attempt to extract a value from pExpr and use it to construct *ppVal.
66433**
66434** If pAlloc is not NULL, then an UnpackedRecord object is created for
66435** pAlloc if one does not exist and the new value is added to the
66436** UnpackedRecord object.
66437**
66438** A value is extracted in the following cases:
66439**
66440**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
66441**
66442**  * The expression is a bound variable, and this is a reprepare, or
66443**
66444**  * The expression is a literal value.
66445**
66446** On success, *ppVal is made to point to the extracted value.  The caller
66447** is responsible for ensuring that the value is eventually freed.
66448*/
66449static int stat4ValueFromExpr(
66450  Parse *pParse,                  /* Parse context */
66451  Expr *pExpr,                    /* The expression to extract a value from */
66452  u8 affinity,                    /* Affinity to use */
66453  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
66454  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
66455){
66456  int rc = SQLITE_OK;
66457  sqlite3_value *pVal = 0;
66458  sqlite3 *db = pParse->db;
66459
66460  /* Skip over any TK_COLLATE nodes */
66461  pExpr = sqlite3ExprSkipCollate(pExpr);
66462
66463  if( !pExpr ){
66464    pVal = valueNew(db, pAlloc);
66465    if( pVal ){
66466      sqlite3VdbeMemSetNull((Mem*)pVal);
66467    }
66468  }else if( pExpr->op==TK_VARIABLE
66469        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
66470  ){
66471    Vdbe *v;
66472    int iBindVar = pExpr->iColumn;
66473    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
66474    if( (v = pParse->pReprepare)!=0 ){
66475      pVal = valueNew(db, pAlloc);
66476      if( pVal ){
66477        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
66478        if( rc==SQLITE_OK ){
66479          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
66480        }
66481        pVal->db = pParse->db;
66482      }
66483    }
66484  }else{
66485    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
66486  }
66487
66488  assert( pVal==0 || pVal->db==db );
66489  *ppVal = pVal;
66490  return rc;
66491}
66492
66493/*
66494** This function is used to allocate and populate UnpackedRecord
66495** structures intended to be compared against sample index keys stored
66496** in the sqlite_stat4 table.
66497**
66498** A single call to this function attempts to populates field iVal (leftmost
66499** is 0 etc.) of the unpacked record with a value extracted from expression
66500** pExpr. Extraction of values is possible if:
66501**
66502**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
66503**
66504**  * The expression is a bound variable, and this is a reprepare, or
66505**
66506**  * The sqlite3ValueFromExpr() function is able to extract a value
66507**    from the expression (i.e. the expression is a literal value).
66508**
66509** If a value can be extracted, the affinity passed as the 5th argument
66510** is applied to it before it is copied into the UnpackedRecord. Output
66511** parameter *pbOk is set to true if a value is extracted, or false
66512** otherwise.
66513**
66514** When this function is called, *ppRec must either point to an object
66515** allocated by an earlier call to this function, or must be NULL. If it
66516** is NULL and a value can be successfully extracted, a new UnpackedRecord
66517** is allocated (and *ppRec set to point to it) before returning.
66518**
66519** Unless an error is encountered, SQLITE_OK is returned. It is not an
66520** error if a value cannot be extracted from pExpr. If an error does
66521** occur, an SQLite error code is returned.
66522*/
66523SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
66524  Parse *pParse,                  /* Parse context */
66525  Index *pIdx,                    /* Index being probed */
66526  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
66527  Expr *pExpr,                    /* The expression to extract a value from */
66528  u8 affinity,                    /* Affinity to use */
66529  int iVal,                       /* Array element to populate */
66530  int *pbOk                       /* OUT: True if value was extracted */
66531){
66532  int rc;
66533  sqlite3_value *pVal = 0;
66534  struct ValueNewStat4Ctx alloc;
66535
66536  alloc.pParse = pParse;
66537  alloc.pIdx = pIdx;
66538  alloc.ppRec = ppRec;
66539  alloc.iVal = iVal;
66540
66541  rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
66542  assert( pVal==0 || pVal->db==pParse->db );
66543  *pbOk = (pVal!=0);
66544  return rc;
66545}
66546
66547/*
66548** Attempt to extract a value from expression pExpr using the methods
66549** as described for sqlite3Stat4ProbeSetValue() above.
66550**
66551** If successful, set *ppVal to point to a new value object and return
66552** SQLITE_OK. If no value can be extracted, but no other error occurs
66553** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
66554** does occur, return an SQLite error code. The final value of *ppVal
66555** is undefined in this case.
66556*/
66557SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
66558  Parse *pParse,                  /* Parse context */
66559  Expr *pExpr,                    /* The expression to extract a value from */
66560  u8 affinity,                    /* Affinity to use */
66561  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
66562){
66563  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
66564}
66565
66566/*
66567** Extract the iCol-th column from the nRec-byte record in pRec.  Write
66568** the column value into *ppVal.  If *ppVal is initially NULL then a new
66569** sqlite3_value object is allocated.
66570**
66571** If *ppVal is initially NULL then the caller is responsible for
66572** ensuring that the value written into *ppVal is eventually freed.
66573*/
66574SQLITE_PRIVATE int sqlite3Stat4Column(
66575  sqlite3 *db,                    /* Database handle */
66576  const void *pRec,               /* Pointer to buffer containing record */
66577  int nRec,                       /* Size of buffer pRec in bytes */
66578  int iCol,                       /* Column to extract */
66579  sqlite3_value **ppVal           /* OUT: Extracted value */
66580){
66581  u32 t;                          /* a column type code */
66582  int nHdr;                       /* Size of the header in the record */
66583  int iHdr;                       /* Next unread header byte */
66584  int iField;                     /* Next unread data byte */
66585  int szField;                    /* Size of the current data field */
66586  int i;                          /* Column index */
66587  u8 *a = (u8*)pRec;              /* Typecast byte array */
66588  Mem *pMem = *ppVal;             /* Write result into this Mem object */
66589
66590  assert( iCol>0 );
66591  iHdr = getVarint32(a, nHdr);
66592  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
66593  iField = nHdr;
66594  for(i=0; i<=iCol; i++){
66595    iHdr += getVarint32(&a[iHdr], t);
66596    testcase( iHdr==nHdr );
66597    testcase( iHdr==nHdr+1 );
66598    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
66599    szField = sqlite3VdbeSerialTypeLen(t);
66600    iField += szField;
66601  }
66602  testcase( iField==nRec );
66603  testcase( iField==nRec+1 );
66604  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
66605  if( pMem==0 ){
66606    pMem = *ppVal = sqlite3ValueNew(db);
66607    if( pMem==0 ) return SQLITE_NOMEM;
66608  }
66609  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
66610  pMem->enc = ENC(db);
66611  return SQLITE_OK;
66612}
66613
66614/*
66615** Unless it is NULL, the argument must be an UnpackedRecord object returned
66616** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
66617** the object.
66618*/
66619SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
66620  if( pRec ){
66621    int i;
66622    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
66623    Mem *aMem = pRec->aMem;
66624    sqlite3 *db = aMem[0].db;
66625    for(i=0; i<nCol; i++){
66626      sqlite3VdbeMemRelease(&aMem[i]);
66627    }
66628    sqlite3KeyInfoUnref(pRec->pKeyInfo);
66629    sqlite3DbFree(db, pRec);
66630  }
66631}
66632#endif /* ifdef SQLITE_ENABLE_STAT4 */
66633
66634/*
66635** Change the string value of an sqlite3_value object
66636*/
66637SQLITE_PRIVATE void sqlite3ValueSetStr(
66638  sqlite3_value *v,     /* Value to be set */
66639  int n,                /* Length of string z */
66640  const void *z,        /* Text of the new string */
66641  u8 enc,               /* Encoding to use */
66642  void (*xDel)(void*)   /* Destructor for the string */
66643){
66644  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
66645}
66646
66647/*
66648** Free an sqlite3_value object
66649*/
66650SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
66651  if( !v ) return;
66652  sqlite3VdbeMemRelease((Mem *)v);
66653  sqlite3DbFree(((Mem*)v)->db, v);
66654}
66655
66656/*
66657** The sqlite3ValueBytes() routine returns the number of bytes in the
66658** sqlite3_value object assuming that it uses the encoding "enc".
66659** The valueBytes() routine is a helper function.
66660*/
66661static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
66662  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
66663}
66664SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
66665  Mem *p = (Mem*)pVal;
66666  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
66667  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
66668    return p->n;
66669  }
66670  if( (p->flags & MEM_Blob)!=0 ){
66671    if( p->flags & MEM_Zero ){
66672      return p->n + p->u.nZero;
66673    }else{
66674      return p->n;
66675    }
66676  }
66677  if( p->flags & MEM_Null ) return 0;
66678  return valueBytes(pVal, enc);
66679}
66680
66681/************** End of vdbemem.c *********************************************/
66682/************** Begin file vdbeaux.c *****************************************/
66683/*
66684** 2003 September 6
66685**
66686** The author disclaims copyright to this source code.  In place of
66687** a legal notice, here is a blessing:
66688**
66689**    May you do good and not evil.
66690**    May you find forgiveness for yourself and forgive others.
66691**    May you share freely, never taking more than you give.
66692**
66693*************************************************************************
66694** This file contains code used for creating, destroying, and populating
66695** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
66696*/
66697/* #include "sqliteInt.h" */
66698/* #include "vdbeInt.h" */
66699
66700/*
66701** Create a new virtual database engine.
66702*/
66703SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
66704  sqlite3 *db = pParse->db;
66705  Vdbe *p;
66706  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
66707  if( p==0 ) return 0;
66708  p->db = db;
66709  if( db->pVdbe ){
66710    db->pVdbe->pPrev = p;
66711  }
66712  p->pNext = db->pVdbe;
66713  p->pPrev = 0;
66714  db->pVdbe = p;
66715  p->magic = VDBE_MAGIC_INIT;
66716  p->pParse = pParse;
66717  assert( pParse->aLabel==0 );
66718  assert( pParse->nLabel==0 );
66719  assert( pParse->nOpAlloc==0 );
66720  return p;
66721}
66722
66723/*
66724** Change the error string stored in Vdbe.zErrMsg
66725*/
66726SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
66727  va_list ap;
66728  sqlite3DbFree(p->db, p->zErrMsg);
66729  va_start(ap, zFormat);
66730  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
66731  va_end(ap);
66732}
66733
66734/*
66735** Remember the SQL string for a prepared statement.
66736*/
66737SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
66738  assert( isPrepareV2==1 || isPrepareV2==0 );
66739  if( p==0 ) return;
66740#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
66741  if( !isPrepareV2 ) return;
66742#endif
66743  assert( p->zSql==0 );
66744  p->zSql = sqlite3DbStrNDup(p->db, z, n);
66745  p->isPrepareV2 = (u8)isPrepareV2;
66746}
66747
66748/*
66749** Return the SQL associated with a prepared statement
66750*/
66751SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
66752  Vdbe *p = (Vdbe *)pStmt;
66753  return p ? p->zSql : 0;
66754}
66755
66756/*
66757** Swap all content between two VDBE structures.
66758*/
66759SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
66760  Vdbe tmp, *pTmp;
66761  char *zTmp;
66762  tmp = *pA;
66763  *pA = *pB;
66764  *pB = tmp;
66765  pTmp = pA->pNext;
66766  pA->pNext = pB->pNext;
66767  pB->pNext = pTmp;
66768  pTmp = pA->pPrev;
66769  pA->pPrev = pB->pPrev;
66770  pB->pPrev = pTmp;
66771  zTmp = pA->zSql;
66772  pA->zSql = pB->zSql;
66773  pB->zSql = zTmp;
66774  pB->isPrepareV2 = pA->isPrepareV2;
66775}
66776
66777/*
66778** Resize the Vdbe.aOp array so that it is at least nOp elements larger
66779** than its current size. nOp is guaranteed to be less than or equal
66780** to 1024/sizeof(Op).
66781**
66782** If an out-of-memory error occurs while resizing the array, return
66783** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
66784** unchanged (this is so that any opcodes already allocated can be
66785** correctly deallocated along with the rest of the Vdbe).
66786*/
66787static int growOpArray(Vdbe *v, int nOp){
66788  VdbeOp *pNew;
66789  Parse *p = v->pParse;
66790
66791  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
66792  ** more frequent reallocs and hence provide more opportunities for
66793  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
66794  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
66795  ** by the minimum* amount required until the size reaches 512.  Normal
66796  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
66797  ** size of the op array or add 1KB of space, whichever is smaller. */
66798#ifdef SQLITE_TEST_REALLOC_STRESS
66799  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
66800#else
66801  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
66802  UNUSED_PARAMETER(nOp);
66803#endif
66804
66805  assert( nOp<=(1024/sizeof(Op)) );
66806  assert( nNew>=(p->nOpAlloc+nOp) );
66807  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
66808  if( pNew ){
66809    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
66810    v->aOp = pNew;
66811  }
66812  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
66813}
66814
66815#ifdef SQLITE_DEBUG
66816/* This routine is just a convenient place to set a breakpoint that will
66817** fire after each opcode is inserted and displayed using
66818** "PRAGMA vdbe_addoptrace=on".
66819*/
66820static void test_addop_breakpoint(void){
66821  static int n = 0;
66822  n++;
66823}
66824#endif
66825
66826/*
66827** Add a new instruction to the list of instructions current in the
66828** VDBE.  Return the address of the new instruction.
66829**
66830** Parameters:
66831**
66832**    p               Pointer to the VDBE
66833**
66834**    op              The opcode for this instruction
66835**
66836**    p1, p2, p3      Operands
66837**
66838** Use the sqlite3VdbeResolveLabel() function to fix an address and
66839** the sqlite3VdbeChangeP4() function to change the value of the P4
66840** operand.
66841*/
66842SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
66843  int i;
66844  VdbeOp *pOp;
66845
66846  i = p->nOp;
66847  assert( p->magic==VDBE_MAGIC_INIT );
66848  assert( op>0 && op<0xff );
66849  if( p->pParse->nOpAlloc<=i ){
66850    if( growOpArray(p, 1) ){
66851      return 1;
66852    }
66853  }
66854  p->nOp++;
66855  pOp = &p->aOp[i];
66856  pOp->opcode = (u8)op;
66857  pOp->p5 = 0;
66858  pOp->p1 = p1;
66859  pOp->p2 = p2;
66860  pOp->p3 = p3;
66861  pOp->p4.p = 0;
66862  pOp->p4type = P4_NOTUSED;
66863#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
66864  pOp->zComment = 0;
66865#endif
66866#ifdef SQLITE_DEBUG
66867  if( p->db->flags & SQLITE_VdbeAddopTrace ){
66868    int jj, kk;
66869    Parse *pParse = p->pParse;
66870    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
66871      struct yColCache *x = pParse->aColCache + jj;
66872      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
66873      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
66874      kk++;
66875    }
66876    if( kk ) printf("\n");
66877    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
66878    test_addop_breakpoint();
66879  }
66880#endif
66881#ifdef VDBE_PROFILE
66882  pOp->cycles = 0;
66883  pOp->cnt = 0;
66884#endif
66885#ifdef SQLITE_VDBE_COVERAGE
66886  pOp->iSrcLine = 0;
66887#endif
66888  return i;
66889}
66890SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
66891  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
66892}
66893SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
66894  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
66895}
66896SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
66897  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
66898}
66899
66900/* Generate code for an unconditional jump to instruction iDest
66901*/
66902SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
66903  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
66904}
66905
66906/* Generate code to cause the string zStr to be loaded into
66907** register iDest
66908*/
66909SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
66910  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
66911}
66912
66913/*
66914** Generate code that initializes multiple registers to string or integer
66915** constants.  The registers begin with iDest and increase consecutively.
66916** One register is initialized for each characgter in zTypes[].  For each
66917** "s" character in zTypes[], the register is a string if the argument is
66918** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
66919** in zTypes[], the register is initialized to an integer.
66920*/
66921SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
66922  va_list ap;
66923  int i;
66924  char c;
66925  va_start(ap, zTypes);
66926  for(i=0; (c = zTypes[i])!=0; i++){
66927    if( c=='s' ){
66928      const char *z = va_arg(ap, const char*);
66929      int addr = sqlite3VdbeAddOp2(p, z==0 ? OP_Null : OP_String8, 0, iDest++);
66930      if( z ) sqlite3VdbeChangeP4(p, addr, z, 0);
66931    }else{
66932      assert( c=='i' );
66933      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
66934    }
66935  }
66936  va_end(ap);
66937}
66938
66939/*
66940** Add an opcode that includes the p4 value as a pointer.
66941*/
66942SQLITE_PRIVATE int sqlite3VdbeAddOp4(
66943  Vdbe *p,            /* Add the opcode to this VM */
66944  int op,             /* The new opcode */
66945  int p1,             /* The P1 operand */
66946  int p2,             /* The P2 operand */
66947  int p3,             /* The P3 operand */
66948  const char *zP4,    /* The P4 operand */
66949  int p4type          /* P4 operand type */
66950){
66951  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
66952  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
66953  return addr;
66954}
66955
66956/*
66957** Add an opcode that includes the p4 value with a P4_INT64 or
66958** P4_REAL type.
66959*/
66960SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
66961  Vdbe *p,            /* Add the opcode to this VM */
66962  int op,             /* The new opcode */
66963  int p1,             /* The P1 operand */
66964  int p2,             /* The P2 operand */
66965  int p3,             /* The P3 operand */
66966  const u8 *zP4,      /* The P4 operand */
66967  int p4type          /* P4 operand type */
66968){
66969  char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
66970  if( p4copy ) memcpy(p4copy, zP4, 8);
66971  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
66972}
66973
66974/*
66975** Add an OP_ParseSchema opcode.  This routine is broken out from
66976** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
66977** as having been used.
66978**
66979** The zWhere string must have been obtained from sqlite3_malloc().
66980** This routine will take ownership of the allocated memory.
66981*/
66982SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
66983  int j;
66984  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
66985  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
66986  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
66987}
66988
66989/*
66990** Add an opcode that includes the p4 value as an integer.
66991*/
66992SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
66993  Vdbe *p,            /* Add the opcode to this VM */
66994  int op,             /* The new opcode */
66995  int p1,             /* The P1 operand */
66996  int p2,             /* The P2 operand */
66997  int p3,             /* The P3 operand */
66998  int p4              /* The P4 operand as an integer */
66999){
67000  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
67001  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
67002  return addr;
67003}
67004
67005/*
67006** Create a new symbolic label for an instruction that has yet to be
67007** coded.  The symbolic label is really just a negative number.  The
67008** label can be used as the P2 value of an operation.  Later, when
67009** the label is resolved to a specific address, the VDBE will scan
67010** through its operation list and change all values of P2 which match
67011** the label into the resolved address.
67012**
67013** The VDBE knows that a P2 value is a label because labels are
67014** always negative and P2 values are suppose to be non-negative.
67015** Hence, a negative P2 value is a label that has yet to be resolved.
67016**
67017** Zero is returned if a malloc() fails.
67018*/
67019SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
67020  Parse *p = v->pParse;
67021  int i = p->nLabel++;
67022  assert( v->magic==VDBE_MAGIC_INIT );
67023  if( (i & (i-1))==0 ){
67024    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
67025                                       (i*2+1)*sizeof(p->aLabel[0]));
67026  }
67027  if( p->aLabel ){
67028    p->aLabel[i] = -1;
67029  }
67030  return -1-i;
67031}
67032
67033/*
67034** Resolve label "x" to be the address of the next instruction to
67035** be inserted.  The parameter "x" must have been obtained from
67036** a prior call to sqlite3VdbeMakeLabel().
67037*/
67038SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
67039  Parse *p = v->pParse;
67040  int j = -1-x;
67041  assert( v->magic==VDBE_MAGIC_INIT );
67042  assert( j<p->nLabel );
67043  assert( j>=0 );
67044  if( p->aLabel ){
67045    p->aLabel[j] = v->nOp;
67046  }
67047  p->iFixedOp = v->nOp - 1;
67048}
67049
67050/*
67051** Mark the VDBE as one that can only be run one time.
67052*/
67053SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
67054  p->runOnlyOnce = 1;
67055}
67056
67057#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
67058
67059/*
67060** The following type and function are used to iterate through all opcodes
67061** in a Vdbe main program and each of the sub-programs (triggers) it may
67062** invoke directly or indirectly. It should be used as follows:
67063**
67064**   Op *pOp;
67065**   VdbeOpIter sIter;
67066**
67067**   memset(&sIter, 0, sizeof(sIter));
67068**   sIter.v = v;                            // v is of type Vdbe*
67069**   while( (pOp = opIterNext(&sIter)) ){
67070**     // Do something with pOp
67071**   }
67072**   sqlite3DbFree(v->db, sIter.apSub);
67073**
67074*/
67075typedef struct VdbeOpIter VdbeOpIter;
67076struct VdbeOpIter {
67077  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
67078  SubProgram **apSub;        /* Array of subprograms */
67079  int nSub;                  /* Number of entries in apSub */
67080  int iAddr;                 /* Address of next instruction to return */
67081  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
67082};
67083static Op *opIterNext(VdbeOpIter *p){
67084  Vdbe *v = p->v;
67085  Op *pRet = 0;
67086  Op *aOp;
67087  int nOp;
67088
67089  if( p->iSub<=p->nSub ){
67090
67091    if( p->iSub==0 ){
67092      aOp = v->aOp;
67093      nOp = v->nOp;
67094    }else{
67095      aOp = p->apSub[p->iSub-1]->aOp;
67096      nOp = p->apSub[p->iSub-1]->nOp;
67097    }
67098    assert( p->iAddr<nOp );
67099
67100    pRet = &aOp[p->iAddr];
67101    p->iAddr++;
67102    if( p->iAddr==nOp ){
67103      p->iSub++;
67104      p->iAddr = 0;
67105    }
67106
67107    if( pRet->p4type==P4_SUBPROGRAM ){
67108      int nByte = (p->nSub+1)*sizeof(SubProgram*);
67109      int j;
67110      for(j=0; j<p->nSub; j++){
67111        if( p->apSub[j]==pRet->p4.pProgram ) break;
67112      }
67113      if( j==p->nSub ){
67114        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
67115        if( !p->apSub ){
67116          pRet = 0;
67117        }else{
67118          p->apSub[p->nSub++] = pRet->p4.pProgram;
67119        }
67120      }
67121    }
67122  }
67123
67124  return pRet;
67125}
67126
67127/*
67128** Check if the program stored in the VM associated with pParse may
67129** throw an ABORT exception (causing the statement, but not entire transaction
67130** to be rolled back). This condition is true if the main program or any
67131** sub-programs contains any of the following:
67132**
67133**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
67134**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
67135**   *  OP_Destroy
67136**   *  OP_VUpdate
67137**   *  OP_VRename
67138**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
67139**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
67140**
67141** Then check that the value of Parse.mayAbort is true if an
67142** ABORT may be thrown, or false otherwise. Return true if it does
67143** match, or false otherwise. This function is intended to be used as
67144** part of an assert statement in the compiler. Similar to:
67145**
67146**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
67147*/
67148SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
67149  int hasAbort = 0;
67150  int hasFkCounter = 0;
67151  int hasCreateTable = 0;
67152  int hasInitCoroutine = 0;
67153  Op *pOp;
67154  VdbeOpIter sIter;
67155  memset(&sIter, 0, sizeof(sIter));
67156  sIter.v = v;
67157
67158  while( (pOp = opIterNext(&sIter))!=0 ){
67159    int opcode = pOp->opcode;
67160    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
67161     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
67162      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
67163    ){
67164      hasAbort = 1;
67165      break;
67166    }
67167    if( opcode==OP_CreateTable ) hasCreateTable = 1;
67168    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
67169#ifndef SQLITE_OMIT_FOREIGN_KEY
67170    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
67171      hasFkCounter = 1;
67172    }
67173#endif
67174  }
67175  sqlite3DbFree(v->db, sIter.apSub);
67176
67177  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
67178  ** If malloc failed, then the while() loop above may not have iterated
67179  ** through all opcodes and hasAbort may be set incorrectly. Return
67180  ** true for this case to prevent the assert() in the callers frame
67181  ** from failing.  */
67182  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
67183              || (hasCreateTable && hasInitCoroutine) );
67184}
67185#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
67186
67187/*
67188** This routine is called after all opcodes have been inserted.  It loops
67189** through all the opcodes and fixes up some details.
67190**
67191** (1) For each jump instruction with a negative P2 value (a label)
67192**     resolve the P2 value to an actual address.
67193**
67194** (2) Compute the maximum number of arguments used by any SQL function
67195**     and store that value in *pMaxFuncArgs.
67196**
67197** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
67198**     indicate what the prepared statement actually does.
67199**
67200** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
67201**
67202** (5) Reclaim the memory allocated for storing labels.
67203*/
67204static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
67205  int i;
67206  int nMaxArgs = *pMaxFuncArgs;
67207  Op *pOp;
67208  Parse *pParse = p->pParse;
67209  int *aLabel = pParse->aLabel;
67210  p->readOnly = 1;
67211  p->bIsReader = 0;
67212  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
67213    u8 opcode = pOp->opcode;
67214
67215    /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
67216    ** cases from this switch! */
67217    switch( opcode ){
67218      case OP_Transaction: {
67219        if( pOp->p2!=0 ) p->readOnly = 0;
67220        /* fall thru */
67221      }
67222      case OP_AutoCommit:
67223      case OP_Savepoint: {
67224        p->bIsReader = 1;
67225        break;
67226      }
67227#ifndef SQLITE_OMIT_WAL
67228      case OP_Checkpoint:
67229#endif
67230      case OP_Vacuum:
67231      case OP_JournalMode: {
67232        p->readOnly = 0;
67233        p->bIsReader = 1;
67234        break;
67235      }
67236#ifndef SQLITE_OMIT_VIRTUALTABLE
67237      case OP_VUpdate: {
67238        if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
67239        break;
67240      }
67241      case OP_VFilter: {
67242        int n;
67243        assert( p->nOp - i >= 3 );
67244        assert( pOp[-1].opcode==OP_Integer );
67245        n = pOp[-1].p1;
67246        if( n>nMaxArgs ) nMaxArgs = n;
67247        break;
67248      }
67249#endif
67250      case OP_Next:
67251      case OP_NextIfOpen:
67252      case OP_SorterNext: {
67253        pOp->p4.xAdvance = sqlite3BtreeNext;
67254        pOp->p4type = P4_ADVANCE;
67255        break;
67256      }
67257      case OP_Prev:
67258      case OP_PrevIfOpen: {
67259        pOp->p4.xAdvance = sqlite3BtreePrevious;
67260        pOp->p4type = P4_ADVANCE;
67261        break;
67262      }
67263    }
67264
67265    pOp->opflags = sqlite3OpcodeProperty[opcode];
67266    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
67267      assert( -1-pOp->p2<pParse->nLabel );
67268      pOp->p2 = aLabel[-1-pOp->p2];
67269    }
67270  }
67271  sqlite3DbFree(p->db, pParse->aLabel);
67272  pParse->aLabel = 0;
67273  pParse->nLabel = 0;
67274  *pMaxFuncArgs = nMaxArgs;
67275  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
67276}
67277
67278/*
67279** Return the address of the next instruction to be inserted.
67280*/
67281SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
67282  assert( p->magic==VDBE_MAGIC_INIT );
67283  return p->nOp;
67284}
67285
67286/*
67287** This function returns a pointer to the array of opcodes associated with
67288** the Vdbe passed as the first argument. It is the callers responsibility
67289** to arrange for the returned array to be eventually freed using the
67290** vdbeFreeOpArray() function.
67291**
67292** Before returning, *pnOp is set to the number of entries in the returned
67293** array. Also, *pnMaxArg is set to the larger of its current value and
67294** the number of entries in the Vdbe.apArg[] array required to execute the
67295** returned program.
67296*/
67297SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
67298  VdbeOp *aOp = p->aOp;
67299  assert( aOp && !p->db->mallocFailed );
67300
67301  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
67302  assert( DbMaskAllZero(p->btreeMask) );
67303
67304  resolveP2Values(p, pnMaxArg);
67305  *pnOp = p->nOp;
67306  p->aOp = 0;
67307  return aOp;
67308}
67309
67310/*
67311** Add a whole list of operations to the operation stack.  Return the
67312** address of the first operation added.
67313*/
67314SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
67315  int addr, i;
67316  VdbeOp *pOut;
67317  assert( nOp>0 );
67318  assert( p->magic==VDBE_MAGIC_INIT );
67319  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
67320    return 0;
67321  }
67322  addr = p->nOp;
67323  pOut = &p->aOp[addr];
67324  for(i=0; i<nOp; i++, aOp++, pOut++){
67325    int p2 = aOp->p2;
67326    pOut->opcode = aOp->opcode;
67327    pOut->p1 = aOp->p1;
67328    if( p2<0 ){
67329      assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
67330      pOut->p2 = addr + ADDR(p2);
67331    }else{
67332      pOut->p2 = p2;
67333    }
67334    pOut->p3 = aOp->p3;
67335    pOut->p4type = P4_NOTUSED;
67336    pOut->p4.p = 0;
67337    pOut->p5 = 0;
67338#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67339    pOut->zComment = 0;
67340#endif
67341#ifdef SQLITE_VDBE_COVERAGE
67342    pOut->iSrcLine = iLineno+i;
67343#else
67344    (void)iLineno;
67345#endif
67346#ifdef SQLITE_DEBUG
67347    if( p->db->flags & SQLITE_VdbeAddopTrace ){
67348      sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
67349    }
67350#endif
67351  }
67352  p->nOp += nOp;
67353  return addr;
67354}
67355
67356#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
67357/*
67358** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
67359*/
67360SQLITE_PRIVATE void sqlite3VdbeScanStatus(
67361  Vdbe *p,                        /* VM to add scanstatus() to */
67362  int addrExplain,                /* Address of OP_Explain (or 0) */
67363  int addrLoop,                   /* Address of loop counter */
67364  int addrVisit,                  /* Address of rows visited counter */
67365  LogEst nEst,                    /* Estimated number of output rows */
67366  const char *zName               /* Name of table or index being scanned */
67367){
67368  int nByte = (p->nScan+1) * sizeof(ScanStatus);
67369  ScanStatus *aNew;
67370  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
67371  if( aNew ){
67372    ScanStatus *pNew = &aNew[p->nScan++];
67373    pNew->addrExplain = addrExplain;
67374    pNew->addrLoop = addrLoop;
67375    pNew->addrVisit = addrVisit;
67376    pNew->nEst = nEst;
67377    pNew->zName = sqlite3DbStrDup(p->db, zName);
67378    p->aScan = aNew;
67379  }
67380}
67381#endif
67382
67383
67384/*
67385** Change the value of the opcode, or P1, P2, P3, or P5 operands
67386** for a specific instruction.
67387*/
67388SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
67389  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
67390}
67391SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
67392  sqlite3VdbeGetOp(p,addr)->p1 = val;
67393}
67394SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
67395  sqlite3VdbeGetOp(p,addr)->p2 = val;
67396}
67397SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
67398  sqlite3VdbeGetOp(p,addr)->p3 = val;
67399}
67400SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
67401  sqlite3VdbeGetOp(p,-1)->p5 = p5;
67402}
67403
67404/*
67405** Change the P2 operand of instruction addr so that it points to
67406** the address of the next instruction to be coded.
67407*/
67408SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
67409  p->pParse->iFixedOp = p->nOp - 1;
67410  sqlite3VdbeChangeP2(p, addr, p->nOp);
67411}
67412
67413
67414/*
67415** If the input FuncDef structure is ephemeral, then free it.  If
67416** the FuncDef is not ephermal, then do nothing.
67417*/
67418static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
67419  if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
67420    sqlite3DbFree(db, pDef);
67421  }
67422}
67423
67424static void vdbeFreeOpArray(sqlite3 *, Op *, int);
67425
67426/*
67427** Delete a P4 value if necessary.
67428*/
67429static void freeP4(sqlite3 *db, int p4type, void *p4){
67430  if( p4 ){
67431    assert( db );
67432    switch( p4type ){
67433      case P4_FUNCCTX: {
67434        freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
67435        /* Fall through into the next case */
67436      }
67437      case P4_REAL:
67438      case P4_INT64:
67439      case P4_DYNAMIC:
67440      case P4_INTARRAY: {
67441        sqlite3DbFree(db, p4);
67442        break;
67443      }
67444      case P4_KEYINFO: {
67445        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
67446        break;
67447      }
67448      case P4_MPRINTF: {
67449        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
67450        break;
67451      }
67452      case P4_FUNCDEF: {
67453        freeEphemeralFunction(db, (FuncDef*)p4);
67454        break;
67455      }
67456      case P4_MEM: {
67457        if( db->pnBytesFreed==0 ){
67458          sqlite3ValueFree((sqlite3_value*)p4);
67459        }else{
67460          Mem *p = (Mem*)p4;
67461          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
67462          sqlite3DbFree(db, p);
67463        }
67464        break;
67465      }
67466      case P4_VTAB : {
67467        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
67468        break;
67469      }
67470    }
67471  }
67472}
67473
67474/*
67475** Free the space allocated for aOp and any p4 values allocated for the
67476** opcodes contained within. If aOp is not NULL it is assumed to contain
67477** nOp entries.
67478*/
67479static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
67480  if( aOp ){
67481    Op *pOp;
67482    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
67483      freeP4(db, pOp->p4type, pOp->p4.p);
67484#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67485      sqlite3DbFree(db, pOp->zComment);
67486#endif
67487    }
67488  }
67489  sqlite3DbFree(db, aOp);
67490}
67491
67492/*
67493** Link the SubProgram object passed as the second argument into the linked
67494** list at Vdbe.pSubProgram. This list is used to delete all sub-program
67495** objects when the VM is no longer required.
67496*/
67497SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
67498  p->pNext = pVdbe->pProgram;
67499  pVdbe->pProgram = p;
67500}
67501
67502/*
67503** Change the opcode at addr into OP_Noop
67504*/
67505SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
67506  if( addr<p->nOp ){
67507    VdbeOp *pOp = &p->aOp[addr];
67508    sqlite3 *db = p->db;
67509    freeP4(db, pOp->p4type, pOp->p4.p);
67510    memset(pOp, 0, sizeof(pOp[0]));
67511    pOp->opcode = OP_Noop;
67512    if( addr==p->nOp-1 ) p->nOp--;
67513  }
67514}
67515
67516/*
67517** If the last opcode is "op" and it is not a jump destination,
67518** then remove it.  Return true if and only if an opcode was removed.
67519*/
67520SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
67521  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
67522    sqlite3VdbeChangeToNoop(p, p->nOp-1);
67523    return 1;
67524  }else{
67525    return 0;
67526  }
67527}
67528
67529/*
67530** Change the value of the P4 operand for a specific instruction.
67531** This routine is useful when a large program is loaded from a
67532** static array using sqlite3VdbeAddOpList but we want to make a
67533** few minor changes to the program.
67534**
67535** If n>=0 then the P4 operand is dynamic, meaning that a copy of
67536** the string is made into memory obtained from sqlite3_malloc().
67537** A value of n==0 means copy bytes of zP4 up to and including the
67538** first null byte.  If n>0 then copy n+1 bytes of zP4.
67539**
67540** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
67541** to a string or structure that is guaranteed to exist for the lifetime of
67542** the Vdbe. In these cases we can just copy the pointer.
67543**
67544** If addr<0 then change P4 on the most recently inserted instruction.
67545*/
67546SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
67547  Op *pOp;
67548  sqlite3 *db;
67549  assert( p!=0 );
67550  db = p->db;
67551  assert( p->magic==VDBE_MAGIC_INIT );
67552  if( p->aOp==0 || db->mallocFailed ){
67553    if( n!=P4_VTAB ){
67554      freeP4(db, n, (void*)*(char**)&zP4);
67555    }
67556    return;
67557  }
67558  assert( p->nOp>0 );
67559  assert( addr<p->nOp );
67560  if( addr<0 ){
67561    addr = p->nOp - 1;
67562  }
67563  pOp = &p->aOp[addr];
67564  assert( pOp->p4type==P4_NOTUSED
67565       || pOp->p4type==P4_INT32
67566       || pOp->p4type==P4_KEYINFO );
67567  freeP4(db, pOp->p4type, pOp->p4.p);
67568  pOp->p4.p = 0;
67569  if( n==P4_INT32 ){
67570    /* Note: this cast is safe, because the origin data point was an int
67571    ** that was cast to a (const char *). */
67572    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
67573    pOp->p4type = P4_INT32;
67574  }else if( zP4==0 ){
67575    pOp->p4.p = 0;
67576    pOp->p4type = P4_NOTUSED;
67577  }else if( n==P4_KEYINFO ){
67578    pOp->p4.p = (void*)zP4;
67579    pOp->p4type = P4_KEYINFO;
67580  }else if( n==P4_VTAB ){
67581    pOp->p4.p = (void*)zP4;
67582    pOp->p4type = P4_VTAB;
67583    sqlite3VtabLock((VTable *)zP4);
67584    assert( ((VTable *)zP4)->db==p->db );
67585  }else if( n<0 ){
67586    pOp->p4.p = (void*)zP4;
67587    pOp->p4type = (signed char)n;
67588  }else{
67589    if( n==0 ) n = sqlite3Strlen30(zP4);
67590    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
67591    pOp->p4type = P4_DYNAMIC;
67592  }
67593}
67594
67595/*
67596** Set the P4 on the most recently added opcode to the KeyInfo for the
67597** index given.
67598*/
67599SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
67600  Vdbe *v = pParse->pVdbe;
67601  assert( v!=0 );
67602  assert( pIdx!=0 );
67603  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
67604                      P4_KEYINFO);
67605}
67606
67607#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67608/*
67609** Change the comment on the most recently coded instruction.  Or
67610** insert a No-op and add the comment to that new instruction.  This
67611** makes the code easier to read during debugging.  None of this happens
67612** in a production build.
67613*/
67614static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
67615  assert( p->nOp>0 || p->aOp==0 );
67616  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
67617  if( p->nOp ){
67618    assert( p->aOp );
67619    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
67620    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
67621  }
67622}
67623SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
67624  va_list ap;
67625  if( p ){
67626    va_start(ap, zFormat);
67627    vdbeVComment(p, zFormat, ap);
67628    va_end(ap);
67629  }
67630}
67631SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
67632  va_list ap;
67633  if( p ){
67634    sqlite3VdbeAddOp0(p, OP_Noop);
67635    va_start(ap, zFormat);
67636    vdbeVComment(p, zFormat, ap);
67637    va_end(ap);
67638  }
67639}
67640#endif  /* NDEBUG */
67641
67642#ifdef SQLITE_VDBE_COVERAGE
67643/*
67644** Set the value if the iSrcLine field for the previously coded instruction.
67645*/
67646SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
67647  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
67648}
67649#endif /* SQLITE_VDBE_COVERAGE */
67650
67651/*
67652** Return the opcode for a given address.  If the address is -1, then
67653** return the most recently inserted opcode.
67654**
67655** If a memory allocation error has occurred prior to the calling of this
67656** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
67657** is readable but not writable, though it is cast to a writable value.
67658** The return of a dummy opcode allows the call to continue functioning
67659** after an OOM fault without having to check to see if the return from
67660** this routine is a valid pointer.  But because the dummy.opcode is 0,
67661** dummy will never be written to.  This is verified by code inspection and
67662** by running with Valgrind.
67663*/
67664SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
67665  /* C89 specifies that the constant "dummy" will be initialized to all
67666  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
67667  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
67668  assert( p->magic==VDBE_MAGIC_INIT );
67669  if( addr<0 ){
67670    addr = p->nOp - 1;
67671  }
67672  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
67673  if( p->db->mallocFailed ){
67674    return (VdbeOp*)&dummy;
67675  }else{
67676    return &p->aOp[addr];
67677  }
67678}
67679
67680#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
67681/*
67682** Return an integer value for one of the parameters to the opcode pOp
67683** determined by character c.
67684*/
67685static int translateP(char c, const Op *pOp){
67686  if( c=='1' ) return pOp->p1;
67687  if( c=='2' ) return pOp->p2;
67688  if( c=='3' ) return pOp->p3;
67689  if( c=='4' ) return pOp->p4.i;
67690  return pOp->p5;
67691}
67692
67693/*
67694** Compute a string for the "comment" field of a VDBE opcode listing.
67695**
67696** The Synopsis: field in comments in the vdbe.c source file gets converted
67697** to an extra string that is appended to the sqlite3OpcodeName().  In the
67698** absence of other comments, this synopsis becomes the comment on the opcode.
67699** Some translation occurs:
67700**
67701**       "PX"      ->  "r[X]"
67702**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
67703**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
67704**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
67705*/
67706static int displayComment(
67707  const Op *pOp,     /* The opcode to be commented */
67708  const char *zP4,   /* Previously obtained value for P4 */
67709  char *zTemp,       /* Write result here */
67710  int nTemp          /* Space available in zTemp[] */
67711){
67712  const char *zOpName;
67713  const char *zSynopsis;
67714  int nOpName;
67715  int ii, jj;
67716  zOpName = sqlite3OpcodeName(pOp->opcode);
67717  nOpName = sqlite3Strlen30(zOpName);
67718  if( zOpName[nOpName+1] ){
67719    int seenCom = 0;
67720    char c;
67721    zSynopsis = zOpName += nOpName + 1;
67722    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
67723      if( c=='P' ){
67724        c = zSynopsis[++ii];
67725        if( c=='4' ){
67726          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
67727        }else if( c=='X' ){
67728          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
67729          seenCom = 1;
67730        }else{
67731          int v1 = translateP(c, pOp);
67732          int v2;
67733          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
67734          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
67735            ii += 3;
67736            jj += sqlite3Strlen30(zTemp+jj);
67737            v2 = translateP(zSynopsis[ii], pOp);
67738            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
67739              ii += 2;
67740              v2++;
67741            }
67742            if( v2>1 ){
67743              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
67744            }
67745          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
67746            ii += 4;
67747          }
67748        }
67749        jj += sqlite3Strlen30(zTemp+jj);
67750      }else{
67751        zTemp[jj++] = c;
67752      }
67753    }
67754    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
67755      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
67756      jj += sqlite3Strlen30(zTemp+jj);
67757    }
67758    if( jj<nTemp ) zTemp[jj] = 0;
67759  }else if( pOp->zComment ){
67760    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
67761    jj = sqlite3Strlen30(zTemp);
67762  }else{
67763    zTemp[0] = 0;
67764    jj = 0;
67765  }
67766  return jj;
67767}
67768#endif /* SQLITE_DEBUG */
67769
67770
67771#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
67772     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
67773/*
67774** Compute a string that describes the P4 parameter for an opcode.
67775** Use zTemp for any required temporary buffer space.
67776*/
67777static char *displayP4(Op *pOp, char *zTemp, int nTemp){
67778  char *zP4 = zTemp;
67779  assert( nTemp>=20 );
67780  switch( pOp->p4type ){
67781    case P4_KEYINFO: {
67782      int i, j;
67783      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
67784      assert( pKeyInfo->aSortOrder!=0 );
67785      sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
67786      i = sqlite3Strlen30(zTemp);
67787      for(j=0; j<pKeyInfo->nField; j++){
67788        CollSeq *pColl = pKeyInfo->aColl[j];
67789        const char *zColl = pColl ? pColl->zName : "nil";
67790        int n = sqlite3Strlen30(zColl);
67791        if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
67792          zColl = "B";
67793          n = 1;
67794        }
67795        if( i+n>nTemp-7 ){
67796          memcpy(&zTemp[i],",...",4);
67797          i += 4;
67798          break;
67799        }
67800        zTemp[i++] = ',';
67801        if( pKeyInfo->aSortOrder[j] ){
67802          zTemp[i++] = '-';
67803        }
67804        memcpy(&zTemp[i], zColl, n+1);
67805        i += n;
67806      }
67807      zTemp[i++] = ')';
67808      zTemp[i] = 0;
67809      assert( i<nTemp );
67810      break;
67811    }
67812    case P4_COLLSEQ: {
67813      CollSeq *pColl = pOp->p4.pColl;
67814      sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
67815      break;
67816    }
67817    case P4_FUNCDEF: {
67818      FuncDef *pDef = pOp->p4.pFunc;
67819      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
67820      break;
67821    }
67822#ifdef SQLITE_DEBUG
67823    case P4_FUNCCTX: {
67824      FuncDef *pDef = pOp->p4.pCtx->pFunc;
67825      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
67826      break;
67827    }
67828#endif
67829    case P4_INT64: {
67830      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
67831      break;
67832    }
67833    case P4_INT32: {
67834      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
67835      break;
67836    }
67837    case P4_REAL: {
67838      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
67839      break;
67840    }
67841    case P4_MEM: {
67842      Mem *pMem = pOp->p4.pMem;
67843      if( pMem->flags & MEM_Str ){
67844        zP4 = pMem->z;
67845      }else if( pMem->flags & MEM_Int ){
67846        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
67847      }else if( pMem->flags & MEM_Real ){
67848        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
67849      }else if( pMem->flags & MEM_Null ){
67850        sqlite3_snprintf(nTemp, zTemp, "NULL");
67851      }else{
67852        assert( pMem->flags & MEM_Blob );
67853        zP4 = "(blob)";
67854      }
67855      break;
67856    }
67857#ifndef SQLITE_OMIT_VIRTUALTABLE
67858    case P4_VTAB: {
67859      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
67860      sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
67861      break;
67862    }
67863#endif
67864    case P4_INTARRAY: {
67865      sqlite3_snprintf(nTemp, zTemp, "intarray");
67866      break;
67867    }
67868    case P4_SUBPROGRAM: {
67869      sqlite3_snprintf(nTemp, zTemp, "program");
67870      break;
67871    }
67872    case P4_ADVANCE: {
67873      zTemp[0] = 0;
67874      break;
67875    }
67876    default: {
67877      zP4 = pOp->p4.z;
67878      if( zP4==0 ){
67879        zP4 = zTemp;
67880        zTemp[0] = 0;
67881      }
67882    }
67883  }
67884  assert( zP4!=0 );
67885  return zP4;
67886}
67887#endif
67888
67889/*
67890** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
67891**
67892** The prepared statements need to know in advance the complete set of
67893** attached databases that will be use.  A mask of these databases
67894** is maintained in p->btreeMask.  The p->lockMask value is the subset of
67895** p->btreeMask of databases that will require a lock.
67896*/
67897SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
67898  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
67899  assert( i<(int)sizeof(p->btreeMask)*8 );
67900  DbMaskSet(p->btreeMask, i);
67901  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
67902    DbMaskSet(p->lockMask, i);
67903  }
67904}
67905
67906#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
67907/*
67908** If SQLite is compiled to support shared-cache mode and to be threadsafe,
67909** this routine obtains the mutex associated with each BtShared structure
67910** that may be accessed by the VM passed as an argument. In doing so it also
67911** sets the BtShared.db member of each of the BtShared structures, ensuring
67912** that the correct busy-handler callback is invoked if required.
67913**
67914** If SQLite is not threadsafe but does support shared-cache mode, then
67915** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
67916** of all of BtShared structures accessible via the database handle
67917** associated with the VM.
67918**
67919** If SQLite is not threadsafe and does not support shared-cache mode, this
67920** function is a no-op.
67921**
67922** The p->btreeMask field is a bitmask of all btrees that the prepared
67923** statement p will ever use.  Let N be the number of bits in p->btreeMask
67924** corresponding to btrees that use shared cache.  Then the runtime of
67925** this routine is N*N.  But as N is rarely more than 1, this should not
67926** be a problem.
67927*/
67928SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
67929  int i;
67930  sqlite3 *db;
67931  Db *aDb;
67932  int nDb;
67933  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
67934  db = p->db;
67935  aDb = db->aDb;
67936  nDb = db->nDb;
67937  for(i=0; i<nDb; i++){
67938    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
67939      sqlite3BtreeEnter(aDb[i].pBt);
67940    }
67941  }
67942}
67943#endif
67944
67945#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
67946/*
67947** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
67948*/
67949static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
67950  int i;
67951  sqlite3 *db;
67952  Db *aDb;
67953  int nDb;
67954  db = p->db;
67955  aDb = db->aDb;
67956  nDb = db->nDb;
67957  for(i=0; i<nDb; i++){
67958    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
67959      sqlite3BtreeLeave(aDb[i].pBt);
67960    }
67961  }
67962}
67963SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
67964  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
67965  vdbeLeave(p);
67966}
67967#endif
67968
67969#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
67970/*
67971** Print a single opcode.  This routine is used for debugging only.
67972*/
67973SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
67974  char *zP4;
67975  char zPtr[50];
67976  char zCom[100];
67977  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
67978  if( pOut==0 ) pOut = stdout;
67979  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
67980#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67981  displayComment(pOp, zP4, zCom, sizeof(zCom));
67982#else
67983  zCom[0] = 0;
67984#endif
67985  /* NB:  The sqlite3OpcodeName() function is implemented by code created
67986  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
67987  ** information from the vdbe.c source text */
67988  fprintf(pOut, zFormat1, pc,
67989      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
67990      zCom
67991  );
67992  fflush(pOut);
67993}
67994#endif
67995
67996/*
67997** Release an array of N Mem elements
67998*/
67999static void releaseMemArray(Mem *p, int N){
68000  if( p && N ){
68001    Mem *pEnd = &p[N];
68002    sqlite3 *db = p->db;
68003    u8 malloc_failed = db->mallocFailed;
68004    if( db->pnBytesFreed ){
68005      do{
68006        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
68007      }while( (++p)<pEnd );
68008      return;
68009    }
68010    do{
68011      assert( (&p[1])==pEnd || p[0].db==p[1].db );
68012      assert( sqlite3VdbeCheckMemInvariants(p) );
68013
68014      /* This block is really an inlined version of sqlite3VdbeMemRelease()
68015      ** that takes advantage of the fact that the memory cell value is
68016      ** being set to NULL after releasing any dynamic resources.
68017      **
68018      ** The justification for duplicating code is that according to
68019      ** callgrind, this causes a certain test case to hit the CPU 4.7
68020      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
68021      ** sqlite3MemRelease() were called from here. With -O2, this jumps
68022      ** to 6.6 percent. The test case is inserting 1000 rows into a table
68023      ** with no indexes using a single prepared INSERT statement, bind()
68024      ** and reset(). Inserts are grouped into a transaction.
68025      */
68026      testcase( p->flags & MEM_Agg );
68027      testcase( p->flags & MEM_Dyn );
68028      testcase( p->flags & MEM_Frame );
68029      testcase( p->flags & MEM_RowSet );
68030      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
68031        sqlite3VdbeMemRelease(p);
68032      }else if( p->szMalloc ){
68033        sqlite3DbFree(db, p->zMalloc);
68034        p->szMalloc = 0;
68035      }
68036
68037      p->flags = MEM_Undefined;
68038    }while( (++p)<pEnd );
68039    db->mallocFailed = malloc_failed;
68040  }
68041}
68042
68043/*
68044** Delete a VdbeFrame object and its contents. VdbeFrame objects are
68045** allocated by the OP_Program opcode in sqlite3VdbeExec().
68046*/
68047SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
68048  int i;
68049  Mem *aMem = VdbeFrameMem(p);
68050  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
68051  for(i=0; i<p->nChildCsr; i++){
68052    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
68053  }
68054  releaseMemArray(aMem, p->nChildMem);
68055  sqlite3DbFree(p->v->db, p);
68056}
68057
68058#ifndef SQLITE_OMIT_EXPLAIN
68059/*
68060** Give a listing of the program in the virtual machine.
68061**
68062** The interface is the same as sqlite3VdbeExec().  But instead of
68063** running the code, it invokes the callback once for each instruction.
68064** This feature is used to implement "EXPLAIN".
68065**
68066** When p->explain==1, each instruction is listed.  When
68067** p->explain==2, only OP_Explain instructions are listed and these
68068** are shown in a different format.  p->explain==2 is used to implement
68069** EXPLAIN QUERY PLAN.
68070**
68071** When p->explain==1, first the main program is listed, then each of
68072** the trigger subprograms are listed one by one.
68073*/
68074SQLITE_PRIVATE int sqlite3VdbeList(
68075  Vdbe *p                   /* The VDBE */
68076){
68077  int nRow;                            /* Stop when row count reaches this */
68078  int nSub = 0;                        /* Number of sub-vdbes seen so far */
68079  SubProgram **apSub = 0;              /* Array of sub-vdbes */
68080  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
68081  sqlite3 *db = p->db;                 /* The database connection */
68082  int i;                               /* Loop counter */
68083  int rc = SQLITE_OK;                  /* Return code */
68084  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
68085
68086  assert( p->explain );
68087  assert( p->magic==VDBE_MAGIC_RUN );
68088  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
68089
68090  /* Even though this opcode does not use dynamic strings for
68091  ** the result, result columns may become dynamic if the user calls
68092  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
68093  */
68094  releaseMemArray(pMem, 8);
68095  p->pResultSet = 0;
68096
68097  if( p->rc==SQLITE_NOMEM ){
68098    /* This happens if a malloc() inside a call to sqlite3_column_text() or
68099    ** sqlite3_column_text16() failed.  */
68100    db->mallocFailed = 1;
68101    return SQLITE_ERROR;
68102  }
68103
68104  /* When the number of output rows reaches nRow, that means the
68105  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
68106  ** nRow is the sum of the number of rows in the main program, plus
68107  ** the sum of the number of rows in all trigger subprograms encountered
68108  ** so far.  The nRow value will increase as new trigger subprograms are
68109  ** encountered, but p->pc will eventually catch up to nRow.
68110  */
68111  nRow = p->nOp;
68112  if( p->explain==1 ){
68113    /* The first 8 memory cells are used for the result set.  So we will
68114    ** commandeer the 9th cell to use as storage for an array of pointers
68115    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
68116    ** cells.  */
68117    assert( p->nMem>9 );
68118    pSub = &p->aMem[9];
68119    if( pSub->flags&MEM_Blob ){
68120      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
68121      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
68122      nSub = pSub->n/sizeof(Vdbe*);
68123      apSub = (SubProgram **)pSub->z;
68124    }
68125    for(i=0; i<nSub; i++){
68126      nRow += apSub[i]->nOp;
68127    }
68128  }
68129
68130  do{
68131    i = p->pc++;
68132  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
68133  if( i>=nRow ){
68134    p->rc = SQLITE_OK;
68135    rc = SQLITE_DONE;
68136  }else if( db->u1.isInterrupted ){
68137    p->rc = SQLITE_INTERRUPT;
68138    rc = SQLITE_ERROR;
68139    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
68140  }else{
68141    char *zP4;
68142    Op *pOp;
68143    if( i<p->nOp ){
68144      /* The output line number is small enough that we are still in the
68145      ** main program. */
68146      pOp = &p->aOp[i];
68147    }else{
68148      /* We are currently listing subprograms.  Figure out which one and
68149      ** pick up the appropriate opcode. */
68150      int j;
68151      i -= p->nOp;
68152      for(j=0; i>=apSub[j]->nOp; j++){
68153        i -= apSub[j]->nOp;
68154      }
68155      pOp = &apSub[j]->aOp[i];
68156    }
68157    if( p->explain==1 ){
68158      pMem->flags = MEM_Int;
68159      pMem->u.i = i;                                /* Program counter */
68160      pMem++;
68161
68162      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
68163      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
68164      assert( pMem->z!=0 );
68165      pMem->n = sqlite3Strlen30(pMem->z);
68166      pMem->enc = SQLITE_UTF8;
68167      pMem++;
68168
68169      /* When an OP_Program opcode is encounter (the only opcode that has
68170      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
68171      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
68172      ** has not already been seen.
68173      */
68174      if( pOp->p4type==P4_SUBPROGRAM ){
68175        int nByte = (nSub+1)*sizeof(SubProgram*);
68176        int j;
68177        for(j=0; j<nSub; j++){
68178          if( apSub[j]==pOp->p4.pProgram ) break;
68179        }
68180        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
68181          apSub = (SubProgram **)pSub->z;
68182          apSub[nSub++] = pOp->p4.pProgram;
68183          pSub->flags |= MEM_Blob;
68184          pSub->n = nSub*sizeof(SubProgram*);
68185        }
68186      }
68187    }
68188
68189    pMem->flags = MEM_Int;
68190    pMem->u.i = pOp->p1;                          /* P1 */
68191    pMem++;
68192
68193    pMem->flags = MEM_Int;
68194    pMem->u.i = pOp->p2;                          /* P2 */
68195    pMem++;
68196
68197    pMem->flags = MEM_Int;
68198    pMem->u.i = pOp->p3;                          /* P3 */
68199    pMem++;
68200
68201    if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
68202      assert( p->db->mallocFailed );
68203      return SQLITE_ERROR;
68204    }
68205    pMem->flags = MEM_Str|MEM_Term;
68206    zP4 = displayP4(pOp, pMem->z, 32);
68207    if( zP4!=pMem->z ){
68208      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
68209    }else{
68210      assert( pMem->z!=0 );
68211      pMem->n = sqlite3Strlen30(pMem->z);
68212      pMem->enc = SQLITE_UTF8;
68213    }
68214    pMem++;
68215
68216    if( p->explain==1 ){
68217      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
68218        assert( p->db->mallocFailed );
68219        return SQLITE_ERROR;
68220      }
68221      pMem->flags = MEM_Str|MEM_Term;
68222      pMem->n = 2;
68223      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
68224      pMem->enc = SQLITE_UTF8;
68225      pMem++;
68226
68227#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
68228      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
68229        assert( p->db->mallocFailed );
68230        return SQLITE_ERROR;
68231      }
68232      pMem->flags = MEM_Str|MEM_Term;
68233      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
68234      pMem->enc = SQLITE_UTF8;
68235#else
68236      pMem->flags = MEM_Null;                       /* Comment */
68237#endif
68238    }
68239
68240    p->nResColumn = 8 - 4*(p->explain-1);
68241    p->pResultSet = &p->aMem[1];
68242    p->rc = SQLITE_OK;
68243    rc = SQLITE_ROW;
68244  }
68245  return rc;
68246}
68247#endif /* SQLITE_OMIT_EXPLAIN */
68248
68249#ifdef SQLITE_DEBUG
68250/*
68251** Print the SQL that was used to generate a VDBE program.
68252*/
68253SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
68254  const char *z = 0;
68255  if( p->zSql ){
68256    z = p->zSql;
68257  }else if( p->nOp>=1 ){
68258    const VdbeOp *pOp = &p->aOp[0];
68259    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
68260      z = pOp->p4.z;
68261      while( sqlite3Isspace(*z) ) z++;
68262    }
68263  }
68264  if( z ) printf("SQL: [%s]\n", z);
68265}
68266#endif
68267
68268#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
68269/*
68270** Print an IOTRACE message showing SQL content.
68271*/
68272SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
68273  int nOp = p->nOp;
68274  VdbeOp *pOp;
68275  if( sqlite3IoTrace==0 ) return;
68276  if( nOp<1 ) return;
68277  pOp = &p->aOp[0];
68278  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
68279    int i, j;
68280    char z[1000];
68281    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
68282    for(i=0; sqlite3Isspace(z[i]); i++){}
68283    for(j=0; z[i]; i++){
68284      if( sqlite3Isspace(z[i]) ){
68285        if( z[i-1]!=' ' ){
68286          z[j++] = ' ';
68287        }
68288      }else{
68289        z[j++] = z[i];
68290      }
68291    }
68292    z[j] = 0;
68293    sqlite3IoTrace("SQL %s\n", z);
68294  }
68295}
68296#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
68297
68298/*
68299** Allocate space from a fixed size buffer and return a pointer to
68300** that space.  If insufficient space is available, return NULL.
68301**
68302** The pBuf parameter is the initial value of a pointer which will
68303** receive the new memory.  pBuf is normally NULL.  If pBuf is not
68304** NULL, it means that memory space has already been allocated and that
68305** this routine should not allocate any new memory.  When pBuf is not
68306** NULL simply return pBuf.  Only allocate new memory space when pBuf
68307** is NULL.
68308**
68309** nByte is the number of bytes of space needed.
68310**
68311** *ppFrom points to available space and pEnd points to the end of the
68312** available space.  When space is allocated, *ppFrom is advanced past
68313** the end of the allocated space.
68314**
68315** *pnByte is a counter of the number of bytes of space that have failed
68316** to allocate.  If there is insufficient space in *ppFrom to satisfy the
68317** request, then increment *pnByte by the amount of the request.
68318*/
68319static void *allocSpace(
68320  void *pBuf,          /* Where return pointer will be stored */
68321  int nByte,           /* Number of bytes to allocate */
68322  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
68323  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
68324  int *pnByte          /* If allocation cannot be made, increment *pnByte */
68325){
68326  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
68327  if( pBuf ) return pBuf;
68328  nByte = ROUND8(nByte);
68329  if( &(*ppFrom)[nByte] <= pEnd ){
68330    pBuf = (void*)*ppFrom;
68331    *ppFrom += nByte;
68332  }else{
68333    *pnByte += nByte;
68334  }
68335  return pBuf;
68336}
68337
68338/*
68339** Rewind the VDBE back to the beginning in preparation for
68340** running it.
68341*/
68342SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
68343#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
68344  int i;
68345#endif
68346  assert( p!=0 );
68347  assert( p->magic==VDBE_MAGIC_INIT );
68348
68349  /* There should be at least one opcode.
68350  */
68351  assert( p->nOp>0 );
68352
68353  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
68354  p->magic = VDBE_MAGIC_RUN;
68355
68356#ifdef SQLITE_DEBUG
68357  for(i=1; i<p->nMem; i++){
68358    assert( p->aMem[i].db==p->db );
68359  }
68360#endif
68361  p->pc = -1;
68362  p->rc = SQLITE_OK;
68363  p->errorAction = OE_Abort;
68364  p->magic = VDBE_MAGIC_RUN;
68365  p->nChange = 0;
68366  p->cacheCtr = 1;
68367  p->minWriteFileFormat = 255;
68368  p->iStatement = 0;
68369  p->nFkConstraint = 0;
68370#ifdef VDBE_PROFILE
68371  for(i=0; i<p->nOp; i++){
68372    p->aOp[i].cnt = 0;
68373    p->aOp[i].cycles = 0;
68374  }
68375#endif
68376}
68377
68378/*
68379** Prepare a virtual machine for execution for the first time after
68380** creating the virtual machine.  This involves things such
68381** as allocating registers and initializing the program counter.
68382** After the VDBE has be prepped, it can be executed by one or more
68383** calls to sqlite3VdbeExec().
68384**
68385** This function may be called exactly once on each virtual machine.
68386** After this routine is called the VM has been "packaged" and is ready
68387** to run.  After this routine is called, further calls to
68388** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
68389** the Vdbe from the Parse object that helped generate it so that the
68390** the Vdbe becomes an independent entity and the Parse object can be
68391** destroyed.
68392**
68393** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
68394** to its initial state after it has been run.
68395*/
68396SQLITE_PRIVATE void sqlite3VdbeMakeReady(
68397  Vdbe *p,                       /* The VDBE */
68398  Parse *pParse                  /* Parsing context */
68399){
68400  sqlite3 *db;                   /* The database connection */
68401  int nVar;                      /* Number of parameters */
68402  int nMem;                      /* Number of VM memory registers */
68403  int nCursor;                   /* Number of cursors required */
68404  int nArg;                      /* Number of arguments in subprograms */
68405  int nOnce;                     /* Number of OP_Once instructions */
68406  int n;                         /* Loop counter */
68407  u8 *zCsr;                      /* Memory available for allocation */
68408  u8 *zEnd;                      /* First byte past allocated memory */
68409  int nByte;                     /* How much extra memory is needed */
68410
68411  assert( p!=0 );
68412  assert( p->nOp>0 );
68413  assert( pParse!=0 );
68414  assert( p->magic==VDBE_MAGIC_INIT );
68415  assert( pParse==p->pParse );
68416  db = p->db;
68417  assert( db->mallocFailed==0 );
68418  nVar = pParse->nVar;
68419  nMem = pParse->nMem;
68420  nCursor = pParse->nTab;
68421  nArg = pParse->nMaxArg;
68422  nOnce = pParse->nOnce;
68423  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
68424
68425  /* For each cursor required, also allocate a memory cell. Memory
68426  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
68427  ** the vdbe program. Instead they are used to allocate space for
68428  ** VdbeCursor/BtCursor structures. The blob of memory associated with
68429  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
68430  ** stores the blob of memory associated with cursor 1, etc.
68431  **
68432  ** See also: allocateCursor().
68433  */
68434  nMem += nCursor;
68435
68436  /* Allocate space for memory registers, SQL variables, VDBE cursors and
68437  ** an array to marshal SQL function arguments in.
68438  */
68439  zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
68440  zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
68441
68442  resolveP2Values(p, &nArg);
68443  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
68444  if( pParse->explain && nMem<10 ){
68445    nMem = 10;
68446  }
68447  memset(zCsr, 0, zEnd-zCsr);
68448  zCsr += (zCsr - (u8*)0)&7;
68449  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
68450  p->expired = 0;
68451
68452  /* Memory for registers, parameters, cursor, etc, is allocated in two
68453  ** passes.  On the first pass, we try to reuse unused space at the
68454  ** end of the opcode array.  If we are unable to satisfy all memory
68455  ** requirements by reusing the opcode array tail, then the second
68456  ** pass will fill in the rest using a fresh allocation.
68457  **
68458  ** This two-pass approach that reuses as much memory as possible from
68459  ** the leftover space at the end of the opcode array can significantly
68460  ** reduce the amount of memory held by a prepared statement.
68461  */
68462  do {
68463    nByte = 0;
68464    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
68465    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
68466    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
68467    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
68468    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
68469                          &zCsr, zEnd, &nByte);
68470    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
68471#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
68472    p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
68473#endif
68474    if( nByte ){
68475      p->pFree = sqlite3DbMallocZero(db, nByte);
68476    }
68477    zCsr = p->pFree;
68478    zEnd = &zCsr[nByte];
68479  }while( nByte && !db->mallocFailed );
68480
68481  p->nCursor = nCursor;
68482  p->nOnceFlag = nOnce;
68483  if( p->aVar ){
68484    p->nVar = (ynVar)nVar;
68485    for(n=0; n<nVar; n++){
68486      p->aVar[n].flags = MEM_Null;
68487      p->aVar[n].db = db;
68488    }
68489  }
68490  if( p->azVar && pParse->nzVar>0 ){
68491    p->nzVar = pParse->nzVar;
68492    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
68493    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
68494  }
68495  if( p->aMem ){
68496    p->aMem--;                      /* aMem[] goes from 1..nMem */
68497    p->nMem = nMem;                 /*       not from 0..nMem-1 */
68498    for(n=1; n<=nMem; n++){
68499      p->aMem[n].flags = MEM_Undefined;
68500      p->aMem[n].db = db;
68501    }
68502  }
68503  p->explain = pParse->explain;
68504  sqlite3VdbeRewind(p);
68505}
68506
68507/*
68508** Close a VDBE cursor and release all the resources that cursor
68509** happens to hold.
68510*/
68511SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
68512  if( pCx==0 ){
68513    return;
68514  }
68515  sqlite3VdbeSorterClose(p->db, pCx);
68516  if( pCx->pBt ){
68517    sqlite3BtreeClose(pCx->pBt);
68518    /* The pCx->pCursor will be close automatically, if it exists, by
68519    ** the call above. */
68520  }else if( pCx->pCursor ){
68521    sqlite3BtreeCloseCursor(pCx->pCursor);
68522  }
68523#ifndef SQLITE_OMIT_VIRTUALTABLE
68524  else if( pCx->pVtabCursor ){
68525    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
68526    const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
68527    assert( pVtabCursor->pVtab->nRef>0 );
68528    pVtabCursor->pVtab->nRef--;
68529    pModule->xClose(pVtabCursor);
68530  }
68531#endif
68532}
68533
68534/*
68535** Close all cursors in the current frame.
68536*/
68537static void closeCursorsInFrame(Vdbe *p){
68538  if( p->apCsr ){
68539    int i;
68540    for(i=0; i<p->nCursor; i++){
68541      VdbeCursor *pC = p->apCsr[i];
68542      if( pC ){
68543        sqlite3VdbeFreeCursor(p, pC);
68544        p->apCsr[i] = 0;
68545      }
68546    }
68547  }
68548}
68549
68550/*
68551** Copy the values stored in the VdbeFrame structure to its Vdbe. This
68552** is used, for example, when a trigger sub-program is halted to restore
68553** control to the main program.
68554*/
68555SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
68556  Vdbe *v = pFrame->v;
68557  closeCursorsInFrame(v);
68558#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
68559  v->anExec = pFrame->anExec;
68560#endif
68561  v->aOnceFlag = pFrame->aOnceFlag;
68562  v->nOnceFlag = pFrame->nOnceFlag;
68563  v->aOp = pFrame->aOp;
68564  v->nOp = pFrame->nOp;
68565  v->aMem = pFrame->aMem;
68566  v->nMem = pFrame->nMem;
68567  v->apCsr = pFrame->apCsr;
68568  v->nCursor = pFrame->nCursor;
68569  v->db->lastRowid = pFrame->lastRowid;
68570  v->nChange = pFrame->nChange;
68571  v->db->nChange = pFrame->nDbChange;
68572  return pFrame->pc;
68573}
68574
68575/*
68576** Close all cursors.
68577**
68578** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
68579** cell array. This is necessary as the memory cell array may contain
68580** pointers to VdbeFrame objects, which may in turn contain pointers to
68581** open cursors.
68582*/
68583static void closeAllCursors(Vdbe *p){
68584  if( p->pFrame ){
68585    VdbeFrame *pFrame;
68586    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
68587    sqlite3VdbeFrameRestore(pFrame);
68588    p->pFrame = 0;
68589    p->nFrame = 0;
68590  }
68591  assert( p->nFrame==0 );
68592  closeCursorsInFrame(p);
68593  if( p->aMem ){
68594    releaseMemArray(&p->aMem[1], p->nMem);
68595  }
68596  while( p->pDelFrame ){
68597    VdbeFrame *pDel = p->pDelFrame;
68598    p->pDelFrame = pDel->pParent;
68599    sqlite3VdbeFrameDelete(pDel);
68600  }
68601
68602  /* Delete any auxdata allocations made by the VM */
68603  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
68604  assert( p->pAuxData==0 );
68605}
68606
68607/*
68608** Clean up the VM after a single run.
68609*/
68610static void Cleanup(Vdbe *p){
68611  sqlite3 *db = p->db;
68612
68613#ifdef SQLITE_DEBUG
68614  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
68615  ** Vdbe.aMem[] arrays have already been cleaned up.  */
68616  int i;
68617  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
68618  if( p->aMem ){
68619    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
68620  }
68621#endif
68622
68623  sqlite3DbFree(db, p->zErrMsg);
68624  p->zErrMsg = 0;
68625  p->pResultSet = 0;
68626}
68627
68628/*
68629** Set the number of result columns that will be returned by this SQL
68630** statement. This is now set at compile time, rather than during
68631** execution of the vdbe program so that sqlite3_column_count() can
68632** be called on an SQL statement before sqlite3_step().
68633*/
68634SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
68635  Mem *pColName;
68636  int n;
68637  sqlite3 *db = p->db;
68638
68639  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
68640  sqlite3DbFree(db, p->aColName);
68641  n = nResColumn*COLNAME_N;
68642  p->nResColumn = (u16)nResColumn;
68643  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
68644  if( p->aColName==0 ) return;
68645  while( n-- > 0 ){
68646    pColName->flags = MEM_Null;
68647    pColName->db = p->db;
68648    pColName++;
68649  }
68650}
68651
68652/*
68653** Set the name of the idx'th column to be returned by the SQL statement.
68654** zName must be a pointer to a nul terminated string.
68655**
68656** This call must be made after a call to sqlite3VdbeSetNumCols().
68657**
68658** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
68659** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
68660** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
68661*/
68662SQLITE_PRIVATE int sqlite3VdbeSetColName(
68663  Vdbe *p,                         /* Vdbe being configured */
68664  int idx,                         /* Index of column zName applies to */
68665  int var,                         /* One of the COLNAME_* constants */
68666  const char *zName,               /* Pointer to buffer containing name */
68667  void (*xDel)(void*)              /* Memory management strategy for zName */
68668){
68669  int rc;
68670  Mem *pColName;
68671  assert( idx<p->nResColumn );
68672  assert( var<COLNAME_N );
68673  if( p->db->mallocFailed ){
68674    assert( !zName || xDel!=SQLITE_DYNAMIC );
68675    return SQLITE_NOMEM;
68676  }
68677  assert( p->aColName!=0 );
68678  pColName = &(p->aColName[idx+var*p->nResColumn]);
68679  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
68680  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
68681  return rc;
68682}
68683
68684/*
68685** A read or write transaction may or may not be active on database handle
68686** db. If a transaction is active, commit it. If there is a
68687** write-transaction spanning more than one database file, this routine
68688** takes care of the master journal trickery.
68689*/
68690static int vdbeCommit(sqlite3 *db, Vdbe *p){
68691  int i;
68692  int nTrans = 0;  /* Number of databases with an active write-transaction */
68693  int rc = SQLITE_OK;
68694  int needXcommit = 0;
68695
68696#ifdef SQLITE_OMIT_VIRTUALTABLE
68697  /* With this option, sqlite3VtabSync() is defined to be simply
68698  ** SQLITE_OK so p is not used.
68699  */
68700  UNUSED_PARAMETER(p);
68701#endif
68702
68703  /* Before doing anything else, call the xSync() callback for any
68704  ** virtual module tables written in this transaction. This has to
68705  ** be done before determining whether a master journal file is
68706  ** required, as an xSync() callback may add an attached database
68707  ** to the transaction.
68708  */
68709  rc = sqlite3VtabSync(db, p);
68710
68711  /* This loop determines (a) if the commit hook should be invoked and
68712  ** (b) how many database files have open write transactions, not
68713  ** including the temp database. (b) is important because if more than
68714  ** one database file has an open write transaction, a master journal
68715  ** file is required for an atomic commit.
68716  */
68717  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68718    Btree *pBt = db->aDb[i].pBt;
68719    if( sqlite3BtreeIsInTrans(pBt) ){
68720      needXcommit = 1;
68721      if( i!=1 ) nTrans++;
68722      sqlite3BtreeEnter(pBt);
68723      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
68724      sqlite3BtreeLeave(pBt);
68725    }
68726  }
68727  if( rc!=SQLITE_OK ){
68728    return rc;
68729  }
68730
68731  /* If there are any write-transactions at all, invoke the commit hook */
68732  if( needXcommit && db->xCommitCallback ){
68733    rc = db->xCommitCallback(db->pCommitArg);
68734    if( rc ){
68735      return SQLITE_CONSTRAINT_COMMITHOOK;
68736    }
68737  }
68738
68739  /* The simple case - no more than one database file (not counting the
68740  ** TEMP database) has a transaction active.   There is no need for the
68741  ** master-journal.
68742  **
68743  ** If the return value of sqlite3BtreeGetFilename() is a zero length
68744  ** string, it means the main database is :memory: or a temp file.  In
68745  ** that case we do not support atomic multi-file commits, so use the
68746  ** simple case then too.
68747  */
68748  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
68749   || nTrans<=1
68750  ){
68751    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68752      Btree *pBt = db->aDb[i].pBt;
68753      if( pBt ){
68754        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
68755      }
68756    }
68757
68758    /* Do the commit only if all databases successfully complete phase 1.
68759    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
68760    ** IO error while deleting or truncating a journal file. It is unlikely,
68761    ** but could happen. In this case abandon processing and return the error.
68762    */
68763    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68764      Btree *pBt = db->aDb[i].pBt;
68765      if( pBt ){
68766        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
68767      }
68768    }
68769    if( rc==SQLITE_OK ){
68770      sqlite3VtabCommit(db);
68771    }
68772  }
68773
68774  /* The complex case - There is a multi-file write-transaction active.
68775  ** This requires a master journal file to ensure the transaction is
68776  ** committed atomically.
68777  */
68778#ifndef SQLITE_OMIT_DISKIO
68779  else{
68780    sqlite3_vfs *pVfs = db->pVfs;
68781    int needSync = 0;
68782    char *zMaster = 0;   /* File-name for the master journal */
68783    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
68784    sqlite3_file *pMaster = 0;
68785    i64 offset = 0;
68786    int res;
68787    int retryCount = 0;
68788    int nMainFile;
68789
68790    /* Select a master journal file name */
68791    nMainFile = sqlite3Strlen30(zMainFile);
68792    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
68793    if( zMaster==0 ) return SQLITE_NOMEM;
68794    do {
68795      u32 iRandom;
68796      if( retryCount ){
68797        if( retryCount>100 ){
68798          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
68799          sqlite3OsDelete(pVfs, zMaster, 0);
68800          break;
68801        }else if( retryCount==1 ){
68802          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
68803        }
68804      }
68805      retryCount++;
68806      sqlite3_randomness(sizeof(iRandom), &iRandom);
68807      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
68808                               (iRandom>>8)&0xffffff, iRandom&0xff);
68809      /* The antipenultimate character of the master journal name must
68810      ** be "9" to avoid name collisions when using 8+3 filenames. */
68811      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
68812      sqlite3FileSuffix3(zMainFile, zMaster);
68813      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
68814    }while( rc==SQLITE_OK && res );
68815    if( rc==SQLITE_OK ){
68816      /* Open the master journal. */
68817      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
68818          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
68819          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
68820      );
68821    }
68822    if( rc!=SQLITE_OK ){
68823      sqlite3DbFree(db, zMaster);
68824      return rc;
68825    }
68826
68827    /* Write the name of each database file in the transaction into the new
68828    ** master journal file. If an error occurs at this point close
68829    ** and delete the master journal file. All the individual journal files
68830    ** still have 'null' as the master journal pointer, so they will roll
68831    ** back independently if a failure occurs.
68832    */
68833    for(i=0; i<db->nDb; i++){
68834      Btree *pBt = db->aDb[i].pBt;
68835      if( sqlite3BtreeIsInTrans(pBt) ){
68836        char const *zFile = sqlite3BtreeGetJournalname(pBt);
68837        if( zFile==0 ){
68838          continue;  /* Ignore TEMP and :memory: databases */
68839        }
68840        assert( zFile[0]!=0 );
68841        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
68842          needSync = 1;
68843        }
68844        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
68845        offset += sqlite3Strlen30(zFile)+1;
68846        if( rc!=SQLITE_OK ){
68847          sqlite3OsCloseFree(pMaster);
68848          sqlite3OsDelete(pVfs, zMaster, 0);
68849          sqlite3DbFree(db, zMaster);
68850          return rc;
68851        }
68852      }
68853    }
68854
68855    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
68856    ** flag is set this is not required.
68857    */
68858    if( needSync
68859     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
68860     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
68861    ){
68862      sqlite3OsCloseFree(pMaster);
68863      sqlite3OsDelete(pVfs, zMaster, 0);
68864      sqlite3DbFree(db, zMaster);
68865      return rc;
68866    }
68867
68868    /* Sync all the db files involved in the transaction. The same call
68869    ** sets the master journal pointer in each individual journal. If
68870    ** an error occurs here, do not delete the master journal file.
68871    **
68872    ** If the error occurs during the first call to
68873    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
68874    ** master journal file will be orphaned. But we cannot delete it,
68875    ** in case the master journal file name was written into the journal
68876    ** file before the failure occurred.
68877    */
68878    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68879      Btree *pBt = db->aDb[i].pBt;
68880      if( pBt ){
68881        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
68882      }
68883    }
68884    sqlite3OsCloseFree(pMaster);
68885    assert( rc!=SQLITE_BUSY );
68886    if( rc!=SQLITE_OK ){
68887      sqlite3DbFree(db, zMaster);
68888      return rc;
68889    }
68890
68891    /* Delete the master journal file. This commits the transaction. After
68892    ** doing this the directory is synced again before any individual
68893    ** transaction files are deleted.
68894    */
68895    rc = sqlite3OsDelete(pVfs, zMaster, needSync);
68896    sqlite3DbFree(db, zMaster);
68897    zMaster = 0;
68898    if( rc ){
68899      return rc;
68900    }
68901
68902    /* All files and directories have already been synced, so the following
68903    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
68904    ** deleting or truncating journals. If something goes wrong while
68905    ** this is happening we don't really care. The integrity of the
68906    ** transaction is already guaranteed, but some stray 'cold' journals
68907    ** may be lying around. Returning an error code won't help matters.
68908    */
68909    disable_simulated_io_errors();
68910    sqlite3BeginBenignMalloc();
68911    for(i=0; i<db->nDb; i++){
68912      Btree *pBt = db->aDb[i].pBt;
68913      if( pBt ){
68914        sqlite3BtreeCommitPhaseTwo(pBt, 1);
68915      }
68916    }
68917    sqlite3EndBenignMalloc();
68918    enable_simulated_io_errors();
68919
68920    sqlite3VtabCommit(db);
68921  }
68922#endif
68923
68924  return rc;
68925}
68926
68927/*
68928** This routine checks that the sqlite3.nVdbeActive count variable
68929** matches the number of vdbe's in the list sqlite3.pVdbe that are
68930** currently active. An assertion fails if the two counts do not match.
68931** This is an internal self-check only - it is not an essential processing
68932** step.
68933**
68934** This is a no-op if NDEBUG is defined.
68935*/
68936#ifndef NDEBUG
68937static void checkActiveVdbeCnt(sqlite3 *db){
68938  Vdbe *p;
68939  int cnt = 0;
68940  int nWrite = 0;
68941  int nRead = 0;
68942  p = db->pVdbe;
68943  while( p ){
68944    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
68945      cnt++;
68946      if( p->readOnly==0 ) nWrite++;
68947      if( p->bIsReader ) nRead++;
68948    }
68949    p = p->pNext;
68950  }
68951  assert( cnt==db->nVdbeActive );
68952  assert( nWrite==db->nVdbeWrite );
68953  assert( nRead==db->nVdbeRead );
68954}
68955#else
68956#define checkActiveVdbeCnt(x)
68957#endif
68958
68959/*
68960** If the Vdbe passed as the first argument opened a statement-transaction,
68961** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
68962** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
68963** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
68964** statement transaction is committed.
68965**
68966** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
68967** Otherwise SQLITE_OK.
68968*/
68969SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
68970  sqlite3 *const db = p->db;
68971  int rc = SQLITE_OK;
68972
68973  /* If p->iStatement is greater than zero, then this Vdbe opened a
68974  ** statement transaction that should be closed here. The only exception
68975  ** is that an IO error may have occurred, causing an emergency rollback.
68976  ** In this case (db->nStatement==0), and there is nothing to do.
68977  */
68978  if( db->nStatement && p->iStatement ){
68979    int i;
68980    const int iSavepoint = p->iStatement-1;
68981
68982    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
68983    assert( db->nStatement>0 );
68984    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
68985
68986    for(i=0; i<db->nDb; i++){
68987      int rc2 = SQLITE_OK;
68988      Btree *pBt = db->aDb[i].pBt;
68989      if( pBt ){
68990        if( eOp==SAVEPOINT_ROLLBACK ){
68991          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
68992        }
68993        if( rc2==SQLITE_OK ){
68994          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
68995        }
68996        if( rc==SQLITE_OK ){
68997          rc = rc2;
68998        }
68999      }
69000    }
69001    db->nStatement--;
69002    p->iStatement = 0;
69003
69004    if( rc==SQLITE_OK ){
69005      if( eOp==SAVEPOINT_ROLLBACK ){
69006        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
69007      }
69008      if( rc==SQLITE_OK ){
69009        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
69010      }
69011    }
69012
69013    /* If the statement transaction is being rolled back, also restore the
69014    ** database handles deferred constraint counter to the value it had when
69015    ** the statement transaction was opened.  */
69016    if( eOp==SAVEPOINT_ROLLBACK ){
69017      db->nDeferredCons = p->nStmtDefCons;
69018      db->nDeferredImmCons = p->nStmtDefImmCons;
69019    }
69020  }
69021  return rc;
69022}
69023
69024/*
69025** This function is called when a transaction opened by the database
69026** handle associated with the VM passed as an argument is about to be
69027** committed. If there are outstanding deferred foreign key constraint
69028** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
69029**
69030** If there are outstanding FK violations and this function returns
69031** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
69032** and write an error message to it. Then return SQLITE_ERROR.
69033*/
69034#ifndef SQLITE_OMIT_FOREIGN_KEY
69035SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
69036  sqlite3 *db = p->db;
69037  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
69038   || (!deferred && p->nFkConstraint>0)
69039  ){
69040    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
69041    p->errorAction = OE_Abort;
69042    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
69043    return SQLITE_ERROR;
69044  }
69045  return SQLITE_OK;
69046}
69047#endif
69048
69049/*
69050** This routine is called the when a VDBE tries to halt.  If the VDBE
69051** has made changes and is in autocommit mode, then commit those
69052** changes.  If a rollback is needed, then do the rollback.
69053**
69054** This routine is the only way to move the state of a VM from
69055** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
69056** call this on a VM that is in the SQLITE_MAGIC_HALT state.
69057**
69058** Return an error code.  If the commit could not complete because of
69059** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
69060** means the close did not happen and needs to be repeated.
69061*/
69062SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
69063  int rc;                         /* Used to store transient return codes */
69064  sqlite3 *db = p->db;
69065
69066  /* This function contains the logic that determines if a statement or
69067  ** transaction will be committed or rolled back as a result of the
69068  ** execution of this virtual machine.
69069  **
69070  ** If any of the following errors occur:
69071  **
69072  **     SQLITE_NOMEM
69073  **     SQLITE_IOERR
69074  **     SQLITE_FULL
69075  **     SQLITE_INTERRUPT
69076  **
69077  ** Then the internal cache might have been left in an inconsistent
69078  ** state.  We need to rollback the statement transaction, if there is
69079  ** one, or the complete transaction if there is no statement transaction.
69080  */
69081
69082  if( p->db->mallocFailed ){
69083    p->rc = SQLITE_NOMEM;
69084  }
69085  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
69086  closeAllCursors(p);
69087  if( p->magic!=VDBE_MAGIC_RUN ){
69088    return SQLITE_OK;
69089  }
69090  checkActiveVdbeCnt(db);
69091
69092  /* No commit or rollback needed if the program never started or if the
69093  ** SQL statement does not read or write a database file.  */
69094  if( p->pc>=0 && p->bIsReader ){
69095    int mrc;   /* Primary error code from p->rc */
69096    int eStatementOp = 0;
69097    int isSpecialError;            /* Set to true if a 'special' error */
69098
69099    /* Lock all btrees used by the statement */
69100    sqlite3VdbeEnter(p);
69101
69102    /* Check for one of the special errors */
69103    mrc = p->rc & 0xff;
69104    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
69105                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
69106    if( isSpecialError ){
69107      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
69108      ** no rollback is necessary. Otherwise, at least a savepoint
69109      ** transaction must be rolled back to restore the database to a
69110      ** consistent state.
69111      **
69112      ** Even if the statement is read-only, it is important to perform
69113      ** a statement or transaction rollback operation. If the error
69114      ** occurred while writing to the journal, sub-journal or database
69115      ** file as part of an effort to free up cache space (see function
69116      ** pagerStress() in pager.c), the rollback is required to restore
69117      ** the pager to a consistent state.
69118      */
69119      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
69120        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
69121          eStatementOp = SAVEPOINT_ROLLBACK;
69122        }else{
69123          /* We are forced to roll back the active transaction. Before doing
69124          ** so, abort any other statements this handle currently has active.
69125          */
69126          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69127          sqlite3CloseSavepoints(db);
69128          db->autoCommit = 1;
69129          p->nChange = 0;
69130        }
69131      }
69132    }
69133
69134    /* Check for immediate foreign key violations. */
69135    if( p->rc==SQLITE_OK ){
69136      sqlite3VdbeCheckFk(p, 0);
69137    }
69138
69139    /* If the auto-commit flag is set and this is the only active writer
69140    ** VM, then we do either a commit or rollback of the current transaction.
69141    **
69142    ** Note: This block also runs if one of the special errors handled
69143    ** above has occurred.
69144    */
69145    if( !sqlite3VtabInSync(db)
69146     && db->autoCommit
69147     && db->nVdbeWrite==(p->readOnly==0)
69148    ){
69149      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
69150        rc = sqlite3VdbeCheckFk(p, 1);
69151        if( rc!=SQLITE_OK ){
69152          if( NEVER(p->readOnly) ){
69153            sqlite3VdbeLeave(p);
69154            return SQLITE_ERROR;
69155          }
69156          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
69157        }else{
69158          /* The auto-commit flag is true, the vdbe program was successful
69159          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
69160          ** key constraints to hold up the transaction. This means a commit
69161          ** is required. */
69162          rc = vdbeCommit(db, p);
69163        }
69164        if( rc==SQLITE_BUSY && p->readOnly ){
69165          sqlite3VdbeLeave(p);
69166          return SQLITE_BUSY;
69167        }else if( rc!=SQLITE_OK ){
69168          p->rc = rc;
69169          sqlite3RollbackAll(db, SQLITE_OK);
69170          p->nChange = 0;
69171        }else{
69172          db->nDeferredCons = 0;
69173          db->nDeferredImmCons = 0;
69174          db->flags &= ~SQLITE_DeferFKs;
69175          sqlite3CommitInternalChanges(db);
69176        }
69177      }else{
69178        sqlite3RollbackAll(db, SQLITE_OK);
69179        p->nChange = 0;
69180      }
69181      db->nStatement = 0;
69182    }else if( eStatementOp==0 ){
69183      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
69184        eStatementOp = SAVEPOINT_RELEASE;
69185      }else if( p->errorAction==OE_Abort ){
69186        eStatementOp = SAVEPOINT_ROLLBACK;
69187      }else{
69188        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69189        sqlite3CloseSavepoints(db);
69190        db->autoCommit = 1;
69191        p->nChange = 0;
69192      }
69193    }
69194
69195    /* If eStatementOp is non-zero, then a statement transaction needs to
69196    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
69197    ** do so. If this operation returns an error, and the current statement
69198    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
69199    ** current statement error code.
69200    */
69201    if( eStatementOp ){
69202      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
69203      if( rc ){
69204        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
69205          p->rc = rc;
69206          sqlite3DbFree(db, p->zErrMsg);
69207          p->zErrMsg = 0;
69208        }
69209        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69210        sqlite3CloseSavepoints(db);
69211        db->autoCommit = 1;
69212        p->nChange = 0;
69213      }
69214    }
69215
69216    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
69217    ** has been rolled back, update the database connection change-counter.
69218    */
69219    if( p->changeCntOn ){
69220      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
69221        sqlite3VdbeSetChanges(db, p->nChange);
69222      }else{
69223        sqlite3VdbeSetChanges(db, 0);
69224      }
69225      p->nChange = 0;
69226    }
69227
69228    /* Release the locks */
69229    sqlite3VdbeLeave(p);
69230  }
69231
69232  /* We have successfully halted and closed the VM.  Record this fact. */
69233  if( p->pc>=0 ){
69234    db->nVdbeActive--;
69235    if( !p->readOnly ) db->nVdbeWrite--;
69236    if( p->bIsReader ) db->nVdbeRead--;
69237    assert( db->nVdbeActive>=db->nVdbeRead );
69238    assert( db->nVdbeRead>=db->nVdbeWrite );
69239    assert( db->nVdbeWrite>=0 );
69240  }
69241  p->magic = VDBE_MAGIC_HALT;
69242  checkActiveVdbeCnt(db);
69243  if( p->db->mallocFailed ){
69244    p->rc = SQLITE_NOMEM;
69245  }
69246
69247  /* If the auto-commit flag is set to true, then any locks that were held
69248  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
69249  ** to invoke any required unlock-notify callbacks.
69250  */
69251  if( db->autoCommit ){
69252    sqlite3ConnectionUnlocked(db);
69253  }
69254
69255  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
69256  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
69257}
69258
69259
69260/*
69261** Each VDBE holds the result of the most recent sqlite3_step() call
69262** in p->rc.  This routine sets that result back to SQLITE_OK.
69263*/
69264SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
69265  p->rc = SQLITE_OK;
69266}
69267
69268/*
69269** Copy the error code and error message belonging to the VDBE passed
69270** as the first argument to its database handle (so that they will be
69271** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
69272**
69273** This function does not clear the VDBE error code or message, just
69274** copies them to the database handle.
69275*/
69276SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
69277  sqlite3 *db = p->db;
69278  int rc = p->rc;
69279  if( p->zErrMsg ){
69280    u8 mallocFailed = db->mallocFailed;
69281    sqlite3BeginBenignMalloc();
69282    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
69283    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
69284    sqlite3EndBenignMalloc();
69285    db->mallocFailed = mallocFailed;
69286    db->errCode = rc;
69287  }else{
69288    sqlite3Error(db, rc);
69289  }
69290  return rc;
69291}
69292
69293#ifdef SQLITE_ENABLE_SQLLOG
69294/*
69295** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
69296** invoke it.
69297*/
69298static void vdbeInvokeSqllog(Vdbe *v){
69299  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
69300    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
69301    assert( v->db->init.busy==0 );
69302    if( zExpanded ){
69303      sqlite3GlobalConfig.xSqllog(
69304          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
69305      );
69306      sqlite3DbFree(v->db, zExpanded);
69307    }
69308  }
69309}
69310#else
69311# define vdbeInvokeSqllog(x)
69312#endif
69313
69314/*
69315** Clean up a VDBE after execution but do not delete the VDBE just yet.
69316** Write any error messages into *pzErrMsg.  Return the result code.
69317**
69318** After this routine is run, the VDBE should be ready to be executed
69319** again.
69320**
69321** To look at it another way, this routine resets the state of the
69322** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
69323** VDBE_MAGIC_INIT.
69324*/
69325SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
69326  sqlite3 *db;
69327  db = p->db;
69328
69329  /* If the VM did not run to completion or if it encountered an
69330  ** error, then it might not have been halted properly.  So halt
69331  ** it now.
69332  */
69333  sqlite3VdbeHalt(p);
69334
69335  /* If the VDBE has be run even partially, then transfer the error code
69336  ** and error message from the VDBE into the main database structure.  But
69337  ** if the VDBE has just been set to run but has not actually executed any
69338  ** instructions yet, leave the main database error information unchanged.
69339  */
69340  if( p->pc>=0 ){
69341    vdbeInvokeSqllog(p);
69342    sqlite3VdbeTransferError(p);
69343    sqlite3DbFree(db, p->zErrMsg);
69344    p->zErrMsg = 0;
69345    if( p->runOnlyOnce ) p->expired = 1;
69346  }else if( p->rc && p->expired ){
69347    /* The expired flag was set on the VDBE before the first call
69348    ** to sqlite3_step(). For consistency (since sqlite3_step() was
69349    ** called), set the database error in this case as well.
69350    */
69351    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
69352    sqlite3DbFree(db, p->zErrMsg);
69353    p->zErrMsg = 0;
69354  }
69355
69356  /* Reclaim all memory used by the VDBE
69357  */
69358  Cleanup(p);
69359
69360  /* Save profiling information from this VDBE run.
69361  */
69362#ifdef VDBE_PROFILE
69363  {
69364    FILE *out = fopen("vdbe_profile.out", "a");
69365    if( out ){
69366      int i;
69367      fprintf(out, "---- ");
69368      for(i=0; i<p->nOp; i++){
69369        fprintf(out, "%02x", p->aOp[i].opcode);
69370      }
69371      fprintf(out, "\n");
69372      if( p->zSql ){
69373        char c, pc = 0;
69374        fprintf(out, "-- ");
69375        for(i=0; (c = p->zSql[i])!=0; i++){
69376          if( pc=='\n' ) fprintf(out, "-- ");
69377          putc(c, out);
69378          pc = c;
69379        }
69380        if( pc!='\n' ) fprintf(out, "\n");
69381      }
69382      for(i=0; i<p->nOp; i++){
69383        char zHdr[100];
69384        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
69385           p->aOp[i].cnt,
69386           p->aOp[i].cycles,
69387           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
69388        );
69389        fprintf(out, "%s", zHdr);
69390        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
69391      }
69392      fclose(out);
69393    }
69394  }
69395#endif
69396  p->iCurrentTime = 0;
69397  p->magic = VDBE_MAGIC_INIT;
69398  return p->rc & db->errMask;
69399}
69400
69401/*
69402** Clean up and delete a VDBE after execution.  Return an integer which is
69403** the result code.  Write any error message text into *pzErrMsg.
69404*/
69405SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
69406  int rc = SQLITE_OK;
69407  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
69408    rc = sqlite3VdbeReset(p);
69409    assert( (rc & p->db->errMask)==rc );
69410  }
69411  sqlite3VdbeDelete(p);
69412  return rc;
69413}
69414
69415/*
69416** If parameter iOp is less than zero, then invoke the destructor for
69417** all auxiliary data pointers currently cached by the VM passed as
69418** the first argument.
69419**
69420** Or, if iOp is greater than or equal to zero, then the destructor is
69421** only invoked for those auxiliary data pointers created by the user
69422** function invoked by the OP_Function opcode at instruction iOp of
69423** VM pVdbe, and only then if:
69424**
69425**    * the associated function parameter is the 32nd or later (counting
69426**      from left to right), or
69427**
69428**    * the corresponding bit in argument mask is clear (where the first
69429**      function parameter corresponds to bit 0 etc.).
69430*/
69431SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
69432  AuxData **pp = &pVdbe->pAuxData;
69433  while( *pp ){
69434    AuxData *pAux = *pp;
69435    if( (iOp<0)
69436     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
69437    ){
69438      testcase( pAux->iArg==31 );
69439      if( pAux->xDelete ){
69440        pAux->xDelete(pAux->pAux);
69441      }
69442      *pp = pAux->pNext;
69443      sqlite3DbFree(pVdbe->db, pAux);
69444    }else{
69445      pp= &pAux->pNext;
69446    }
69447  }
69448}
69449
69450/*
69451** Free all memory associated with the Vdbe passed as the second argument,
69452** except for object itself, which is preserved.
69453**
69454** The difference between this function and sqlite3VdbeDelete() is that
69455** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
69456** the database connection and frees the object itself.
69457*/
69458SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
69459  SubProgram *pSub, *pNext;
69460  int i;
69461  assert( p->db==0 || p->db==db );
69462  releaseMemArray(p->aVar, p->nVar);
69463  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
69464  for(pSub=p->pProgram; pSub; pSub=pNext){
69465    pNext = pSub->pNext;
69466    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
69467    sqlite3DbFree(db, pSub);
69468  }
69469  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
69470  vdbeFreeOpArray(db, p->aOp, p->nOp);
69471  sqlite3DbFree(db, p->aColName);
69472  sqlite3DbFree(db, p->zSql);
69473  sqlite3DbFree(db, p->pFree);
69474#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
69475  for(i=0; i<p->nScan; i++){
69476    sqlite3DbFree(db, p->aScan[i].zName);
69477  }
69478  sqlite3DbFree(db, p->aScan);
69479#endif
69480}
69481
69482/*
69483** Delete an entire VDBE.
69484*/
69485SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
69486  sqlite3 *db;
69487
69488  if( NEVER(p==0) ) return;
69489  db = p->db;
69490  assert( sqlite3_mutex_held(db->mutex) );
69491  sqlite3VdbeClearObject(db, p);
69492  if( p->pPrev ){
69493    p->pPrev->pNext = p->pNext;
69494  }else{
69495    assert( db->pVdbe==p );
69496    db->pVdbe = p->pNext;
69497  }
69498  if( p->pNext ){
69499    p->pNext->pPrev = p->pPrev;
69500  }
69501  p->magic = VDBE_MAGIC_DEAD;
69502  p->db = 0;
69503  sqlite3DbFree(db, p);
69504}
69505
69506/*
69507** The cursor "p" has a pending seek operation that has not yet been
69508** carried out.  Seek the cursor now.  If an error occurs, return
69509** the appropriate error code.
69510*/
69511static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
69512  int res, rc;
69513#ifdef SQLITE_TEST
69514  extern int sqlite3_search_count;
69515#endif
69516  assert( p->deferredMoveto );
69517  assert( p->isTable );
69518  rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
69519  if( rc ) return rc;
69520  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
69521#ifdef SQLITE_TEST
69522  sqlite3_search_count++;
69523#endif
69524  p->deferredMoveto = 0;
69525  p->cacheStatus = CACHE_STALE;
69526  return SQLITE_OK;
69527}
69528
69529/*
69530** Something has moved cursor "p" out of place.  Maybe the row it was
69531** pointed to was deleted out from under it.  Or maybe the btree was
69532** rebalanced.  Whatever the cause, try to restore "p" to the place it
69533** is supposed to be pointing.  If the row was deleted out from under the
69534** cursor, set the cursor to point to a NULL row.
69535*/
69536static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
69537  int isDifferentRow, rc;
69538  assert( p->pCursor!=0 );
69539  assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
69540  rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
69541  p->cacheStatus = CACHE_STALE;
69542  if( isDifferentRow ) p->nullRow = 1;
69543  return rc;
69544}
69545
69546/*
69547** Check to ensure that the cursor is valid.  Restore the cursor
69548** if need be.  Return any I/O error from the restore operation.
69549*/
69550SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
69551  if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
69552    return handleMovedCursor(p);
69553  }
69554  return SQLITE_OK;
69555}
69556
69557/*
69558** Make sure the cursor p is ready to read or write the row to which it
69559** was last positioned.  Return an error code if an OOM fault or I/O error
69560** prevents us from positioning the cursor to its correct position.
69561**
69562** If a MoveTo operation is pending on the given cursor, then do that
69563** MoveTo now.  If no move is pending, check to see if the row has been
69564** deleted out from under the cursor and if it has, mark the row as
69565** a NULL row.
69566**
69567** If the cursor is already pointing to the correct row and that row has
69568** not been deleted out from under the cursor, then this routine is a no-op.
69569*/
69570SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
69571  if( p->deferredMoveto ){
69572    return handleDeferredMoveto(p);
69573  }
69574  if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
69575    return handleMovedCursor(p);
69576  }
69577  return SQLITE_OK;
69578}
69579
69580/*
69581** The following functions:
69582**
69583** sqlite3VdbeSerialType()
69584** sqlite3VdbeSerialTypeLen()
69585** sqlite3VdbeSerialLen()
69586** sqlite3VdbeSerialPut()
69587** sqlite3VdbeSerialGet()
69588**
69589** encapsulate the code that serializes values for storage in SQLite
69590** data and index records. Each serialized value consists of a
69591** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
69592** integer, stored as a varint.
69593**
69594** In an SQLite index record, the serial type is stored directly before
69595** the blob of data that it corresponds to. In a table record, all serial
69596** types are stored at the start of the record, and the blobs of data at
69597** the end. Hence these functions allow the caller to handle the
69598** serial-type and data blob separately.
69599**
69600** The following table describes the various storage classes for data:
69601**
69602**   serial type        bytes of data      type
69603**   --------------     ---------------    ---------------
69604**      0                     0            NULL
69605**      1                     1            signed integer
69606**      2                     2            signed integer
69607**      3                     3            signed integer
69608**      4                     4            signed integer
69609**      5                     6            signed integer
69610**      6                     8            signed integer
69611**      7                     8            IEEE float
69612**      8                     0            Integer constant 0
69613**      9                     0            Integer constant 1
69614**     10,11                               reserved for expansion
69615**    N>=12 and even       (N-12)/2        BLOB
69616**    N>=13 and odd        (N-13)/2        text
69617**
69618** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
69619** of SQLite will not understand those serial types.
69620*/
69621
69622/*
69623** Return the serial-type for the value stored in pMem.
69624*/
69625SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
69626  int flags = pMem->flags;
69627  u32 n;
69628
69629  if( flags&MEM_Null ){
69630    return 0;
69631  }
69632  if( flags&MEM_Int ){
69633    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
69634#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
69635    i64 i = pMem->u.i;
69636    u64 u;
69637    if( i<0 ){
69638      u = ~i;
69639    }else{
69640      u = i;
69641    }
69642    if( u<=127 ){
69643      return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
69644    }
69645    if( u<=32767 ) return 2;
69646    if( u<=8388607 ) return 3;
69647    if( u<=2147483647 ) return 4;
69648    if( u<=MAX_6BYTE ) return 5;
69649    return 6;
69650  }
69651  if( flags&MEM_Real ){
69652    return 7;
69653  }
69654  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
69655  assert( pMem->n>=0 );
69656  n = (u32)pMem->n;
69657  if( flags & MEM_Zero ){
69658    n += pMem->u.nZero;
69659  }
69660  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
69661}
69662
69663/*
69664** The sizes for serial types less than 12
69665*/
69666static const u8 sqlite3SmallTypeSizes[] = {
69667  0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0
69668};
69669
69670/*
69671** Return the length of the data corresponding to the supplied serial-type.
69672*/
69673SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
69674  if( serial_type>=12 ){
69675    return (serial_type-12)/2;
69676  }else{
69677    return sqlite3SmallTypeSizes[serial_type];
69678  }
69679}
69680
69681/*
69682** If we are on an architecture with mixed-endian floating
69683** points (ex: ARM7) then swap the lower 4 bytes with the
69684** upper 4 bytes.  Return the result.
69685**
69686** For most architectures, this is a no-op.
69687**
69688** (later):  It is reported to me that the mixed-endian problem
69689** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
69690** that early versions of GCC stored the two words of a 64-bit
69691** float in the wrong order.  And that error has been propagated
69692** ever since.  The blame is not necessarily with GCC, though.
69693** GCC might have just copying the problem from a prior compiler.
69694** I am also told that newer versions of GCC that follow a different
69695** ABI get the byte order right.
69696**
69697** Developers using SQLite on an ARM7 should compile and run their
69698** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
69699** enabled, some asserts below will ensure that the byte order of
69700** floating point values is correct.
69701**
69702** (2007-08-30)  Frank van Vugt has studied this problem closely
69703** and has send his findings to the SQLite developers.  Frank
69704** writes that some Linux kernels offer floating point hardware
69705** emulation that uses only 32-bit mantissas instead of a full
69706** 48-bits as required by the IEEE standard.  (This is the
69707** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
69708** byte swapping becomes very complicated.  To avoid problems,
69709** the necessary byte swapping is carried out using a 64-bit integer
69710** rather than a 64-bit float.  Frank assures us that the code here
69711** works for him.  We, the developers, have no way to independently
69712** verify this, but Frank seems to know what he is talking about
69713** so we trust him.
69714*/
69715#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
69716static u64 floatSwap(u64 in){
69717  union {
69718    u64 r;
69719    u32 i[2];
69720  } u;
69721  u32 t;
69722
69723  u.r = in;
69724  t = u.i[0];
69725  u.i[0] = u.i[1];
69726  u.i[1] = t;
69727  return u.r;
69728}
69729# define swapMixedEndianFloat(X)  X = floatSwap(X)
69730#else
69731# define swapMixedEndianFloat(X)
69732#endif
69733
69734/*
69735** Write the serialized data blob for the value stored in pMem into
69736** buf. It is assumed that the caller has allocated sufficient space.
69737** Return the number of bytes written.
69738**
69739** nBuf is the amount of space left in buf[].  The caller is responsible
69740** for allocating enough space to buf[] to hold the entire field, exclusive
69741** of the pMem->u.nZero bytes for a MEM_Zero value.
69742**
69743** Return the number of bytes actually written into buf[].  The number
69744** of bytes in the zero-filled tail is included in the return value only
69745** if those bytes were zeroed in buf[].
69746*/
69747SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
69748  u32 len;
69749
69750  /* Integer and Real */
69751  if( serial_type<=7 && serial_type>0 ){
69752    u64 v;
69753    u32 i;
69754    if( serial_type==7 ){
69755      assert( sizeof(v)==sizeof(pMem->u.r) );
69756      memcpy(&v, &pMem->u.r, sizeof(v));
69757      swapMixedEndianFloat(v);
69758    }else{
69759      v = pMem->u.i;
69760    }
69761    len = i = sqlite3SmallTypeSizes[serial_type];
69762    assert( i>0 );
69763    do{
69764      buf[--i] = (u8)(v&0xFF);
69765      v >>= 8;
69766    }while( i );
69767    return len;
69768  }
69769
69770  /* String or blob */
69771  if( serial_type>=12 ){
69772    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
69773             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
69774    len = pMem->n;
69775    memcpy(buf, pMem->z, len);
69776    return len;
69777  }
69778
69779  /* NULL or constants 0 or 1 */
69780  return 0;
69781}
69782
69783/* Input "x" is a sequence of unsigned characters that represent a
69784** big-endian integer.  Return the equivalent native integer
69785*/
69786#define ONE_BYTE_INT(x)    ((i8)(x)[0])
69787#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
69788#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
69789#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
69790#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
69791
69792/*
69793** Deserialize the data blob pointed to by buf as serial type serial_type
69794** and store the result in pMem.  Return the number of bytes read.
69795**
69796** This function is implemented as two separate routines for performance.
69797** The few cases that require local variables are broken out into a separate
69798** routine so that in most cases the overhead of moving the stack pointer
69799** is avoided.
69800*/
69801static u32 SQLITE_NOINLINE serialGet(
69802  const unsigned char *buf,     /* Buffer to deserialize from */
69803  u32 serial_type,              /* Serial type to deserialize */
69804  Mem *pMem                     /* Memory cell to write value into */
69805){
69806  u64 x = FOUR_BYTE_UINT(buf);
69807  u32 y = FOUR_BYTE_UINT(buf+4);
69808  x = (x<<32) + y;
69809  if( serial_type==6 ){
69810    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
69811    ** twos-complement integer. */
69812    pMem->u.i = *(i64*)&x;
69813    pMem->flags = MEM_Int;
69814    testcase( pMem->u.i<0 );
69815  }else{
69816    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
69817    ** floating point number. */
69818#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
69819    /* Verify that integers and floating point values use the same
69820    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
69821    ** defined that 64-bit floating point values really are mixed
69822    ** endian.
69823    */
69824    static const u64 t1 = ((u64)0x3ff00000)<<32;
69825    static const double r1 = 1.0;
69826    u64 t2 = t1;
69827    swapMixedEndianFloat(t2);
69828    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
69829#endif
69830    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
69831    swapMixedEndianFloat(x);
69832    memcpy(&pMem->u.r, &x, sizeof(x));
69833    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
69834  }
69835  return 8;
69836}
69837SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
69838  const unsigned char *buf,     /* Buffer to deserialize from */
69839  u32 serial_type,              /* Serial type to deserialize */
69840  Mem *pMem                     /* Memory cell to write value into */
69841){
69842  switch( serial_type ){
69843    case 10:   /* Reserved for future use */
69844    case 11:   /* Reserved for future use */
69845    case 0: {  /* Null */
69846      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
69847      pMem->flags = MEM_Null;
69848      break;
69849    }
69850    case 1: {
69851      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
69852      ** integer. */
69853      pMem->u.i = ONE_BYTE_INT(buf);
69854      pMem->flags = MEM_Int;
69855      testcase( pMem->u.i<0 );
69856      return 1;
69857    }
69858    case 2: { /* 2-byte signed integer */
69859      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
69860      ** twos-complement integer. */
69861      pMem->u.i = TWO_BYTE_INT(buf);
69862      pMem->flags = MEM_Int;
69863      testcase( pMem->u.i<0 );
69864      return 2;
69865    }
69866    case 3: { /* 3-byte signed integer */
69867      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
69868      ** twos-complement integer. */
69869      pMem->u.i = THREE_BYTE_INT(buf);
69870      pMem->flags = MEM_Int;
69871      testcase( pMem->u.i<0 );
69872      return 3;
69873    }
69874    case 4: { /* 4-byte signed integer */
69875      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
69876      ** twos-complement integer. */
69877      pMem->u.i = FOUR_BYTE_INT(buf);
69878      pMem->flags = MEM_Int;
69879      testcase( pMem->u.i<0 );
69880      return 4;
69881    }
69882    case 5: { /* 6-byte signed integer */
69883      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
69884      ** twos-complement integer. */
69885      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
69886      pMem->flags = MEM_Int;
69887      testcase( pMem->u.i<0 );
69888      return 6;
69889    }
69890    case 6:   /* 8-byte signed integer */
69891    case 7: { /* IEEE floating point */
69892      /* These use local variables, so do them in a separate routine
69893      ** to avoid having to move the frame pointer in the common case */
69894      return serialGet(buf,serial_type,pMem);
69895    }
69896    case 8:    /* Integer 0 */
69897    case 9: {  /* Integer 1 */
69898      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
69899      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
69900      pMem->u.i = serial_type-8;
69901      pMem->flags = MEM_Int;
69902      return 0;
69903    }
69904    default: {
69905      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
69906      ** length.
69907      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
69908      ** (N-13)/2 bytes in length. */
69909      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
69910      pMem->z = (char *)buf;
69911      pMem->n = (serial_type-12)/2;
69912      pMem->flags = aFlag[serial_type&1];
69913      return pMem->n;
69914    }
69915  }
69916  return 0;
69917}
69918/*
69919** This routine is used to allocate sufficient space for an UnpackedRecord
69920** structure large enough to be used with sqlite3VdbeRecordUnpack() if
69921** the first argument is a pointer to KeyInfo structure pKeyInfo.
69922**
69923** The space is either allocated using sqlite3DbMallocRaw() or from within
69924** the unaligned buffer passed via the second and third arguments (presumably
69925** stack space). If the former, then *ppFree is set to a pointer that should
69926** be eventually freed by the caller using sqlite3DbFree(). Or, if the
69927** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
69928** before returning.
69929**
69930** If an OOM error occurs, NULL is returned.
69931*/
69932SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
69933  KeyInfo *pKeyInfo,              /* Description of the record */
69934  char *pSpace,                   /* Unaligned space available */
69935  int szSpace,                    /* Size of pSpace[] in bytes */
69936  char **ppFree                   /* OUT: Caller should free this pointer */
69937){
69938  UnpackedRecord *p;              /* Unpacked record to return */
69939  int nOff;                       /* Increment pSpace by nOff to align it */
69940  int nByte;                      /* Number of bytes required for *p */
69941
69942  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
69943  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
69944  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
69945  */
69946  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
69947  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
69948  if( nByte>szSpace+nOff ){
69949    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
69950    *ppFree = (char *)p;
69951    if( !p ) return 0;
69952  }else{
69953    p = (UnpackedRecord*)&pSpace[nOff];
69954    *ppFree = 0;
69955  }
69956
69957  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
69958  assert( pKeyInfo->aSortOrder!=0 );
69959  p->pKeyInfo = pKeyInfo;
69960  p->nField = pKeyInfo->nField + 1;
69961  return p;
69962}
69963
69964/*
69965** Given the nKey-byte encoding of a record in pKey[], populate the
69966** UnpackedRecord structure indicated by the fourth argument with the
69967** contents of the decoded record.
69968*/
69969SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
69970  KeyInfo *pKeyInfo,     /* Information about the record format */
69971  int nKey,              /* Size of the binary record */
69972  const void *pKey,      /* The binary record */
69973  UnpackedRecord *p      /* Populate this structure before returning. */
69974){
69975  const unsigned char *aKey = (const unsigned char *)pKey;
69976  int d;
69977  u32 idx;                        /* Offset in aKey[] to read from */
69978  u16 u;                          /* Unsigned loop counter */
69979  u32 szHdr;
69980  Mem *pMem = p->aMem;
69981
69982  p->default_rc = 0;
69983  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69984  idx = getVarint32(aKey, szHdr);
69985  d = szHdr;
69986  u = 0;
69987  while( idx<szHdr && d<=nKey ){
69988    u32 serial_type;
69989
69990    idx += getVarint32(&aKey[idx], serial_type);
69991    pMem->enc = pKeyInfo->enc;
69992    pMem->db = pKeyInfo->db;
69993    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
69994    pMem->szMalloc = 0;
69995    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
69996    pMem++;
69997    if( (++u)>=p->nField ) break;
69998  }
69999  assert( u<=pKeyInfo->nField + 1 );
70000  p->nField = u;
70001}
70002
70003#if SQLITE_DEBUG
70004/*
70005** This function compares two index or table record keys in the same way
70006** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
70007** this function deserializes and compares values using the
70008** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
70009** in assert() statements to ensure that the optimized code in
70010** sqlite3VdbeRecordCompare() returns results with these two primitives.
70011**
70012** Return true if the result of comparison is equivalent to desiredResult.
70013** Return false if there is a disagreement.
70014*/
70015static int vdbeRecordCompareDebug(
70016  int nKey1, const void *pKey1, /* Left key */
70017  const UnpackedRecord *pPKey2, /* Right key */
70018  int desiredResult             /* Correct answer */
70019){
70020  u32 d1;            /* Offset into aKey[] of next data element */
70021  u32 idx1;          /* Offset into aKey[] of next header element */
70022  u32 szHdr1;        /* Number of bytes in header */
70023  int i = 0;
70024  int rc = 0;
70025  const unsigned char *aKey1 = (const unsigned char *)pKey1;
70026  KeyInfo *pKeyInfo;
70027  Mem mem1;
70028
70029  pKeyInfo = pPKey2->pKeyInfo;
70030  if( pKeyInfo->db==0 ) return 1;
70031  mem1.enc = pKeyInfo->enc;
70032  mem1.db = pKeyInfo->db;
70033  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
70034  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
70035
70036  /* Compilers may complain that mem1.u.i is potentially uninitialized.
70037  ** We could initialize it, as shown here, to silence those complaints.
70038  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
70039  ** the unnecessary initialization has a measurable negative performance
70040  ** impact, since this routine is a very high runner.  And so, we choose
70041  ** to ignore the compiler warnings and leave this variable uninitialized.
70042  */
70043  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
70044
70045  idx1 = getVarint32(aKey1, szHdr1);
70046  if( szHdr1>98307 ) return SQLITE_CORRUPT;
70047  d1 = szHdr1;
70048  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
70049  assert( pKeyInfo->aSortOrder!=0 );
70050  assert( pKeyInfo->nField>0 );
70051  assert( idx1<=szHdr1 || CORRUPT_DB );
70052  do{
70053    u32 serial_type1;
70054
70055    /* Read the serial types for the next element in each key. */
70056    idx1 += getVarint32( aKey1+idx1, serial_type1 );
70057
70058    /* Verify that there is enough key space remaining to avoid
70059    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
70060    ** always be greater than or equal to the amount of required key space.
70061    ** Use that approximation to avoid the more expensive call to
70062    ** sqlite3VdbeSerialTypeLen() in the common case.
70063    */
70064    if( d1+serial_type1+2>(u32)nKey1
70065     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
70066    ){
70067      break;
70068    }
70069
70070    /* Extract the values to be compared.
70071    */
70072    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
70073
70074    /* Do the comparison
70075    */
70076    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
70077    if( rc!=0 ){
70078      assert( mem1.szMalloc==0 );  /* See comment below */
70079      if( pKeyInfo->aSortOrder[i] ){
70080        rc = -rc;  /* Invert the result for DESC sort order. */
70081      }
70082      goto debugCompareEnd;
70083    }
70084    i++;
70085  }while( idx1<szHdr1 && i<pPKey2->nField );
70086
70087  /* No memory allocation is ever used on mem1.  Prove this using
70088  ** the following assert().  If the assert() fails, it indicates a
70089  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
70090  */
70091  assert( mem1.szMalloc==0 );
70092
70093  /* rc==0 here means that one of the keys ran out of fields and
70094  ** all the fields up to that point were equal. Return the default_rc
70095  ** value.  */
70096  rc = pPKey2->default_rc;
70097
70098debugCompareEnd:
70099  if( desiredResult==0 && rc==0 ) return 1;
70100  if( desiredResult<0 && rc<0 ) return 1;
70101  if( desiredResult>0 && rc>0 ) return 1;
70102  if( CORRUPT_DB ) return 1;
70103  if( pKeyInfo->db->mallocFailed ) return 1;
70104  return 0;
70105}
70106#endif
70107
70108#if SQLITE_DEBUG
70109/*
70110** Count the number of fields (a.k.a. columns) in the record given by
70111** pKey,nKey.  The verify that this count is less than or equal to the
70112** limit given by pKeyInfo->nField + pKeyInfo->nXField.
70113**
70114** If this constraint is not satisfied, it means that the high-speed
70115** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
70116** not work correctly.  If this assert() ever fires, it probably means
70117** that the KeyInfo.nField or KeyInfo.nXField values were computed
70118** incorrectly.
70119*/
70120static void vdbeAssertFieldCountWithinLimits(
70121  int nKey, const void *pKey,   /* The record to verify */
70122  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
70123){
70124  int nField = 0;
70125  u32 szHdr;
70126  u32 idx;
70127  u32 notUsed;
70128  const unsigned char *aKey = (const unsigned char*)pKey;
70129
70130  if( CORRUPT_DB ) return;
70131  idx = getVarint32(aKey, szHdr);
70132  assert( nKey>=0 );
70133  assert( szHdr<=(u32)nKey );
70134  while( idx<szHdr ){
70135    idx += getVarint32(aKey+idx, notUsed);
70136    nField++;
70137  }
70138  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
70139}
70140#else
70141# define vdbeAssertFieldCountWithinLimits(A,B,C)
70142#endif
70143
70144/*
70145** Both *pMem1 and *pMem2 contain string values. Compare the two values
70146** using the collation sequence pColl. As usual, return a negative , zero
70147** or positive value if *pMem1 is less than, equal to or greater than
70148** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
70149*/
70150static int vdbeCompareMemString(
70151  const Mem *pMem1,
70152  const Mem *pMem2,
70153  const CollSeq *pColl,
70154  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
70155){
70156  if( pMem1->enc==pColl->enc ){
70157    /* The strings are already in the correct encoding.  Call the
70158     ** comparison function directly */
70159    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
70160  }else{
70161    int rc;
70162    const void *v1, *v2;
70163    int n1, n2;
70164    Mem c1;
70165    Mem c2;
70166    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
70167    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
70168    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
70169    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
70170    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
70171    n1 = v1==0 ? 0 : c1.n;
70172    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
70173    n2 = v2==0 ? 0 : c2.n;
70174    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
70175    sqlite3VdbeMemRelease(&c1);
70176    sqlite3VdbeMemRelease(&c2);
70177    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
70178    return rc;
70179  }
70180}
70181
70182/*
70183** Compare two blobs.  Return negative, zero, or positive if the first
70184** is less than, equal to, or greater than the second, respectively.
70185** If one blob is a prefix of the other, then the shorter is the lessor.
70186*/
70187static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
70188  int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
70189  if( c ) return c;
70190  return pB1->n - pB2->n;
70191}
70192
70193
70194/*
70195** Compare the values contained by the two memory cells, returning
70196** negative, zero or positive if pMem1 is less than, equal to, or greater
70197** than pMem2. Sorting order is NULL's first, followed by numbers (integers
70198** and reals) sorted numerically, followed by text ordered by the collating
70199** sequence pColl and finally blob's ordered by memcmp().
70200**
70201** Two NULL values are considered equal by this function.
70202*/
70203SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
70204  int f1, f2;
70205  int combined_flags;
70206
70207  f1 = pMem1->flags;
70208  f2 = pMem2->flags;
70209  combined_flags = f1|f2;
70210  assert( (combined_flags & MEM_RowSet)==0 );
70211
70212  /* If one value is NULL, it is less than the other. If both values
70213  ** are NULL, return 0.
70214  */
70215  if( combined_flags&MEM_Null ){
70216    return (f2&MEM_Null) - (f1&MEM_Null);
70217  }
70218
70219  /* If one value is a number and the other is not, the number is less.
70220  ** If both are numbers, compare as reals if one is a real, or as integers
70221  ** if both values are integers.
70222  */
70223  if( combined_flags&(MEM_Int|MEM_Real) ){
70224    double r1, r2;
70225    if( (f1 & f2 & MEM_Int)!=0 ){
70226      if( pMem1->u.i < pMem2->u.i ) return -1;
70227      if( pMem1->u.i > pMem2->u.i ) return 1;
70228      return 0;
70229    }
70230    if( (f1&MEM_Real)!=0 ){
70231      r1 = pMem1->u.r;
70232    }else if( (f1&MEM_Int)!=0 ){
70233      r1 = (double)pMem1->u.i;
70234    }else{
70235      return 1;
70236    }
70237    if( (f2&MEM_Real)!=0 ){
70238      r2 = pMem2->u.r;
70239    }else if( (f2&MEM_Int)!=0 ){
70240      r2 = (double)pMem2->u.i;
70241    }else{
70242      return -1;
70243    }
70244    if( r1<r2 ) return -1;
70245    if( r1>r2 ) return 1;
70246    return 0;
70247  }
70248
70249  /* If one value is a string and the other is a blob, the string is less.
70250  ** If both are strings, compare using the collating functions.
70251  */
70252  if( combined_flags&MEM_Str ){
70253    if( (f1 & MEM_Str)==0 ){
70254      return 1;
70255    }
70256    if( (f2 & MEM_Str)==0 ){
70257      return -1;
70258    }
70259
70260    assert( pMem1->enc==pMem2->enc );
70261    assert( pMem1->enc==SQLITE_UTF8 ||
70262            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
70263
70264    /* The collation sequence must be defined at this point, even if
70265    ** the user deletes the collation sequence after the vdbe program is
70266    ** compiled (this was not always the case).
70267    */
70268    assert( !pColl || pColl->xCmp );
70269
70270    if( pColl ){
70271      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
70272    }
70273    /* If a NULL pointer was passed as the collate function, fall through
70274    ** to the blob case and use memcmp().  */
70275  }
70276
70277  /* Both values must be blobs.  Compare using memcmp().  */
70278  return sqlite3BlobCompare(pMem1, pMem2);
70279}
70280
70281
70282/*
70283** The first argument passed to this function is a serial-type that
70284** corresponds to an integer - all values between 1 and 9 inclusive
70285** except 7. The second points to a buffer containing an integer value
70286** serialized according to serial_type. This function deserializes
70287** and returns the value.
70288*/
70289static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
70290  u32 y;
70291  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
70292  switch( serial_type ){
70293    case 0:
70294    case 1:
70295      testcase( aKey[0]&0x80 );
70296      return ONE_BYTE_INT(aKey);
70297    case 2:
70298      testcase( aKey[0]&0x80 );
70299      return TWO_BYTE_INT(aKey);
70300    case 3:
70301      testcase( aKey[0]&0x80 );
70302      return THREE_BYTE_INT(aKey);
70303    case 4: {
70304      testcase( aKey[0]&0x80 );
70305      y = FOUR_BYTE_UINT(aKey);
70306      return (i64)*(int*)&y;
70307    }
70308    case 5: {
70309      testcase( aKey[0]&0x80 );
70310      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
70311    }
70312    case 6: {
70313      u64 x = FOUR_BYTE_UINT(aKey);
70314      testcase( aKey[0]&0x80 );
70315      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
70316      return (i64)*(i64*)&x;
70317    }
70318  }
70319
70320  return (serial_type - 8);
70321}
70322
70323/*
70324** This function compares the two table rows or index records
70325** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
70326** or positive integer if key1 is less than, equal to or
70327** greater than key2.  The {nKey1, pKey1} key must be a blob
70328** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
70329** key must be a parsed key such as obtained from
70330** sqlite3VdbeParseRecord.
70331**
70332** If argument bSkip is non-zero, it is assumed that the caller has already
70333** determined that the first fields of the keys are equal.
70334**
70335** Key1 and Key2 do not have to contain the same number of fields. If all
70336** fields that appear in both keys are equal, then pPKey2->default_rc is
70337** returned.
70338**
70339** If database corruption is discovered, set pPKey2->errCode to
70340** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
70341** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
70342** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
70343*/
70344SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
70345  int nKey1, const void *pKey1,   /* Left key */
70346  UnpackedRecord *pPKey2,         /* Right key */
70347  int bSkip                       /* If true, skip the first field */
70348){
70349  u32 d1;                         /* Offset into aKey[] of next data element */
70350  int i;                          /* Index of next field to compare */
70351  u32 szHdr1;                     /* Size of record header in bytes */
70352  u32 idx1;                       /* Offset of first type in header */
70353  int rc = 0;                     /* Return value */
70354  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
70355  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
70356  const unsigned char *aKey1 = (const unsigned char *)pKey1;
70357  Mem mem1;
70358
70359  /* If bSkip is true, then the caller has already determined that the first
70360  ** two elements in the keys are equal. Fix the various stack variables so
70361  ** that this routine begins comparing at the second field. */
70362  if( bSkip ){
70363    u32 s1;
70364    idx1 = 1 + getVarint32(&aKey1[1], s1);
70365    szHdr1 = aKey1[0];
70366    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
70367    i = 1;
70368    pRhs++;
70369  }else{
70370    idx1 = getVarint32(aKey1, szHdr1);
70371    d1 = szHdr1;
70372    if( d1>(unsigned)nKey1 ){
70373      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70374      return 0;  /* Corruption */
70375    }
70376    i = 0;
70377  }
70378
70379  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
70380  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
70381       || CORRUPT_DB );
70382  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
70383  assert( pPKey2->pKeyInfo->nField>0 );
70384  assert( idx1<=szHdr1 || CORRUPT_DB );
70385  do{
70386    u32 serial_type;
70387
70388    /* RHS is an integer */
70389    if( pRhs->flags & MEM_Int ){
70390      serial_type = aKey1[idx1];
70391      testcase( serial_type==12 );
70392      if( serial_type>=10 ){
70393        rc = +1;
70394      }else if( serial_type==0 ){
70395        rc = -1;
70396      }else if( serial_type==7 ){
70397        double rhs = (double)pRhs->u.i;
70398        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
70399        if( mem1.u.r<rhs ){
70400          rc = -1;
70401        }else if( mem1.u.r>rhs ){
70402          rc = +1;
70403        }
70404      }else{
70405        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
70406        i64 rhs = pRhs->u.i;
70407        if( lhs<rhs ){
70408          rc = -1;
70409        }else if( lhs>rhs ){
70410          rc = +1;
70411        }
70412      }
70413    }
70414
70415    /* RHS is real */
70416    else if( pRhs->flags & MEM_Real ){
70417      serial_type = aKey1[idx1];
70418      if( serial_type>=10 ){
70419        /* Serial types 12 or greater are strings and blobs (greater than
70420        ** numbers). Types 10 and 11 are currently "reserved for future
70421        ** use", so it doesn't really matter what the results of comparing
70422        ** them to numberic values are.  */
70423        rc = +1;
70424      }else if( serial_type==0 ){
70425        rc = -1;
70426      }else{
70427        double rhs = pRhs->u.r;
70428        double lhs;
70429        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
70430        if( serial_type==7 ){
70431          lhs = mem1.u.r;
70432        }else{
70433          lhs = (double)mem1.u.i;
70434        }
70435        if( lhs<rhs ){
70436          rc = -1;
70437        }else if( lhs>rhs ){
70438          rc = +1;
70439        }
70440      }
70441    }
70442
70443    /* RHS is a string */
70444    else if( pRhs->flags & MEM_Str ){
70445      getVarint32(&aKey1[idx1], serial_type);
70446      testcase( serial_type==12 );
70447      if( serial_type<12 ){
70448        rc = -1;
70449      }else if( !(serial_type & 0x01) ){
70450        rc = +1;
70451      }else{
70452        mem1.n = (serial_type - 12) / 2;
70453        testcase( (d1+mem1.n)==(unsigned)nKey1 );
70454        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
70455        if( (d1+mem1.n) > (unsigned)nKey1 ){
70456          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70457          return 0;                /* Corruption */
70458        }else if( pKeyInfo->aColl[i] ){
70459          mem1.enc = pKeyInfo->enc;
70460          mem1.db = pKeyInfo->db;
70461          mem1.flags = MEM_Str;
70462          mem1.z = (char*)&aKey1[d1];
70463          rc = vdbeCompareMemString(
70464              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
70465          );
70466        }else{
70467          int nCmp = MIN(mem1.n, pRhs->n);
70468          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
70469          if( rc==0 ) rc = mem1.n - pRhs->n;
70470        }
70471      }
70472    }
70473
70474    /* RHS is a blob */
70475    else if( pRhs->flags & MEM_Blob ){
70476      getVarint32(&aKey1[idx1], serial_type);
70477      testcase( serial_type==12 );
70478      if( serial_type<12 || (serial_type & 0x01) ){
70479        rc = -1;
70480      }else{
70481        int nStr = (serial_type - 12) / 2;
70482        testcase( (d1+nStr)==(unsigned)nKey1 );
70483        testcase( (d1+nStr+1)==(unsigned)nKey1 );
70484        if( (d1+nStr) > (unsigned)nKey1 ){
70485          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70486          return 0;                /* Corruption */
70487        }else{
70488          int nCmp = MIN(nStr, pRhs->n);
70489          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
70490          if( rc==0 ) rc = nStr - pRhs->n;
70491        }
70492      }
70493    }
70494
70495    /* RHS is null */
70496    else{
70497      serial_type = aKey1[idx1];
70498      rc = (serial_type!=0);
70499    }
70500
70501    if( rc!=0 ){
70502      if( pKeyInfo->aSortOrder[i] ){
70503        rc = -rc;
70504      }
70505      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
70506      assert( mem1.szMalloc==0 );  /* See comment below */
70507      return rc;
70508    }
70509
70510    i++;
70511    pRhs++;
70512    d1 += sqlite3VdbeSerialTypeLen(serial_type);
70513    idx1 += sqlite3VarintLen(serial_type);
70514  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
70515
70516  /* No memory allocation is ever used on mem1.  Prove this using
70517  ** the following assert().  If the assert() fails, it indicates a
70518  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
70519  assert( mem1.szMalloc==0 );
70520
70521  /* rc==0 here means that one or both of the keys ran out of fields and
70522  ** all the fields up to that point were equal. Return the default_rc
70523  ** value.  */
70524  assert( CORRUPT_DB
70525       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
70526       || pKeyInfo->db->mallocFailed
70527  );
70528  return pPKey2->default_rc;
70529}
70530SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
70531  int nKey1, const void *pKey1,   /* Left key */
70532  UnpackedRecord *pPKey2          /* Right key */
70533){
70534  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
70535}
70536
70537
70538/*
70539** This function is an optimized version of sqlite3VdbeRecordCompare()
70540** that (a) the first field of pPKey2 is an integer, and (b) the
70541** size-of-header varint at the start of (pKey1/nKey1) fits in a single
70542** byte (i.e. is less than 128).
70543**
70544** To avoid concerns about buffer overreads, this routine is only used
70545** on schemas where the maximum valid header size is 63 bytes or less.
70546*/
70547static int vdbeRecordCompareInt(
70548  int nKey1, const void *pKey1, /* Left key */
70549  UnpackedRecord *pPKey2        /* Right key */
70550){
70551  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
70552  int serial_type = ((const u8*)pKey1)[1];
70553  int res;
70554  u32 y;
70555  u64 x;
70556  i64 v = pPKey2->aMem[0].u.i;
70557  i64 lhs;
70558
70559  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
70560  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
70561  switch( serial_type ){
70562    case 1: { /* 1-byte signed integer */
70563      lhs = ONE_BYTE_INT(aKey);
70564      testcase( lhs<0 );
70565      break;
70566    }
70567    case 2: { /* 2-byte signed integer */
70568      lhs = TWO_BYTE_INT(aKey);
70569      testcase( lhs<0 );
70570      break;
70571    }
70572    case 3: { /* 3-byte signed integer */
70573      lhs = THREE_BYTE_INT(aKey);
70574      testcase( lhs<0 );
70575      break;
70576    }
70577    case 4: { /* 4-byte signed integer */
70578      y = FOUR_BYTE_UINT(aKey);
70579      lhs = (i64)*(int*)&y;
70580      testcase( lhs<0 );
70581      break;
70582    }
70583    case 5: { /* 6-byte signed integer */
70584      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
70585      testcase( lhs<0 );
70586      break;
70587    }
70588    case 6: { /* 8-byte signed integer */
70589      x = FOUR_BYTE_UINT(aKey);
70590      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
70591      lhs = *(i64*)&x;
70592      testcase( lhs<0 );
70593      break;
70594    }
70595    case 8:
70596      lhs = 0;
70597      break;
70598    case 9:
70599      lhs = 1;
70600      break;
70601
70602    /* This case could be removed without changing the results of running
70603    ** this code. Including it causes gcc to generate a faster switch
70604    ** statement (since the range of switch targets now starts at zero and
70605    ** is contiguous) but does not cause any duplicate code to be generated
70606    ** (as gcc is clever enough to combine the two like cases). Other
70607    ** compilers might be similar.  */
70608    case 0: case 7:
70609      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
70610
70611    default:
70612      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
70613  }
70614
70615  if( v>lhs ){
70616    res = pPKey2->r1;
70617  }else if( v<lhs ){
70618    res = pPKey2->r2;
70619  }else if( pPKey2->nField>1 ){
70620    /* The first fields of the two keys are equal. Compare the trailing
70621    ** fields.  */
70622    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
70623  }else{
70624    /* The first fields of the two keys are equal and there are no trailing
70625    ** fields. Return pPKey2->default_rc in this case. */
70626    res = pPKey2->default_rc;
70627  }
70628
70629  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
70630  return res;
70631}
70632
70633/*
70634** This function is an optimized version of sqlite3VdbeRecordCompare()
70635** that (a) the first field of pPKey2 is a string, that (b) the first field
70636** uses the collation sequence BINARY and (c) that the size-of-header varint
70637** at the start of (pKey1/nKey1) fits in a single byte.
70638*/
70639static int vdbeRecordCompareString(
70640  int nKey1, const void *pKey1, /* Left key */
70641  UnpackedRecord *pPKey2        /* Right key */
70642){
70643  const u8 *aKey1 = (const u8*)pKey1;
70644  int serial_type;
70645  int res;
70646
70647  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
70648  getVarint32(&aKey1[1], serial_type);
70649  if( serial_type<12 ){
70650    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
70651  }else if( !(serial_type & 0x01) ){
70652    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
70653  }else{
70654    int nCmp;
70655    int nStr;
70656    int szHdr = aKey1[0];
70657
70658    nStr = (serial_type-12) / 2;
70659    if( (szHdr + nStr) > nKey1 ){
70660      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70661      return 0;    /* Corruption */
70662    }
70663    nCmp = MIN( pPKey2->aMem[0].n, nStr );
70664    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
70665
70666    if( res==0 ){
70667      res = nStr - pPKey2->aMem[0].n;
70668      if( res==0 ){
70669        if( pPKey2->nField>1 ){
70670          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
70671        }else{
70672          res = pPKey2->default_rc;
70673        }
70674      }else if( res>0 ){
70675        res = pPKey2->r2;
70676      }else{
70677        res = pPKey2->r1;
70678      }
70679    }else if( res>0 ){
70680      res = pPKey2->r2;
70681    }else{
70682      res = pPKey2->r1;
70683    }
70684  }
70685
70686  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
70687       || CORRUPT_DB
70688       || pPKey2->pKeyInfo->db->mallocFailed
70689  );
70690  return res;
70691}
70692
70693/*
70694** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
70695** suitable for comparing serialized records to the unpacked record passed
70696** as the only argument.
70697*/
70698SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
70699  /* varintRecordCompareInt() and varintRecordCompareString() both assume
70700  ** that the size-of-header varint that occurs at the start of each record
70701  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
70702  ** also assumes that it is safe to overread a buffer by at least the
70703  ** maximum possible legal header size plus 8 bytes. Because there is
70704  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
70705  ** buffer passed to varintRecordCompareInt() this makes it convenient to
70706  ** limit the size of the header to 64 bytes in cases where the first field
70707  ** is an integer.
70708  **
70709  ** The easiest way to enforce this limit is to consider only records with
70710  ** 13 fields or less. If the first field is an integer, the maximum legal
70711  ** header size is (12*5 + 1 + 1) bytes.  */
70712  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
70713    int flags = p->aMem[0].flags;
70714    if( p->pKeyInfo->aSortOrder[0] ){
70715      p->r1 = 1;
70716      p->r2 = -1;
70717    }else{
70718      p->r1 = -1;
70719      p->r2 = 1;
70720    }
70721    if( (flags & MEM_Int) ){
70722      return vdbeRecordCompareInt;
70723    }
70724    testcase( flags & MEM_Real );
70725    testcase( flags & MEM_Null );
70726    testcase( flags & MEM_Blob );
70727    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
70728      assert( flags & MEM_Str );
70729      return vdbeRecordCompareString;
70730    }
70731  }
70732
70733  return sqlite3VdbeRecordCompare;
70734}
70735
70736/*
70737** pCur points at an index entry created using the OP_MakeRecord opcode.
70738** Read the rowid (the last field in the record) and store it in *rowid.
70739** Return SQLITE_OK if everything works, or an error code otherwise.
70740**
70741** pCur might be pointing to text obtained from a corrupt database file.
70742** So the content cannot be trusted.  Do appropriate checks on the content.
70743*/
70744SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
70745  i64 nCellKey = 0;
70746  int rc;
70747  u32 szHdr;        /* Size of the header */
70748  u32 typeRowid;    /* Serial type of the rowid */
70749  u32 lenRowid;     /* Size of the rowid */
70750  Mem m, v;
70751
70752  /* Get the size of the index entry.  Only indices entries of less
70753  ** than 2GiB are support - anything large must be database corruption.
70754  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
70755  ** this code can safely assume that nCellKey is 32-bits
70756  */
70757  assert( sqlite3BtreeCursorIsValid(pCur) );
70758  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
70759  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
70760  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
70761
70762  /* Read in the complete content of the index entry */
70763  sqlite3VdbeMemInit(&m, db, 0);
70764  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
70765  if( rc ){
70766    return rc;
70767  }
70768
70769  /* The index entry must begin with a header size */
70770  (void)getVarint32((u8*)m.z, szHdr);
70771  testcase( szHdr==3 );
70772  testcase( szHdr==m.n );
70773  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
70774    goto idx_rowid_corruption;
70775  }
70776
70777  /* The last field of the index should be an integer - the ROWID.
70778  ** Verify that the last entry really is an integer. */
70779  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
70780  testcase( typeRowid==1 );
70781  testcase( typeRowid==2 );
70782  testcase( typeRowid==3 );
70783  testcase( typeRowid==4 );
70784  testcase( typeRowid==5 );
70785  testcase( typeRowid==6 );
70786  testcase( typeRowid==8 );
70787  testcase( typeRowid==9 );
70788  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
70789    goto idx_rowid_corruption;
70790  }
70791  lenRowid = sqlite3SmallTypeSizes[typeRowid];
70792  testcase( (u32)m.n==szHdr+lenRowid );
70793  if( unlikely((u32)m.n<szHdr+lenRowid) ){
70794    goto idx_rowid_corruption;
70795  }
70796
70797  /* Fetch the integer off the end of the index record */
70798  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
70799  *rowid = v.u.i;
70800  sqlite3VdbeMemRelease(&m);
70801  return SQLITE_OK;
70802
70803  /* Jump here if database corruption is detected after m has been
70804  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
70805idx_rowid_corruption:
70806  testcase( m.szMalloc!=0 );
70807  sqlite3VdbeMemRelease(&m);
70808  return SQLITE_CORRUPT_BKPT;
70809}
70810
70811/*
70812** Compare the key of the index entry that cursor pC is pointing to against
70813** the key string in pUnpacked.  Write into *pRes a number
70814** that is negative, zero, or positive if pC is less than, equal to,
70815** or greater than pUnpacked.  Return SQLITE_OK on success.
70816**
70817** pUnpacked is either created without a rowid or is truncated so that it
70818** omits the rowid at the end.  The rowid at the end of the index entry
70819** is ignored as well.  Hence, this routine only compares the prefixes
70820** of the keys prior to the final rowid, not the entire key.
70821*/
70822SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
70823  sqlite3 *db,                     /* Database connection */
70824  VdbeCursor *pC,                  /* The cursor to compare against */
70825  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
70826  int *res                         /* Write the comparison result here */
70827){
70828  i64 nCellKey = 0;
70829  int rc;
70830  BtCursor *pCur = pC->pCursor;
70831  Mem m;
70832
70833  assert( sqlite3BtreeCursorIsValid(pCur) );
70834  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
70835  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
70836  /* nCellKey will always be between 0 and 0xffffffff because of the way
70837  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
70838  if( nCellKey<=0 || nCellKey>0x7fffffff ){
70839    *res = 0;
70840    return SQLITE_CORRUPT_BKPT;
70841  }
70842  sqlite3VdbeMemInit(&m, db, 0);
70843  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
70844  if( rc ){
70845    return rc;
70846  }
70847  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
70848  sqlite3VdbeMemRelease(&m);
70849  return SQLITE_OK;
70850}
70851
70852/*
70853** This routine sets the value to be returned by subsequent calls to
70854** sqlite3_changes() on the database handle 'db'.
70855*/
70856SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
70857  assert( sqlite3_mutex_held(db->mutex) );
70858  db->nChange = nChange;
70859  db->nTotalChange += nChange;
70860}
70861
70862/*
70863** Set a flag in the vdbe to update the change counter when it is finalised
70864** or reset.
70865*/
70866SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
70867  v->changeCntOn = 1;
70868}
70869
70870/*
70871** Mark every prepared statement associated with a database connection
70872** as expired.
70873**
70874** An expired statement means that recompilation of the statement is
70875** recommend.  Statements expire when things happen that make their
70876** programs obsolete.  Removing user-defined functions or collating
70877** sequences, or changing an authorization function are the types of
70878** things that make prepared statements obsolete.
70879*/
70880SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
70881  Vdbe *p;
70882  for(p = db->pVdbe; p; p=p->pNext){
70883    p->expired = 1;
70884  }
70885}
70886
70887/*
70888** Return the database associated with the Vdbe.
70889*/
70890SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
70891  return v->db;
70892}
70893
70894/*
70895** Return a pointer to an sqlite3_value structure containing the value bound
70896** parameter iVar of VM v. Except, if the value is an SQL NULL, return
70897** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
70898** constants) to the value before returning it.
70899**
70900** The returned value must be freed by the caller using sqlite3ValueFree().
70901*/
70902SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
70903  assert( iVar>0 );
70904  if( v ){
70905    Mem *pMem = &v->aVar[iVar-1];
70906    if( 0==(pMem->flags & MEM_Null) ){
70907      sqlite3_value *pRet = sqlite3ValueNew(v->db);
70908      if( pRet ){
70909        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
70910        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
70911      }
70912      return pRet;
70913    }
70914  }
70915  return 0;
70916}
70917
70918/*
70919** Configure SQL variable iVar so that binding a new value to it signals
70920** to sqlite3_reoptimize() that re-preparing the statement may result
70921** in a better query plan.
70922*/
70923SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
70924  assert( iVar>0 );
70925  if( iVar>32 ){
70926    v->expmask = 0xffffffff;
70927  }else{
70928    v->expmask |= ((u32)1 << (iVar-1));
70929  }
70930}
70931
70932#ifndef SQLITE_OMIT_VIRTUALTABLE
70933/*
70934** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
70935** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
70936** in memory obtained from sqlite3DbMalloc).
70937*/
70938SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
70939  sqlite3 *db = p->db;
70940  sqlite3DbFree(db, p->zErrMsg);
70941  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
70942  sqlite3_free(pVtab->zErrMsg);
70943  pVtab->zErrMsg = 0;
70944}
70945#endif /* SQLITE_OMIT_VIRTUALTABLE */
70946
70947/************** End of vdbeaux.c *********************************************/
70948/************** Begin file vdbeapi.c *****************************************/
70949/*
70950** 2004 May 26
70951**
70952** The author disclaims copyright to this source code.  In place of
70953** a legal notice, here is a blessing:
70954**
70955**    May you do good and not evil.
70956**    May you find forgiveness for yourself and forgive others.
70957**    May you share freely, never taking more than you give.
70958**
70959*************************************************************************
70960**
70961** This file contains code use to implement APIs that are part of the
70962** VDBE.
70963*/
70964/* #include "sqliteInt.h" */
70965/* #include "vdbeInt.h" */
70966
70967#ifndef SQLITE_OMIT_DEPRECATED
70968/*
70969** Return TRUE (non-zero) of the statement supplied as an argument needs
70970** to be recompiled.  A statement needs to be recompiled whenever the
70971** execution environment changes in a way that would alter the program
70972** that sqlite3_prepare() generates.  For example, if new functions or
70973** collating sequences are registered or if an authorizer function is
70974** added or changed.
70975*/
70976SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
70977  Vdbe *p = (Vdbe*)pStmt;
70978  return p==0 || p->expired;
70979}
70980#endif
70981
70982/*
70983** Check on a Vdbe to make sure it has not been finalized.  Log
70984** an error and return true if it has been finalized (or is otherwise
70985** invalid).  Return false if it is ok.
70986*/
70987static int vdbeSafety(Vdbe *p){
70988  if( p->db==0 ){
70989    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
70990    return 1;
70991  }else{
70992    return 0;
70993  }
70994}
70995static int vdbeSafetyNotNull(Vdbe *p){
70996  if( p==0 ){
70997    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
70998    return 1;
70999  }else{
71000    return vdbeSafety(p);
71001  }
71002}
71003
71004#ifndef SQLITE_OMIT_TRACE
71005/*
71006** Invoke the profile callback.  This routine is only called if we already
71007** know that the profile callback is defined and needs to be invoked.
71008*/
71009static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
71010  sqlite3_int64 iNow;
71011  assert( p->startTime>0 );
71012  assert( db->xProfile!=0 );
71013  assert( db->init.busy==0 );
71014  assert( p->zSql!=0 );
71015  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
71016  db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
71017  p->startTime = 0;
71018}
71019/*
71020** The checkProfileCallback(DB,P) macro checks to see if a profile callback
71021** is needed, and it invokes the callback if it is needed.
71022*/
71023# define checkProfileCallback(DB,P) \
71024   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
71025#else
71026# define checkProfileCallback(DB,P)  /*no-op*/
71027#endif
71028
71029/*
71030** The following routine destroys a virtual machine that is created by
71031** the sqlite3_compile() routine. The integer returned is an SQLITE_
71032** success/failure code that describes the result of executing the virtual
71033** machine.
71034**
71035** This routine sets the error code and string returned by
71036** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
71037*/
71038SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
71039  int rc;
71040  if( pStmt==0 ){
71041    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
71042    ** pointer is a harmless no-op. */
71043    rc = SQLITE_OK;
71044  }else{
71045    Vdbe *v = (Vdbe*)pStmt;
71046    sqlite3 *db = v->db;
71047    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
71048    sqlite3_mutex_enter(db->mutex);
71049    checkProfileCallback(db, v);
71050    rc = sqlite3VdbeFinalize(v);
71051    rc = sqlite3ApiExit(db, rc);
71052    sqlite3LeaveMutexAndCloseZombie(db);
71053  }
71054  return rc;
71055}
71056
71057/*
71058** Terminate the current execution of an SQL statement and reset it
71059** back to its starting state so that it can be reused. A success code from
71060** the prior execution is returned.
71061**
71062** This routine sets the error code and string returned by
71063** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
71064*/
71065SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
71066  int rc;
71067  if( pStmt==0 ){
71068    rc = SQLITE_OK;
71069  }else{
71070    Vdbe *v = (Vdbe*)pStmt;
71071    sqlite3 *db = v->db;
71072    sqlite3_mutex_enter(db->mutex);
71073    checkProfileCallback(db, v);
71074    rc = sqlite3VdbeReset(v);
71075    sqlite3VdbeRewind(v);
71076    assert( (rc & (db->errMask))==rc );
71077    rc = sqlite3ApiExit(db, rc);
71078    sqlite3_mutex_leave(db->mutex);
71079  }
71080  return rc;
71081}
71082
71083/*
71084** Set all the parameters in the compiled SQL statement to NULL.
71085*/
71086SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
71087  int i;
71088  int rc = SQLITE_OK;
71089  Vdbe *p = (Vdbe*)pStmt;
71090#if SQLITE_THREADSAFE
71091  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
71092#endif
71093  sqlite3_mutex_enter(mutex);
71094  for(i=0; i<p->nVar; i++){
71095    sqlite3VdbeMemRelease(&p->aVar[i]);
71096    p->aVar[i].flags = MEM_Null;
71097  }
71098  if( p->isPrepareV2 && p->expmask ){
71099    p->expired = 1;
71100  }
71101  sqlite3_mutex_leave(mutex);
71102  return rc;
71103}
71104
71105
71106/**************************** sqlite3_value_  *******************************
71107** The following routines extract information from a Mem or sqlite3_value
71108** structure.
71109*/
71110SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
71111  Mem *p = (Mem*)pVal;
71112  if( p->flags & (MEM_Blob|MEM_Str) ){
71113    if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
71114      assert( p->flags==MEM_Null && p->z==0 );
71115      return 0;
71116    }
71117    p->flags |= MEM_Blob;
71118    return p->n ? p->z : 0;
71119  }else{
71120    return sqlite3_value_text(pVal);
71121  }
71122}
71123SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
71124  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
71125}
71126SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
71127  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
71128}
71129SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
71130  return sqlite3VdbeRealValue((Mem*)pVal);
71131}
71132SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
71133  return (int)sqlite3VdbeIntValue((Mem*)pVal);
71134}
71135SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
71136  return sqlite3VdbeIntValue((Mem*)pVal);
71137}
71138SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
71139  return ((Mem*)pVal)->eSubtype;
71140}
71141SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
71142  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
71143}
71144#ifndef SQLITE_OMIT_UTF16
71145SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
71146  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
71147}
71148SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
71149  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
71150}
71151SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
71152  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
71153}
71154#endif /* SQLITE_OMIT_UTF16 */
71155/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
71156** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
71157** point number string BLOB NULL
71158*/
71159SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
71160  static const u8 aType[] = {
71161     SQLITE_BLOB,     /* 0x00 */
71162     SQLITE_NULL,     /* 0x01 */
71163     SQLITE_TEXT,     /* 0x02 */
71164     SQLITE_NULL,     /* 0x03 */
71165     SQLITE_INTEGER,  /* 0x04 */
71166     SQLITE_NULL,     /* 0x05 */
71167     SQLITE_INTEGER,  /* 0x06 */
71168     SQLITE_NULL,     /* 0x07 */
71169     SQLITE_FLOAT,    /* 0x08 */
71170     SQLITE_NULL,     /* 0x09 */
71171     SQLITE_FLOAT,    /* 0x0a */
71172     SQLITE_NULL,     /* 0x0b */
71173     SQLITE_INTEGER,  /* 0x0c */
71174     SQLITE_NULL,     /* 0x0d */
71175     SQLITE_INTEGER,  /* 0x0e */
71176     SQLITE_NULL,     /* 0x0f */
71177     SQLITE_BLOB,     /* 0x10 */
71178     SQLITE_NULL,     /* 0x11 */
71179     SQLITE_TEXT,     /* 0x12 */
71180     SQLITE_NULL,     /* 0x13 */
71181     SQLITE_INTEGER,  /* 0x14 */
71182     SQLITE_NULL,     /* 0x15 */
71183     SQLITE_INTEGER,  /* 0x16 */
71184     SQLITE_NULL,     /* 0x17 */
71185     SQLITE_FLOAT,    /* 0x18 */
71186     SQLITE_NULL,     /* 0x19 */
71187     SQLITE_FLOAT,    /* 0x1a */
71188     SQLITE_NULL,     /* 0x1b */
71189     SQLITE_INTEGER,  /* 0x1c */
71190     SQLITE_NULL,     /* 0x1d */
71191     SQLITE_INTEGER,  /* 0x1e */
71192     SQLITE_NULL,     /* 0x1f */
71193  };
71194  return aType[pVal->flags&MEM_AffMask];
71195}
71196
71197/* Make a copy of an sqlite3_value object
71198*/
71199SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
71200  sqlite3_value *pNew;
71201  if( pOrig==0 ) return 0;
71202  pNew = sqlite3_malloc( sizeof(*pNew) );
71203  if( pNew==0 ) return 0;
71204  memset(pNew, 0, sizeof(*pNew));
71205  memcpy(pNew, pOrig, MEMCELLSIZE);
71206  pNew->flags &= ~MEM_Dyn;
71207  pNew->db = 0;
71208  if( pNew->flags&(MEM_Str|MEM_Blob) ){
71209    pNew->flags &= ~(MEM_Static|MEM_Dyn);
71210    pNew->flags |= MEM_Ephem;
71211    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
71212      sqlite3ValueFree(pNew);
71213      pNew = 0;
71214    }
71215  }
71216  return pNew;
71217}
71218
71219/* Destroy an sqlite3_value object previously obtained from
71220** sqlite3_value_dup().
71221*/
71222SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
71223  sqlite3ValueFree(pOld);
71224}
71225
71226
71227/**************************** sqlite3_result_  *******************************
71228** The following routines are used by user-defined functions to specify
71229** the function result.
71230**
71231** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
71232** result as a string or blob but if the string or blob is too large, it
71233** then sets the error code to SQLITE_TOOBIG
71234**
71235** The invokeValueDestructor(P,X) routine invokes destructor function X()
71236** on value P is not going to be used and need to be destroyed.
71237*/
71238static void setResultStrOrError(
71239  sqlite3_context *pCtx,  /* Function context */
71240  const char *z,          /* String pointer */
71241  int n,                  /* Bytes in string, or negative */
71242  u8 enc,                 /* Encoding of z.  0 for BLOBs */
71243  void (*xDel)(void*)     /* Destructor function */
71244){
71245  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
71246    sqlite3_result_error_toobig(pCtx);
71247  }
71248}
71249static int invokeValueDestructor(
71250  const void *p,             /* Value to destroy */
71251  void (*xDel)(void*),       /* The destructor */
71252  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
71253){
71254  assert( xDel!=SQLITE_DYNAMIC );
71255  if( xDel==0 ){
71256    /* noop */
71257  }else if( xDel==SQLITE_TRANSIENT ){
71258    /* noop */
71259  }else{
71260    xDel((void*)p);
71261  }
71262  if( pCtx ) sqlite3_result_error_toobig(pCtx);
71263  return SQLITE_TOOBIG;
71264}
71265SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
71266  sqlite3_context *pCtx,
71267  const void *z,
71268  int n,
71269  void (*xDel)(void *)
71270){
71271  assert( n>=0 );
71272  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71273  setResultStrOrError(pCtx, z, n, 0, xDel);
71274}
71275SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
71276  sqlite3_context *pCtx,
71277  const void *z,
71278  sqlite3_uint64 n,
71279  void (*xDel)(void *)
71280){
71281  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71282  assert( xDel!=SQLITE_DYNAMIC );
71283  if( n>0x7fffffff ){
71284    (void)invokeValueDestructor(z, xDel, pCtx);
71285  }else{
71286    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
71287  }
71288}
71289SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
71290  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71291  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
71292}
71293SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
71294  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71295  pCtx->isError = SQLITE_ERROR;
71296  pCtx->fErrorOrAux = 1;
71297  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
71298}
71299#ifndef SQLITE_OMIT_UTF16
71300SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
71301  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71302  pCtx->isError = SQLITE_ERROR;
71303  pCtx->fErrorOrAux = 1;
71304  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
71305}
71306#endif
71307SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
71308  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71309  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
71310}
71311SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
71312  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71313  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
71314}
71315SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
71316  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71317  sqlite3VdbeMemSetNull(pCtx->pOut);
71318}
71319SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
71320  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71321  pCtx->pOut->eSubtype = eSubtype & 0xff;
71322}
71323SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
71324  sqlite3_context *pCtx,
71325  const char *z,
71326  int n,
71327  void (*xDel)(void *)
71328){
71329  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71330  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
71331}
71332SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
71333  sqlite3_context *pCtx,
71334  const char *z,
71335  sqlite3_uint64 n,
71336  void (*xDel)(void *),
71337  unsigned char enc
71338){
71339  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71340  assert( xDel!=SQLITE_DYNAMIC );
71341  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
71342  if( n>0x7fffffff ){
71343    (void)invokeValueDestructor(z, xDel, pCtx);
71344  }else{
71345    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
71346  }
71347}
71348#ifndef SQLITE_OMIT_UTF16
71349SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
71350  sqlite3_context *pCtx,
71351  const void *z,
71352  int n,
71353  void (*xDel)(void *)
71354){
71355  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71356  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
71357}
71358SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
71359  sqlite3_context *pCtx,
71360  const void *z,
71361  int n,
71362  void (*xDel)(void *)
71363){
71364  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71365  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
71366}
71367SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
71368  sqlite3_context *pCtx,
71369  const void *z,
71370  int n,
71371  void (*xDel)(void *)
71372){
71373  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71374  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
71375}
71376#endif /* SQLITE_OMIT_UTF16 */
71377SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
71378  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71379  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
71380}
71381SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
71382  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71383  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
71384}
71385SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
71386  Mem *pOut = pCtx->pOut;
71387  assert( sqlite3_mutex_held(pOut->db->mutex) );
71388  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
71389    return SQLITE_TOOBIG;
71390  }
71391  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
71392  return SQLITE_OK;
71393}
71394SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
71395  pCtx->isError = errCode;
71396  pCtx->fErrorOrAux = 1;
71397#ifdef SQLITE_DEBUG
71398  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
71399#endif
71400  if( pCtx->pOut->flags & MEM_Null ){
71401    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
71402                         SQLITE_UTF8, SQLITE_STATIC);
71403  }
71404}
71405
71406/* Force an SQLITE_TOOBIG error. */
71407SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
71408  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71409  pCtx->isError = SQLITE_TOOBIG;
71410  pCtx->fErrorOrAux = 1;
71411  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
71412                       SQLITE_UTF8, SQLITE_STATIC);
71413}
71414
71415/* An SQLITE_NOMEM error. */
71416SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
71417  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71418  sqlite3VdbeMemSetNull(pCtx->pOut);
71419  pCtx->isError = SQLITE_NOMEM;
71420  pCtx->fErrorOrAux = 1;
71421  pCtx->pOut->db->mallocFailed = 1;
71422}
71423
71424/*
71425** This function is called after a transaction has been committed. It
71426** invokes callbacks registered with sqlite3_wal_hook() as required.
71427*/
71428static int doWalCallbacks(sqlite3 *db){
71429  int rc = SQLITE_OK;
71430#ifndef SQLITE_OMIT_WAL
71431  int i;
71432  for(i=0; i<db->nDb; i++){
71433    Btree *pBt = db->aDb[i].pBt;
71434    if( pBt ){
71435      int nEntry;
71436      sqlite3BtreeEnter(pBt);
71437      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
71438      sqlite3BtreeLeave(pBt);
71439      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
71440        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
71441      }
71442    }
71443  }
71444#endif
71445  return rc;
71446}
71447
71448
71449/*
71450** Execute the statement pStmt, either until a row of data is ready, the
71451** statement is completely executed or an error occurs.
71452**
71453** This routine implements the bulk of the logic behind the sqlite_step()
71454** API.  The only thing omitted is the automatic recompile if a
71455** schema change has occurred.  That detail is handled by the
71456** outer sqlite3_step() wrapper procedure.
71457*/
71458static int sqlite3Step(Vdbe *p){
71459  sqlite3 *db;
71460  int rc;
71461
71462  assert(p);
71463  if( p->magic!=VDBE_MAGIC_RUN ){
71464    /* We used to require that sqlite3_reset() be called before retrying
71465    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
71466    ** with version 3.7.0, we changed this so that sqlite3_reset() would
71467    ** be called automatically instead of throwing the SQLITE_MISUSE error.
71468    ** This "automatic-reset" change is not technically an incompatibility,
71469    ** since any application that receives an SQLITE_MISUSE is broken by
71470    ** definition.
71471    **
71472    ** Nevertheless, some published applications that were originally written
71473    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
71474    ** returns, and those were broken by the automatic-reset change.  As a
71475    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
71476    ** legacy behavior of returning SQLITE_MISUSE for cases where the
71477    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
71478    ** or SQLITE_BUSY error.
71479    */
71480#ifdef SQLITE_OMIT_AUTORESET
71481    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
71482      sqlite3_reset((sqlite3_stmt*)p);
71483    }else{
71484      return SQLITE_MISUSE_BKPT;
71485    }
71486#else
71487    sqlite3_reset((sqlite3_stmt*)p);
71488#endif
71489  }
71490
71491  /* Check that malloc() has not failed. If it has, return early. */
71492  db = p->db;
71493  if( db->mallocFailed ){
71494    p->rc = SQLITE_NOMEM;
71495    return SQLITE_NOMEM;
71496  }
71497
71498  if( p->pc<=0 && p->expired ){
71499    p->rc = SQLITE_SCHEMA;
71500    rc = SQLITE_ERROR;
71501    goto end_of_step;
71502  }
71503  if( p->pc<0 ){
71504    /* If there are no other statements currently running, then
71505    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
71506    ** from interrupting a statement that has not yet started.
71507    */
71508    if( db->nVdbeActive==0 ){
71509      db->u1.isInterrupted = 0;
71510    }
71511
71512    assert( db->nVdbeWrite>0 || db->autoCommit==0
71513        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
71514    );
71515
71516#ifndef SQLITE_OMIT_TRACE
71517    if( db->xProfile && !db->init.busy && p->zSql ){
71518      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
71519    }else{
71520      assert( p->startTime==0 );
71521    }
71522#endif
71523
71524    db->nVdbeActive++;
71525    if( p->readOnly==0 ) db->nVdbeWrite++;
71526    if( p->bIsReader ) db->nVdbeRead++;
71527    p->pc = 0;
71528  }
71529#ifdef SQLITE_DEBUG
71530  p->rcApp = SQLITE_OK;
71531#endif
71532#ifndef SQLITE_OMIT_EXPLAIN
71533  if( p->explain ){
71534    rc = sqlite3VdbeList(p);
71535  }else
71536#endif /* SQLITE_OMIT_EXPLAIN */
71537  {
71538    db->nVdbeExec++;
71539    rc = sqlite3VdbeExec(p);
71540    db->nVdbeExec--;
71541  }
71542
71543#ifndef SQLITE_OMIT_TRACE
71544  /* If the statement completed successfully, invoke the profile callback */
71545  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
71546#endif
71547
71548  if( rc==SQLITE_DONE ){
71549    assert( p->rc==SQLITE_OK );
71550    p->rc = doWalCallbacks(db);
71551    if( p->rc!=SQLITE_OK ){
71552      rc = SQLITE_ERROR;
71553    }
71554  }
71555
71556  db->errCode = rc;
71557  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
71558    p->rc = SQLITE_NOMEM;
71559  }
71560end_of_step:
71561  /* At this point local variable rc holds the value that should be
71562  ** returned if this statement was compiled using the legacy
71563  ** sqlite3_prepare() interface. According to the docs, this can only
71564  ** be one of the values in the first assert() below. Variable p->rc
71565  ** contains the value that would be returned if sqlite3_finalize()
71566  ** were called on statement p.
71567  */
71568  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
71569       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
71570  );
71571  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
71572  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
71573    /* If this statement was prepared using sqlite3_prepare_v2(), and an
71574    ** error has occurred, then return the error code in p->rc to the
71575    ** caller. Set the error code in the database handle to the same value.
71576    */
71577    rc = sqlite3VdbeTransferError(p);
71578  }
71579  return (rc&db->errMask);
71580}
71581
71582/*
71583** This is the top-level implementation of sqlite3_step().  Call
71584** sqlite3Step() to do most of the work.  If a schema error occurs,
71585** call sqlite3Reprepare() and try again.
71586*/
71587SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
71588  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
71589  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
71590  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
71591  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
71592  sqlite3 *db;             /* The database connection */
71593
71594  if( vdbeSafetyNotNull(v) ){
71595    return SQLITE_MISUSE_BKPT;
71596  }
71597  db = v->db;
71598  sqlite3_mutex_enter(db->mutex);
71599  v->doingRerun = 0;
71600  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
71601         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
71602    int savedPc = v->pc;
71603    rc2 = rc = sqlite3Reprepare(v);
71604    if( rc!=SQLITE_OK) break;
71605    sqlite3_reset(pStmt);
71606    if( savedPc>=0 ) v->doingRerun = 1;
71607    assert( v->expired==0 );
71608  }
71609  if( rc2!=SQLITE_OK ){
71610    /* This case occurs after failing to recompile an sql statement.
71611    ** The error message from the SQL compiler has already been loaded
71612    ** into the database handle. This block copies the error message
71613    ** from the database handle into the statement and sets the statement
71614    ** program counter to 0 to ensure that when the statement is
71615    ** finalized or reset the parser error message is available via
71616    ** sqlite3_errmsg() and sqlite3_errcode().
71617    */
71618    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
71619    sqlite3DbFree(db, v->zErrMsg);
71620    if( !db->mallocFailed ){
71621      v->zErrMsg = sqlite3DbStrDup(db, zErr);
71622      v->rc = rc2;
71623    } else {
71624      v->zErrMsg = 0;
71625      v->rc = rc = SQLITE_NOMEM;
71626    }
71627  }
71628  rc = sqlite3ApiExit(db, rc);
71629  sqlite3_mutex_leave(db->mutex);
71630  return rc;
71631}
71632
71633
71634/*
71635** Extract the user data from a sqlite3_context structure and return a
71636** pointer to it.
71637*/
71638SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
71639  assert( p && p->pFunc );
71640  return p->pFunc->pUserData;
71641}
71642
71643/*
71644** Extract the user data from a sqlite3_context structure and return a
71645** pointer to it.
71646**
71647** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
71648** returns a copy of the pointer to the database connection (the 1st
71649** parameter) of the sqlite3_create_function() and
71650** sqlite3_create_function16() routines that originally registered the
71651** application defined function.
71652*/
71653SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
71654  assert( p && p->pOut );
71655  return p->pOut->db;
71656}
71657
71658/*
71659** Return the current time for a statement.  If the current time
71660** is requested more than once within the same run of a single prepared
71661** statement, the exact same time is returned for each invocation regardless
71662** of the amount of time that elapses between invocations.  In other words,
71663** the time returned is always the time of the first call.
71664*/
71665SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
71666  int rc;
71667#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
71668  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
71669  assert( p->pVdbe!=0 );
71670#else
71671  sqlite3_int64 iTime = 0;
71672  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
71673#endif
71674  if( *piTime==0 ){
71675    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
71676    if( rc ) *piTime = 0;
71677  }
71678  return *piTime;
71679}
71680
71681/*
71682** The following is the implementation of an SQL function that always
71683** fails with an error message stating that the function is used in the
71684** wrong context.  The sqlite3_overload_function() API might construct
71685** SQL function that use this routine so that the functions will exist
71686** for name resolution but are actually overloaded by the xFindFunction
71687** method of virtual tables.
71688*/
71689SQLITE_PRIVATE void sqlite3InvalidFunction(
71690  sqlite3_context *context,  /* The function calling context */
71691  int NotUsed,               /* Number of arguments to the function */
71692  sqlite3_value **NotUsed2   /* Value of each argument */
71693){
71694  const char *zName = context->pFunc->zName;
71695  char *zErr;
71696  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71697  zErr = sqlite3_mprintf(
71698      "unable to use function %s in the requested context", zName);
71699  sqlite3_result_error(context, zErr, -1);
71700  sqlite3_free(zErr);
71701}
71702
71703/*
71704** Create a new aggregate context for p and return a pointer to
71705** its pMem->z element.
71706*/
71707static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
71708  Mem *pMem = p->pMem;
71709  assert( (pMem->flags & MEM_Agg)==0 );
71710  if( nByte<=0 ){
71711    sqlite3VdbeMemSetNull(pMem);
71712    pMem->z = 0;
71713  }else{
71714    sqlite3VdbeMemClearAndResize(pMem, nByte);
71715    pMem->flags = MEM_Agg;
71716    pMem->u.pDef = p->pFunc;
71717    if( pMem->z ){
71718      memset(pMem->z, 0, nByte);
71719    }
71720  }
71721  return (void*)pMem->z;
71722}
71723
71724/*
71725** Allocate or return the aggregate context for a user function.  A new
71726** context is allocated on the first call.  Subsequent calls return the
71727** same context that was returned on prior calls.
71728*/
71729SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
71730  assert( p && p->pFunc && p->pFunc->xStep );
71731  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
71732  testcase( nByte<0 );
71733  if( (p->pMem->flags & MEM_Agg)==0 ){
71734    return createAggContext(p, nByte);
71735  }else{
71736    return (void*)p->pMem->z;
71737  }
71738}
71739
71740/*
71741** Return the auxiliary data pointer, if any, for the iArg'th argument to
71742** the user-function defined by pCtx.
71743*/
71744SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
71745  AuxData *pAuxData;
71746
71747  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71748#if SQLITE_ENABLE_STAT3_OR_STAT4
71749  if( pCtx->pVdbe==0 ) return 0;
71750#else
71751  assert( pCtx->pVdbe!=0 );
71752#endif
71753  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
71754    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
71755  }
71756
71757  return (pAuxData ? pAuxData->pAux : 0);
71758}
71759
71760/*
71761** Set the auxiliary data pointer and delete function, for the iArg'th
71762** argument to the user-function defined by pCtx. Any previous value is
71763** deleted by calling the delete function specified when it was set.
71764*/
71765SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
71766  sqlite3_context *pCtx,
71767  int iArg,
71768  void *pAux,
71769  void (*xDelete)(void*)
71770){
71771  AuxData *pAuxData;
71772  Vdbe *pVdbe = pCtx->pVdbe;
71773
71774  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71775  if( iArg<0 ) goto failed;
71776#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71777  if( pVdbe==0 ) goto failed;
71778#else
71779  assert( pVdbe!=0 );
71780#endif
71781
71782  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
71783    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
71784  }
71785  if( pAuxData==0 ){
71786    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
71787    if( !pAuxData ) goto failed;
71788    pAuxData->iOp = pCtx->iOp;
71789    pAuxData->iArg = iArg;
71790    pAuxData->pNext = pVdbe->pAuxData;
71791    pVdbe->pAuxData = pAuxData;
71792    if( pCtx->fErrorOrAux==0 ){
71793      pCtx->isError = 0;
71794      pCtx->fErrorOrAux = 1;
71795    }
71796  }else if( pAuxData->xDelete ){
71797    pAuxData->xDelete(pAuxData->pAux);
71798  }
71799
71800  pAuxData->pAux = pAux;
71801  pAuxData->xDelete = xDelete;
71802  return;
71803
71804failed:
71805  if( xDelete ){
71806    xDelete(pAux);
71807  }
71808}
71809
71810#ifndef SQLITE_OMIT_DEPRECATED
71811/*
71812** Return the number of times the Step function of an aggregate has been
71813** called.
71814**
71815** This function is deprecated.  Do not use it for new code.  It is
71816** provide only to avoid breaking legacy code.  New aggregate function
71817** implementations should keep their own counts within their aggregate
71818** context.
71819*/
71820SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
71821  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
71822  return p->pMem->n;
71823}
71824#endif
71825
71826/*
71827** Return the number of columns in the result set for the statement pStmt.
71828*/
71829SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
71830  Vdbe *pVm = (Vdbe *)pStmt;
71831  return pVm ? pVm->nResColumn : 0;
71832}
71833
71834/*
71835** Return the number of values available from the current row of the
71836** currently executing statement pStmt.
71837*/
71838SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
71839  Vdbe *pVm = (Vdbe *)pStmt;
71840  if( pVm==0 || pVm->pResultSet==0 ) return 0;
71841  return pVm->nResColumn;
71842}
71843
71844/*
71845** Return a pointer to static memory containing an SQL NULL value.
71846*/
71847static const Mem *columnNullValue(void){
71848  /* Even though the Mem structure contains an element
71849  ** of type i64, on certain architectures (x86) with certain compiler
71850  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
71851  ** instead of an 8-byte one. This all works fine, except that when
71852  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
71853  ** that a Mem structure is located on an 8-byte boundary. To prevent
71854  ** these assert()s from failing, when building with SQLITE_DEBUG defined
71855  ** using gcc, we force nullMem to be 8-byte aligned using the magical
71856  ** __attribute__((aligned(8))) macro.  */
71857  static const Mem nullMem
71858#if defined(SQLITE_DEBUG) && defined(__GNUC__)
71859    __attribute__((aligned(8)))
71860#endif
71861    = {
71862        /* .u          = */ {0},
71863        /* .flags      = */ (u16)MEM_Null,
71864        /* .enc        = */ (u8)0,
71865        /* .eSubtype   = */ (u8)0,
71866        /* .n          = */ (int)0,
71867        /* .z          = */ (char*)0,
71868        /* .zMalloc    = */ (char*)0,
71869        /* .szMalloc   = */ (int)0,
71870        /* .uTemp      = */ (u32)0,
71871        /* .db         = */ (sqlite3*)0,
71872        /* .xDel       = */ (void(*)(void*))0,
71873#ifdef SQLITE_DEBUG
71874        /* .pScopyFrom = */ (Mem*)0,
71875        /* .pFiller    = */ (void*)0,
71876#endif
71877      };
71878  return &nullMem;
71879}
71880
71881/*
71882** Check to see if column iCol of the given statement is valid.  If
71883** it is, return a pointer to the Mem for the value of that column.
71884** If iCol is not valid, return a pointer to a Mem which has a value
71885** of NULL.
71886*/
71887static Mem *columnMem(sqlite3_stmt *pStmt, int i){
71888  Vdbe *pVm;
71889  Mem *pOut;
71890
71891  pVm = (Vdbe *)pStmt;
71892  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
71893    sqlite3_mutex_enter(pVm->db->mutex);
71894    pOut = &pVm->pResultSet[i];
71895  }else{
71896    if( pVm && ALWAYS(pVm->db) ){
71897      sqlite3_mutex_enter(pVm->db->mutex);
71898      sqlite3Error(pVm->db, SQLITE_RANGE);
71899    }
71900    pOut = (Mem*)columnNullValue();
71901  }
71902  return pOut;
71903}
71904
71905/*
71906** This function is called after invoking an sqlite3_value_XXX function on a
71907** column value (i.e. a value returned by evaluating an SQL expression in the
71908** select list of a SELECT statement) that may cause a malloc() failure. If
71909** malloc() has failed, the threads mallocFailed flag is cleared and the result
71910** code of statement pStmt set to SQLITE_NOMEM.
71911**
71912** Specifically, this is called from within:
71913**
71914**     sqlite3_column_int()
71915**     sqlite3_column_int64()
71916**     sqlite3_column_text()
71917**     sqlite3_column_text16()
71918**     sqlite3_column_real()
71919**     sqlite3_column_bytes()
71920**     sqlite3_column_bytes16()
71921**     sqiite3_column_blob()
71922*/
71923static void columnMallocFailure(sqlite3_stmt *pStmt)
71924{
71925  /* If malloc() failed during an encoding conversion within an
71926  ** sqlite3_column_XXX API, then set the return code of the statement to
71927  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
71928  ** and _finalize() will return NOMEM.
71929  */
71930  Vdbe *p = (Vdbe *)pStmt;
71931  if( p ){
71932    p->rc = sqlite3ApiExit(p->db, p->rc);
71933    sqlite3_mutex_leave(p->db->mutex);
71934  }
71935}
71936
71937/**************************** sqlite3_column_  *******************************
71938** The following routines are used to access elements of the current row
71939** in the result set.
71940*/
71941SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
71942  const void *val;
71943  val = sqlite3_value_blob( columnMem(pStmt,i) );
71944  /* Even though there is no encoding conversion, value_blob() might
71945  ** need to call malloc() to expand the result of a zeroblob()
71946  ** expression.
71947  */
71948  columnMallocFailure(pStmt);
71949  return val;
71950}
71951SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
71952  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
71953  columnMallocFailure(pStmt);
71954  return val;
71955}
71956SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
71957  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
71958  columnMallocFailure(pStmt);
71959  return val;
71960}
71961SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
71962  double val = sqlite3_value_double( columnMem(pStmt,i) );
71963  columnMallocFailure(pStmt);
71964  return val;
71965}
71966SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
71967  int val = sqlite3_value_int( columnMem(pStmt,i) );
71968  columnMallocFailure(pStmt);
71969  return val;
71970}
71971SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
71972  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
71973  columnMallocFailure(pStmt);
71974  return val;
71975}
71976SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
71977  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
71978  columnMallocFailure(pStmt);
71979  return val;
71980}
71981SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
71982  Mem *pOut = columnMem(pStmt, i);
71983  if( pOut->flags&MEM_Static ){
71984    pOut->flags &= ~MEM_Static;
71985    pOut->flags |= MEM_Ephem;
71986  }
71987  columnMallocFailure(pStmt);
71988  return (sqlite3_value *)pOut;
71989}
71990#ifndef SQLITE_OMIT_UTF16
71991SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
71992  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
71993  columnMallocFailure(pStmt);
71994  return val;
71995}
71996#endif /* SQLITE_OMIT_UTF16 */
71997SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
71998  int iType = sqlite3_value_type( columnMem(pStmt,i) );
71999  columnMallocFailure(pStmt);
72000  return iType;
72001}
72002
72003/*
72004** Convert the N-th element of pStmt->pColName[] into a string using
72005** xFunc() then return that string.  If N is out of range, return 0.
72006**
72007** There are up to 5 names for each column.  useType determines which
72008** name is returned.  Here are the names:
72009**
72010**    0      The column name as it should be displayed for output
72011**    1      The datatype name for the column
72012**    2      The name of the database that the column derives from
72013**    3      The name of the table that the column derives from
72014**    4      The name of the table column that the result column derives from
72015**
72016** If the result is not a simple column reference (if it is an expression
72017** or a constant) then useTypes 2, 3, and 4 return NULL.
72018*/
72019static const void *columnName(
72020  sqlite3_stmt *pStmt,
72021  int N,
72022  const void *(*xFunc)(Mem*),
72023  int useType
72024){
72025  const void *ret;
72026  Vdbe *p;
72027  int n;
72028  sqlite3 *db;
72029#ifdef SQLITE_ENABLE_API_ARMOR
72030  if( pStmt==0 ){
72031    (void)SQLITE_MISUSE_BKPT;
72032    return 0;
72033  }
72034#endif
72035  ret = 0;
72036  p = (Vdbe *)pStmt;
72037  db = p->db;
72038  assert( db!=0 );
72039  n = sqlite3_column_count(pStmt);
72040  if( N<n && N>=0 ){
72041    N += useType*n;
72042    sqlite3_mutex_enter(db->mutex);
72043    assert( db->mallocFailed==0 );
72044    ret = xFunc(&p->aColName[N]);
72045     /* A malloc may have failed inside of the xFunc() call. If this
72046    ** is the case, clear the mallocFailed flag and return NULL.
72047    */
72048    if( db->mallocFailed ){
72049      db->mallocFailed = 0;
72050      ret = 0;
72051    }
72052    sqlite3_mutex_leave(db->mutex);
72053  }
72054  return ret;
72055}
72056
72057/*
72058** Return the name of the Nth column of the result set returned by SQL
72059** statement pStmt.
72060*/
72061SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
72062  return columnName(
72063      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
72064}
72065#ifndef SQLITE_OMIT_UTF16
72066SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
72067  return columnName(
72068      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
72069}
72070#endif
72071
72072/*
72073** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
72074** not define OMIT_DECLTYPE.
72075*/
72076#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
72077# error "Must not define both SQLITE_OMIT_DECLTYPE \
72078         and SQLITE_ENABLE_COLUMN_METADATA"
72079#endif
72080
72081#ifndef SQLITE_OMIT_DECLTYPE
72082/*
72083** Return the column declaration type (if applicable) of the 'i'th column
72084** of the result set of SQL statement pStmt.
72085*/
72086SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
72087  return columnName(
72088      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
72089}
72090#ifndef SQLITE_OMIT_UTF16
72091SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
72092  return columnName(
72093      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
72094}
72095#endif /* SQLITE_OMIT_UTF16 */
72096#endif /* SQLITE_OMIT_DECLTYPE */
72097
72098#ifdef SQLITE_ENABLE_COLUMN_METADATA
72099/*
72100** Return the name of the database from which a result column derives.
72101** NULL is returned if the result column is an expression or constant or
72102** anything else which is not an unambiguous reference to a database column.
72103*/
72104SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
72105  return columnName(
72106      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
72107}
72108#ifndef SQLITE_OMIT_UTF16
72109SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
72110  return columnName(
72111      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
72112}
72113#endif /* SQLITE_OMIT_UTF16 */
72114
72115/*
72116** Return the name of the table from which a result column derives.
72117** NULL is returned if the result column is an expression or constant or
72118** anything else which is not an unambiguous reference to a database column.
72119*/
72120SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
72121  return columnName(
72122      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
72123}
72124#ifndef SQLITE_OMIT_UTF16
72125SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
72126  return columnName(
72127      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
72128}
72129#endif /* SQLITE_OMIT_UTF16 */
72130
72131/*
72132** Return the name of the table column from which a result column derives.
72133** NULL is returned if the result column is an expression or constant or
72134** anything else which is not an unambiguous reference to a database column.
72135*/
72136SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
72137  return columnName(
72138      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
72139}
72140#ifndef SQLITE_OMIT_UTF16
72141SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
72142  return columnName(
72143      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
72144}
72145#endif /* SQLITE_OMIT_UTF16 */
72146#endif /* SQLITE_ENABLE_COLUMN_METADATA */
72147
72148
72149/******************************* sqlite3_bind_  ***************************
72150**
72151** Routines used to attach values to wildcards in a compiled SQL statement.
72152*/
72153/*
72154** Unbind the value bound to variable i in virtual machine p. This is the
72155** the same as binding a NULL value to the column. If the "i" parameter is
72156** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
72157**
72158** A successful evaluation of this routine acquires the mutex on p.
72159** the mutex is released if any kind of error occurs.
72160**
72161** The error code stored in database p->db is overwritten with the return
72162** value in any case.
72163*/
72164static int vdbeUnbind(Vdbe *p, int i){
72165  Mem *pVar;
72166  if( vdbeSafetyNotNull(p) ){
72167    return SQLITE_MISUSE_BKPT;
72168  }
72169  sqlite3_mutex_enter(p->db->mutex);
72170  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
72171    sqlite3Error(p->db, SQLITE_MISUSE);
72172    sqlite3_mutex_leave(p->db->mutex);
72173    sqlite3_log(SQLITE_MISUSE,
72174        "bind on a busy prepared statement: [%s]", p->zSql);
72175    return SQLITE_MISUSE_BKPT;
72176  }
72177  if( i<1 || i>p->nVar ){
72178    sqlite3Error(p->db, SQLITE_RANGE);
72179    sqlite3_mutex_leave(p->db->mutex);
72180    return SQLITE_RANGE;
72181  }
72182  i--;
72183  pVar = &p->aVar[i];
72184  sqlite3VdbeMemRelease(pVar);
72185  pVar->flags = MEM_Null;
72186  sqlite3Error(p->db, SQLITE_OK);
72187
72188  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
72189  ** binding a new value to this variable invalidates the current query plan.
72190  **
72191  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
72192  ** parameter in the WHERE clause might influence the choice of query plan
72193  ** for a statement, then the statement will be automatically recompiled,
72194  ** as if there had been a schema change, on the first sqlite3_step() call
72195  ** following any change to the bindings of that parameter.
72196  */
72197  if( p->isPrepareV2 &&
72198     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
72199  ){
72200    p->expired = 1;
72201  }
72202  return SQLITE_OK;
72203}
72204
72205/*
72206** Bind a text or BLOB value.
72207*/
72208static int bindText(
72209  sqlite3_stmt *pStmt,   /* The statement to bind against */
72210  int i,                 /* Index of the parameter to bind */
72211  const void *zData,     /* Pointer to the data to be bound */
72212  int nData,             /* Number of bytes of data to be bound */
72213  void (*xDel)(void*),   /* Destructor for the data */
72214  u8 encoding            /* Encoding for the data */
72215){
72216  Vdbe *p = (Vdbe *)pStmt;
72217  Mem *pVar;
72218  int rc;
72219
72220  rc = vdbeUnbind(p, i);
72221  if( rc==SQLITE_OK ){
72222    if( zData!=0 ){
72223      pVar = &p->aVar[i-1];
72224      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
72225      if( rc==SQLITE_OK && encoding!=0 ){
72226        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
72227      }
72228      sqlite3Error(p->db, rc);
72229      rc = sqlite3ApiExit(p->db, rc);
72230    }
72231    sqlite3_mutex_leave(p->db->mutex);
72232  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
72233    xDel((void*)zData);
72234  }
72235  return rc;
72236}
72237
72238
72239/*
72240** Bind a blob value to an SQL statement variable.
72241*/
72242SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
72243  sqlite3_stmt *pStmt,
72244  int i,
72245  const void *zData,
72246  int nData,
72247  void (*xDel)(void*)
72248){
72249  return bindText(pStmt, i, zData, nData, xDel, 0);
72250}
72251SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
72252  sqlite3_stmt *pStmt,
72253  int i,
72254  const void *zData,
72255  sqlite3_uint64 nData,
72256  void (*xDel)(void*)
72257){
72258  assert( xDel!=SQLITE_DYNAMIC );
72259  if( nData>0x7fffffff ){
72260    return invokeValueDestructor(zData, xDel, 0);
72261  }else{
72262    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
72263  }
72264}
72265SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
72266  int rc;
72267  Vdbe *p = (Vdbe *)pStmt;
72268  rc = vdbeUnbind(p, i);
72269  if( rc==SQLITE_OK ){
72270    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
72271    sqlite3_mutex_leave(p->db->mutex);
72272  }
72273  return rc;
72274}
72275SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
72276  return sqlite3_bind_int64(p, i, (i64)iValue);
72277}
72278SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
72279  int rc;
72280  Vdbe *p = (Vdbe *)pStmt;
72281  rc = vdbeUnbind(p, i);
72282  if( rc==SQLITE_OK ){
72283    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
72284    sqlite3_mutex_leave(p->db->mutex);
72285  }
72286  return rc;
72287}
72288SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
72289  int rc;
72290  Vdbe *p = (Vdbe*)pStmt;
72291  rc = vdbeUnbind(p, i);
72292  if( rc==SQLITE_OK ){
72293    sqlite3_mutex_leave(p->db->mutex);
72294  }
72295  return rc;
72296}
72297SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
72298  sqlite3_stmt *pStmt,
72299  int i,
72300  const char *zData,
72301  int nData,
72302  void (*xDel)(void*)
72303){
72304  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
72305}
72306SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
72307  sqlite3_stmt *pStmt,
72308  int i,
72309  const char *zData,
72310  sqlite3_uint64 nData,
72311  void (*xDel)(void*),
72312  unsigned char enc
72313){
72314  assert( xDel!=SQLITE_DYNAMIC );
72315  if( nData>0x7fffffff ){
72316    return invokeValueDestructor(zData, xDel, 0);
72317  }else{
72318    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
72319    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
72320  }
72321}
72322#ifndef SQLITE_OMIT_UTF16
72323SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
72324  sqlite3_stmt *pStmt,
72325  int i,
72326  const void *zData,
72327  int nData,
72328  void (*xDel)(void*)
72329){
72330  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
72331}
72332#endif /* SQLITE_OMIT_UTF16 */
72333SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
72334  int rc;
72335  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
72336    case SQLITE_INTEGER: {
72337      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
72338      break;
72339    }
72340    case SQLITE_FLOAT: {
72341      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
72342      break;
72343    }
72344    case SQLITE_BLOB: {
72345      if( pValue->flags & MEM_Zero ){
72346        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
72347      }else{
72348        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
72349      }
72350      break;
72351    }
72352    case SQLITE_TEXT: {
72353      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
72354                              pValue->enc);
72355      break;
72356    }
72357    default: {
72358      rc = sqlite3_bind_null(pStmt, i);
72359      break;
72360    }
72361  }
72362  return rc;
72363}
72364SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
72365  int rc;
72366  Vdbe *p = (Vdbe *)pStmt;
72367  rc = vdbeUnbind(p, i);
72368  if( rc==SQLITE_OK ){
72369    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
72370    sqlite3_mutex_leave(p->db->mutex);
72371  }
72372  return rc;
72373}
72374SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
72375  int rc;
72376  Vdbe *p = (Vdbe *)pStmt;
72377  sqlite3_mutex_enter(p->db->mutex);
72378  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
72379    rc = SQLITE_TOOBIG;
72380  }else{
72381    assert( (n & 0x7FFFFFFF)==n );
72382    rc = sqlite3_bind_zeroblob(pStmt, i, n);
72383  }
72384  rc = sqlite3ApiExit(p->db, rc);
72385  sqlite3_mutex_leave(p->db->mutex);
72386  return rc;
72387}
72388
72389/*
72390** Return the number of wildcards that can be potentially bound to.
72391** This routine is added to support DBD::SQLite.
72392*/
72393SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
72394  Vdbe *p = (Vdbe*)pStmt;
72395  return p ? p->nVar : 0;
72396}
72397
72398/*
72399** Return the name of a wildcard parameter.  Return NULL if the index
72400** is out of range or if the wildcard is unnamed.
72401**
72402** The result is always UTF-8.
72403*/
72404SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
72405  Vdbe *p = (Vdbe*)pStmt;
72406  if( p==0 || i<1 || i>p->nzVar ){
72407    return 0;
72408  }
72409  return p->azVar[i-1];
72410}
72411
72412/*
72413** Given a wildcard parameter name, return the index of the variable
72414** with that name.  If there is no variable with the given name,
72415** return 0.
72416*/
72417SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
72418  int i;
72419  if( p==0 ){
72420    return 0;
72421  }
72422  if( zName ){
72423    for(i=0; i<p->nzVar; i++){
72424      const char *z = p->azVar[i];
72425      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
72426        return i+1;
72427      }
72428    }
72429  }
72430  return 0;
72431}
72432SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
72433  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
72434}
72435
72436/*
72437** Transfer all bindings from the first statement over to the second.
72438*/
72439SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
72440  Vdbe *pFrom = (Vdbe*)pFromStmt;
72441  Vdbe *pTo = (Vdbe*)pToStmt;
72442  int i;
72443  assert( pTo->db==pFrom->db );
72444  assert( pTo->nVar==pFrom->nVar );
72445  sqlite3_mutex_enter(pTo->db->mutex);
72446  for(i=0; i<pFrom->nVar; i++){
72447    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
72448  }
72449  sqlite3_mutex_leave(pTo->db->mutex);
72450  return SQLITE_OK;
72451}
72452
72453#ifndef SQLITE_OMIT_DEPRECATED
72454/*
72455** Deprecated external interface.  Internal/core SQLite code
72456** should call sqlite3TransferBindings.
72457**
72458** It is misuse to call this routine with statements from different
72459** database connections.  But as this is a deprecated interface, we
72460** will not bother to check for that condition.
72461**
72462** If the two statements contain a different number of bindings, then
72463** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
72464** SQLITE_OK is returned.
72465*/
72466SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
72467  Vdbe *pFrom = (Vdbe*)pFromStmt;
72468  Vdbe *pTo = (Vdbe*)pToStmt;
72469  if( pFrom->nVar!=pTo->nVar ){
72470    return SQLITE_ERROR;
72471  }
72472  if( pTo->isPrepareV2 && pTo->expmask ){
72473    pTo->expired = 1;
72474  }
72475  if( pFrom->isPrepareV2 && pFrom->expmask ){
72476    pFrom->expired = 1;
72477  }
72478  return sqlite3TransferBindings(pFromStmt, pToStmt);
72479}
72480#endif
72481
72482/*
72483** Return the sqlite3* database handle to which the prepared statement given
72484** in the argument belongs.  This is the same database handle that was
72485** the first argument to the sqlite3_prepare() that was used to create
72486** the statement in the first place.
72487*/
72488SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
72489  return pStmt ? ((Vdbe*)pStmt)->db : 0;
72490}
72491
72492/*
72493** Return true if the prepared statement is guaranteed to not modify the
72494** database.
72495*/
72496SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
72497  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
72498}
72499
72500/*
72501** Return true if the prepared statement is in need of being reset.
72502*/
72503SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
72504  Vdbe *v = (Vdbe*)pStmt;
72505  return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
72506}
72507
72508/*
72509** Return a pointer to the next prepared statement after pStmt associated
72510** with database connection pDb.  If pStmt is NULL, return the first
72511** prepared statement for the database connection.  Return NULL if there
72512** are no more.
72513*/
72514SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
72515  sqlite3_stmt *pNext;
72516#ifdef SQLITE_ENABLE_API_ARMOR
72517  if( !sqlite3SafetyCheckOk(pDb) ){
72518    (void)SQLITE_MISUSE_BKPT;
72519    return 0;
72520  }
72521#endif
72522  sqlite3_mutex_enter(pDb->mutex);
72523  if( pStmt==0 ){
72524    pNext = (sqlite3_stmt*)pDb->pVdbe;
72525  }else{
72526    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
72527  }
72528  sqlite3_mutex_leave(pDb->mutex);
72529  return pNext;
72530}
72531
72532/*
72533** Return the value of a status counter for a prepared statement
72534*/
72535SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
72536  Vdbe *pVdbe = (Vdbe*)pStmt;
72537  u32 v;
72538#ifdef SQLITE_ENABLE_API_ARMOR
72539  if( !pStmt ){
72540    (void)SQLITE_MISUSE_BKPT;
72541    return 0;
72542  }
72543#endif
72544  v = pVdbe->aCounter[op];
72545  if( resetFlag ) pVdbe->aCounter[op] = 0;
72546  return (int)v;
72547}
72548
72549#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72550/*
72551** Return status data for a single loop within query pStmt.
72552*/
72553SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
72554  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
72555  int idx,                        /* Index of loop to report on */
72556  int iScanStatusOp,              /* Which metric to return */
72557  void *pOut                      /* OUT: Write the answer here */
72558){
72559  Vdbe *p = (Vdbe*)pStmt;
72560  ScanStatus *pScan;
72561  if( idx<0 || idx>=p->nScan ) return 1;
72562  pScan = &p->aScan[idx];
72563  switch( iScanStatusOp ){
72564    case SQLITE_SCANSTAT_NLOOP: {
72565      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
72566      break;
72567    }
72568    case SQLITE_SCANSTAT_NVISIT: {
72569      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
72570      break;
72571    }
72572    case SQLITE_SCANSTAT_EST: {
72573      double r = 1.0;
72574      LogEst x = pScan->nEst;
72575      while( x<100 ){
72576        x += 10;
72577        r *= 0.5;
72578      }
72579      *(double*)pOut = r*sqlite3LogEstToInt(x);
72580      break;
72581    }
72582    case SQLITE_SCANSTAT_NAME: {
72583      *(const char**)pOut = pScan->zName;
72584      break;
72585    }
72586    case SQLITE_SCANSTAT_EXPLAIN: {
72587      if( pScan->addrExplain ){
72588        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
72589      }else{
72590        *(const char**)pOut = 0;
72591      }
72592      break;
72593    }
72594    case SQLITE_SCANSTAT_SELECTID: {
72595      if( pScan->addrExplain ){
72596        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
72597      }else{
72598        *(int*)pOut = -1;
72599      }
72600      break;
72601    }
72602    default: {
72603      return 1;
72604    }
72605  }
72606  return 0;
72607}
72608
72609/*
72610** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
72611*/
72612SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
72613  Vdbe *p = (Vdbe*)pStmt;
72614  memset(p->anExec, 0, p->nOp * sizeof(i64));
72615}
72616#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
72617
72618/************** End of vdbeapi.c *********************************************/
72619/************** Begin file vdbetrace.c ***************************************/
72620/*
72621** 2009 November 25
72622**
72623** The author disclaims copyright to this source code.  In place of
72624** a legal notice, here is a blessing:
72625**
72626**    May you do good and not evil.
72627**    May you find forgiveness for yourself and forgive others.
72628**    May you share freely, never taking more than you give.
72629**
72630*************************************************************************
72631**
72632** This file contains code used to insert the values of host parameters
72633** (aka "wildcards") into the SQL text output by sqlite3_trace().
72634**
72635** The Vdbe parse-tree explainer is also found here.
72636*/
72637/* #include "sqliteInt.h" */
72638/* #include "vdbeInt.h" */
72639
72640#ifndef SQLITE_OMIT_TRACE
72641
72642/*
72643** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
72644** bytes in this text up to but excluding the first character in
72645** a host parameter.  If the text contains no host parameters, return
72646** the total number of bytes in the text.
72647*/
72648static int findNextHostParameter(const char *zSql, int *pnToken){
72649  int tokenType;
72650  int nTotal = 0;
72651  int n;
72652
72653  *pnToken = 0;
72654  while( zSql[0] ){
72655    n = sqlite3GetToken((u8*)zSql, &tokenType);
72656    assert( n>0 && tokenType!=TK_ILLEGAL );
72657    if( tokenType==TK_VARIABLE ){
72658      *pnToken = n;
72659      break;
72660    }
72661    nTotal += n;
72662    zSql += n;
72663  }
72664  return nTotal;
72665}
72666
72667/*
72668** This function returns a pointer to a nul-terminated string in memory
72669** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
72670** string contains a copy of zRawSql but with host parameters expanded to
72671** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
72672** then the returned string holds a copy of zRawSql with "-- " prepended
72673** to each line of text.
72674**
72675** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
72676** then long strings and blobs are truncated to that many bytes.  This
72677** can be used to prevent unreasonably large trace strings when dealing
72678** with large (multi-megabyte) strings and blobs.
72679**
72680** The calling function is responsible for making sure the memory returned
72681** is eventually freed.
72682**
72683** ALGORITHM:  Scan the input string looking for host parameters in any of
72684** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
72685** string literals, quoted identifier names, and comments.  For text forms,
72686** the host parameter index is found by scanning the prepared
72687** statement for the corresponding OP_Variable opcode.  Once the host
72688** parameter index is known, locate the value in p->aVar[].  Then render
72689** the value as a literal in place of the host parameter name.
72690*/
72691SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
72692  Vdbe *p,                 /* The prepared statement being evaluated */
72693  const char *zRawSql      /* Raw text of the SQL statement */
72694){
72695  sqlite3 *db;             /* The database connection */
72696  int idx = 0;             /* Index of a host parameter */
72697  int nextIndex = 1;       /* Index of next ? host parameter */
72698  int n;                   /* Length of a token prefix */
72699  int nToken;              /* Length of the parameter token */
72700  int i;                   /* Loop counter */
72701  Mem *pVar;               /* Value of a host parameter */
72702  StrAccum out;            /* Accumulate the output here */
72703  char zBase[100];         /* Initial working space */
72704
72705  db = p->db;
72706  sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
72707                      db->aLimit[SQLITE_LIMIT_LENGTH]);
72708  if( db->nVdbeExec>1 ){
72709    while( *zRawSql ){
72710      const char *zStart = zRawSql;
72711      while( *(zRawSql++)!='\n' && *zRawSql );
72712      sqlite3StrAccumAppend(&out, "-- ", 3);
72713      assert( (zRawSql - zStart) > 0 );
72714      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
72715    }
72716  }else if( p->nVar==0 ){
72717    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
72718  }else{
72719    while( zRawSql[0] ){
72720      n = findNextHostParameter(zRawSql, &nToken);
72721      assert( n>0 );
72722      sqlite3StrAccumAppend(&out, zRawSql, n);
72723      zRawSql += n;
72724      assert( zRawSql[0] || nToken==0 );
72725      if( nToken==0 ) break;
72726      if( zRawSql[0]=='?' ){
72727        if( nToken>1 ){
72728          assert( sqlite3Isdigit(zRawSql[1]) );
72729          sqlite3GetInt32(&zRawSql[1], &idx);
72730        }else{
72731          idx = nextIndex;
72732        }
72733      }else{
72734        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
72735                zRawSql[0]=='@' || zRawSql[0]=='#' );
72736        testcase( zRawSql[0]==':' );
72737        testcase( zRawSql[0]=='$' );
72738        testcase( zRawSql[0]=='@' );
72739        testcase( zRawSql[0]=='#' );
72740        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
72741        assert( idx>0 );
72742      }
72743      zRawSql += nToken;
72744      nextIndex = idx + 1;
72745      assert( idx>0 && idx<=p->nVar );
72746      pVar = &p->aVar[idx-1];
72747      if( pVar->flags & MEM_Null ){
72748        sqlite3StrAccumAppend(&out, "NULL", 4);
72749      }else if( pVar->flags & MEM_Int ){
72750        sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
72751      }else if( pVar->flags & MEM_Real ){
72752        sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
72753      }else if( pVar->flags & MEM_Str ){
72754        int nOut;  /* Number of bytes of the string text to include in output */
72755#ifndef SQLITE_OMIT_UTF16
72756        u8 enc = ENC(db);
72757        Mem utf8;
72758        if( enc!=SQLITE_UTF8 ){
72759          memset(&utf8, 0, sizeof(utf8));
72760          utf8.db = db;
72761          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
72762          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
72763          pVar = &utf8;
72764        }
72765#endif
72766        nOut = pVar->n;
72767#ifdef SQLITE_TRACE_SIZE_LIMIT
72768        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
72769          nOut = SQLITE_TRACE_SIZE_LIMIT;
72770          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
72771        }
72772#endif
72773        sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
72774#ifdef SQLITE_TRACE_SIZE_LIMIT
72775        if( nOut<pVar->n ){
72776          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
72777        }
72778#endif
72779#ifndef SQLITE_OMIT_UTF16
72780        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
72781#endif
72782      }else if( pVar->flags & MEM_Zero ){
72783        sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
72784      }else{
72785        int nOut;  /* Number of bytes of the blob to include in output */
72786        assert( pVar->flags & MEM_Blob );
72787        sqlite3StrAccumAppend(&out, "x'", 2);
72788        nOut = pVar->n;
72789#ifdef SQLITE_TRACE_SIZE_LIMIT
72790        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
72791#endif
72792        for(i=0; i<nOut; i++){
72793          sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
72794        }
72795        sqlite3StrAccumAppend(&out, "'", 1);
72796#ifdef SQLITE_TRACE_SIZE_LIMIT
72797        if( nOut<pVar->n ){
72798          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
72799        }
72800#endif
72801      }
72802    }
72803  }
72804  return sqlite3StrAccumFinish(&out);
72805}
72806
72807#endif /* #ifndef SQLITE_OMIT_TRACE */
72808
72809/************** End of vdbetrace.c *******************************************/
72810/************** Begin file vdbe.c ********************************************/
72811/*
72812** 2001 September 15
72813**
72814** The author disclaims copyright to this source code.  In place of
72815** a legal notice, here is a blessing:
72816**
72817**    May you do good and not evil.
72818**    May you find forgiveness for yourself and forgive others.
72819**    May you share freely, never taking more than you give.
72820**
72821*************************************************************************
72822** The code in this file implements the function that runs the
72823** bytecode of a prepared statement.
72824**
72825** Various scripts scan this source file in order to generate HTML
72826** documentation, headers files, or other derived files.  The formatting
72827** of the code in this file is, therefore, important.  See other comments
72828** in this file for details.  If in doubt, do not deviate from existing
72829** commenting and indentation practices when changing or adding code.
72830*/
72831/* #include "sqliteInt.h" */
72832/* #include "vdbeInt.h" */
72833
72834/*
72835** Invoke this macro on memory cells just prior to changing the
72836** value of the cell.  This macro verifies that shallow copies are
72837** not misused.  A shallow copy of a string or blob just copies a
72838** pointer to the string or blob, not the content.  If the original
72839** is changed while the copy is still in use, the string or blob might
72840** be changed out from under the copy.  This macro verifies that nothing
72841** like that ever happens.
72842*/
72843#ifdef SQLITE_DEBUG
72844# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
72845#else
72846# define memAboutToChange(P,M)
72847#endif
72848
72849/*
72850** The following global variable is incremented every time a cursor
72851** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
72852** procedures use this information to make sure that indices are
72853** working correctly.  This variable has no function other than to
72854** help verify the correct operation of the library.
72855*/
72856#ifdef SQLITE_TEST
72857SQLITE_API int sqlite3_search_count = 0;
72858#endif
72859
72860/*
72861** When this global variable is positive, it gets decremented once before
72862** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
72863** field of the sqlite3 structure is set in order to simulate an interrupt.
72864**
72865** This facility is used for testing purposes only.  It does not function
72866** in an ordinary build.
72867*/
72868#ifdef SQLITE_TEST
72869SQLITE_API int sqlite3_interrupt_count = 0;
72870#endif
72871
72872/*
72873** The next global variable is incremented each type the OP_Sort opcode
72874** is executed.  The test procedures use this information to make sure that
72875** sorting is occurring or not occurring at appropriate times.   This variable
72876** has no function other than to help verify the correct operation of the
72877** library.
72878*/
72879#ifdef SQLITE_TEST
72880SQLITE_API int sqlite3_sort_count = 0;
72881#endif
72882
72883/*
72884** The next global variable records the size of the largest MEM_Blob
72885** or MEM_Str that has been used by a VDBE opcode.  The test procedures
72886** use this information to make sure that the zero-blob functionality
72887** is working correctly.   This variable has no function other than to
72888** help verify the correct operation of the library.
72889*/
72890#ifdef SQLITE_TEST
72891SQLITE_API int sqlite3_max_blobsize = 0;
72892static void updateMaxBlobsize(Mem *p){
72893  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
72894    sqlite3_max_blobsize = p->n;
72895  }
72896}
72897#endif
72898
72899/*
72900** The next global variable is incremented each time the OP_Found opcode
72901** is executed. This is used to test whether or not the foreign key
72902** operation implemented using OP_FkIsZero is working. This variable
72903** has no function other than to help verify the correct operation of the
72904** library.
72905*/
72906#ifdef SQLITE_TEST
72907SQLITE_API int sqlite3_found_count = 0;
72908#endif
72909
72910/*
72911** Test a register to see if it exceeds the current maximum blob size.
72912** If it does, record the new maximum blob size.
72913*/
72914#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
72915# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
72916#else
72917# define UPDATE_MAX_BLOBSIZE(P)
72918#endif
72919
72920/*
72921** Invoke the VDBE coverage callback, if that callback is defined.  This
72922** feature is used for test suite validation only and does not appear an
72923** production builds.
72924**
72925** M is an integer, 2 or 3, that indices how many different ways the
72926** branch can go.  It is usually 2.  "I" is the direction the branch
72927** goes.  0 means falls through.  1 means branch is taken.  2 means the
72928** second alternative branch is taken.
72929**
72930** iSrcLine is the source code line (from the __LINE__ macro) that
72931** generated the VDBE instruction.  This instrumentation assumes that all
72932** source code is in a single file (the amalgamation).  Special values 1
72933** and 2 for the iSrcLine parameter mean that this particular branch is
72934** always taken or never taken, respectively.
72935*/
72936#if !defined(SQLITE_VDBE_COVERAGE)
72937# define VdbeBranchTaken(I,M)
72938#else
72939# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
72940  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
72941    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
72942      M = iSrcLine;
72943      /* Assert the truth of VdbeCoverageAlwaysTaken() and
72944      ** VdbeCoverageNeverTaken() */
72945      assert( (M & I)==I );
72946    }else{
72947      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
72948      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
72949                                      iSrcLine,I,M);
72950    }
72951  }
72952#endif
72953
72954/*
72955** Convert the given register into a string if it isn't one
72956** already. Return non-zero if a malloc() fails.
72957*/
72958#define Stringify(P, enc) \
72959   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
72960     { goto no_mem; }
72961
72962/*
72963** An ephemeral string value (signified by the MEM_Ephem flag) contains
72964** a pointer to a dynamically allocated string where some other entity
72965** is responsible for deallocating that string.  Because the register
72966** does not control the string, it might be deleted without the register
72967** knowing it.
72968**
72969** This routine converts an ephemeral string into a dynamically allocated
72970** string that the register itself controls.  In other words, it
72971** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
72972*/
72973#define Deephemeralize(P) \
72974   if( ((P)->flags&MEM_Ephem)!=0 \
72975       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
72976
72977/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
72978#define isSorter(x) ((x)->pSorter!=0)
72979
72980/*
72981** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
72982** if we run out of memory.
72983*/
72984static VdbeCursor *allocateCursor(
72985  Vdbe *p,              /* The virtual machine */
72986  int iCur,             /* Index of the new VdbeCursor */
72987  int nField,           /* Number of fields in the table or index */
72988  int iDb,              /* Database the cursor belongs to, or -1 */
72989  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
72990){
72991  /* Find the memory cell that will be used to store the blob of memory
72992  ** required for this VdbeCursor structure. It is convenient to use a
72993  ** vdbe memory cell to manage the memory allocation required for a
72994  ** VdbeCursor structure for the following reasons:
72995  **
72996  **   * Sometimes cursor numbers are used for a couple of different
72997  **     purposes in a vdbe program. The different uses might require
72998  **     different sized allocations. Memory cells provide growable
72999  **     allocations.
73000  **
73001  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
73002  **     be freed lazily via the sqlite3_release_memory() API. This
73003  **     minimizes the number of malloc calls made by the system.
73004  **
73005  ** Memory cells for cursors are allocated at the top of the address
73006  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
73007  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
73008  */
73009  Mem *pMem = &p->aMem[p->nMem-iCur];
73010
73011  int nByte;
73012  VdbeCursor *pCx = 0;
73013  nByte =
73014      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
73015      (isBtreeCursor?sqlite3BtreeCursorSize():0);
73016
73017  assert( iCur<p->nCursor );
73018  if( p->apCsr[iCur] ){
73019    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
73020    p->apCsr[iCur] = 0;
73021  }
73022  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
73023    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
73024    memset(pCx, 0, sizeof(VdbeCursor));
73025    pCx->iDb = iDb;
73026    pCx->nField = nField;
73027    pCx->aOffset = &pCx->aType[nField];
73028    if( isBtreeCursor ){
73029      pCx->pCursor = (BtCursor*)
73030          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
73031      sqlite3BtreeCursorZero(pCx->pCursor);
73032    }
73033  }
73034  return pCx;
73035}
73036
73037/*
73038** Try to convert a value into a numeric representation if we can
73039** do so without loss of information.  In other words, if the string
73040** looks like a number, convert it into a number.  If it does not
73041** look like a number, leave it alone.
73042**
73043** If the bTryForInt flag is true, then extra effort is made to give
73044** an integer representation.  Strings that look like floating point
73045** values but which have no fractional component (example: '48.00')
73046** will have a MEM_Int representation when bTryForInt is true.
73047**
73048** If bTryForInt is false, then if the input string contains a decimal
73049** point or exponential notation, the result is only MEM_Real, even
73050** if there is an exact integer representation of the quantity.
73051*/
73052static void applyNumericAffinity(Mem *pRec, int bTryForInt){
73053  double rValue;
73054  i64 iValue;
73055  u8 enc = pRec->enc;
73056  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
73057  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
73058  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
73059    pRec->u.i = iValue;
73060    pRec->flags |= MEM_Int;
73061  }else{
73062    pRec->u.r = rValue;
73063    pRec->flags |= MEM_Real;
73064    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
73065  }
73066}
73067
73068/*
73069** Processing is determine by the affinity parameter:
73070**
73071** SQLITE_AFF_INTEGER:
73072** SQLITE_AFF_REAL:
73073** SQLITE_AFF_NUMERIC:
73074**    Try to convert pRec to an integer representation or a
73075**    floating-point representation if an integer representation
73076**    is not possible.  Note that the integer representation is
73077**    always preferred, even if the affinity is REAL, because
73078**    an integer representation is more space efficient on disk.
73079**
73080** SQLITE_AFF_TEXT:
73081**    Convert pRec to a text representation.
73082**
73083** SQLITE_AFF_BLOB:
73084**    No-op.  pRec is unchanged.
73085*/
73086static void applyAffinity(
73087  Mem *pRec,          /* The value to apply affinity to */
73088  char affinity,      /* The affinity to be applied */
73089  u8 enc              /* Use this text encoding */
73090){
73091  if( affinity>=SQLITE_AFF_NUMERIC ){
73092    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
73093             || affinity==SQLITE_AFF_NUMERIC );
73094    if( (pRec->flags & MEM_Int)==0 ){
73095      if( (pRec->flags & MEM_Real)==0 ){
73096        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
73097      }else{
73098        sqlite3VdbeIntegerAffinity(pRec);
73099      }
73100    }
73101  }else if( affinity==SQLITE_AFF_TEXT ){
73102    /* Only attempt the conversion to TEXT if there is an integer or real
73103    ** representation (blob and NULL do not get converted) but no string
73104    ** representation.
73105    */
73106    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
73107      sqlite3VdbeMemStringify(pRec, enc, 1);
73108    }
73109    pRec->flags &= ~(MEM_Real|MEM_Int);
73110  }
73111}
73112
73113/*
73114** Try to convert the type of a function argument or a result column
73115** into a numeric representation.  Use either INTEGER or REAL whichever
73116** is appropriate.  But only do the conversion if it is possible without
73117** loss of information and return the revised type of the argument.
73118*/
73119SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
73120  int eType = sqlite3_value_type(pVal);
73121  if( eType==SQLITE_TEXT ){
73122    Mem *pMem = (Mem*)pVal;
73123    applyNumericAffinity(pMem, 0);
73124    eType = sqlite3_value_type(pVal);
73125  }
73126  return eType;
73127}
73128
73129/*
73130** Exported version of applyAffinity(). This one works on sqlite3_value*,
73131** not the internal Mem* type.
73132*/
73133SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
73134  sqlite3_value *pVal,
73135  u8 affinity,
73136  u8 enc
73137){
73138  applyAffinity((Mem *)pVal, affinity, enc);
73139}
73140
73141/*
73142** pMem currently only holds a string type (or maybe a BLOB that we can
73143** interpret as a string if we want to).  Compute its corresponding
73144** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
73145** accordingly.
73146*/
73147static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
73148  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
73149  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
73150  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
73151    return 0;
73152  }
73153  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
73154    return MEM_Int;
73155  }
73156  return MEM_Real;
73157}
73158
73159/*
73160** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
73161** none.
73162**
73163** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
73164** But it does set pMem->u.r and pMem->u.i appropriately.
73165*/
73166static u16 numericType(Mem *pMem){
73167  if( pMem->flags & (MEM_Int|MEM_Real) ){
73168    return pMem->flags & (MEM_Int|MEM_Real);
73169  }
73170  if( pMem->flags & (MEM_Str|MEM_Blob) ){
73171    return computeNumericType(pMem);
73172  }
73173  return 0;
73174}
73175
73176#ifdef SQLITE_DEBUG
73177/*
73178** Write a nice string representation of the contents of cell pMem
73179** into buffer zBuf, length nBuf.
73180*/
73181SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
73182  char *zCsr = zBuf;
73183  int f = pMem->flags;
73184
73185  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
73186
73187  if( f&MEM_Blob ){
73188    int i;
73189    char c;
73190    if( f & MEM_Dyn ){
73191      c = 'z';
73192      assert( (f & (MEM_Static|MEM_Ephem))==0 );
73193    }else if( f & MEM_Static ){
73194      c = 't';
73195      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
73196    }else if( f & MEM_Ephem ){
73197      c = 'e';
73198      assert( (f & (MEM_Static|MEM_Dyn))==0 );
73199    }else{
73200      c = 's';
73201    }
73202
73203    sqlite3_snprintf(100, zCsr, "%c", c);
73204    zCsr += sqlite3Strlen30(zCsr);
73205    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
73206    zCsr += sqlite3Strlen30(zCsr);
73207    for(i=0; i<16 && i<pMem->n; i++){
73208      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
73209      zCsr += sqlite3Strlen30(zCsr);
73210    }
73211    for(i=0; i<16 && i<pMem->n; i++){
73212      char z = pMem->z[i];
73213      if( z<32 || z>126 ) *zCsr++ = '.';
73214      else *zCsr++ = z;
73215    }
73216
73217    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
73218    zCsr += sqlite3Strlen30(zCsr);
73219    if( f & MEM_Zero ){
73220      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
73221      zCsr += sqlite3Strlen30(zCsr);
73222    }
73223    *zCsr = '\0';
73224  }else if( f & MEM_Str ){
73225    int j, k;
73226    zBuf[0] = ' ';
73227    if( f & MEM_Dyn ){
73228      zBuf[1] = 'z';
73229      assert( (f & (MEM_Static|MEM_Ephem))==0 );
73230    }else if( f & MEM_Static ){
73231      zBuf[1] = 't';
73232      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
73233    }else if( f & MEM_Ephem ){
73234      zBuf[1] = 'e';
73235      assert( (f & (MEM_Static|MEM_Dyn))==0 );
73236    }else{
73237      zBuf[1] = 's';
73238    }
73239    k = 2;
73240    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
73241    k += sqlite3Strlen30(&zBuf[k]);
73242    zBuf[k++] = '[';
73243    for(j=0; j<15 && j<pMem->n; j++){
73244      u8 c = pMem->z[j];
73245      if( c>=0x20 && c<0x7f ){
73246        zBuf[k++] = c;
73247      }else{
73248        zBuf[k++] = '.';
73249      }
73250    }
73251    zBuf[k++] = ']';
73252    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
73253    k += sqlite3Strlen30(&zBuf[k]);
73254    zBuf[k++] = 0;
73255  }
73256}
73257#endif
73258
73259#ifdef SQLITE_DEBUG
73260/*
73261** Print the value of a register for tracing purposes:
73262*/
73263static void memTracePrint(Mem *p){
73264  if( p->flags & MEM_Undefined ){
73265    printf(" undefined");
73266  }else if( p->flags & MEM_Null ){
73267    printf(" NULL");
73268  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
73269    printf(" si:%lld", p->u.i);
73270  }else if( p->flags & MEM_Int ){
73271    printf(" i:%lld", p->u.i);
73272#ifndef SQLITE_OMIT_FLOATING_POINT
73273  }else if( p->flags & MEM_Real ){
73274    printf(" r:%g", p->u.r);
73275#endif
73276  }else if( p->flags & MEM_RowSet ){
73277    printf(" (rowset)");
73278  }else{
73279    char zBuf[200];
73280    sqlite3VdbeMemPrettyPrint(p, zBuf);
73281    printf(" %s", zBuf);
73282  }
73283}
73284static void registerTrace(int iReg, Mem *p){
73285  printf("REG[%d] = ", iReg);
73286  memTracePrint(p);
73287  printf("\n");
73288}
73289#endif
73290
73291#ifdef SQLITE_DEBUG
73292#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
73293#else
73294#  define REGISTER_TRACE(R,M)
73295#endif
73296
73297
73298#ifdef VDBE_PROFILE
73299
73300/*
73301** hwtime.h contains inline assembler code for implementing
73302** high-performance timing routines.
73303*/
73304/************** Include hwtime.h in the middle of vdbe.c *********************/
73305/************** Begin file hwtime.h ******************************************/
73306/*
73307** 2008 May 27
73308**
73309** The author disclaims copyright to this source code.  In place of
73310** a legal notice, here is a blessing:
73311**
73312**    May you do good and not evil.
73313**    May you find forgiveness for yourself and forgive others.
73314**    May you share freely, never taking more than you give.
73315**
73316******************************************************************************
73317**
73318** This file contains inline asm code for retrieving "high-performance"
73319** counters for x86 class CPUs.
73320*/
73321#ifndef _HWTIME_H_
73322#define _HWTIME_H_
73323
73324/*
73325** The following routine only works on pentium-class (or newer) processors.
73326** It uses the RDTSC opcode to read the cycle count value out of the
73327** processor and returns that value.  This can be used for high-res
73328** profiling.
73329*/
73330#if (defined(__GNUC__) || defined(_MSC_VER)) && \
73331      (defined(i386) || defined(__i386__) || defined(_M_IX86))
73332
73333  #if defined(__GNUC__)
73334
73335  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73336     unsigned int lo, hi;
73337     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
73338     return (sqlite_uint64)hi << 32 | lo;
73339  }
73340
73341  #elif defined(_MSC_VER)
73342
73343  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
73344     __asm {
73345        rdtsc
73346        ret       ; return value at EDX:EAX
73347     }
73348  }
73349
73350  #endif
73351
73352#elif (defined(__GNUC__) && defined(__x86_64__))
73353
73354  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73355      unsigned long val;
73356      __asm__ __volatile__ ("rdtsc" : "=A" (val));
73357      return val;
73358  }
73359
73360#elif (defined(__GNUC__) && defined(__ppc__))
73361
73362  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73363      unsigned long long retval;
73364      unsigned long junk;
73365      __asm__ __volatile__ ("\n\
73366          1:      mftbu   %1\n\
73367                  mftb    %L0\n\
73368                  mftbu   %0\n\
73369                  cmpw    %0,%1\n\
73370                  bne     1b"
73371                  : "=r" (retval), "=r" (junk));
73372      return retval;
73373  }
73374
73375#else
73376
73377  #error Need implementation of sqlite3Hwtime() for your platform.
73378
73379  /*
73380  ** To compile without implementing sqlite3Hwtime() for your platform,
73381  ** you can remove the above #error and use the following
73382  ** stub function.  You will lose timing support for many
73383  ** of the debugging and testing utilities, but it should at
73384  ** least compile and run.
73385  */
73386SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
73387
73388#endif
73389
73390#endif /* !defined(_HWTIME_H_) */
73391
73392/************** End of hwtime.h **********************************************/
73393/************** Continuing where we left off in vdbe.c ***********************/
73394
73395#endif
73396
73397#ifndef NDEBUG
73398/*
73399** This function is only called from within an assert() expression. It
73400** checks that the sqlite3.nTransaction variable is correctly set to
73401** the number of non-transaction savepoints currently in the
73402** linked list starting at sqlite3.pSavepoint.
73403**
73404** Usage:
73405**
73406**     assert( checkSavepointCount(db) );
73407*/
73408static int checkSavepointCount(sqlite3 *db){
73409  int n = 0;
73410  Savepoint *p;
73411  for(p=db->pSavepoint; p; p=p->pNext) n++;
73412  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
73413  return 1;
73414}
73415#endif
73416
73417/*
73418** Return the register of pOp->p2 after first preparing it to be
73419** overwritten with an integer value.
73420*/
73421static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
73422  Mem *pOut;
73423  assert( pOp->p2>0 );
73424  assert( pOp->p2<=(p->nMem-p->nCursor) );
73425  pOut = &p->aMem[pOp->p2];
73426  memAboutToChange(p, pOut);
73427  if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
73428  pOut->flags = MEM_Int;
73429  return pOut;
73430}
73431
73432
73433/*
73434** Execute as much of a VDBE program as we can.
73435** This is the core of sqlite3_step().
73436*/
73437SQLITE_PRIVATE int sqlite3VdbeExec(
73438  Vdbe *p                    /* The VDBE */
73439){
73440  Op *aOp = p->aOp;          /* Copy of p->aOp */
73441  Op *pOp = aOp;             /* Current operation */
73442#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73443  Op *pOrigOp;               /* Value of pOp at the top of the loop */
73444#endif
73445  int rc = SQLITE_OK;        /* Value to return */
73446  sqlite3 *db = p->db;       /* The database */
73447  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
73448  u8 encoding = ENC(db);     /* The database encoding */
73449  int iCompare = 0;          /* Result of last OP_Compare operation */
73450  unsigned nVmStep = 0;      /* Number of virtual machine steps */
73451#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73452  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
73453#endif
73454  Mem *aMem = p->aMem;       /* Copy of p->aMem */
73455  Mem *pIn1 = 0;             /* 1st input operand */
73456  Mem *pIn2 = 0;             /* 2nd input operand */
73457  Mem *pIn3 = 0;             /* 3rd input operand */
73458  Mem *pOut = 0;             /* Output operand */
73459  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
73460  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
73461#ifdef VDBE_PROFILE
73462  u64 start;                 /* CPU clock count at start of opcode */
73463#endif
73464  /*** INSERT STACK UNION HERE ***/
73465
73466  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
73467  sqlite3VdbeEnter(p);
73468  if( p->rc==SQLITE_NOMEM ){
73469    /* This happens if a malloc() inside a call to sqlite3_column_text() or
73470    ** sqlite3_column_text16() failed.  */
73471    goto no_mem;
73472  }
73473  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
73474  assert( p->bIsReader || p->readOnly!=0 );
73475  p->rc = SQLITE_OK;
73476  p->iCurrentTime = 0;
73477  assert( p->explain==0 );
73478  p->pResultSet = 0;
73479  db->busyHandler.nBusy = 0;
73480  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
73481  sqlite3VdbeIOTraceSql(p);
73482#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73483  if( db->xProgress ){
73484    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
73485    assert( 0 < db->nProgressOps );
73486    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
73487  }
73488#endif
73489#ifdef SQLITE_DEBUG
73490  sqlite3BeginBenignMalloc();
73491  if( p->pc==0
73492   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
73493  ){
73494    int i;
73495    int once = 1;
73496    sqlite3VdbePrintSql(p);
73497    if( p->db->flags & SQLITE_VdbeListing ){
73498      printf("VDBE Program Listing:\n");
73499      for(i=0; i<p->nOp; i++){
73500        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
73501      }
73502    }
73503    if( p->db->flags & SQLITE_VdbeEQP ){
73504      for(i=0; i<p->nOp; i++){
73505        if( aOp[i].opcode==OP_Explain ){
73506          if( once ) printf("VDBE Query Plan:\n");
73507          printf("%s\n", aOp[i].p4.z);
73508          once = 0;
73509        }
73510      }
73511    }
73512    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
73513  }
73514  sqlite3EndBenignMalloc();
73515#endif
73516  for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
73517    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
73518    if( db->mallocFailed ) goto no_mem;
73519#ifdef VDBE_PROFILE
73520    start = sqlite3Hwtime();
73521#endif
73522    nVmStep++;
73523#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73524    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
73525#endif
73526
73527    /* Only allow tracing if SQLITE_DEBUG is defined.
73528    */
73529#ifdef SQLITE_DEBUG
73530    if( db->flags & SQLITE_VdbeTrace ){
73531      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
73532    }
73533#endif
73534
73535
73536    /* Check to see if we need to simulate an interrupt.  This only happens
73537    ** if we have a special test build.
73538    */
73539#ifdef SQLITE_TEST
73540    if( sqlite3_interrupt_count>0 ){
73541      sqlite3_interrupt_count--;
73542      if( sqlite3_interrupt_count==0 ){
73543        sqlite3_interrupt(db);
73544      }
73545    }
73546#endif
73547
73548    /* Sanity checking on other operands */
73549#ifdef SQLITE_DEBUG
73550    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
73551    if( (pOp->opflags & OPFLG_IN1)!=0 ){
73552      assert( pOp->p1>0 );
73553      assert( pOp->p1<=(p->nMem-p->nCursor) );
73554      assert( memIsValid(&aMem[pOp->p1]) );
73555      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
73556      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
73557    }
73558    if( (pOp->opflags & OPFLG_IN2)!=0 ){
73559      assert( pOp->p2>0 );
73560      assert( pOp->p2<=(p->nMem-p->nCursor) );
73561      assert( memIsValid(&aMem[pOp->p2]) );
73562      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
73563      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
73564    }
73565    if( (pOp->opflags & OPFLG_IN3)!=0 ){
73566      assert( pOp->p3>0 );
73567      assert( pOp->p3<=(p->nMem-p->nCursor) );
73568      assert( memIsValid(&aMem[pOp->p3]) );
73569      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
73570      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
73571    }
73572    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
73573      assert( pOp->p2>0 );
73574      assert( pOp->p2<=(p->nMem-p->nCursor) );
73575      memAboutToChange(p, &aMem[pOp->p2]);
73576    }
73577    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
73578      assert( pOp->p3>0 );
73579      assert( pOp->p3<=(p->nMem-p->nCursor) );
73580      memAboutToChange(p, &aMem[pOp->p3]);
73581    }
73582#endif
73583#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73584    pOrigOp = pOp;
73585#endif
73586
73587    switch( pOp->opcode ){
73588
73589/*****************************************************************************
73590** What follows is a massive switch statement where each case implements a
73591** separate instruction in the virtual machine.  If we follow the usual
73592** indentation conventions, each case should be indented by 6 spaces.  But
73593** that is a lot of wasted space on the left margin.  So the code within
73594** the switch statement will break with convention and be flush-left. Another
73595** big comment (similar to this one) will mark the point in the code where
73596** we transition back to normal indentation.
73597**
73598** The formatting of each case is important.  The makefile for SQLite
73599** generates two C files "opcodes.h" and "opcodes.c" by scanning this
73600** file looking for lines that begin with "case OP_".  The opcodes.h files
73601** will be filled with #defines that give unique integer values to each
73602** opcode and the opcodes.c file is filled with an array of strings where
73603** each string is the symbolic name for the corresponding opcode.  If the
73604** case statement is followed by a comment of the form "/# same as ... #/"
73605** that comment is used to determine the particular value of the opcode.
73606**
73607** Other keywords in the comment that follows each case are used to
73608** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
73609** Keywords include: in1, in2, in3, out2, out3.  See
73610** the mkopcodeh.awk script for additional information.
73611**
73612** Documentation about VDBE opcodes is generated by scanning this file
73613** for lines of that contain "Opcode:".  That line and all subsequent
73614** comment lines are used in the generation of the opcode.html documentation
73615** file.
73616**
73617** SUMMARY:
73618**
73619**     Formatting is important to scripts that scan this file.
73620**     Do not deviate from the formatting style currently in use.
73621**
73622*****************************************************************************/
73623
73624/* Opcode:  Goto * P2 * * *
73625**
73626** An unconditional jump to address P2.
73627** The next instruction executed will be
73628** the one at index P2 from the beginning of
73629** the program.
73630**
73631** The P1 parameter is not actually used by this opcode.  However, it
73632** is sometimes set to 1 instead of 0 as a hint to the command-line shell
73633** that this Goto is the bottom of a loop and that the lines from P2 down
73634** to the current line should be indented for EXPLAIN output.
73635*/
73636case OP_Goto: {             /* jump */
73637jump_to_p2_and_check_for_interrupt:
73638  pOp = &aOp[pOp->p2 - 1];
73639
73640  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
73641  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
73642  ** completion.  Check to see if sqlite3_interrupt() has been called
73643  ** or if the progress callback needs to be invoked.
73644  **
73645  ** This code uses unstructured "goto" statements and does not look clean.
73646  ** But that is not due to sloppy coding habits. The code is written this
73647  ** way for performance, to avoid having to run the interrupt and progress
73648  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
73649  ** faster according to "valgrind --tool=cachegrind" */
73650check_for_interrupt:
73651  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
73652#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73653  /* Call the progress callback if it is configured and the required number
73654  ** of VDBE ops have been executed (either since this invocation of
73655  ** sqlite3VdbeExec() or since last time the progress callback was called).
73656  ** If the progress callback returns non-zero, exit the virtual machine with
73657  ** a return code SQLITE_ABORT.
73658  */
73659  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
73660    assert( db->nProgressOps!=0 );
73661    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
73662    if( db->xProgress(db->pProgressArg) ){
73663      rc = SQLITE_INTERRUPT;
73664      goto vdbe_error_halt;
73665    }
73666  }
73667#endif
73668
73669  break;
73670}
73671
73672/* Opcode:  Gosub P1 P2 * * *
73673**
73674** Write the current address onto register P1
73675** and then jump to address P2.
73676*/
73677case OP_Gosub: {            /* jump */
73678  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
73679  pIn1 = &aMem[pOp->p1];
73680  assert( VdbeMemDynamic(pIn1)==0 );
73681  memAboutToChange(p, pIn1);
73682  pIn1->flags = MEM_Int;
73683  pIn1->u.i = (int)(pOp-aOp);
73684  REGISTER_TRACE(pOp->p1, pIn1);
73685
73686  /* Most jump operations do a goto to this spot in order to update
73687  ** the pOp pointer. */
73688jump_to_p2:
73689  pOp = &aOp[pOp->p2 - 1];
73690  break;
73691}
73692
73693/* Opcode:  Return P1 * * * *
73694**
73695** Jump to the next instruction after the address in register P1.  After
73696** the jump, register P1 becomes undefined.
73697*/
73698case OP_Return: {           /* in1 */
73699  pIn1 = &aMem[pOp->p1];
73700  assert( pIn1->flags==MEM_Int );
73701  pOp = &aOp[pIn1->u.i];
73702  pIn1->flags = MEM_Undefined;
73703  break;
73704}
73705
73706/* Opcode: InitCoroutine P1 P2 P3 * *
73707**
73708** Set up register P1 so that it will Yield to the coroutine
73709** located at address P3.
73710**
73711** If P2!=0 then the coroutine implementation immediately follows
73712** this opcode.  So jump over the coroutine implementation to
73713** address P2.
73714**
73715** See also: EndCoroutine
73716*/
73717case OP_InitCoroutine: {     /* jump */
73718  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
73719  assert( pOp->p2>=0 && pOp->p2<p->nOp );
73720  assert( pOp->p3>=0 && pOp->p3<p->nOp );
73721  pOut = &aMem[pOp->p1];
73722  assert( !VdbeMemDynamic(pOut) );
73723  pOut->u.i = pOp->p3 - 1;
73724  pOut->flags = MEM_Int;
73725  if( pOp->p2 ) goto jump_to_p2;
73726  break;
73727}
73728
73729/* Opcode:  EndCoroutine P1 * * * *
73730**
73731** The instruction at the address in register P1 is a Yield.
73732** Jump to the P2 parameter of that Yield.
73733** After the jump, register P1 becomes undefined.
73734**
73735** See also: InitCoroutine
73736*/
73737case OP_EndCoroutine: {           /* in1 */
73738  VdbeOp *pCaller;
73739  pIn1 = &aMem[pOp->p1];
73740  assert( pIn1->flags==MEM_Int );
73741  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
73742  pCaller = &aOp[pIn1->u.i];
73743  assert( pCaller->opcode==OP_Yield );
73744  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
73745  pOp = &aOp[pCaller->p2 - 1];
73746  pIn1->flags = MEM_Undefined;
73747  break;
73748}
73749
73750/* Opcode:  Yield P1 P2 * * *
73751**
73752** Swap the program counter with the value in register P1.  This
73753** has the effect of yielding to a coroutine.
73754**
73755** If the coroutine that is launched by this instruction ends with
73756** Yield or Return then continue to the next instruction.  But if
73757** the coroutine launched by this instruction ends with
73758** EndCoroutine, then jump to P2 rather than continuing with the
73759** next instruction.
73760**
73761** See also: InitCoroutine
73762*/
73763case OP_Yield: {            /* in1, jump */
73764  int pcDest;
73765  pIn1 = &aMem[pOp->p1];
73766  assert( VdbeMemDynamic(pIn1)==0 );
73767  pIn1->flags = MEM_Int;
73768  pcDest = (int)pIn1->u.i;
73769  pIn1->u.i = (int)(pOp - aOp);
73770  REGISTER_TRACE(pOp->p1, pIn1);
73771  pOp = &aOp[pcDest];
73772  break;
73773}
73774
73775/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
73776** Synopsis:  if r[P3]=null halt
73777**
73778** Check the value in register P3.  If it is NULL then Halt using
73779** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
73780** value in register P3 is not NULL, then this routine is a no-op.
73781** The P5 parameter should be 1.
73782*/
73783case OP_HaltIfNull: {      /* in3 */
73784  pIn3 = &aMem[pOp->p3];
73785  if( (pIn3->flags & MEM_Null)==0 ) break;
73786  /* Fall through into OP_Halt */
73787}
73788
73789/* Opcode:  Halt P1 P2 * P4 P5
73790**
73791** Exit immediately.  All open cursors, etc are closed
73792** automatically.
73793**
73794** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
73795** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
73796** For errors, it can be some other value.  If P1!=0 then P2 will determine
73797** whether or not to rollback the current transaction.  Do not rollback
73798** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
73799** then back out all changes that have occurred during this execution of the
73800** VDBE, but do not rollback the transaction.
73801**
73802** If P4 is not null then it is an error message string.
73803**
73804** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
73805**
73806**    0:  (no change)
73807**    1:  NOT NULL contraint failed: P4
73808**    2:  UNIQUE constraint failed: P4
73809**    3:  CHECK constraint failed: P4
73810**    4:  FOREIGN KEY constraint failed: P4
73811**
73812** If P5 is not zero and P4 is NULL, then everything after the ":" is
73813** omitted.
73814**
73815** There is an implied "Halt 0 0 0" instruction inserted at the very end of
73816** every program.  So a jump past the last instruction of the program
73817** is the same as executing Halt.
73818*/
73819case OP_Halt: {
73820  const char *zType;
73821  const char *zLogFmt;
73822  VdbeFrame *pFrame;
73823  int pcx;
73824
73825  pcx = (int)(pOp - aOp);
73826  if( pOp->p1==SQLITE_OK && p->pFrame ){
73827    /* Halt the sub-program. Return control to the parent frame. */
73828    pFrame = p->pFrame;
73829    p->pFrame = pFrame->pParent;
73830    p->nFrame--;
73831    sqlite3VdbeSetChanges(db, p->nChange);
73832    pcx = sqlite3VdbeFrameRestore(pFrame);
73833    lastRowid = db->lastRowid;
73834    if( pOp->p2==OE_Ignore ){
73835      /* Instruction pcx is the OP_Program that invoked the sub-program
73836      ** currently being halted. If the p2 instruction of this OP_Halt
73837      ** instruction is set to OE_Ignore, then the sub-program is throwing
73838      ** an IGNORE exception. In this case jump to the address specified
73839      ** as the p2 of the calling OP_Program.  */
73840      pcx = p->aOp[pcx].p2-1;
73841    }
73842    aOp = p->aOp;
73843    aMem = p->aMem;
73844    pOp = &aOp[pcx];
73845    break;
73846  }
73847  p->rc = pOp->p1;
73848  p->errorAction = (u8)pOp->p2;
73849  p->pc = pcx;
73850  if( p->rc ){
73851    if( pOp->p5 ){
73852      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
73853                                             "FOREIGN KEY" };
73854      assert( pOp->p5>=1 && pOp->p5<=4 );
73855      testcase( pOp->p5==1 );
73856      testcase( pOp->p5==2 );
73857      testcase( pOp->p5==3 );
73858      testcase( pOp->p5==4 );
73859      zType = azType[pOp->p5-1];
73860    }else{
73861      zType = 0;
73862    }
73863    assert( zType!=0 || pOp->p4.z!=0 );
73864    zLogFmt = "abort at %d in [%s]: %s";
73865    if( zType && pOp->p4.z ){
73866      sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
73867    }else if( pOp->p4.z ){
73868      sqlite3VdbeError(p, "%s", pOp->p4.z);
73869    }else{
73870      sqlite3VdbeError(p, "%s constraint failed", zType);
73871    }
73872    sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
73873  }
73874  rc = sqlite3VdbeHalt(p);
73875  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
73876  if( rc==SQLITE_BUSY ){
73877    p->rc = rc = SQLITE_BUSY;
73878  }else{
73879    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
73880    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
73881    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
73882  }
73883  goto vdbe_return;
73884}
73885
73886/* Opcode: Integer P1 P2 * * *
73887** Synopsis: r[P2]=P1
73888**
73889** The 32-bit integer value P1 is written into register P2.
73890*/
73891case OP_Integer: {         /* out2 */
73892  pOut = out2Prerelease(p, pOp);
73893  pOut->u.i = pOp->p1;
73894  break;
73895}
73896
73897/* Opcode: Int64 * P2 * P4 *
73898** Synopsis: r[P2]=P4
73899**
73900** P4 is a pointer to a 64-bit integer value.
73901** Write that value into register P2.
73902*/
73903case OP_Int64: {           /* out2 */
73904  pOut = out2Prerelease(p, pOp);
73905  assert( pOp->p4.pI64!=0 );
73906  pOut->u.i = *pOp->p4.pI64;
73907  break;
73908}
73909
73910#ifndef SQLITE_OMIT_FLOATING_POINT
73911/* Opcode: Real * P2 * P4 *
73912** Synopsis: r[P2]=P4
73913**
73914** P4 is a pointer to a 64-bit floating point value.
73915** Write that value into register P2.
73916*/
73917case OP_Real: {            /* same as TK_FLOAT, out2 */
73918  pOut = out2Prerelease(p, pOp);
73919  pOut->flags = MEM_Real;
73920  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
73921  pOut->u.r = *pOp->p4.pReal;
73922  break;
73923}
73924#endif
73925
73926/* Opcode: String8 * P2 * P4 *
73927** Synopsis: r[P2]='P4'
73928**
73929** P4 points to a nul terminated UTF-8 string. This opcode is transformed
73930** into a String opcode before it is executed for the first time.  During
73931** this transformation, the length of string P4 is computed and stored
73932** as the P1 parameter.
73933*/
73934case OP_String8: {         /* same as TK_STRING, out2 */
73935  assert( pOp->p4.z!=0 );
73936  pOut = out2Prerelease(p, pOp);
73937  pOp->opcode = OP_String;
73938  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
73939
73940#ifndef SQLITE_OMIT_UTF16
73941  if( encoding!=SQLITE_UTF8 ){
73942    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
73943    if( rc==SQLITE_TOOBIG ) goto too_big;
73944    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
73945    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
73946    assert( VdbeMemDynamic(pOut)==0 );
73947    pOut->szMalloc = 0;
73948    pOut->flags |= MEM_Static;
73949    if( pOp->p4type==P4_DYNAMIC ){
73950      sqlite3DbFree(db, pOp->p4.z);
73951    }
73952    pOp->p4type = P4_DYNAMIC;
73953    pOp->p4.z = pOut->z;
73954    pOp->p1 = pOut->n;
73955  }
73956#endif
73957  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73958    goto too_big;
73959  }
73960  /* Fall through to the next case, OP_String */
73961}
73962
73963/* Opcode: String P1 P2 P3 P4 P5
73964** Synopsis: r[P2]='P4' (len=P1)
73965**
73966** The string value P4 of length P1 (bytes) is stored in register P2.
73967**
73968** If P5!=0 and the content of register P3 is greater than zero, then
73969** the datatype of the register P2 is converted to BLOB.  The content is
73970** the same sequence of bytes, it is merely interpreted as a BLOB instead
73971** of a string, as if it had been CAST.
73972*/
73973case OP_String: {          /* out2 */
73974  assert( pOp->p4.z!=0 );
73975  pOut = out2Prerelease(p, pOp);
73976  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
73977  pOut->z = pOp->p4.z;
73978  pOut->n = pOp->p1;
73979  pOut->enc = encoding;
73980  UPDATE_MAX_BLOBSIZE(pOut);
73981  if( pOp->p5 ){
73982    assert( pOp->p3>0 );
73983    assert( pOp->p3<=(p->nMem-p->nCursor) );
73984    pIn3 = &aMem[pOp->p3];
73985    assert( pIn3->flags & MEM_Int );
73986    if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
73987  }
73988  break;
73989}
73990
73991/* Opcode: Null P1 P2 P3 * *
73992** Synopsis:  r[P2..P3]=NULL
73993**
73994** Write a NULL into registers P2.  If P3 greater than P2, then also write
73995** NULL into register P3 and every register in between P2 and P3.  If P3
73996** is less than P2 (typically P3 is zero) then only register P2 is
73997** set to NULL.
73998**
73999** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
74000** NULL values will not compare equal even if SQLITE_NULLEQ is set on
74001** OP_Ne or OP_Eq.
74002*/
74003case OP_Null: {           /* out2 */
74004  int cnt;
74005  u16 nullFlag;
74006  pOut = out2Prerelease(p, pOp);
74007  cnt = pOp->p3-pOp->p2;
74008  assert( pOp->p3<=(p->nMem-p->nCursor) );
74009  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
74010  while( cnt>0 ){
74011    pOut++;
74012    memAboutToChange(p, pOut);
74013    sqlite3VdbeMemSetNull(pOut);
74014    pOut->flags = nullFlag;
74015    cnt--;
74016  }
74017  break;
74018}
74019
74020/* Opcode: SoftNull P1 * * * *
74021** Synopsis:  r[P1]=NULL
74022**
74023** Set register P1 to have the value NULL as seen by the OP_MakeRecord
74024** instruction, but do not free any string or blob memory associated with
74025** the register, so that if the value was a string or blob that was
74026** previously copied using OP_SCopy, the copies will continue to be valid.
74027*/
74028case OP_SoftNull: {
74029  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
74030  pOut = &aMem[pOp->p1];
74031  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
74032  break;
74033}
74034
74035/* Opcode: Blob P1 P2 * P4 *
74036** Synopsis: r[P2]=P4 (len=P1)
74037**
74038** P4 points to a blob of data P1 bytes long.  Store this
74039** blob in register P2.
74040*/
74041case OP_Blob: {                /* out2 */
74042  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
74043  pOut = out2Prerelease(p, pOp);
74044  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
74045  pOut->enc = encoding;
74046  UPDATE_MAX_BLOBSIZE(pOut);
74047  break;
74048}
74049
74050/* Opcode: Variable P1 P2 * P4 *
74051** Synopsis: r[P2]=parameter(P1,P4)
74052**
74053** Transfer the values of bound parameter P1 into register P2
74054**
74055** If the parameter is named, then its name appears in P4.
74056** The P4 value is used by sqlite3_bind_parameter_name().
74057*/
74058case OP_Variable: {            /* out2 */
74059  Mem *pVar;       /* Value being transferred */
74060
74061  assert( pOp->p1>0 && pOp->p1<=p->nVar );
74062  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
74063  pVar = &p->aVar[pOp->p1 - 1];
74064  if( sqlite3VdbeMemTooBig(pVar) ){
74065    goto too_big;
74066  }
74067  pOut = out2Prerelease(p, pOp);
74068  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
74069  UPDATE_MAX_BLOBSIZE(pOut);
74070  break;
74071}
74072
74073/* Opcode: Move P1 P2 P3 * *
74074** Synopsis:  r[P2@P3]=r[P1@P3]
74075**
74076** Move the P3 values in register P1..P1+P3-1 over into
74077** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
74078** left holding a NULL.  It is an error for register ranges
74079** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
74080** for P3 to be less than 1.
74081*/
74082case OP_Move: {
74083  int n;           /* Number of registers left to copy */
74084  int p1;          /* Register to copy from */
74085  int p2;          /* Register to copy to */
74086
74087  n = pOp->p3;
74088  p1 = pOp->p1;
74089  p2 = pOp->p2;
74090  assert( n>0 && p1>0 && p2>0 );
74091  assert( p1+n<=p2 || p2+n<=p1 );
74092
74093  pIn1 = &aMem[p1];
74094  pOut = &aMem[p2];
74095  do{
74096    assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
74097    assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
74098    assert( memIsValid(pIn1) );
74099    memAboutToChange(p, pOut);
74100    sqlite3VdbeMemMove(pOut, pIn1);
74101#ifdef SQLITE_DEBUG
74102    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
74103      pOut->pScopyFrom += pOp->p2 - p1;
74104    }
74105#endif
74106    Deephemeralize(pOut);
74107    REGISTER_TRACE(p2++, pOut);
74108    pIn1++;
74109    pOut++;
74110  }while( --n );
74111  break;
74112}
74113
74114/* Opcode: Copy P1 P2 P3 * *
74115** Synopsis: r[P2@P3+1]=r[P1@P3+1]
74116**
74117** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
74118**
74119** This instruction makes a deep copy of the value.  A duplicate
74120** is made of any string or blob constant.  See also OP_SCopy.
74121*/
74122case OP_Copy: {
74123  int n;
74124
74125  n = pOp->p3;
74126  pIn1 = &aMem[pOp->p1];
74127  pOut = &aMem[pOp->p2];
74128  assert( pOut!=pIn1 );
74129  while( 1 ){
74130    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
74131    Deephemeralize(pOut);
74132#ifdef SQLITE_DEBUG
74133    pOut->pScopyFrom = 0;
74134#endif
74135    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
74136    if( (n--)==0 ) break;
74137    pOut++;
74138    pIn1++;
74139  }
74140  break;
74141}
74142
74143/* Opcode: SCopy P1 P2 * * *
74144** Synopsis: r[P2]=r[P1]
74145**
74146** Make a shallow copy of register P1 into register P2.
74147**
74148** This instruction makes a shallow copy of the value.  If the value
74149** is a string or blob, then the copy is only a pointer to the
74150** original and hence if the original changes so will the copy.
74151** Worse, if the original is deallocated, the copy becomes invalid.
74152** Thus the program must guarantee that the original will not change
74153** during the lifetime of the copy.  Use OP_Copy to make a complete
74154** copy.
74155*/
74156case OP_SCopy: {            /* out2 */
74157  pIn1 = &aMem[pOp->p1];
74158  pOut = &aMem[pOp->p2];
74159  assert( pOut!=pIn1 );
74160  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
74161#ifdef SQLITE_DEBUG
74162  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
74163#endif
74164  break;
74165}
74166
74167/* Opcode: ResultRow P1 P2 * * *
74168** Synopsis:  output=r[P1@P2]
74169**
74170** The registers P1 through P1+P2-1 contain a single row of
74171** results. This opcode causes the sqlite3_step() call to terminate
74172** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
74173** structure to provide access to the r(P1)..r(P1+P2-1) values as
74174** the result row.
74175*/
74176case OP_ResultRow: {
74177  Mem *pMem;
74178  int i;
74179  assert( p->nResColumn==pOp->p2 );
74180  assert( pOp->p1>0 );
74181  assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
74182
74183#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
74184  /* Run the progress counter just before returning.
74185  */
74186  if( db->xProgress!=0
74187   && nVmStep>=nProgressLimit
74188   && db->xProgress(db->pProgressArg)!=0
74189  ){
74190    rc = SQLITE_INTERRUPT;
74191    goto vdbe_error_halt;
74192  }
74193#endif
74194
74195  /* If this statement has violated immediate foreign key constraints, do
74196  ** not return the number of rows modified. And do not RELEASE the statement
74197  ** transaction. It needs to be rolled back.  */
74198  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
74199    assert( db->flags&SQLITE_CountRows );
74200    assert( p->usesStmtJournal );
74201    break;
74202  }
74203
74204  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
74205  ** DML statements invoke this opcode to return the number of rows
74206  ** modified to the user. This is the only way that a VM that
74207  ** opens a statement transaction may invoke this opcode.
74208  **
74209  ** In case this is such a statement, close any statement transaction
74210  ** opened by this VM before returning control to the user. This is to
74211  ** ensure that statement-transactions are always nested, not overlapping.
74212  ** If the open statement-transaction is not closed here, then the user
74213  ** may step another VM that opens its own statement transaction. This
74214  ** may lead to overlapping statement transactions.
74215  **
74216  ** The statement transaction is never a top-level transaction.  Hence
74217  ** the RELEASE call below can never fail.
74218  */
74219  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
74220  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
74221  if( NEVER(rc!=SQLITE_OK) ){
74222    break;
74223  }
74224
74225  /* Invalidate all ephemeral cursor row caches */
74226  p->cacheCtr = (p->cacheCtr + 2)|1;
74227
74228  /* Make sure the results of the current row are \000 terminated
74229  ** and have an assigned type.  The results are de-ephemeralized as
74230  ** a side effect.
74231  */
74232  pMem = p->pResultSet = &aMem[pOp->p1];
74233  for(i=0; i<pOp->p2; i++){
74234    assert( memIsValid(&pMem[i]) );
74235    Deephemeralize(&pMem[i]);
74236    assert( (pMem[i].flags & MEM_Ephem)==0
74237            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
74238    sqlite3VdbeMemNulTerminate(&pMem[i]);
74239    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
74240  }
74241  if( db->mallocFailed ) goto no_mem;
74242
74243  /* Return SQLITE_ROW
74244  */
74245  p->pc = (int)(pOp - aOp) + 1;
74246  rc = SQLITE_ROW;
74247  goto vdbe_return;
74248}
74249
74250/* Opcode: Concat P1 P2 P3 * *
74251** Synopsis: r[P3]=r[P2]+r[P1]
74252**
74253** Add the text in register P1 onto the end of the text in
74254** register P2 and store the result in register P3.
74255** If either the P1 or P2 text are NULL then store NULL in P3.
74256**
74257**   P3 = P2 || P1
74258**
74259** It is illegal for P1 and P3 to be the same register. Sometimes,
74260** if P3 is the same register as P2, the implementation is able
74261** to avoid a memcpy().
74262*/
74263case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
74264  i64 nByte;
74265
74266  pIn1 = &aMem[pOp->p1];
74267  pIn2 = &aMem[pOp->p2];
74268  pOut = &aMem[pOp->p3];
74269  assert( pIn1!=pOut );
74270  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
74271    sqlite3VdbeMemSetNull(pOut);
74272    break;
74273  }
74274  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
74275  Stringify(pIn1, encoding);
74276  Stringify(pIn2, encoding);
74277  nByte = pIn1->n + pIn2->n;
74278  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
74279    goto too_big;
74280  }
74281  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
74282    goto no_mem;
74283  }
74284  MemSetTypeFlag(pOut, MEM_Str);
74285  if( pOut!=pIn2 ){
74286    memcpy(pOut->z, pIn2->z, pIn2->n);
74287  }
74288  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
74289  pOut->z[nByte]=0;
74290  pOut->z[nByte+1] = 0;
74291  pOut->flags |= MEM_Term;
74292  pOut->n = (int)nByte;
74293  pOut->enc = encoding;
74294  UPDATE_MAX_BLOBSIZE(pOut);
74295  break;
74296}
74297
74298/* Opcode: Add P1 P2 P3 * *
74299** Synopsis:  r[P3]=r[P1]+r[P2]
74300**
74301** Add the value in register P1 to the value in register P2
74302** and store the result in register P3.
74303** If either input is NULL, the result is NULL.
74304*/
74305/* Opcode: Multiply P1 P2 P3 * *
74306** Synopsis:  r[P3]=r[P1]*r[P2]
74307**
74308**
74309** Multiply the value in register P1 by the value in register P2
74310** and store the result in register P3.
74311** If either input is NULL, the result is NULL.
74312*/
74313/* Opcode: Subtract P1 P2 P3 * *
74314** Synopsis:  r[P3]=r[P2]-r[P1]
74315**
74316** Subtract the value in register P1 from the value in register P2
74317** and store the result in register P3.
74318** If either input is NULL, the result is NULL.
74319*/
74320/* Opcode: Divide P1 P2 P3 * *
74321** Synopsis:  r[P3]=r[P2]/r[P1]
74322**
74323** Divide the value in register P1 by the value in register P2
74324** and store the result in register P3 (P3=P2/P1). If the value in
74325** register P1 is zero, then the result is NULL. If either input is
74326** NULL, the result is NULL.
74327*/
74328/* Opcode: Remainder P1 P2 P3 * *
74329** Synopsis:  r[P3]=r[P2]%r[P1]
74330**
74331** Compute the remainder after integer register P2 is divided by
74332** register P1 and store the result in register P3.
74333** If the value in register P1 is zero the result is NULL.
74334** If either operand is NULL, the result is NULL.
74335*/
74336case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
74337case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
74338case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
74339case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
74340case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
74341  char bIntint;   /* Started out as two integer operands */
74342  u16 flags;      /* Combined MEM_* flags from both inputs */
74343  u16 type1;      /* Numeric type of left operand */
74344  u16 type2;      /* Numeric type of right operand */
74345  i64 iA;         /* Integer value of left operand */
74346  i64 iB;         /* Integer value of right operand */
74347  double rA;      /* Real value of left operand */
74348  double rB;      /* Real value of right operand */
74349
74350  pIn1 = &aMem[pOp->p1];
74351  type1 = numericType(pIn1);
74352  pIn2 = &aMem[pOp->p2];
74353  type2 = numericType(pIn2);
74354  pOut = &aMem[pOp->p3];
74355  flags = pIn1->flags | pIn2->flags;
74356  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
74357  if( (type1 & type2 & MEM_Int)!=0 ){
74358    iA = pIn1->u.i;
74359    iB = pIn2->u.i;
74360    bIntint = 1;
74361    switch( pOp->opcode ){
74362      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
74363      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
74364      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
74365      case OP_Divide: {
74366        if( iA==0 ) goto arithmetic_result_is_null;
74367        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
74368        iB /= iA;
74369        break;
74370      }
74371      default: {
74372        if( iA==0 ) goto arithmetic_result_is_null;
74373        if( iA==-1 ) iA = 1;
74374        iB %= iA;
74375        break;
74376      }
74377    }
74378    pOut->u.i = iB;
74379    MemSetTypeFlag(pOut, MEM_Int);
74380  }else{
74381    bIntint = 0;
74382fp_math:
74383    rA = sqlite3VdbeRealValue(pIn1);
74384    rB = sqlite3VdbeRealValue(pIn2);
74385    switch( pOp->opcode ){
74386      case OP_Add:         rB += rA;       break;
74387      case OP_Subtract:    rB -= rA;       break;
74388      case OP_Multiply:    rB *= rA;       break;
74389      case OP_Divide: {
74390        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
74391        if( rA==(double)0 ) goto arithmetic_result_is_null;
74392        rB /= rA;
74393        break;
74394      }
74395      default: {
74396        iA = (i64)rA;
74397        iB = (i64)rB;
74398        if( iA==0 ) goto arithmetic_result_is_null;
74399        if( iA==-1 ) iA = 1;
74400        rB = (double)(iB % iA);
74401        break;
74402      }
74403    }
74404#ifdef SQLITE_OMIT_FLOATING_POINT
74405    pOut->u.i = rB;
74406    MemSetTypeFlag(pOut, MEM_Int);
74407#else
74408    if( sqlite3IsNaN(rB) ){
74409      goto arithmetic_result_is_null;
74410    }
74411    pOut->u.r = rB;
74412    MemSetTypeFlag(pOut, MEM_Real);
74413    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
74414      sqlite3VdbeIntegerAffinity(pOut);
74415    }
74416#endif
74417  }
74418  break;
74419
74420arithmetic_result_is_null:
74421  sqlite3VdbeMemSetNull(pOut);
74422  break;
74423}
74424
74425/* Opcode: CollSeq P1 * * P4
74426**
74427** P4 is a pointer to a CollSeq struct. If the next call to a user function
74428** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
74429** be returned. This is used by the built-in min(), max() and nullif()
74430** functions.
74431**
74432** If P1 is not zero, then it is a register that a subsequent min() or
74433** max() aggregate will set to 1 if the current row is not the minimum or
74434** maximum.  The P1 register is initialized to 0 by this instruction.
74435**
74436** The interface used by the implementation of the aforementioned functions
74437** to retrieve the collation sequence set by this opcode is not available
74438** publicly.  Only built-in functions have access to this feature.
74439*/
74440case OP_CollSeq: {
74441  assert( pOp->p4type==P4_COLLSEQ );
74442  if( pOp->p1 ){
74443    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
74444  }
74445  break;
74446}
74447
74448/* Opcode: Function0 P1 P2 P3 P4 P5
74449** Synopsis: r[P3]=func(r[P2@P5])
74450**
74451** Invoke a user function (P4 is a pointer to a FuncDef object that
74452** defines the function) with P5 arguments taken from register P2 and
74453** successors.  The result of the function is stored in register P3.
74454** Register P3 must not be one of the function inputs.
74455**
74456** P1 is a 32-bit bitmask indicating whether or not each argument to the
74457** function was determined to be constant at compile time. If the first
74458** argument was constant then bit 0 of P1 is set. This is used to determine
74459** whether meta data associated with a user function argument using the
74460** sqlite3_set_auxdata() API may be safely retained until the next
74461** invocation of this opcode.
74462**
74463** See also: Function, AggStep, AggFinal
74464*/
74465/* Opcode: Function P1 P2 P3 P4 P5
74466** Synopsis: r[P3]=func(r[P2@P5])
74467**
74468** Invoke a user function (P4 is a pointer to an sqlite3_context object that
74469** contains a pointer to the function to be run) with P5 arguments taken
74470** from register P2 and successors.  The result of the function is stored
74471** in register P3.  Register P3 must not be one of the function inputs.
74472**
74473** P1 is a 32-bit bitmask indicating whether or not each argument to the
74474** function was determined to be constant at compile time. If the first
74475** argument was constant then bit 0 of P1 is set. This is used to determine
74476** whether meta data associated with a user function argument using the
74477** sqlite3_set_auxdata() API may be safely retained until the next
74478** invocation of this opcode.
74479**
74480** SQL functions are initially coded as OP_Function0 with P4 pointing
74481** to a FuncDef object.  But on first evaluation, the P4 operand is
74482** automatically converted into an sqlite3_context object and the operation
74483** changed to this OP_Function opcode.  In this way, the initialization of
74484** the sqlite3_context object occurs only once, rather than once for each
74485** evaluation of the function.
74486**
74487** See also: Function0, AggStep, AggFinal
74488*/
74489case OP_Function0: {
74490  int n;
74491  sqlite3_context *pCtx;
74492
74493  assert( pOp->p4type==P4_FUNCDEF );
74494  n = pOp->p5;
74495  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74496  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
74497  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
74498  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
74499  if( pCtx==0 ) goto no_mem;
74500  pCtx->pOut = 0;
74501  pCtx->pFunc = pOp->p4.pFunc;
74502  pCtx->iOp = (int)(pOp - aOp);
74503  pCtx->pVdbe = p;
74504  pCtx->argc = n;
74505  pOp->p4type = P4_FUNCCTX;
74506  pOp->p4.pCtx = pCtx;
74507  pOp->opcode = OP_Function;
74508  /* Fall through into OP_Function */
74509}
74510case OP_Function: {
74511  int i;
74512  sqlite3_context *pCtx;
74513
74514  assert( pOp->p4type==P4_FUNCCTX );
74515  pCtx = pOp->p4.pCtx;
74516
74517  /* If this function is inside of a trigger, the register array in aMem[]
74518  ** might change from one evaluation to the next.  The next block of code
74519  ** checks to see if the register array has changed, and if so it
74520  ** reinitializes the relavant parts of the sqlite3_context object */
74521  pOut = &aMem[pOp->p3];
74522  if( pCtx->pOut != pOut ){
74523    pCtx->pOut = pOut;
74524    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
74525  }
74526
74527  memAboutToChange(p, pCtx->pOut);
74528#ifdef SQLITE_DEBUG
74529  for(i=0; i<pCtx->argc; i++){
74530    assert( memIsValid(pCtx->argv[i]) );
74531    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
74532  }
74533#endif
74534  MemSetTypeFlag(pCtx->pOut, MEM_Null);
74535  pCtx->fErrorOrAux = 0;
74536  db->lastRowid = lastRowid;
74537  (*pCtx->pFunc->xFunc)(pCtx, pCtx->argc, pCtx->argv); /* IMP: R-24505-23230 */
74538  lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
74539
74540  /* If the function returned an error, throw an exception */
74541  if( pCtx->fErrorOrAux ){
74542    if( pCtx->isError ){
74543      sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
74544      rc = pCtx->isError;
74545    }
74546    sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
74547  }
74548
74549  /* Copy the result of the function into register P3 */
74550  if( pOut->flags & (MEM_Str|MEM_Blob) ){
74551    sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
74552    if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
74553  }
74554
74555  REGISTER_TRACE(pOp->p3, pCtx->pOut);
74556  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
74557  break;
74558}
74559
74560/* Opcode: BitAnd P1 P2 P3 * *
74561** Synopsis:  r[P3]=r[P1]&r[P2]
74562**
74563** Take the bit-wise AND of the values in register P1 and P2 and
74564** store the result in register P3.
74565** If either input is NULL, the result is NULL.
74566*/
74567/* Opcode: BitOr P1 P2 P3 * *
74568** Synopsis:  r[P3]=r[P1]|r[P2]
74569**
74570** Take the bit-wise OR of the values in register P1 and P2 and
74571** store the result in register P3.
74572** If either input is NULL, the result is NULL.
74573*/
74574/* Opcode: ShiftLeft P1 P2 P3 * *
74575** Synopsis:  r[P3]=r[P2]<<r[P1]
74576**
74577** Shift the integer value in register P2 to the left by the
74578** number of bits specified by the integer in register P1.
74579** Store the result in register P3.
74580** If either input is NULL, the result is NULL.
74581*/
74582/* Opcode: ShiftRight P1 P2 P3 * *
74583** Synopsis:  r[P3]=r[P2]>>r[P1]
74584**
74585** Shift the integer value in register P2 to the right by the
74586** number of bits specified by the integer in register P1.
74587** Store the result in register P3.
74588** If either input is NULL, the result is NULL.
74589*/
74590case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
74591case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
74592case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
74593case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
74594  i64 iA;
74595  u64 uA;
74596  i64 iB;
74597  u8 op;
74598
74599  pIn1 = &aMem[pOp->p1];
74600  pIn2 = &aMem[pOp->p2];
74601  pOut = &aMem[pOp->p3];
74602  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
74603    sqlite3VdbeMemSetNull(pOut);
74604    break;
74605  }
74606  iA = sqlite3VdbeIntValue(pIn2);
74607  iB = sqlite3VdbeIntValue(pIn1);
74608  op = pOp->opcode;
74609  if( op==OP_BitAnd ){
74610    iA &= iB;
74611  }else if( op==OP_BitOr ){
74612    iA |= iB;
74613  }else if( iB!=0 ){
74614    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
74615
74616    /* If shifting by a negative amount, shift in the other direction */
74617    if( iB<0 ){
74618      assert( OP_ShiftRight==OP_ShiftLeft+1 );
74619      op = 2*OP_ShiftLeft + 1 - op;
74620      iB = iB>(-64) ? -iB : 64;
74621    }
74622
74623    if( iB>=64 ){
74624      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
74625    }else{
74626      memcpy(&uA, &iA, sizeof(uA));
74627      if( op==OP_ShiftLeft ){
74628        uA <<= iB;
74629      }else{
74630        uA >>= iB;
74631        /* Sign-extend on a right shift of a negative number */
74632        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
74633      }
74634      memcpy(&iA, &uA, sizeof(iA));
74635    }
74636  }
74637  pOut->u.i = iA;
74638  MemSetTypeFlag(pOut, MEM_Int);
74639  break;
74640}
74641
74642/* Opcode: AddImm  P1 P2 * * *
74643** Synopsis:  r[P1]=r[P1]+P2
74644**
74645** Add the constant P2 to the value in register P1.
74646** The result is always an integer.
74647**
74648** To force any register to be an integer, just add 0.
74649*/
74650case OP_AddImm: {            /* in1 */
74651  pIn1 = &aMem[pOp->p1];
74652  memAboutToChange(p, pIn1);
74653  sqlite3VdbeMemIntegerify(pIn1);
74654  pIn1->u.i += pOp->p2;
74655  break;
74656}
74657
74658/* Opcode: MustBeInt P1 P2 * * *
74659**
74660** Force the value in register P1 to be an integer.  If the value
74661** in P1 is not an integer and cannot be converted into an integer
74662** without data loss, then jump immediately to P2, or if P2==0
74663** raise an SQLITE_MISMATCH exception.
74664*/
74665case OP_MustBeInt: {            /* jump, in1 */
74666  pIn1 = &aMem[pOp->p1];
74667  if( (pIn1->flags & MEM_Int)==0 ){
74668    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
74669    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
74670    if( (pIn1->flags & MEM_Int)==0 ){
74671      if( pOp->p2==0 ){
74672        rc = SQLITE_MISMATCH;
74673        goto abort_due_to_error;
74674      }else{
74675        goto jump_to_p2;
74676      }
74677    }
74678  }
74679  MemSetTypeFlag(pIn1, MEM_Int);
74680  break;
74681}
74682
74683#ifndef SQLITE_OMIT_FLOATING_POINT
74684/* Opcode: RealAffinity P1 * * * *
74685**
74686** If register P1 holds an integer convert it to a real value.
74687**
74688** This opcode is used when extracting information from a column that
74689** has REAL affinity.  Such column values may still be stored as
74690** integers, for space efficiency, but after extraction we want them
74691** to have only a real value.
74692*/
74693case OP_RealAffinity: {                  /* in1 */
74694  pIn1 = &aMem[pOp->p1];
74695  if( pIn1->flags & MEM_Int ){
74696    sqlite3VdbeMemRealify(pIn1);
74697  }
74698  break;
74699}
74700#endif
74701
74702#ifndef SQLITE_OMIT_CAST
74703/* Opcode: Cast P1 P2 * * *
74704** Synopsis: affinity(r[P1])
74705**
74706** Force the value in register P1 to be the type defined by P2.
74707**
74708** <ul>
74709** <li value="97"> TEXT
74710** <li value="98"> BLOB
74711** <li value="99"> NUMERIC
74712** <li value="100"> INTEGER
74713** <li value="101"> REAL
74714** </ul>
74715**
74716** A NULL value is not changed by this routine.  It remains NULL.
74717*/
74718case OP_Cast: {                  /* in1 */
74719  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
74720  testcase( pOp->p2==SQLITE_AFF_TEXT );
74721  testcase( pOp->p2==SQLITE_AFF_BLOB );
74722  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
74723  testcase( pOp->p2==SQLITE_AFF_INTEGER );
74724  testcase( pOp->p2==SQLITE_AFF_REAL );
74725  pIn1 = &aMem[pOp->p1];
74726  memAboutToChange(p, pIn1);
74727  rc = ExpandBlob(pIn1);
74728  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
74729  UPDATE_MAX_BLOBSIZE(pIn1);
74730  break;
74731}
74732#endif /* SQLITE_OMIT_CAST */
74733
74734/* Opcode: Lt P1 P2 P3 P4 P5
74735** Synopsis: if r[P1]<r[P3] goto P2
74736**
74737** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
74738** jump to address P2.
74739**
74740** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
74741** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
74742** bit is clear then fall through if either operand is NULL.
74743**
74744** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
74745** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
74746** to coerce both inputs according to this affinity before the
74747** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
74748** affinity is used. Note that the affinity conversions are stored
74749** back into the input registers P1 and P3.  So this opcode can cause
74750** persistent changes to registers P1 and P3.
74751**
74752** Once any conversions have taken place, and neither value is NULL,
74753** the values are compared. If both values are blobs then memcmp() is
74754** used to determine the results of the comparison.  If both values
74755** are text, then the appropriate collating function specified in
74756** P4 is  used to do the comparison.  If P4 is not specified then
74757** memcmp() is used to compare text string.  If both values are
74758** numeric, then a numeric comparison is used. If the two values
74759** are of different types, then numbers are considered less than
74760** strings and strings are considered less than blobs.
74761**
74762** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
74763** store a boolean result (either 0, or 1, or NULL) in register P2.
74764**
74765** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
74766** equal to one another, provided that they do not have their MEM_Cleared
74767** bit set.
74768*/
74769/* Opcode: Ne P1 P2 P3 P4 P5
74770** Synopsis: if r[P1]!=r[P3] goto P2
74771**
74772** This works just like the Lt opcode except that the jump is taken if
74773** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
74774** additional information.
74775**
74776** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
74777** true or false and is never NULL.  If both operands are NULL then the result
74778** of comparison is false.  If either operand is NULL then the result is true.
74779** If neither operand is NULL the result is the same as it would be if
74780** the SQLITE_NULLEQ flag were omitted from P5.
74781*/
74782/* Opcode: Eq P1 P2 P3 P4 P5
74783** Synopsis: if r[P1]==r[P3] goto P2
74784**
74785** This works just like the Lt opcode except that the jump is taken if
74786** the operands in registers P1 and P3 are equal.
74787** See the Lt opcode for additional information.
74788**
74789** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
74790** true or false and is never NULL.  If both operands are NULL then the result
74791** of comparison is true.  If either operand is NULL then the result is false.
74792** If neither operand is NULL the result is the same as it would be if
74793** the SQLITE_NULLEQ flag were omitted from P5.
74794*/
74795/* Opcode: Le P1 P2 P3 P4 P5
74796** Synopsis: if r[P1]<=r[P3] goto P2
74797**
74798** This works just like the Lt opcode except that the jump is taken if
74799** the content of register P3 is less than or equal to the content of
74800** register P1.  See the Lt opcode for additional information.
74801*/
74802/* Opcode: Gt P1 P2 P3 P4 P5
74803** Synopsis: if r[P1]>r[P3] goto P2
74804**
74805** This works just like the Lt opcode except that the jump is taken if
74806** the content of register P3 is greater than the content of
74807** register P1.  See the Lt opcode for additional information.
74808*/
74809/* Opcode: Ge P1 P2 P3 P4 P5
74810** Synopsis: if r[P1]>=r[P3] goto P2
74811**
74812** This works just like the Lt opcode except that the jump is taken if
74813** the content of register P3 is greater than or equal to the content of
74814** register P1.  See the Lt opcode for additional information.
74815*/
74816case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
74817case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
74818case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
74819case OP_Le:               /* same as TK_LE, jump, in1, in3 */
74820case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
74821case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
74822  int res;            /* Result of the comparison of pIn1 against pIn3 */
74823  char affinity;      /* Affinity to use for comparison */
74824  u16 flags1;         /* Copy of initial value of pIn1->flags */
74825  u16 flags3;         /* Copy of initial value of pIn3->flags */
74826
74827  pIn1 = &aMem[pOp->p1];
74828  pIn3 = &aMem[pOp->p3];
74829  flags1 = pIn1->flags;
74830  flags3 = pIn3->flags;
74831  if( (flags1 | flags3)&MEM_Null ){
74832    /* One or both operands are NULL */
74833    if( pOp->p5 & SQLITE_NULLEQ ){
74834      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
74835      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
74836      ** or not both operands are null.
74837      */
74838      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
74839      assert( (flags1 & MEM_Cleared)==0 );
74840      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
74841      if( (flags1&MEM_Null)!=0
74842       && (flags3&MEM_Null)!=0
74843       && (flags3&MEM_Cleared)==0
74844      ){
74845        res = 0;  /* Results are equal */
74846      }else{
74847        res = 1;  /* Results are not equal */
74848      }
74849    }else{
74850      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
74851      ** then the result is always NULL.
74852      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
74853      */
74854      if( pOp->p5 & SQLITE_STOREP2 ){
74855        pOut = &aMem[pOp->p2];
74856        MemSetTypeFlag(pOut, MEM_Null);
74857        REGISTER_TRACE(pOp->p2, pOut);
74858      }else{
74859        VdbeBranchTaken(2,3);
74860        if( pOp->p5 & SQLITE_JUMPIFNULL ){
74861          goto jump_to_p2;
74862        }
74863      }
74864      break;
74865    }
74866  }else{
74867    /* Neither operand is NULL.  Do a comparison. */
74868    affinity = pOp->p5 & SQLITE_AFF_MASK;
74869    if( affinity>=SQLITE_AFF_NUMERIC ){
74870      if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74871        applyNumericAffinity(pIn1,0);
74872      }
74873      if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74874        applyNumericAffinity(pIn3,0);
74875      }
74876    }else if( affinity==SQLITE_AFF_TEXT ){
74877      if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
74878        testcase( pIn1->flags & MEM_Int );
74879        testcase( pIn1->flags & MEM_Real );
74880        sqlite3VdbeMemStringify(pIn1, encoding, 1);
74881        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
74882        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
74883      }
74884      if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
74885        testcase( pIn3->flags & MEM_Int );
74886        testcase( pIn3->flags & MEM_Real );
74887        sqlite3VdbeMemStringify(pIn3, encoding, 1);
74888        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
74889        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
74890      }
74891    }
74892    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
74893    if( pIn1->flags & MEM_Zero ){
74894      sqlite3VdbeMemExpandBlob(pIn1);
74895      flags1 &= ~MEM_Zero;
74896    }
74897    if( pIn3->flags & MEM_Zero ){
74898      sqlite3VdbeMemExpandBlob(pIn3);
74899      flags3 &= ~MEM_Zero;
74900    }
74901    if( db->mallocFailed ) goto no_mem;
74902    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
74903  }
74904  switch( pOp->opcode ){
74905    case OP_Eq:    res = res==0;     break;
74906    case OP_Ne:    res = res!=0;     break;
74907    case OP_Lt:    res = res<0;      break;
74908    case OP_Le:    res = res<=0;     break;
74909    case OP_Gt:    res = res>0;      break;
74910    default:       res = res>=0;     break;
74911  }
74912
74913  /* Undo any changes made by applyAffinity() to the input registers. */
74914  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
74915  pIn1->flags = flags1;
74916  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
74917  pIn3->flags = flags3;
74918
74919  if( pOp->p5 & SQLITE_STOREP2 ){
74920    pOut = &aMem[pOp->p2];
74921    memAboutToChange(p, pOut);
74922    MemSetTypeFlag(pOut, MEM_Int);
74923    pOut->u.i = res;
74924    REGISTER_TRACE(pOp->p2, pOut);
74925  }else{
74926    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
74927    if( res ){
74928      goto jump_to_p2;
74929    }
74930  }
74931  break;
74932}
74933
74934/* Opcode: Permutation * * * P4 *
74935**
74936** Set the permutation used by the OP_Compare operator to be the array
74937** of integers in P4.
74938**
74939** The permutation is only valid until the next OP_Compare that has
74940** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
74941** occur immediately prior to the OP_Compare.
74942*/
74943case OP_Permutation: {
74944  assert( pOp->p4type==P4_INTARRAY );
74945  assert( pOp->p4.ai );
74946  aPermute = pOp->p4.ai;
74947  break;
74948}
74949
74950/* Opcode: Compare P1 P2 P3 P4 P5
74951** Synopsis: r[P1@P3] <-> r[P2@P3]
74952**
74953** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
74954** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
74955** the comparison for use by the next OP_Jump instruct.
74956**
74957** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
74958** determined by the most recent OP_Permutation operator.  If the
74959** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
74960** order.
74961**
74962** P4 is a KeyInfo structure that defines collating sequences and sort
74963** orders for the comparison.  The permutation applies to registers
74964** only.  The KeyInfo elements are used sequentially.
74965**
74966** The comparison is a sort comparison, so NULLs compare equal,
74967** NULLs are less than numbers, numbers are less than strings,
74968** and strings are less than blobs.
74969*/
74970case OP_Compare: {
74971  int n;
74972  int i;
74973  int p1;
74974  int p2;
74975  const KeyInfo *pKeyInfo;
74976  int idx;
74977  CollSeq *pColl;    /* Collating sequence to use on this term */
74978  int bRev;          /* True for DESCENDING sort order */
74979
74980  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
74981  n = pOp->p3;
74982  pKeyInfo = pOp->p4.pKeyInfo;
74983  assert( n>0 );
74984  assert( pKeyInfo!=0 );
74985  p1 = pOp->p1;
74986  p2 = pOp->p2;
74987#if SQLITE_DEBUG
74988  if( aPermute ){
74989    int k, mx = 0;
74990    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
74991    assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
74992    assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
74993  }else{
74994    assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
74995    assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
74996  }
74997#endif /* SQLITE_DEBUG */
74998  for(i=0; i<n; i++){
74999    idx = aPermute ? aPermute[i] : i;
75000    assert( memIsValid(&aMem[p1+idx]) );
75001    assert( memIsValid(&aMem[p2+idx]) );
75002    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
75003    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
75004    assert( i<pKeyInfo->nField );
75005    pColl = pKeyInfo->aColl[i];
75006    bRev = pKeyInfo->aSortOrder[i];
75007    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
75008    if( iCompare ){
75009      if( bRev ) iCompare = -iCompare;
75010      break;
75011    }
75012  }
75013  aPermute = 0;
75014  break;
75015}
75016
75017/* Opcode: Jump P1 P2 P3 * *
75018**
75019** Jump to the instruction at address P1, P2, or P3 depending on whether
75020** in the most recent OP_Compare instruction the P1 vector was less than
75021** equal to, or greater than the P2 vector, respectively.
75022*/
75023case OP_Jump: {             /* jump */
75024  if( iCompare<0 ){
75025    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
75026  }else if( iCompare==0 ){
75027    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
75028  }else{
75029    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
75030  }
75031  break;
75032}
75033
75034/* Opcode: And P1 P2 P3 * *
75035** Synopsis: r[P3]=(r[P1] && r[P2])
75036**
75037** Take the logical AND of the values in registers P1 and P2 and
75038** write the result into register P3.
75039**
75040** If either P1 or P2 is 0 (false) then the result is 0 even if
75041** the other input is NULL.  A NULL and true or two NULLs give
75042** a NULL output.
75043*/
75044/* Opcode: Or P1 P2 P3 * *
75045** Synopsis: r[P3]=(r[P1] || r[P2])
75046**
75047** Take the logical OR of the values in register P1 and P2 and
75048** store the answer in register P3.
75049**
75050** If either P1 or P2 is nonzero (true) then the result is 1 (true)
75051** even if the other input is NULL.  A NULL and false or two NULLs
75052** give a NULL output.
75053*/
75054case OP_And:              /* same as TK_AND, in1, in2, out3 */
75055case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
75056  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
75057  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
75058
75059  pIn1 = &aMem[pOp->p1];
75060  if( pIn1->flags & MEM_Null ){
75061    v1 = 2;
75062  }else{
75063    v1 = sqlite3VdbeIntValue(pIn1)!=0;
75064  }
75065  pIn2 = &aMem[pOp->p2];
75066  if( pIn2->flags & MEM_Null ){
75067    v2 = 2;
75068  }else{
75069    v2 = sqlite3VdbeIntValue(pIn2)!=0;
75070  }
75071  if( pOp->opcode==OP_And ){
75072    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
75073    v1 = and_logic[v1*3+v2];
75074  }else{
75075    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
75076    v1 = or_logic[v1*3+v2];
75077  }
75078  pOut = &aMem[pOp->p3];
75079  if( v1==2 ){
75080    MemSetTypeFlag(pOut, MEM_Null);
75081  }else{
75082    pOut->u.i = v1;
75083    MemSetTypeFlag(pOut, MEM_Int);
75084  }
75085  break;
75086}
75087
75088/* Opcode: Not P1 P2 * * *
75089** Synopsis: r[P2]= !r[P1]
75090**
75091** Interpret the value in register P1 as a boolean value.  Store the
75092** boolean complement in register P2.  If the value in register P1 is
75093** NULL, then a NULL is stored in P2.
75094*/
75095case OP_Not: {                /* same as TK_NOT, in1, out2 */
75096  pIn1 = &aMem[pOp->p1];
75097  pOut = &aMem[pOp->p2];
75098  sqlite3VdbeMemSetNull(pOut);
75099  if( (pIn1->flags & MEM_Null)==0 ){
75100    pOut->flags = MEM_Int;
75101    pOut->u.i = !sqlite3VdbeIntValue(pIn1);
75102  }
75103  break;
75104}
75105
75106/* Opcode: BitNot P1 P2 * * *
75107** Synopsis: r[P1]= ~r[P1]
75108**
75109** Interpret the content of register P1 as an integer.  Store the
75110** ones-complement of the P1 value into register P2.  If P1 holds
75111** a NULL then store a NULL in P2.
75112*/
75113case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
75114  pIn1 = &aMem[pOp->p1];
75115  pOut = &aMem[pOp->p2];
75116  sqlite3VdbeMemSetNull(pOut);
75117  if( (pIn1->flags & MEM_Null)==0 ){
75118    pOut->flags = MEM_Int;
75119    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
75120  }
75121  break;
75122}
75123
75124/* Opcode: Once P1 P2 * * *
75125**
75126** Check the "once" flag number P1. If it is set, jump to instruction P2.
75127** Otherwise, set the flag and fall through to the next instruction.
75128** In other words, this opcode causes all following opcodes up through P2
75129** (but not including P2) to run just once and to be skipped on subsequent
75130** times through the loop.
75131**
75132** All "once" flags are initially cleared whenever a prepared statement
75133** first begins to run.
75134*/
75135case OP_Once: {             /* jump */
75136  assert( pOp->p1<p->nOnceFlag );
75137  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
75138  if( p->aOnceFlag[pOp->p1] ){
75139    goto jump_to_p2;
75140  }else{
75141    p->aOnceFlag[pOp->p1] = 1;
75142  }
75143  break;
75144}
75145
75146/* Opcode: If P1 P2 P3 * *
75147**
75148** Jump to P2 if the value in register P1 is true.  The value
75149** is considered true if it is numeric and non-zero.  If the value
75150** in P1 is NULL then take the jump if and only if P3 is non-zero.
75151*/
75152/* Opcode: IfNot P1 P2 P3 * *
75153**
75154** Jump to P2 if the value in register P1 is False.  The value
75155** is considered false if it has a numeric value of zero.  If the value
75156** in P1 is NULL then take the jump if and only if P3 is non-zero.
75157*/
75158case OP_If:                 /* jump, in1 */
75159case OP_IfNot: {            /* jump, in1 */
75160  int c;
75161  pIn1 = &aMem[pOp->p1];
75162  if( pIn1->flags & MEM_Null ){
75163    c = pOp->p3;
75164  }else{
75165#ifdef SQLITE_OMIT_FLOATING_POINT
75166    c = sqlite3VdbeIntValue(pIn1)!=0;
75167#else
75168    c = sqlite3VdbeRealValue(pIn1)!=0.0;
75169#endif
75170    if( pOp->opcode==OP_IfNot ) c = !c;
75171  }
75172  VdbeBranchTaken(c!=0, 2);
75173  if( c ){
75174    goto jump_to_p2;
75175  }
75176  break;
75177}
75178
75179/* Opcode: IsNull P1 P2 * * *
75180** Synopsis:  if r[P1]==NULL goto P2
75181**
75182** Jump to P2 if the value in register P1 is NULL.
75183*/
75184case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
75185  pIn1 = &aMem[pOp->p1];
75186  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
75187  if( (pIn1->flags & MEM_Null)!=0 ){
75188    goto jump_to_p2;
75189  }
75190  break;
75191}
75192
75193/* Opcode: NotNull P1 P2 * * *
75194** Synopsis: if r[P1]!=NULL goto P2
75195**
75196** Jump to P2 if the value in register P1 is not NULL.
75197*/
75198case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
75199  pIn1 = &aMem[pOp->p1];
75200  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
75201  if( (pIn1->flags & MEM_Null)==0 ){
75202    goto jump_to_p2;
75203  }
75204  break;
75205}
75206
75207/* Opcode: Column P1 P2 P3 P4 P5
75208** Synopsis:  r[P3]=PX
75209**
75210** Interpret the data that cursor P1 points to as a structure built using
75211** the MakeRecord instruction.  (See the MakeRecord opcode for additional
75212** information about the format of the data.)  Extract the P2-th column
75213** from this record.  If there are less that (P2+1)
75214** values in the record, extract a NULL.
75215**
75216** The value extracted is stored in register P3.
75217**
75218** If the column contains fewer than P2 fields, then extract a NULL.  Or,
75219** if the P4 argument is a P4_MEM use the value of the P4 argument as
75220** the result.
75221**
75222** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
75223** then the cache of the cursor is reset prior to extracting the column.
75224** The first OP_Column against a pseudo-table after the value of the content
75225** register has changed should have this bit set.
75226**
75227** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
75228** the result is guaranteed to only be used as the argument of a length()
75229** or typeof() function, respectively.  The loading of large blobs can be
75230** skipped for length() and all content loading can be skipped for typeof().
75231*/
75232case OP_Column: {
75233  i64 payloadSize64; /* Number of bytes in the record */
75234  int p2;            /* column number to retrieve */
75235  VdbeCursor *pC;    /* The VDBE cursor */
75236  BtCursor *pCrsr;   /* The BTree cursor */
75237  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
75238  int len;           /* The length of the serialized data for the column */
75239  int i;             /* Loop counter */
75240  Mem *pDest;        /* Where to write the extracted value */
75241  Mem sMem;          /* For storing the record being decoded */
75242  const u8 *zData;   /* Part of the record being decoded */
75243  const u8 *zHdr;    /* Next unparsed byte of the header */
75244  const u8 *zEndHdr; /* Pointer to first byte after the header */
75245  u32 offset;        /* Offset into the data */
75246  u32 szField;       /* Number of bytes in the content of a field */
75247  u32 avail;         /* Number of bytes of available data */
75248  u32 t;             /* A type code from the record header */
75249  u16 fx;            /* pDest->flags value */
75250  Mem *pReg;         /* PseudoTable input register */
75251
75252  p2 = pOp->p2;
75253  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75254  pDest = &aMem[pOp->p3];
75255  memAboutToChange(p, pDest);
75256  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75257  pC = p->apCsr[pOp->p1];
75258  assert( pC!=0 );
75259  assert( p2<pC->nField );
75260  aOffset = pC->aOffset;
75261#ifndef SQLITE_OMIT_VIRTUALTABLE
75262  assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
75263#endif
75264  pCrsr = pC->pCursor;
75265  assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
75266  assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
75267
75268  /* If the cursor cache is stale, bring it up-to-date */
75269  rc = sqlite3VdbeCursorMoveto(pC);
75270  if( rc ) goto abort_due_to_error;
75271  if( pC->cacheStatus!=p->cacheCtr ){
75272    if( pC->nullRow ){
75273      if( pCrsr==0 ){
75274        assert( pC->pseudoTableReg>0 );
75275        pReg = &aMem[pC->pseudoTableReg];
75276        assert( pReg->flags & MEM_Blob );
75277        assert( memIsValid(pReg) );
75278        pC->payloadSize = pC->szRow = avail = pReg->n;
75279        pC->aRow = (u8*)pReg->z;
75280      }else{
75281        sqlite3VdbeMemSetNull(pDest);
75282        goto op_column_out;
75283      }
75284    }else{
75285      assert( pCrsr );
75286      if( pC->isTable==0 ){
75287        assert( sqlite3BtreeCursorIsValid(pCrsr) );
75288        VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
75289        assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
75290        /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
75291        ** payload size, so it is impossible for payloadSize64 to be
75292        ** larger than 32 bits. */
75293        assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
75294        pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
75295        pC->payloadSize = (u32)payloadSize64;
75296      }else{
75297        assert( sqlite3BtreeCursorIsValid(pCrsr) );
75298        VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
75299        assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
75300        pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
75301      }
75302      assert( avail<=65536 );  /* Maximum page size is 64KiB */
75303      if( pC->payloadSize <= (u32)avail ){
75304        pC->szRow = pC->payloadSize;
75305      }else{
75306        pC->szRow = avail;
75307      }
75308      if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
75309        goto too_big;
75310      }
75311    }
75312    pC->cacheStatus = p->cacheCtr;
75313    pC->iHdrOffset = getVarint32(pC->aRow, offset);
75314    pC->nHdrParsed = 0;
75315    aOffset[0] = offset;
75316
75317    /* Make sure a corrupt database has not given us an oversize header.
75318    ** Do this now to avoid an oversize memory allocation.
75319    **
75320    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
75321    ** types use so much data space that there can only be 4096 and 32 of
75322    ** them, respectively.  So the maximum header length results from a
75323    ** 3-byte type for each of the maximum of 32768 columns plus three
75324    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
75325    */
75326    if( offset > 98307 || offset > pC->payloadSize ){
75327      rc = SQLITE_CORRUPT_BKPT;
75328      goto op_column_error;
75329    }
75330
75331    if( avail<offset ){
75332      /* pC->aRow does not have to hold the entire row, but it does at least
75333      ** need to cover the header of the record.  If pC->aRow does not contain
75334      ** the complete header, then set it to zero, forcing the header to be
75335      ** dynamically allocated. */
75336      pC->aRow = 0;
75337      pC->szRow = 0;
75338    }
75339
75340    /* The following goto is an optimization.  It can be omitted and
75341    ** everything will still work.  But OP_Column is measurably faster
75342    ** by skipping the subsequent conditional, which is always true.
75343    */
75344    assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
75345    goto op_column_read_header;
75346  }
75347
75348  /* Make sure at least the first p2+1 entries of the header have been
75349  ** parsed and valid information is in aOffset[] and pC->aType[].
75350  */
75351  if( pC->nHdrParsed<=p2 ){
75352    /* If there is more header available for parsing in the record, try
75353    ** to extract additional fields up through the p2+1-th field
75354    */
75355    op_column_read_header:
75356    if( pC->iHdrOffset<aOffset[0] ){
75357      /* Make sure zData points to enough of the record to cover the header. */
75358      if( pC->aRow==0 ){
75359        memset(&sMem, 0, sizeof(sMem));
75360        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
75361                                     !pC->isTable, &sMem);
75362        if( rc!=SQLITE_OK ){
75363          goto op_column_error;
75364        }
75365        zData = (u8*)sMem.z;
75366      }else{
75367        zData = pC->aRow;
75368      }
75369
75370      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
75371      i = pC->nHdrParsed;
75372      offset = aOffset[i];
75373      zHdr = zData + pC->iHdrOffset;
75374      zEndHdr = zData + aOffset[0];
75375      assert( i<=p2 && zHdr<zEndHdr );
75376      do{
75377        if( zHdr[0]<0x80 ){
75378          t = zHdr[0];
75379          zHdr++;
75380        }else{
75381          zHdr += sqlite3GetVarint32(zHdr, &t);
75382        }
75383        pC->aType[i] = t;
75384        szField = sqlite3VdbeSerialTypeLen(t);
75385        offset += szField;
75386        if( offset<szField ){  /* True if offset overflows */
75387          zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
75388          break;
75389        }
75390        i++;
75391        aOffset[i] = offset;
75392      }while( i<=p2 && zHdr<zEndHdr );
75393      pC->nHdrParsed = i;
75394      pC->iHdrOffset = (u32)(zHdr - zData);
75395      if( pC->aRow==0 ){
75396        sqlite3VdbeMemRelease(&sMem);
75397        sMem.flags = MEM_Null;
75398      }
75399
75400      /* The record is corrupt if any of the following are true:
75401      ** (1) the bytes of the header extend past the declared header size
75402      **          (zHdr>zEndHdr)
75403      ** (2) the entire header was used but not all data was used
75404      **          (zHdr==zEndHdr && offset!=pC->payloadSize)
75405      ** (3) the end of the data extends beyond the end of the record.
75406      **          (offset > pC->payloadSize)
75407      */
75408      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
75409       || (offset > pC->payloadSize)
75410      ){
75411        rc = SQLITE_CORRUPT_BKPT;
75412        goto op_column_error;
75413      }
75414    }
75415
75416    /* If after trying to extract new entries from the header, nHdrParsed is
75417    ** still not up to p2, that means that the record has fewer than p2
75418    ** columns.  So the result will be either the default value or a NULL.
75419    */
75420    if( pC->nHdrParsed<=p2 ){
75421      if( pOp->p4type==P4_MEM ){
75422        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
75423      }else{
75424        sqlite3VdbeMemSetNull(pDest);
75425      }
75426      goto op_column_out;
75427    }
75428  }
75429
75430  /* Extract the content for the p2+1-th column.  Control can only
75431  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
75432  ** all valid.
75433  */
75434  assert( p2<pC->nHdrParsed );
75435  assert( rc==SQLITE_OK );
75436  assert( sqlite3VdbeCheckMemInvariants(pDest) );
75437  if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
75438  t = pC->aType[p2];
75439  if( pC->szRow>=aOffset[p2+1] ){
75440    /* This is the common case where the desired content fits on the original
75441    ** page - where the content is not on an overflow page */
75442    sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
75443  }else{
75444    /* This branch happens only when content is on overflow pages */
75445    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
75446          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
75447     || (len = sqlite3VdbeSerialTypeLen(t))==0
75448    ){
75449      /* Content is irrelevant for
75450      **    1. the typeof() function,
75451      **    2. the length(X) function if X is a blob, and
75452      **    3. if the content length is zero.
75453      ** So we might as well use bogus content rather than reading
75454      ** content from disk.  NULL will work for the value for strings
75455      ** and blobs and whatever is in the payloadSize64 variable
75456      ** will work for everything else. */
75457      sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
75458    }else{
75459      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
75460                                   pDest);
75461      if( rc!=SQLITE_OK ){
75462        goto op_column_error;
75463      }
75464      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
75465      pDest->flags &= ~MEM_Ephem;
75466    }
75467  }
75468  pDest->enc = encoding;
75469
75470op_column_out:
75471  /* If the column value is an ephemeral string, go ahead and persist
75472  ** that string in case the cursor moves before the column value is
75473  ** used.  The following code does the equivalent of Deephemeralize()
75474  ** but does it faster. */
75475  if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
75476    fx = pDest->flags & (MEM_Str|MEM_Blob);
75477    assert( fx!=0 );
75478    zData = (const u8*)pDest->z;
75479    len = pDest->n;
75480    if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
75481    memcpy(pDest->z, zData, len);
75482    pDest->z[len] = 0;
75483    pDest->z[len+1] = 0;
75484    pDest->flags = fx|MEM_Term;
75485  }
75486op_column_error:
75487  UPDATE_MAX_BLOBSIZE(pDest);
75488  REGISTER_TRACE(pOp->p3, pDest);
75489  break;
75490}
75491
75492/* Opcode: Affinity P1 P2 * P4 *
75493** Synopsis: affinity(r[P1@P2])
75494**
75495** Apply affinities to a range of P2 registers starting with P1.
75496**
75497** P4 is a string that is P2 characters long. The nth character of the
75498** string indicates the column affinity that should be used for the nth
75499** memory cell in the range.
75500*/
75501case OP_Affinity: {
75502  const char *zAffinity;   /* The affinity to be applied */
75503  char cAff;               /* A single character of affinity */
75504
75505  zAffinity = pOp->p4.z;
75506  assert( zAffinity!=0 );
75507  assert( zAffinity[pOp->p2]==0 );
75508  pIn1 = &aMem[pOp->p1];
75509  while( (cAff = *(zAffinity++))!=0 ){
75510    assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
75511    assert( memIsValid(pIn1) );
75512    applyAffinity(pIn1, cAff, encoding);
75513    pIn1++;
75514  }
75515  break;
75516}
75517
75518/* Opcode: MakeRecord P1 P2 P3 P4 *
75519** Synopsis: r[P3]=mkrec(r[P1@P2])
75520**
75521** Convert P2 registers beginning with P1 into the [record format]
75522** use as a data record in a database table or as a key
75523** in an index.  The OP_Column opcode can decode the record later.
75524**
75525** P4 may be a string that is P2 characters long.  The nth character of the
75526** string indicates the column affinity that should be used for the nth
75527** field of the index key.
75528**
75529** The mapping from character to affinity is given by the SQLITE_AFF_
75530** macros defined in sqliteInt.h.
75531**
75532** If P4 is NULL then all index fields have the affinity BLOB.
75533*/
75534case OP_MakeRecord: {
75535  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
75536  Mem *pRec;             /* The new record */
75537  u64 nData;             /* Number of bytes of data space */
75538  int nHdr;              /* Number of bytes of header space */
75539  i64 nByte;             /* Data space required for this record */
75540  i64 nZero;             /* Number of zero bytes at the end of the record */
75541  int nVarint;           /* Number of bytes in a varint */
75542  u32 serial_type;       /* Type field */
75543  Mem *pData0;           /* First field to be combined into the record */
75544  Mem *pLast;            /* Last field of the record */
75545  int nField;            /* Number of fields in the record */
75546  char *zAffinity;       /* The affinity string for the record */
75547  int file_format;       /* File format to use for encoding */
75548  int i;                 /* Space used in zNewRecord[] header */
75549  int j;                 /* Space used in zNewRecord[] content */
75550  int len;               /* Length of a field */
75551
75552  /* Assuming the record contains N fields, the record format looks
75553  ** like this:
75554  **
75555  ** ------------------------------------------------------------------------
75556  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
75557  ** ------------------------------------------------------------------------
75558  **
75559  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
75560  ** and so forth.
75561  **
75562  ** Each type field is a varint representing the serial type of the
75563  ** corresponding data element (see sqlite3VdbeSerialType()). The
75564  ** hdr-size field is also a varint which is the offset from the beginning
75565  ** of the record to data0.
75566  */
75567  nData = 0;         /* Number of bytes of data space */
75568  nHdr = 0;          /* Number of bytes of header space */
75569  nZero = 0;         /* Number of zero bytes at the end of the record */
75570  nField = pOp->p1;
75571  zAffinity = pOp->p4.z;
75572  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
75573  pData0 = &aMem[nField];
75574  nField = pOp->p2;
75575  pLast = &pData0[nField-1];
75576  file_format = p->minWriteFileFormat;
75577
75578  /* Identify the output register */
75579  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
75580  pOut = &aMem[pOp->p3];
75581  memAboutToChange(p, pOut);
75582
75583  /* Apply the requested affinity to all inputs
75584  */
75585  assert( pData0<=pLast );
75586  if( zAffinity ){
75587    pRec = pData0;
75588    do{
75589      applyAffinity(pRec++, *(zAffinity++), encoding);
75590      assert( zAffinity[0]==0 || pRec<=pLast );
75591    }while( zAffinity[0] );
75592  }
75593
75594  /* Loop through the elements that will make up the record to figure
75595  ** out how much space is required for the new record.
75596  */
75597  pRec = pLast;
75598  do{
75599    assert( memIsValid(pRec) );
75600    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
75601    len = sqlite3VdbeSerialTypeLen(serial_type);
75602    if( pRec->flags & MEM_Zero ){
75603      if( nData ){
75604        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
75605      }else{
75606        nZero += pRec->u.nZero;
75607        len -= pRec->u.nZero;
75608      }
75609    }
75610    nData += len;
75611    testcase( serial_type==127 );
75612    testcase( serial_type==128 );
75613    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
75614  }while( (--pRec)>=pData0 );
75615
75616  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
75617  ** which determines the total number of bytes in the header. The varint
75618  ** value is the size of the header in bytes including the size varint
75619  ** itself. */
75620  testcase( nHdr==126 );
75621  testcase( nHdr==127 );
75622  if( nHdr<=126 ){
75623    /* The common case */
75624    nHdr += 1;
75625  }else{
75626    /* Rare case of a really large header */
75627    nVarint = sqlite3VarintLen(nHdr);
75628    nHdr += nVarint;
75629    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
75630  }
75631  nByte = nHdr+nData;
75632  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
75633    goto too_big;
75634  }
75635
75636  /* Make sure the output register has a buffer large enough to store
75637  ** the new record. The output register (pOp->p3) is not allowed to
75638  ** be one of the input registers (because the following call to
75639  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
75640  */
75641  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
75642    goto no_mem;
75643  }
75644  zNewRecord = (u8 *)pOut->z;
75645
75646  /* Write the record */
75647  i = putVarint32(zNewRecord, nHdr);
75648  j = nHdr;
75649  assert( pData0<=pLast );
75650  pRec = pData0;
75651  do{
75652    serial_type = pRec->uTemp;
75653    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
75654    ** additional varints, one per column. */
75655    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
75656    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
75657    ** immediately follow the header. */
75658    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
75659  }while( (++pRec)<=pLast );
75660  assert( i==nHdr );
75661  assert( j==nByte );
75662
75663  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75664  pOut->n = (int)nByte;
75665  pOut->flags = MEM_Blob;
75666  if( nZero ){
75667    pOut->u.nZero = nZero;
75668    pOut->flags |= MEM_Zero;
75669  }
75670  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
75671  REGISTER_TRACE(pOp->p3, pOut);
75672  UPDATE_MAX_BLOBSIZE(pOut);
75673  break;
75674}
75675
75676/* Opcode: Count P1 P2 * * *
75677** Synopsis: r[P2]=count()
75678**
75679** Store the number of entries (an integer value) in the table or index
75680** opened by cursor P1 in register P2
75681*/
75682#ifndef SQLITE_OMIT_BTREECOUNT
75683case OP_Count: {         /* out2 */
75684  i64 nEntry;
75685  BtCursor *pCrsr;
75686
75687  pCrsr = p->apCsr[pOp->p1]->pCursor;
75688  assert( pCrsr );
75689  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
75690  rc = sqlite3BtreeCount(pCrsr, &nEntry);
75691  pOut = out2Prerelease(p, pOp);
75692  pOut->u.i = nEntry;
75693  break;
75694}
75695#endif
75696
75697/* Opcode: Savepoint P1 * * P4 *
75698**
75699** Open, release or rollback the savepoint named by parameter P4, depending
75700** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
75701** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
75702*/
75703case OP_Savepoint: {
75704  int p1;                         /* Value of P1 operand */
75705  char *zName;                    /* Name of savepoint */
75706  int nName;
75707  Savepoint *pNew;
75708  Savepoint *pSavepoint;
75709  Savepoint *pTmp;
75710  int iSavepoint;
75711  int ii;
75712
75713  p1 = pOp->p1;
75714  zName = pOp->p4.z;
75715
75716  /* Assert that the p1 parameter is valid. Also that if there is no open
75717  ** transaction, then there cannot be any savepoints.
75718  */
75719  assert( db->pSavepoint==0 || db->autoCommit==0 );
75720  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
75721  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
75722  assert( checkSavepointCount(db) );
75723  assert( p->bIsReader );
75724
75725  if( p1==SAVEPOINT_BEGIN ){
75726    if( db->nVdbeWrite>0 ){
75727      /* A new savepoint cannot be created if there are active write
75728      ** statements (i.e. open read/write incremental blob handles).
75729      */
75730      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
75731      rc = SQLITE_BUSY;
75732    }else{
75733      nName = sqlite3Strlen30(zName);
75734
75735#ifndef SQLITE_OMIT_VIRTUALTABLE
75736      /* This call is Ok even if this savepoint is actually a transaction
75737      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
75738      ** If this is a transaction savepoint being opened, it is guaranteed
75739      ** that the db->aVTrans[] array is empty.  */
75740      assert( db->autoCommit==0 || db->nVTrans==0 );
75741      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
75742                                db->nStatement+db->nSavepoint);
75743      if( rc!=SQLITE_OK ) goto abort_due_to_error;
75744#endif
75745
75746      /* Create a new savepoint structure. */
75747      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
75748      if( pNew ){
75749        pNew->zName = (char *)&pNew[1];
75750        memcpy(pNew->zName, zName, nName+1);
75751
75752        /* If there is no open transaction, then mark this as a special
75753        ** "transaction savepoint". */
75754        if( db->autoCommit ){
75755          db->autoCommit = 0;
75756          db->isTransactionSavepoint = 1;
75757        }else{
75758          db->nSavepoint++;
75759        }
75760
75761        /* Link the new savepoint into the database handle's list. */
75762        pNew->pNext = db->pSavepoint;
75763        db->pSavepoint = pNew;
75764        pNew->nDeferredCons = db->nDeferredCons;
75765        pNew->nDeferredImmCons = db->nDeferredImmCons;
75766      }
75767    }
75768  }else{
75769    iSavepoint = 0;
75770
75771    /* Find the named savepoint. If there is no such savepoint, then an
75772    ** an error is returned to the user.  */
75773    for(
75774      pSavepoint = db->pSavepoint;
75775      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
75776      pSavepoint = pSavepoint->pNext
75777    ){
75778      iSavepoint++;
75779    }
75780    if( !pSavepoint ){
75781      sqlite3VdbeError(p, "no such savepoint: %s", zName);
75782      rc = SQLITE_ERROR;
75783    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
75784      /* It is not possible to release (commit) a savepoint if there are
75785      ** active write statements.
75786      */
75787      sqlite3VdbeError(p, "cannot release savepoint - "
75788                          "SQL statements in progress");
75789      rc = SQLITE_BUSY;
75790    }else{
75791
75792      /* Determine whether or not this is a transaction savepoint. If so,
75793      ** and this is a RELEASE command, then the current transaction
75794      ** is committed.
75795      */
75796      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
75797      if( isTransaction && p1==SAVEPOINT_RELEASE ){
75798        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
75799          goto vdbe_return;
75800        }
75801        db->autoCommit = 1;
75802        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
75803          p->pc = (int)(pOp - aOp);
75804          db->autoCommit = 0;
75805          p->rc = rc = SQLITE_BUSY;
75806          goto vdbe_return;
75807        }
75808        db->isTransactionSavepoint = 0;
75809        rc = p->rc;
75810      }else{
75811        int isSchemaChange;
75812        iSavepoint = db->nSavepoint - iSavepoint - 1;
75813        if( p1==SAVEPOINT_ROLLBACK ){
75814          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
75815          for(ii=0; ii<db->nDb; ii++){
75816            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
75817                                       SQLITE_ABORT_ROLLBACK,
75818                                       isSchemaChange==0);
75819            if( rc!=SQLITE_OK ) goto abort_due_to_error;
75820          }
75821        }else{
75822          isSchemaChange = 0;
75823        }
75824        for(ii=0; ii<db->nDb; ii++){
75825          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
75826          if( rc!=SQLITE_OK ){
75827            goto abort_due_to_error;
75828          }
75829        }
75830        if( isSchemaChange ){
75831          sqlite3ExpirePreparedStatements(db);
75832          sqlite3ResetAllSchemasOfConnection(db);
75833          db->flags = (db->flags | SQLITE_InternChanges);
75834        }
75835      }
75836
75837      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
75838      ** savepoints nested inside of the savepoint being operated on. */
75839      while( db->pSavepoint!=pSavepoint ){
75840        pTmp = db->pSavepoint;
75841        db->pSavepoint = pTmp->pNext;
75842        sqlite3DbFree(db, pTmp);
75843        db->nSavepoint--;
75844      }
75845
75846      /* If it is a RELEASE, then destroy the savepoint being operated on
75847      ** too. If it is a ROLLBACK TO, then set the number of deferred
75848      ** constraint violations present in the database to the value stored
75849      ** when the savepoint was created.  */
75850      if( p1==SAVEPOINT_RELEASE ){
75851        assert( pSavepoint==db->pSavepoint );
75852        db->pSavepoint = pSavepoint->pNext;
75853        sqlite3DbFree(db, pSavepoint);
75854        if( !isTransaction ){
75855          db->nSavepoint--;
75856        }
75857      }else{
75858        db->nDeferredCons = pSavepoint->nDeferredCons;
75859        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
75860      }
75861
75862      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
75863        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
75864        if( rc!=SQLITE_OK ) goto abort_due_to_error;
75865      }
75866    }
75867  }
75868
75869  break;
75870}
75871
75872/* Opcode: AutoCommit P1 P2 * * *
75873**
75874** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
75875** back any currently active btree transactions. If there are any active
75876** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
75877** there are active writing VMs or active VMs that use shared cache.
75878**
75879** This instruction causes the VM to halt.
75880*/
75881case OP_AutoCommit: {
75882  int desiredAutoCommit;
75883  int iRollback;
75884  int turnOnAC;
75885
75886  desiredAutoCommit = pOp->p1;
75887  iRollback = pOp->p2;
75888  turnOnAC = desiredAutoCommit && !db->autoCommit;
75889  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
75890  assert( desiredAutoCommit==1 || iRollback==0 );
75891  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
75892  assert( p->bIsReader );
75893
75894  if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
75895    /* If this instruction implements a COMMIT and other VMs are writing
75896    ** return an error indicating that the other VMs must complete first.
75897    */
75898    sqlite3VdbeError(p, "cannot commit transaction - "
75899                        "SQL statements in progress");
75900    rc = SQLITE_BUSY;
75901  }else if( desiredAutoCommit!=db->autoCommit ){
75902    if( iRollback ){
75903      assert( desiredAutoCommit==1 );
75904      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
75905      db->autoCommit = 1;
75906    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
75907      goto vdbe_return;
75908    }else{
75909      db->autoCommit = (u8)desiredAutoCommit;
75910    }
75911    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
75912      p->pc = (int)(pOp - aOp);
75913      db->autoCommit = (u8)(1-desiredAutoCommit);
75914      p->rc = rc = SQLITE_BUSY;
75915      goto vdbe_return;
75916    }
75917    assert( db->nStatement==0 );
75918    sqlite3CloseSavepoints(db);
75919    if( p->rc==SQLITE_OK ){
75920      rc = SQLITE_DONE;
75921    }else{
75922      rc = SQLITE_ERROR;
75923    }
75924    goto vdbe_return;
75925  }else{
75926    sqlite3VdbeError(p,
75927        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
75928        (iRollback)?"cannot rollback - no transaction is active":
75929                   "cannot commit - no transaction is active"));
75930
75931    rc = SQLITE_ERROR;
75932  }
75933  break;
75934}
75935
75936/* Opcode: Transaction P1 P2 P3 P4 P5
75937**
75938** Begin a transaction on database P1 if a transaction is not already
75939** active.
75940** If P2 is non-zero, then a write-transaction is started, or if a
75941** read-transaction is already active, it is upgraded to a write-transaction.
75942** If P2 is zero, then a read-transaction is started.
75943**
75944** P1 is the index of the database file on which the transaction is
75945** started.  Index 0 is the main database file and index 1 is the
75946** file used for temporary tables.  Indices of 2 or more are used for
75947** attached databases.
75948**
75949** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
75950** true (this flag is set if the Vdbe may modify more than one row and may
75951** throw an ABORT exception), a statement transaction may also be opened.
75952** More specifically, a statement transaction is opened iff the database
75953** connection is currently not in autocommit mode, or if there are other
75954** active statements. A statement transaction allows the changes made by this
75955** VDBE to be rolled back after an error without having to roll back the
75956** entire transaction. If no error is encountered, the statement transaction
75957** will automatically commit when the VDBE halts.
75958**
75959** If P5!=0 then this opcode also checks the schema cookie against P3
75960** and the schema generation counter against P4.
75961** The cookie changes its value whenever the database schema changes.
75962** This operation is used to detect when that the cookie has changed
75963** and that the current process needs to reread the schema.  If the schema
75964** cookie in P3 differs from the schema cookie in the database header or
75965** if the schema generation counter in P4 differs from the current
75966** generation counter, then an SQLITE_SCHEMA error is raised and execution
75967** halts.  The sqlite3_step() wrapper function might then reprepare the
75968** statement and rerun it from the beginning.
75969*/
75970case OP_Transaction: {
75971  Btree *pBt;
75972  int iMeta;
75973  int iGen;
75974
75975  assert( p->bIsReader );
75976  assert( p->readOnly==0 || pOp->p2==0 );
75977  assert( pOp->p1>=0 && pOp->p1<db->nDb );
75978  assert( DbMaskTest(p->btreeMask, pOp->p1) );
75979  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
75980    rc = SQLITE_READONLY;
75981    goto abort_due_to_error;
75982  }
75983  pBt = db->aDb[pOp->p1].pBt;
75984
75985  if( pBt ){
75986    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
75987    testcase( rc==SQLITE_BUSY_SNAPSHOT );
75988    testcase( rc==SQLITE_BUSY_RECOVERY );
75989    if( (rc&0xff)==SQLITE_BUSY ){
75990      p->pc = (int)(pOp - aOp);
75991      p->rc = rc;
75992      goto vdbe_return;
75993    }
75994    if( rc!=SQLITE_OK ){
75995      goto abort_due_to_error;
75996    }
75997
75998    if( pOp->p2 && p->usesStmtJournal
75999     && (db->autoCommit==0 || db->nVdbeRead>1)
76000    ){
76001      assert( sqlite3BtreeIsInTrans(pBt) );
76002      if( p->iStatement==0 ){
76003        assert( db->nStatement>=0 && db->nSavepoint>=0 );
76004        db->nStatement++;
76005        p->iStatement = db->nSavepoint + db->nStatement;
76006      }
76007
76008      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
76009      if( rc==SQLITE_OK ){
76010        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
76011      }
76012
76013      /* Store the current value of the database handles deferred constraint
76014      ** counter. If the statement transaction needs to be rolled back,
76015      ** the value of this counter needs to be restored too.  */
76016      p->nStmtDefCons = db->nDeferredCons;
76017      p->nStmtDefImmCons = db->nDeferredImmCons;
76018    }
76019
76020    /* Gather the schema version number for checking:
76021    ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
76022    ** each time a query is executed to ensure that the internal cache of the
76023    ** schema used when compiling the SQL query matches the schema of the
76024    ** database against which the compiled query is actually executed.
76025    */
76026    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
76027    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
76028  }else{
76029    iGen = iMeta = 0;
76030  }
76031  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
76032  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
76033    sqlite3DbFree(db, p->zErrMsg);
76034    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
76035    /* If the schema-cookie from the database file matches the cookie
76036    ** stored with the in-memory representation of the schema, do
76037    ** not reload the schema from the database file.
76038    **
76039    ** If virtual-tables are in use, this is not just an optimization.
76040    ** Often, v-tables store their data in other SQLite tables, which
76041    ** are queried from within xNext() and other v-table methods using
76042    ** prepared queries. If such a query is out-of-date, we do not want to
76043    ** discard the database schema, as the user code implementing the
76044    ** v-table would have to be ready for the sqlite3_vtab structure itself
76045    ** to be invalidated whenever sqlite3_step() is called from within
76046    ** a v-table method.
76047    */
76048    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
76049      sqlite3ResetOneSchema(db, pOp->p1);
76050    }
76051    p->expired = 1;
76052    rc = SQLITE_SCHEMA;
76053  }
76054  break;
76055}
76056
76057/* Opcode: ReadCookie P1 P2 P3 * *
76058**
76059** Read cookie number P3 from database P1 and write it into register P2.
76060** P3==1 is the schema version.  P3==2 is the database format.
76061** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
76062** the main database file and P1==1 is the database file used to store
76063** temporary tables.
76064**
76065** There must be a read-lock on the database (either a transaction
76066** must be started or there must be an open cursor) before
76067** executing this instruction.
76068*/
76069case OP_ReadCookie: {               /* out2 */
76070  int iMeta;
76071  int iDb;
76072  int iCookie;
76073
76074  assert( p->bIsReader );
76075  iDb = pOp->p1;
76076  iCookie = pOp->p3;
76077  assert( pOp->p3<SQLITE_N_BTREE_META );
76078  assert( iDb>=0 && iDb<db->nDb );
76079  assert( db->aDb[iDb].pBt!=0 );
76080  assert( DbMaskTest(p->btreeMask, iDb) );
76081
76082  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
76083  pOut = out2Prerelease(p, pOp);
76084  pOut->u.i = iMeta;
76085  break;
76086}
76087
76088/* Opcode: SetCookie P1 P2 P3 * *
76089**
76090** Write the content of register P3 (interpreted as an integer)
76091** into cookie number P2 of database P1.  P2==1 is the schema version.
76092** P2==2 is the database format. P2==3 is the recommended pager cache
76093** size, and so forth.  P1==0 is the main database file and P1==1 is the
76094** database file used to store temporary tables.
76095**
76096** A transaction must be started before executing this opcode.
76097*/
76098case OP_SetCookie: {       /* in3 */
76099  Db *pDb;
76100  assert( pOp->p2<SQLITE_N_BTREE_META );
76101  assert( pOp->p1>=0 && pOp->p1<db->nDb );
76102  assert( DbMaskTest(p->btreeMask, pOp->p1) );
76103  assert( p->readOnly==0 );
76104  pDb = &db->aDb[pOp->p1];
76105  assert( pDb->pBt!=0 );
76106  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
76107  pIn3 = &aMem[pOp->p3];
76108  sqlite3VdbeMemIntegerify(pIn3);
76109  /* See note about index shifting on OP_ReadCookie */
76110  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
76111  if( pOp->p2==BTREE_SCHEMA_VERSION ){
76112    /* When the schema cookie changes, record the new cookie internally */
76113    pDb->pSchema->schema_cookie = (int)pIn3->u.i;
76114    db->flags |= SQLITE_InternChanges;
76115  }else if( pOp->p2==BTREE_FILE_FORMAT ){
76116    /* Record changes in the file format */
76117    pDb->pSchema->file_format = (u8)pIn3->u.i;
76118  }
76119  if( pOp->p1==1 ){
76120    /* Invalidate all prepared statements whenever the TEMP database
76121    ** schema is changed.  Ticket #1644 */
76122    sqlite3ExpirePreparedStatements(db);
76123    p->expired = 0;
76124  }
76125  break;
76126}
76127
76128/* Opcode: OpenRead P1 P2 P3 P4 P5
76129** Synopsis: root=P2 iDb=P3
76130**
76131** Open a read-only cursor for the database table whose root page is
76132** P2 in a database file.  The database file is determined by P3.
76133** P3==0 means the main database, P3==1 means the database used for
76134** temporary tables, and P3>1 means used the corresponding attached
76135** database.  Give the new cursor an identifier of P1.  The P1
76136** values need not be contiguous but all P1 values should be small integers.
76137** It is an error for P1 to be negative.
76138**
76139** If P5!=0 then use the content of register P2 as the root page, not
76140** the value of P2 itself.
76141**
76142** There will be a read lock on the database whenever there is an
76143** open cursor.  If the database was unlocked prior to this instruction
76144** then a read lock is acquired as part of this instruction.  A read
76145** lock allows other processes to read the database but prohibits
76146** any other process from modifying the database.  The read lock is
76147** released when all cursors are closed.  If this instruction attempts
76148** to get a read lock but fails, the script terminates with an
76149** SQLITE_BUSY error code.
76150**
76151** The P4 value may be either an integer (P4_INT32) or a pointer to
76152** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
76153** structure, then said structure defines the content and collating
76154** sequence of the index being opened. Otherwise, if P4 is an integer
76155** value, it is set to the number of columns in the table.
76156**
76157** See also: OpenWrite, ReopenIdx
76158*/
76159/* Opcode: ReopenIdx P1 P2 P3 P4 P5
76160** Synopsis: root=P2 iDb=P3
76161**
76162** The ReopenIdx opcode works exactly like ReadOpen except that it first
76163** checks to see if the cursor on P1 is already open with a root page
76164** number of P2 and if it is this opcode becomes a no-op.  In other words,
76165** if the cursor is already open, do not reopen it.
76166**
76167** The ReopenIdx opcode may only be used with P5==0 and with P4 being
76168** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
76169** every other ReopenIdx or OpenRead for the same cursor number.
76170**
76171** See the OpenRead opcode documentation for additional information.
76172*/
76173/* Opcode: OpenWrite P1 P2 P3 P4 P5
76174** Synopsis: root=P2 iDb=P3
76175**
76176** Open a read/write cursor named P1 on the table or index whose root
76177** page is P2.  Or if P5!=0 use the content of register P2 to find the
76178** root page.
76179**
76180** The P4 value may be either an integer (P4_INT32) or a pointer to
76181** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
76182** structure, then said structure defines the content and collating
76183** sequence of the index being opened. Otherwise, if P4 is an integer
76184** value, it is set to the number of columns in the table, or to the
76185** largest index of any column of the table that is actually used.
76186**
76187** This instruction works just like OpenRead except that it opens the cursor
76188** in read/write mode.  For a given table, there can be one or more read-only
76189** cursors or a single read/write cursor but not both.
76190**
76191** See also OpenRead.
76192*/
76193case OP_ReopenIdx: {
76194  int nField;
76195  KeyInfo *pKeyInfo;
76196  int p2;
76197  int iDb;
76198  int wrFlag;
76199  Btree *pX;
76200  VdbeCursor *pCur;
76201  Db *pDb;
76202
76203  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
76204  assert( pOp->p4type==P4_KEYINFO );
76205  pCur = p->apCsr[pOp->p1];
76206  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
76207    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
76208    goto open_cursor_set_hints;
76209  }
76210  /* If the cursor is not currently open or is open on a different
76211  ** index, then fall through into OP_OpenRead to force a reopen */
76212case OP_OpenRead:
76213case OP_OpenWrite:
76214
76215  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
76216  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
76217  assert( p->bIsReader );
76218  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
76219          || p->readOnly==0 );
76220
76221  if( p->expired ){
76222    rc = SQLITE_ABORT_ROLLBACK;
76223    break;
76224  }
76225
76226  nField = 0;
76227  pKeyInfo = 0;
76228  p2 = pOp->p2;
76229  iDb = pOp->p3;
76230  assert( iDb>=0 && iDb<db->nDb );
76231  assert( DbMaskTest(p->btreeMask, iDb) );
76232  pDb = &db->aDb[iDb];
76233  pX = pDb->pBt;
76234  assert( pX!=0 );
76235  if( pOp->opcode==OP_OpenWrite ){
76236    wrFlag = 1;
76237    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76238    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
76239      p->minWriteFileFormat = pDb->pSchema->file_format;
76240    }
76241  }else{
76242    wrFlag = 0;
76243  }
76244  if( pOp->p5 & OPFLAG_P2ISREG ){
76245    assert( p2>0 );
76246    assert( p2<=(p->nMem-p->nCursor) );
76247    pIn2 = &aMem[p2];
76248    assert( memIsValid(pIn2) );
76249    assert( (pIn2->flags & MEM_Int)!=0 );
76250    sqlite3VdbeMemIntegerify(pIn2);
76251    p2 = (int)pIn2->u.i;
76252    /* The p2 value always comes from a prior OP_CreateTable opcode and
76253    ** that opcode will always set the p2 value to 2 or more or else fail.
76254    ** If there were a failure, the prepared statement would have halted
76255    ** before reaching this instruction. */
76256    if( NEVER(p2<2) ) {
76257      rc = SQLITE_CORRUPT_BKPT;
76258      goto abort_due_to_error;
76259    }
76260  }
76261  if( pOp->p4type==P4_KEYINFO ){
76262    pKeyInfo = pOp->p4.pKeyInfo;
76263    assert( pKeyInfo->enc==ENC(db) );
76264    assert( pKeyInfo->db==db );
76265    nField = pKeyInfo->nField+pKeyInfo->nXField;
76266  }else if( pOp->p4type==P4_INT32 ){
76267    nField = pOp->p4.i;
76268  }
76269  assert( pOp->p1>=0 );
76270  assert( nField>=0 );
76271  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
76272  pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
76273  if( pCur==0 ) goto no_mem;
76274  pCur->nullRow = 1;
76275  pCur->isOrdered = 1;
76276  pCur->pgnoRoot = p2;
76277  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
76278  pCur->pKeyInfo = pKeyInfo;
76279  /* Set the VdbeCursor.isTable variable. Previous versions of
76280  ** SQLite used to check if the root-page flags were sane at this point
76281  ** and report database corruption if they were not, but this check has
76282  ** since moved into the btree layer.  */
76283  pCur->isTable = pOp->p4type!=P4_KEYINFO;
76284
76285open_cursor_set_hints:
76286  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
76287  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
76288  sqlite3BtreeCursorHints(pCur->pCursor,
76289                          (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
76290  break;
76291}
76292
76293/* Opcode: OpenEphemeral P1 P2 * P4 P5
76294** Synopsis: nColumn=P2
76295**
76296** Open a new cursor P1 to a transient table.
76297** The cursor is always opened read/write even if
76298** the main database is read-only.  The ephemeral
76299** table is deleted automatically when the cursor is closed.
76300**
76301** P2 is the number of columns in the ephemeral table.
76302** The cursor points to a BTree table if P4==0 and to a BTree index
76303** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
76304** that defines the format of keys in the index.
76305**
76306** The P5 parameter can be a mask of the BTREE_* flags defined
76307** in btree.h.  These flags control aspects of the operation of
76308** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
76309** added automatically.
76310*/
76311/* Opcode: OpenAutoindex P1 P2 * P4 *
76312** Synopsis: nColumn=P2
76313**
76314** This opcode works the same as OP_OpenEphemeral.  It has a
76315** different name to distinguish its use.  Tables created using
76316** by this opcode will be used for automatically created transient
76317** indices in joins.
76318*/
76319case OP_OpenAutoindex:
76320case OP_OpenEphemeral: {
76321  VdbeCursor *pCx;
76322  KeyInfo *pKeyInfo;
76323
76324  static const int vfsFlags =
76325      SQLITE_OPEN_READWRITE |
76326      SQLITE_OPEN_CREATE |
76327      SQLITE_OPEN_EXCLUSIVE |
76328      SQLITE_OPEN_DELETEONCLOSE |
76329      SQLITE_OPEN_TRANSIENT_DB;
76330  assert( pOp->p1>=0 );
76331  assert( pOp->p2>=0 );
76332  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
76333  if( pCx==0 ) goto no_mem;
76334  pCx->nullRow = 1;
76335  pCx->isEphemeral = 1;
76336  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
76337                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
76338  if( rc==SQLITE_OK ){
76339    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
76340  }
76341  if( rc==SQLITE_OK ){
76342    /* If a transient index is required, create it by calling
76343    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
76344    ** opening it. If a transient table is required, just use the
76345    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
76346    */
76347    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
76348      int pgno;
76349      assert( pOp->p4type==P4_KEYINFO );
76350      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
76351      if( rc==SQLITE_OK ){
76352        assert( pgno==MASTER_ROOT+1 );
76353        assert( pKeyInfo->db==db );
76354        assert( pKeyInfo->enc==ENC(db) );
76355        pCx->pKeyInfo = pKeyInfo;
76356        rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
76357      }
76358      pCx->isTable = 0;
76359    }else{
76360      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
76361      pCx->isTable = 1;
76362    }
76363  }
76364  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
76365  break;
76366}
76367
76368/* Opcode: SorterOpen P1 P2 P3 P4 *
76369**
76370** This opcode works like OP_OpenEphemeral except that it opens
76371** a transient index that is specifically designed to sort large
76372** tables using an external merge-sort algorithm.
76373**
76374** If argument P3 is non-zero, then it indicates that the sorter may
76375** assume that a stable sort considering the first P3 fields of each
76376** key is sufficient to produce the required results.
76377*/
76378case OP_SorterOpen: {
76379  VdbeCursor *pCx;
76380
76381  assert( pOp->p1>=0 );
76382  assert( pOp->p2>=0 );
76383  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
76384  if( pCx==0 ) goto no_mem;
76385  pCx->pKeyInfo = pOp->p4.pKeyInfo;
76386  assert( pCx->pKeyInfo->db==db );
76387  assert( pCx->pKeyInfo->enc==ENC(db) );
76388  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
76389  break;
76390}
76391
76392/* Opcode: SequenceTest P1 P2 * * *
76393** Synopsis: if( cursor[P1].ctr++ ) pc = P2
76394**
76395** P1 is a sorter cursor. If the sequence counter is currently zero, jump
76396** to P2. Regardless of whether or not the jump is taken, increment the
76397** the sequence value.
76398*/
76399case OP_SequenceTest: {
76400  VdbeCursor *pC;
76401  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76402  pC = p->apCsr[pOp->p1];
76403  assert( pC->pSorter );
76404  if( (pC->seqCount++)==0 ){
76405    goto jump_to_p2;
76406  }
76407  break;
76408}
76409
76410/* Opcode: OpenPseudo P1 P2 P3 * *
76411** Synopsis: P3 columns in r[P2]
76412**
76413** Open a new cursor that points to a fake table that contains a single
76414** row of data.  The content of that one row is the content of memory
76415** register P2.  In other words, cursor P1 becomes an alias for the
76416** MEM_Blob content contained in register P2.
76417**
76418** A pseudo-table created by this opcode is used to hold a single
76419** row output from the sorter so that the row can be decomposed into
76420** individual columns using the OP_Column opcode.  The OP_Column opcode
76421** is the only cursor opcode that works with a pseudo-table.
76422**
76423** P3 is the number of fields in the records that will be stored by
76424** the pseudo-table.
76425*/
76426case OP_OpenPseudo: {
76427  VdbeCursor *pCx;
76428
76429  assert( pOp->p1>=0 );
76430  assert( pOp->p3>=0 );
76431  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
76432  if( pCx==0 ) goto no_mem;
76433  pCx->nullRow = 1;
76434  pCx->pseudoTableReg = pOp->p2;
76435  pCx->isTable = 1;
76436  assert( pOp->p5==0 );
76437  break;
76438}
76439
76440/* Opcode: Close P1 * * * *
76441**
76442** Close a cursor previously opened as P1.  If P1 is not
76443** currently open, this instruction is a no-op.
76444*/
76445case OP_Close: {
76446  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76447  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
76448  p->apCsr[pOp->p1] = 0;
76449  break;
76450}
76451
76452#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
76453/* Opcode: ColumnsUsed P1 * * P4 *
76454**
76455** This opcode (which only exists if SQLite was compiled with
76456** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
76457** table or index for cursor P1 are used.  P4 is a 64-bit integer
76458** (P4_INT64) in which the first 63 bits are one for each of the
76459** first 63 columns of the table or index that are actually used
76460** by the cursor.  The high-order bit is set if any column after
76461** the 64th is used.
76462*/
76463case OP_ColumnsUsed: {
76464  VdbeCursor *pC;
76465  pC = p->apCsr[pOp->p1];
76466  assert( pC->pCursor );
76467  pC->maskUsed = *(u64*)pOp->p4.pI64;
76468  break;
76469}
76470#endif
76471
76472/* Opcode: SeekGE P1 P2 P3 P4 *
76473** Synopsis: key=r[P3@P4]
76474**
76475** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
76476** use the value in register P3 as the key.  If cursor P1 refers
76477** to an SQL index, then P3 is the first in an array of P4 registers
76478** that are used as an unpacked index key.
76479**
76480** Reposition cursor P1 so that  it points to the smallest entry that
76481** is greater than or equal to the key value. If there are no records
76482** greater than or equal to the key and P2 is not zero, then jump to P2.
76483**
76484** This opcode leaves the cursor configured to move in forward order,
76485** from the beginning toward the end.  In other words, the cursor is
76486** configured to use Next, not Prev.
76487**
76488** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
76489*/
76490/* Opcode: SeekGT P1 P2 P3 P4 *
76491** Synopsis: key=r[P3@P4]
76492**
76493** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
76494** use the value in register P3 as a key. If cursor P1 refers
76495** to an SQL index, then P3 is the first in an array of P4 registers
76496** that are used as an unpacked index key.
76497**
76498** Reposition cursor P1 so that  it points to the smallest entry that
76499** is greater than the key value. If there are no records greater than
76500** the key and P2 is not zero, then jump to P2.
76501**
76502** This opcode leaves the cursor configured to move in forward order,
76503** from the beginning toward the end.  In other words, the cursor is
76504** configured to use Next, not Prev.
76505**
76506** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
76507*/
76508/* Opcode: SeekLT P1 P2 P3 P4 *
76509** Synopsis: key=r[P3@P4]
76510**
76511** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
76512** use the value in register P3 as a key. If cursor P1 refers
76513** to an SQL index, then P3 is the first in an array of P4 registers
76514** that are used as an unpacked index key.
76515**
76516** Reposition cursor P1 so that  it points to the largest entry that
76517** is less than the key value. If there are no records less than
76518** the key and P2 is not zero, then jump to P2.
76519**
76520** This opcode leaves the cursor configured to move in reverse order,
76521** from the end toward the beginning.  In other words, the cursor is
76522** configured to use Prev, not Next.
76523**
76524** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
76525*/
76526/* Opcode: SeekLE P1 P2 P3 P4 *
76527** Synopsis: key=r[P3@P4]
76528**
76529** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
76530** use the value in register P3 as a key. If cursor P1 refers
76531** to an SQL index, then P3 is the first in an array of P4 registers
76532** that are used as an unpacked index key.
76533**
76534** Reposition cursor P1 so that it points to the largest entry that
76535** is less than or equal to the key value. If there are no records
76536** less than or equal to the key and P2 is not zero, then jump to P2.
76537**
76538** This opcode leaves the cursor configured to move in reverse order,
76539** from the end toward the beginning.  In other words, the cursor is
76540** configured to use Prev, not Next.
76541**
76542** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
76543*/
76544case OP_SeekLT:         /* jump, in3 */
76545case OP_SeekLE:         /* jump, in3 */
76546case OP_SeekGE:         /* jump, in3 */
76547case OP_SeekGT: {       /* jump, in3 */
76548  int res;
76549  int oc;
76550  VdbeCursor *pC;
76551  UnpackedRecord r;
76552  int nField;
76553  i64 iKey;      /* The rowid we are to seek to */
76554
76555  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76556  assert( pOp->p2!=0 );
76557  pC = p->apCsr[pOp->p1];
76558  assert( pC!=0 );
76559  assert( pC->pseudoTableReg==0 );
76560  assert( OP_SeekLE == OP_SeekLT+1 );
76561  assert( OP_SeekGE == OP_SeekLT+2 );
76562  assert( OP_SeekGT == OP_SeekLT+3 );
76563  assert( pC->isOrdered );
76564  assert( pC->pCursor!=0 );
76565  oc = pOp->opcode;
76566  pC->nullRow = 0;
76567#ifdef SQLITE_DEBUG
76568  pC->seekOp = pOp->opcode;
76569#endif
76570
76571  /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
76572  ** OP_SeekLE opcodes are allowed, and these must be immediately followed
76573  ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
76574  */
76575#ifdef SQLITE_DEBUG
76576  if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
76577    assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
76578    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
76579    assert( pOp[1].p1==pOp[0].p1 );
76580    assert( pOp[1].p2==pOp[0].p2 );
76581    assert( pOp[1].p3==pOp[0].p3 );
76582    assert( pOp[1].p4.i==pOp[0].p4.i );
76583  }
76584#endif
76585
76586  if( pC->isTable ){
76587    /* The input value in P3 might be of any type: integer, real, string,
76588    ** blob, or NULL.  But it needs to be an integer before we can do
76589    ** the seek, so convert it. */
76590    pIn3 = &aMem[pOp->p3];
76591    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76592      applyNumericAffinity(pIn3, 0);
76593    }
76594    iKey = sqlite3VdbeIntValue(pIn3);
76595
76596    /* If the P3 value could not be converted into an integer without
76597    ** loss of information, then special processing is required... */
76598    if( (pIn3->flags & MEM_Int)==0 ){
76599      if( (pIn3->flags & MEM_Real)==0 ){
76600        /* If the P3 value cannot be converted into any kind of a number,
76601        ** then the seek is not possible, so jump to P2 */
76602        VdbeBranchTaken(1,2); goto jump_to_p2;
76603        break;
76604      }
76605
76606      /* If the approximation iKey is larger than the actual real search
76607      ** term, substitute >= for > and < for <=. e.g. if the search term
76608      ** is 4.9 and the integer approximation 5:
76609      **
76610      **        (x >  4.9)    ->     (x >= 5)
76611      **        (x <= 4.9)    ->     (x <  5)
76612      */
76613      if( pIn3->u.r<(double)iKey ){
76614        assert( OP_SeekGE==(OP_SeekGT-1) );
76615        assert( OP_SeekLT==(OP_SeekLE-1) );
76616        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
76617        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
76618      }
76619
76620      /* If the approximation iKey is smaller than the actual real search
76621      ** term, substitute <= for < and > for >=.  */
76622      else if( pIn3->u.r>(double)iKey ){
76623        assert( OP_SeekLE==(OP_SeekLT+1) );
76624        assert( OP_SeekGT==(OP_SeekGE+1) );
76625        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
76626        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
76627      }
76628    }
76629    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
76630    pC->movetoTarget = iKey;  /* Used by OP_Delete */
76631    if( rc!=SQLITE_OK ){
76632      goto abort_due_to_error;
76633    }
76634  }else{
76635    nField = pOp->p4.i;
76636    assert( pOp->p4type==P4_INT32 );
76637    assert( nField>0 );
76638    r.pKeyInfo = pC->pKeyInfo;
76639    r.nField = (u16)nField;
76640
76641    /* The next line of code computes as follows, only faster:
76642    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
76643    **     r.default_rc = -1;
76644    **   }else{
76645    **     r.default_rc = +1;
76646    **   }
76647    */
76648    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
76649    assert( oc!=OP_SeekGT || r.default_rc==-1 );
76650    assert( oc!=OP_SeekLE || r.default_rc==-1 );
76651    assert( oc!=OP_SeekGE || r.default_rc==+1 );
76652    assert( oc!=OP_SeekLT || r.default_rc==+1 );
76653
76654    r.aMem = &aMem[pOp->p3];
76655#ifdef SQLITE_DEBUG
76656    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
76657#endif
76658    ExpandBlob(r.aMem);
76659    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
76660    if( rc!=SQLITE_OK ){
76661      goto abort_due_to_error;
76662    }
76663  }
76664  pC->deferredMoveto = 0;
76665  pC->cacheStatus = CACHE_STALE;
76666#ifdef SQLITE_TEST
76667  sqlite3_search_count++;
76668#endif
76669  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
76670    if( res<0 || (res==0 && oc==OP_SeekGT) ){
76671      res = 0;
76672      rc = sqlite3BtreeNext(pC->pCursor, &res);
76673      if( rc!=SQLITE_OK ) goto abort_due_to_error;
76674    }else{
76675      res = 0;
76676    }
76677  }else{
76678    assert( oc==OP_SeekLT || oc==OP_SeekLE );
76679    if( res>0 || (res==0 && oc==OP_SeekLT) ){
76680      res = 0;
76681      rc = sqlite3BtreePrevious(pC->pCursor, &res);
76682      if( rc!=SQLITE_OK ) goto abort_due_to_error;
76683    }else{
76684      /* res might be negative because the table is empty.  Check to
76685      ** see if this is the case.
76686      */
76687      res = sqlite3BtreeEof(pC->pCursor);
76688    }
76689  }
76690  assert( pOp->p2>0 );
76691  VdbeBranchTaken(res!=0,2);
76692  if( res ){
76693    goto jump_to_p2;
76694  }
76695  break;
76696}
76697
76698/* Opcode: Seek P1 P2 * * *
76699** Synopsis:  intkey=r[P2]
76700**
76701** P1 is an open table cursor and P2 is a rowid integer.  Arrange
76702** for P1 to move so that it points to the rowid given by P2.
76703**
76704** This is actually a deferred seek.  Nothing actually happens until
76705** the cursor is used to read a record.  That way, if no reads
76706** occur, no unnecessary I/O happens.
76707*/
76708case OP_Seek: {    /* in2 */
76709  VdbeCursor *pC;
76710
76711  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76712  pC = p->apCsr[pOp->p1];
76713  assert( pC!=0 );
76714  assert( pC->pCursor!=0 );
76715  assert( pC->isTable );
76716  pC->nullRow = 0;
76717  pIn2 = &aMem[pOp->p2];
76718  pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
76719  pC->deferredMoveto = 1;
76720  break;
76721}
76722
76723
76724/* Opcode: Found P1 P2 P3 P4 *
76725** Synopsis: key=r[P3@P4]
76726**
76727** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76728** P4>0 then register P3 is the first of P4 registers that form an unpacked
76729** record.
76730**
76731** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76732** is a prefix of any entry in P1 then a jump is made to P2 and
76733** P1 is left pointing at the matching entry.
76734**
76735** This operation leaves the cursor in a state where it can be
76736** advanced in the forward direction.  The Next instruction will work,
76737** but not the Prev instruction.
76738**
76739** See also: NotFound, NoConflict, NotExists. SeekGe
76740*/
76741/* Opcode: NotFound P1 P2 P3 P4 *
76742** Synopsis: key=r[P3@P4]
76743**
76744** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76745** P4>0 then register P3 is the first of P4 registers that form an unpacked
76746** record.
76747**
76748** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76749** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
76750** does contain an entry whose prefix matches the P3/P4 record then control
76751** falls through to the next instruction and P1 is left pointing at the
76752** matching entry.
76753**
76754** This operation leaves the cursor in a state where it cannot be
76755** advanced in either direction.  In other words, the Next and Prev
76756** opcodes do not work after this operation.
76757**
76758** See also: Found, NotExists, NoConflict
76759*/
76760/* Opcode: NoConflict P1 P2 P3 P4 *
76761** Synopsis: key=r[P3@P4]
76762**
76763** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76764** P4>0 then register P3 is the first of P4 registers that form an unpacked
76765** record.
76766**
76767** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76768** contains any NULL value, jump immediately to P2.  If all terms of the
76769** record are not-NULL then a check is done to determine if any row in the
76770** P1 index btree has a matching key prefix.  If there are no matches, jump
76771** immediately to P2.  If there is a match, fall through and leave the P1
76772** cursor pointing to the matching row.
76773**
76774** This opcode is similar to OP_NotFound with the exceptions that the
76775** branch is always taken if any part of the search key input is NULL.
76776**
76777** This operation leaves the cursor in a state where it cannot be
76778** advanced in either direction.  In other words, the Next and Prev
76779** opcodes do not work after this operation.
76780**
76781** See also: NotFound, Found, NotExists
76782*/
76783case OP_NoConflict:     /* jump, in3 */
76784case OP_NotFound:       /* jump, in3 */
76785case OP_Found: {        /* jump, in3 */
76786  int alreadyExists;
76787  int takeJump;
76788  int ii;
76789  VdbeCursor *pC;
76790  int res;
76791  char *pFree;
76792  UnpackedRecord *pIdxKey;
76793  UnpackedRecord r;
76794  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
76795
76796#ifdef SQLITE_TEST
76797  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
76798#endif
76799
76800  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76801  assert( pOp->p4type==P4_INT32 );
76802  pC = p->apCsr[pOp->p1];
76803  assert( pC!=0 );
76804#ifdef SQLITE_DEBUG
76805  pC->seekOp = pOp->opcode;
76806#endif
76807  pIn3 = &aMem[pOp->p3];
76808  assert( pC->pCursor!=0 );
76809  assert( pC->isTable==0 );
76810  pFree = 0;
76811  if( pOp->p4.i>0 ){
76812    r.pKeyInfo = pC->pKeyInfo;
76813    r.nField = (u16)pOp->p4.i;
76814    r.aMem = pIn3;
76815    for(ii=0; ii<r.nField; ii++){
76816      assert( memIsValid(&r.aMem[ii]) );
76817      ExpandBlob(&r.aMem[ii]);
76818#ifdef SQLITE_DEBUG
76819      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
76820#endif
76821    }
76822    pIdxKey = &r;
76823  }else{
76824    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
76825        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
76826    );
76827    if( pIdxKey==0 ) goto no_mem;
76828    assert( pIn3->flags & MEM_Blob );
76829    ExpandBlob(pIn3);
76830    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
76831  }
76832  pIdxKey->default_rc = 0;
76833  takeJump = 0;
76834  if( pOp->opcode==OP_NoConflict ){
76835    /* For the OP_NoConflict opcode, take the jump if any of the
76836    ** input fields are NULL, since any key with a NULL will not
76837    ** conflict */
76838    for(ii=0; ii<pIdxKey->nField; ii++){
76839      if( pIdxKey->aMem[ii].flags & MEM_Null ){
76840        takeJump = 1;
76841        break;
76842      }
76843    }
76844  }
76845  rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
76846  sqlite3DbFree(db, pFree);
76847  if( rc!=SQLITE_OK ){
76848    break;
76849  }
76850  pC->seekResult = res;
76851  alreadyExists = (res==0);
76852  pC->nullRow = 1-alreadyExists;
76853  pC->deferredMoveto = 0;
76854  pC->cacheStatus = CACHE_STALE;
76855  if( pOp->opcode==OP_Found ){
76856    VdbeBranchTaken(alreadyExists!=0,2);
76857    if( alreadyExists ) goto jump_to_p2;
76858  }else{
76859    VdbeBranchTaken(takeJump||alreadyExists==0,2);
76860    if( takeJump || !alreadyExists ) goto jump_to_p2;
76861  }
76862  break;
76863}
76864
76865/* Opcode: NotExists P1 P2 P3 * *
76866** Synopsis: intkey=r[P3]
76867**
76868** P1 is the index of a cursor open on an SQL table btree (with integer
76869** keys).  P3 is an integer rowid.  If P1 does not contain a record with
76870** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
76871** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
76872** leave the cursor pointing at that record and fall through to the next
76873** instruction.
76874**
76875** The OP_NotFound opcode performs the same operation on index btrees
76876** (with arbitrary multi-value keys).
76877**
76878** This opcode leaves the cursor in a state where it cannot be advanced
76879** in either direction.  In other words, the Next and Prev opcodes will
76880** not work following this opcode.
76881**
76882** See also: Found, NotFound, NoConflict
76883*/
76884case OP_NotExists: {        /* jump, in3 */
76885  VdbeCursor *pC;
76886  BtCursor *pCrsr;
76887  int res;
76888  u64 iKey;
76889
76890  pIn3 = &aMem[pOp->p3];
76891  assert( pIn3->flags & MEM_Int );
76892  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76893  pC = p->apCsr[pOp->p1];
76894  assert( pC!=0 );
76895#ifdef SQLITE_DEBUG
76896  pC->seekOp = 0;
76897#endif
76898  assert( pC->isTable );
76899  assert( pC->pseudoTableReg==0 );
76900  pCrsr = pC->pCursor;
76901  assert( pCrsr!=0 );
76902  res = 0;
76903  iKey = pIn3->u.i;
76904  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
76905  assert( rc==SQLITE_OK || res==0 );
76906  pC->movetoTarget = iKey;  /* Used by OP_Delete */
76907  pC->nullRow = 0;
76908  pC->cacheStatus = CACHE_STALE;
76909  pC->deferredMoveto = 0;
76910  VdbeBranchTaken(res!=0,2);
76911  pC->seekResult = res;
76912  if( res!=0 ){
76913    assert( rc==SQLITE_OK );
76914    if( pOp->p2==0 ){
76915      rc = SQLITE_CORRUPT_BKPT;
76916    }else{
76917      goto jump_to_p2;
76918    }
76919  }
76920  break;
76921}
76922
76923/* Opcode: Sequence P1 P2 * * *
76924** Synopsis: r[P2]=cursor[P1].ctr++
76925**
76926** Find the next available sequence number for cursor P1.
76927** Write the sequence number into register P2.
76928** The sequence number on the cursor is incremented after this
76929** instruction.
76930*/
76931case OP_Sequence: {           /* out2 */
76932  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76933  assert( p->apCsr[pOp->p1]!=0 );
76934  pOut = out2Prerelease(p, pOp);
76935  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
76936  break;
76937}
76938
76939
76940/* Opcode: NewRowid P1 P2 P3 * *
76941** Synopsis: r[P2]=rowid
76942**
76943** Get a new integer record number (a.k.a "rowid") used as the key to a table.
76944** The record number is not previously used as a key in the database
76945** table that cursor P1 points to.  The new record number is written
76946** written to register P2.
76947**
76948** If P3>0 then P3 is a register in the root frame of this VDBE that holds
76949** the largest previously generated record number. No new record numbers are
76950** allowed to be less than this value. When this value reaches its maximum,
76951** an SQLITE_FULL error is generated. The P3 register is updated with the '
76952** generated record number. This P3 mechanism is used to help implement the
76953** AUTOINCREMENT feature.
76954*/
76955case OP_NewRowid: {           /* out2 */
76956  i64 v;                 /* The new rowid */
76957  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
76958  int res;               /* Result of an sqlite3BtreeLast() */
76959  int cnt;               /* Counter to limit the number of searches */
76960  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
76961  VdbeFrame *pFrame;     /* Root frame of VDBE */
76962
76963  v = 0;
76964  res = 0;
76965  pOut = out2Prerelease(p, pOp);
76966  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76967  pC = p->apCsr[pOp->p1];
76968  assert( pC!=0 );
76969  assert( pC->pCursor!=0 );
76970  {
76971    /* The next rowid or record number (different terms for the same
76972    ** thing) is obtained in a two-step algorithm.
76973    **
76974    ** First we attempt to find the largest existing rowid and add one
76975    ** to that.  But if the largest existing rowid is already the maximum
76976    ** positive integer, we have to fall through to the second
76977    ** probabilistic algorithm
76978    **
76979    ** The second algorithm is to select a rowid at random and see if
76980    ** it already exists in the table.  If it does not exist, we have
76981    ** succeeded.  If the random rowid does exist, we select a new one
76982    ** and try again, up to 100 times.
76983    */
76984    assert( pC->isTable );
76985
76986#ifdef SQLITE_32BIT_ROWID
76987#   define MAX_ROWID 0x7fffffff
76988#else
76989    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
76990    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
76991    ** to provide the constant while making all compilers happy.
76992    */
76993#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
76994#endif
76995
76996    if( !pC->useRandomRowid ){
76997      rc = sqlite3BtreeLast(pC->pCursor, &res);
76998      if( rc!=SQLITE_OK ){
76999        goto abort_due_to_error;
77000      }
77001      if( res ){
77002        v = 1;   /* IMP: R-61914-48074 */
77003      }else{
77004        assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
77005        rc = sqlite3BtreeKeySize(pC->pCursor, &v);
77006        assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
77007        if( v>=MAX_ROWID ){
77008          pC->useRandomRowid = 1;
77009        }else{
77010          v++;   /* IMP: R-29538-34987 */
77011        }
77012      }
77013    }
77014
77015#ifndef SQLITE_OMIT_AUTOINCREMENT
77016    if( pOp->p3 ){
77017      /* Assert that P3 is a valid memory cell. */
77018      assert( pOp->p3>0 );
77019      if( p->pFrame ){
77020        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
77021        /* Assert that P3 is a valid memory cell. */
77022        assert( pOp->p3<=pFrame->nMem );
77023        pMem = &pFrame->aMem[pOp->p3];
77024      }else{
77025        /* Assert that P3 is a valid memory cell. */
77026        assert( pOp->p3<=(p->nMem-p->nCursor) );
77027        pMem = &aMem[pOp->p3];
77028        memAboutToChange(p, pMem);
77029      }
77030      assert( memIsValid(pMem) );
77031
77032      REGISTER_TRACE(pOp->p3, pMem);
77033      sqlite3VdbeMemIntegerify(pMem);
77034      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
77035      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
77036        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
77037        goto abort_due_to_error;
77038      }
77039      if( v<pMem->u.i+1 ){
77040        v = pMem->u.i + 1;
77041      }
77042      pMem->u.i = v;
77043    }
77044#endif
77045    if( pC->useRandomRowid ){
77046      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
77047      ** largest possible integer (9223372036854775807) then the database
77048      ** engine starts picking positive candidate ROWIDs at random until
77049      ** it finds one that is not previously used. */
77050      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
77051                             ** an AUTOINCREMENT table. */
77052      cnt = 0;
77053      do{
77054        sqlite3_randomness(sizeof(v), &v);
77055        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
77056      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
77057                                                 0, &res))==SQLITE_OK)
77058            && (res==0)
77059            && (++cnt<100));
77060      if( rc==SQLITE_OK && res==0 ){
77061        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
77062        goto abort_due_to_error;
77063      }
77064      assert( v>0 );  /* EV: R-40812-03570 */
77065    }
77066    pC->deferredMoveto = 0;
77067    pC->cacheStatus = CACHE_STALE;
77068  }
77069  pOut->u.i = v;
77070  break;
77071}
77072
77073/* Opcode: Insert P1 P2 P3 P4 P5
77074** Synopsis: intkey=r[P3] data=r[P2]
77075**
77076** Write an entry into the table of cursor P1.  A new entry is
77077** created if it doesn't already exist or the data for an existing
77078** entry is overwritten.  The data is the value MEM_Blob stored in register
77079** number P2. The key is stored in register P3. The key must
77080** be a MEM_Int.
77081**
77082** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
77083** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
77084** then rowid is stored for subsequent return by the
77085** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
77086**
77087** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
77088** the last seek operation (OP_NotExists) was a success, then this
77089** operation will not attempt to find the appropriate row before doing
77090** the insert but will instead overwrite the row that the cursor is
77091** currently pointing to.  Presumably, the prior OP_NotExists opcode
77092** has already positioned the cursor correctly.  This is an optimization
77093** that boosts performance by avoiding redundant seeks.
77094**
77095** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
77096** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
77097** is part of an INSERT operation.  The difference is only important to
77098** the update hook.
77099**
77100** Parameter P4 may point to a string containing the table-name, or
77101** may be NULL. If it is not NULL, then the update-hook
77102** (sqlite3.xUpdateCallback) is invoked following a successful insert.
77103**
77104** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
77105** allocated, then ownership of P2 is transferred to the pseudo-cursor
77106** and register P2 becomes ephemeral.  If the cursor is changed, the
77107** value of register P2 will then change.  Make sure this does not
77108** cause any problems.)
77109**
77110** This instruction only works on tables.  The equivalent instruction
77111** for indices is OP_IdxInsert.
77112*/
77113/* Opcode: InsertInt P1 P2 P3 P4 P5
77114** Synopsis:  intkey=P3 data=r[P2]
77115**
77116** This works exactly like OP_Insert except that the key is the
77117** integer value P3, not the value of the integer stored in register P3.
77118*/
77119case OP_Insert:
77120case OP_InsertInt: {
77121  Mem *pData;       /* MEM cell holding data for the record to be inserted */
77122  Mem *pKey;        /* MEM cell holding key  for the record */
77123  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
77124  VdbeCursor *pC;   /* Cursor to table into which insert is written */
77125  int nZero;        /* Number of zero-bytes to append */
77126  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
77127  const char *zDb;  /* database name - used by the update hook */
77128  const char *zTbl; /* Table name - used by the opdate hook */
77129  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
77130
77131  pData = &aMem[pOp->p2];
77132  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77133  assert( memIsValid(pData) );
77134  pC = p->apCsr[pOp->p1];
77135  assert( pC!=0 );
77136  assert( pC->pCursor!=0 );
77137  assert( pC->pseudoTableReg==0 );
77138  assert( pC->isTable );
77139  REGISTER_TRACE(pOp->p2, pData);
77140
77141  if( pOp->opcode==OP_Insert ){
77142    pKey = &aMem[pOp->p3];
77143    assert( pKey->flags & MEM_Int );
77144    assert( memIsValid(pKey) );
77145    REGISTER_TRACE(pOp->p3, pKey);
77146    iKey = pKey->u.i;
77147  }else{
77148    assert( pOp->opcode==OP_InsertInt );
77149    iKey = pOp->p3;
77150  }
77151
77152  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
77153  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
77154  if( pData->flags & MEM_Null ){
77155    pData->z = 0;
77156    pData->n = 0;
77157  }else{
77158    assert( pData->flags & (MEM_Blob|MEM_Str) );
77159  }
77160  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
77161  if( pData->flags & MEM_Zero ){
77162    nZero = pData->u.nZero;
77163  }else{
77164    nZero = 0;
77165  }
77166  rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
77167                          pData->z, pData->n, nZero,
77168                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
77169  );
77170  pC->deferredMoveto = 0;
77171  pC->cacheStatus = CACHE_STALE;
77172
77173  /* Invoke the update-hook if required. */
77174  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
77175    zDb = db->aDb[pC->iDb].zName;
77176    zTbl = pOp->p4.z;
77177    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
77178    assert( pC->isTable );
77179    db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
77180    assert( pC->iDb>=0 );
77181  }
77182  break;
77183}
77184
77185/* Opcode: Delete P1 P2 * P4 P5
77186**
77187** Delete the record at which the P1 cursor is currently pointing.
77188**
77189** If the P5 parameter is non-zero, the cursor will be left pointing at
77190** either the next or the previous record in the table. If it is left
77191** pointing at the next record, then the next Next instruction will be a
77192** no-op. As a result, in this case it is OK to delete a record from within a
77193** Next loop. If P5 is zero, then the cursor is left in an undefined state.
77194**
77195** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
77196** incremented (otherwise not).
77197**
77198** P1 must not be pseudo-table.  It has to be a real table with
77199** multiple rows.
77200**
77201** If P4 is not NULL, then it is the name of the table that P1 is
77202** pointing to.  The update hook will be invoked, if it exists.
77203** If P4 is not NULL then the P1 cursor must have been positioned
77204** using OP_NotFound prior to invoking this opcode.
77205*/
77206case OP_Delete: {
77207  VdbeCursor *pC;
77208  u8 hasUpdateCallback;
77209
77210  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77211  pC = p->apCsr[pOp->p1];
77212  assert( pC!=0 );
77213  assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
77214  assert( pC->deferredMoveto==0 );
77215
77216  hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
77217  if( pOp->p5 && hasUpdateCallback ){
77218    sqlite3BtreeKeySize(pC->pCursor, &pC->movetoTarget);
77219  }
77220
77221#ifdef SQLITE_DEBUG
77222  /* The seek operation that positioned the cursor prior to OP_Delete will
77223  ** have also set the pC->movetoTarget field to the rowid of the row that
77224  ** is being deleted */
77225  if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
77226    i64 iKey = 0;
77227    sqlite3BtreeKeySize(pC->pCursor, &iKey);
77228    assert( pC->movetoTarget==iKey );
77229  }
77230#endif
77231
77232  rc = sqlite3BtreeDelete(pC->pCursor, pOp->p5);
77233  pC->cacheStatus = CACHE_STALE;
77234
77235  /* Invoke the update-hook if required. */
77236  if( rc==SQLITE_OK && hasUpdateCallback ){
77237    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
77238                        db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
77239    assert( pC->iDb>=0 );
77240  }
77241  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
77242  break;
77243}
77244/* Opcode: ResetCount * * * * *
77245**
77246** The value of the change counter is copied to the database handle
77247** change counter (returned by subsequent calls to sqlite3_changes()).
77248** Then the VMs internal change counter resets to 0.
77249** This is used by trigger programs.
77250*/
77251case OP_ResetCount: {
77252  sqlite3VdbeSetChanges(db, p->nChange);
77253  p->nChange = 0;
77254  break;
77255}
77256
77257/* Opcode: SorterCompare P1 P2 P3 P4
77258** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
77259**
77260** P1 is a sorter cursor. This instruction compares a prefix of the
77261** record blob in register P3 against a prefix of the entry that
77262** the sorter cursor currently points to.  Only the first P4 fields
77263** of r[P3] and the sorter record are compared.
77264**
77265** If either P3 or the sorter contains a NULL in one of their significant
77266** fields (not counting the P4 fields at the end which are ignored) then
77267** the comparison is assumed to be equal.
77268**
77269** Fall through to next instruction if the two records compare equal to
77270** each other.  Jump to P2 if they are different.
77271*/
77272case OP_SorterCompare: {
77273  VdbeCursor *pC;
77274  int res;
77275  int nKeyCol;
77276
77277  pC = p->apCsr[pOp->p1];
77278  assert( isSorter(pC) );
77279  assert( pOp->p4type==P4_INT32 );
77280  pIn3 = &aMem[pOp->p3];
77281  nKeyCol = pOp->p4.i;
77282  res = 0;
77283  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
77284  VdbeBranchTaken(res!=0,2);
77285  if( res ) goto jump_to_p2;
77286  break;
77287};
77288
77289/* Opcode: SorterData P1 P2 P3 * *
77290** Synopsis: r[P2]=data
77291**
77292** Write into register P2 the current sorter data for sorter cursor P1.
77293** Then clear the column header cache on cursor P3.
77294**
77295** This opcode is normally use to move a record out of the sorter and into
77296** a register that is the source for a pseudo-table cursor created using
77297** OpenPseudo.  That pseudo-table cursor is the one that is identified by
77298** parameter P3.  Clearing the P3 column cache as part of this opcode saves
77299** us from having to issue a separate NullRow instruction to clear that cache.
77300*/
77301case OP_SorterData: {
77302  VdbeCursor *pC;
77303
77304  pOut = &aMem[pOp->p2];
77305  pC = p->apCsr[pOp->p1];
77306  assert( isSorter(pC) );
77307  rc = sqlite3VdbeSorterRowkey(pC, pOut);
77308  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
77309  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77310  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
77311  break;
77312}
77313
77314/* Opcode: RowData P1 P2 * * *
77315** Synopsis: r[P2]=data
77316**
77317** Write into register P2 the complete row data for cursor P1.
77318** There is no interpretation of the data.
77319** It is just copied onto the P2 register exactly as
77320** it is found in the database file.
77321**
77322** If the P1 cursor must be pointing to a valid row (not a NULL row)
77323** of a real table, not a pseudo-table.
77324*/
77325/* Opcode: RowKey P1 P2 * * *
77326** Synopsis: r[P2]=key
77327**
77328** Write into register P2 the complete row key for cursor P1.
77329** There is no interpretation of the data.
77330** The key is copied onto the P2 register exactly as
77331** it is found in the database file.
77332**
77333** If the P1 cursor must be pointing to a valid row (not a NULL row)
77334** of a real table, not a pseudo-table.
77335*/
77336case OP_RowKey:
77337case OP_RowData: {
77338  VdbeCursor *pC;
77339  BtCursor *pCrsr;
77340  u32 n;
77341  i64 n64;
77342
77343  pOut = &aMem[pOp->p2];
77344  memAboutToChange(p, pOut);
77345
77346  /* Note that RowKey and RowData are really exactly the same instruction */
77347  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77348  pC = p->apCsr[pOp->p1];
77349  assert( isSorter(pC)==0 );
77350  assert( pC->isTable || pOp->opcode!=OP_RowData );
77351  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
77352  assert( pC!=0 );
77353  assert( pC->nullRow==0 );
77354  assert( pC->pseudoTableReg==0 );
77355  assert( pC->pCursor!=0 );
77356  pCrsr = pC->pCursor;
77357
77358  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
77359  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
77360  ** the cursor.  If this where not the case, on of the following assert()s
77361  ** would fail.  Should this ever change (because of changes in the code
77362  ** generator) then the fix would be to insert a call to
77363  ** sqlite3VdbeCursorMoveto().
77364  */
77365  assert( pC->deferredMoveto==0 );
77366  assert( sqlite3BtreeCursorIsValid(pCrsr) );
77367#if 0  /* Not required due to the previous to assert() statements */
77368  rc = sqlite3VdbeCursorMoveto(pC);
77369  if( rc!=SQLITE_OK ) goto abort_due_to_error;
77370#endif
77371
77372  if( pC->isTable==0 ){
77373    assert( !pC->isTable );
77374    VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
77375    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
77376    if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77377      goto too_big;
77378    }
77379    n = (u32)n64;
77380  }else{
77381    VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
77382    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
77383    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
77384      goto too_big;
77385    }
77386  }
77387  testcase( n==0 );
77388  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
77389    goto no_mem;
77390  }
77391  pOut->n = n;
77392  MemSetTypeFlag(pOut, MEM_Blob);
77393  if( pC->isTable==0 ){
77394    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
77395  }else{
77396    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
77397  }
77398  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
77399  UPDATE_MAX_BLOBSIZE(pOut);
77400  REGISTER_TRACE(pOp->p2, pOut);
77401  break;
77402}
77403
77404/* Opcode: Rowid P1 P2 * * *
77405** Synopsis: r[P2]=rowid
77406**
77407** Store in register P2 an integer which is the key of the table entry that
77408** P1 is currently point to.
77409**
77410** P1 can be either an ordinary table or a virtual table.  There used to
77411** be a separate OP_VRowid opcode for use with virtual tables, but this
77412** one opcode now works for both table types.
77413*/
77414case OP_Rowid: {                 /* out2 */
77415  VdbeCursor *pC;
77416  i64 v;
77417  sqlite3_vtab *pVtab;
77418  const sqlite3_module *pModule;
77419
77420  pOut = out2Prerelease(p, pOp);
77421  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77422  pC = p->apCsr[pOp->p1];
77423  assert( pC!=0 );
77424  assert( pC->pseudoTableReg==0 || pC->nullRow );
77425  if( pC->nullRow ){
77426    pOut->flags = MEM_Null;
77427    break;
77428  }else if( pC->deferredMoveto ){
77429    v = pC->movetoTarget;
77430#ifndef SQLITE_OMIT_VIRTUALTABLE
77431  }else if( pC->pVtabCursor ){
77432    pVtab = pC->pVtabCursor->pVtab;
77433    pModule = pVtab->pModule;
77434    assert( pModule->xRowid );
77435    rc = pModule->xRowid(pC->pVtabCursor, &v);
77436    sqlite3VtabImportErrmsg(p, pVtab);
77437#endif /* SQLITE_OMIT_VIRTUALTABLE */
77438  }else{
77439    assert( pC->pCursor!=0 );
77440    rc = sqlite3VdbeCursorRestore(pC);
77441    if( rc ) goto abort_due_to_error;
77442    if( pC->nullRow ){
77443      pOut->flags = MEM_Null;
77444      break;
77445    }
77446    rc = sqlite3BtreeKeySize(pC->pCursor, &v);
77447    assert( rc==SQLITE_OK );  /* Always so because of CursorRestore() above */
77448  }
77449  pOut->u.i = v;
77450  break;
77451}
77452
77453/* Opcode: NullRow P1 * * * *
77454**
77455** Move the cursor P1 to a null row.  Any OP_Column operations
77456** that occur while the cursor is on the null row will always
77457** write a NULL.
77458*/
77459case OP_NullRow: {
77460  VdbeCursor *pC;
77461
77462  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77463  pC = p->apCsr[pOp->p1];
77464  assert( pC!=0 );
77465  pC->nullRow = 1;
77466  pC->cacheStatus = CACHE_STALE;
77467  if( pC->pCursor ){
77468    sqlite3BtreeClearCursor(pC->pCursor);
77469  }
77470  break;
77471}
77472
77473/* Opcode: Last P1 P2 P3 * *
77474**
77475** The next use of the Rowid or Column or Prev instruction for P1
77476** will refer to the last entry in the database table or index.
77477** If the table or index is empty and P2>0, then jump immediately to P2.
77478** If P2 is 0 or if the table or index is not empty, fall through
77479** to the following instruction.
77480**
77481** This opcode leaves the cursor configured to move in reverse order,
77482** from the end toward the beginning.  In other words, the cursor is
77483** configured to use Prev, not Next.
77484*/
77485case OP_Last: {        /* jump */
77486  VdbeCursor *pC;
77487  BtCursor *pCrsr;
77488  int res;
77489
77490  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77491  pC = p->apCsr[pOp->p1];
77492  assert( pC!=0 );
77493  pCrsr = pC->pCursor;
77494  res = 0;
77495  assert( pCrsr!=0 );
77496  rc = sqlite3BtreeLast(pCrsr, &res);
77497  pC->nullRow = (u8)res;
77498  pC->deferredMoveto = 0;
77499  pC->cacheStatus = CACHE_STALE;
77500  pC->seekResult = pOp->p3;
77501#ifdef SQLITE_DEBUG
77502  pC->seekOp = OP_Last;
77503#endif
77504  if( pOp->p2>0 ){
77505    VdbeBranchTaken(res!=0,2);
77506    if( res ) goto jump_to_p2;
77507  }
77508  break;
77509}
77510
77511
77512/* Opcode: Sort P1 P2 * * *
77513**
77514** This opcode does exactly the same thing as OP_Rewind except that
77515** it increments an undocumented global variable used for testing.
77516**
77517** Sorting is accomplished by writing records into a sorting index,
77518** then rewinding that index and playing it back from beginning to
77519** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
77520** rewinding so that the global variable will be incremented and
77521** regression tests can determine whether or not the optimizer is
77522** correctly optimizing out sorts.
77523*/
77524case OP_SorterSort:    /* jump */
77525case OP_Sort: {        /* jump */
77526#ifdef SQLITE_TEST
77527  sqlite3_sort_count++;
77528  sqlite3_search_count--;
77529#endif
77530  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
77531  /* Fall through into OP_Rewind */
77532}
77533/* Opcode: Rewind P1 P2 * * *
77534**
77535** The next use of the Rowid or Column or Next instruction for P1
77536** will refer to the first entry in the database table or index.
77537** If the table or index is empty, jump immediately to P2.
77538** If the table or index is not empty, fall through to the following
77539** instruction.
77540**
77541** This opcode leaves the cursor configured to move in forward order,
77542** from the beginning toward the end.  In other words, the cursor is
77543** configured to use Next, not Prev.
77544*/
77545case OP_Rewind: {        /* jump */
77546  VdbeCursor *pC;
77547  BtCursor *pCrsr;
77548  int res;
77549
77550  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77551  pC = p->apCsr[pOp->p1];
77552  assert( pC!=0 );
77553  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
77554  res = 1;
77555#ifdef SQLITE_DEBUG
77556  pC->seekOp = OP_Rewind;
77557#endif
77558  if( isSorter(pC) ){
77559    rc = sqlite3VdbeSorterRewind(pC, &res);
77560  }else{
77561    pCrsr = pC->pCursor;
77562    assert( pCrsr );
77563    rc = sqlite3BtreeFirst(pCrsr, &res);
77564    pC->deferredMoveto = 0;
77565    pC->cacheStatus = CACHE_STALE;
77566  }
77567  pC->nullRow = (u8)res;
77568  assert( pOp->p2>0 && pOp->p2<p->nOp );
77569  VdbeBranchTaken(res!=0,2);
77570  if( res ) goto jump_to_p2;
77571  break;
77572}
77573
77574/* Opcode: Next P1 P2 P3 P4 P5
77575**
77576** Advance cursor P1 so that it points to the next key/data pair in its
77577** table or index.  If there are no more key/value pairs then fall through
77578** to the following instruction.  But if the cursor advance was successful,
77579** jump immediately to P2.
77580**
77581** The Next opcode is only valid following an SeekGT, SeekGE, or
77582** OP_Rewind opcode used to position the cursor.  Next is not allowed
77583** to follow SeekLT, SeekLE, or OP_Last.
77584**
77585** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
77586** been opened prior to this opcode or the program will segfault.
77587**
77588** The P3 value is a hint to the btree implementation. If P3==1, that
77589** means P1 is an SQL index and that this instruction could have been
77590** omitted if that index had been unique.  P3 is usually 0.  P3 is
77591** always either 0 or 1.
77592**
77593** P4 is always of type P4_ADVANCE. The function pointer points to
77594** sqlite3BtreeNext().
77595**
77596** If P5 is positive and the jump is taken, then event counter
77597** number P5-1 in the prepared statement is incremented.
77598**
77599** See also: Prev, NextIfOpen
77600*/
77601/* Opcode: NextIfOpen P1 P2 P3 P4 P5
77602**
77603** This opcode works just like Next except that if cursor P1 is not
77604** open it behaves a no-op.
77605*/
77606/* Opcode: Prev P1 P2 P3 P4 P5
77607**
77608** Back up cursor P1 so that it points to the previous key/data pair in its
77609** table or index.  If there is no previous key/value pairs then fall through
77610** to the following instruction.  But if the cursor backup was successful,
77611** jump immediately to P2.
77612**
77613**
77614** The Prev opcode is only valid following an SeekLT, SeekLE, or
77615** OP_Last opcode used to position the cursor.  Prev is not allowed
77616** to follow SeekGT, SeekGE, or OP_Rewind.
77617**
77618** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
77619** not open then the behavior is undefined.
77620**
77621** The P3 value is a hint to the btree implementation. If P3==1, that
77622** means P1 is an SQL index and that this instruction could have been
77623** omitted if that index had been unique.  P3 is usually 0.  P3 is
77624** always either 0 or 1.
77625**
77626** P4 is always of type P4_ADVANCE. The function pointer points to
77627** sqlite3BtreePrevious().
77628**
77629** If P5 is positive and the jump is taken, then event counter
77630** number P5-1 in the prepared statement is incremented.
77631*/
77632/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
77633**
77634** This opcode works just like Prev except that if cursor P1 is not
77635** open it behaves a no-op.
77636*/
77637case OP_SorterNext: {  /* jump */
77638  VdbeCursor *pC;
77639  int res;
77640
77641  pC = p->apCsr[pOp->p1];
77642  assert( isSorter(pC) );
77643  res = 0;
77644  rc = sqlite3VdbeSorterNext(db, pC, &res);
77645  goto next_tail;
77646case OP_PrevIfOpen:    /* jump */
77647case OP_NextIfOpen:    /* jump */
77648  if( p->apCsr[pOp->p1]==0 ) break;
77649  /* Fall through */
77650case OP_Prev:          /* jump */
77651case OP_Next:          /* jump */
77652  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77653  assert( pOp->p5<ArraySize(p->aCounter) );
77654  pC = p->apCsr[pOp->p1];
77655  res = pOp->p3;
77656  assert( pC!=0 );
77657  assert( pC->deferredMoveto==0 );
77658  assert( pC->pCursor );
77659  assert( res==0 || (res==1 && pC->isTable==0) );
77660  testcase( res==1 );
77661  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
77662  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
77663  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
77664  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
77665
77666  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
77667  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
77668  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
77669       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
77670       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
77671  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
77672       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
77673       || pC->seekOp==OP_Last );
77674
77675  rc = pOp->p4.xAdvance(pC->pCursor, &res);
77676next_tail:
77677  pC->cacheStatus = CACHE_STALE;
77678  VdbeBranchTaken(res==0,2);
77679  if( res==0 ){
77680    pC->nullRow = 0;
77681    p->aCounter[pOp->p5]++;
77682#ifdef SQLITE_TEST
77683    sqlite3_search_count++;
77684#endif
77685    goto jump_to_p2_and_check_for_interrupt;
77686  }else{
77687    pC->nullRow = 1;
77688  }
77689  goto check_for_interrupt;
77690}
77691
77692/* Opcode: IdxInsert P1 P2 P3 * P5
77693** Synopsis: key=r[P2]
77694**
77695** Register P2 holds an SQL index key made using the
77696** MakeRecord instructions.  This opcode writes that key
77697** into the index P1.  Data for the entry is nil.
77698**
77699** P3 is a flag that provides a hint to the b-tree layer that this
77700** insert is likely to be an append.
77701**
77702** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
77703** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
77704** then the change counter is unchanged.
77705**
77706** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
77707** just done a seek to the spot where the new entry is to be inserted.
77708** This flag avoids doing an extra seek.
77709**
77710** This instruction only works for indices.  The equivalent instruction
77711** for tables is OP_Insert.
77712*/
77713case OP_SorterInsert:       /* in2 */
77714case OP_IdxInsert: {        /* in2 */
77715  VdbeCursor *pC;
77716  int nKey;
77717  const char *zKey;
77718
77719  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77720  pC = p->apCsr[pOp->p1];
77721  assert( pC!=0 );
77722  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
77723  pIn2 = &aMem[pOp->p2];
77724  assert( pIn2->flags & MEM_Blob );
77725  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
77726  assert( pC->pCursor!=0 );
77727  assert( pC->isTable==0 );
77728  rc = ExpandBlob(pIn2);
77729  if( rc==SQLITE_OK ){
77730    if( pOp->opcode==OP_SorterInsert ){
77731      rc = sqlite3VdbeSorterWrite(pC, pIn2);
77732    }else{
77733      nKey = pIn2->n;
77734      zKey = pIn2->z;
77735      rc = sqlite3BtreeInsert(pC->pCursor, zKey, nKey, "", 0, 0, pOp->p3,
77736          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
77737          );
77738      assert( pC->deferredMoveto==0 );
77739      pC->cacheStatus = CACHE_STALE;
77740    }
77741  }
77742  break;
77743}
77744
77745/* Opcode: IdxDelete P1 P2 P3 * *
77746** Synopsis: key=r[P2@P3]
77747**
77748** The content of P3 registers starting at register P2 form
77749** an unpacked index key. This opcode removes that entry from the
77750** index opened by cursor P1.
77751*/
77752case OP_IdxDelete: {
77753  VdbeCursor *pC;
77754  BtCursor *pCrsr;
77755  int res;
77756  UnpackedRecord r;
77757
77758  assert( pOp->p3>0 );
77759  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
77760  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77761  pC = p->apCsr[pOp->p1];
77762  assert( pC!=0 );
77763  pCrsr = pC->pCursor;
77764  assert( pCrsr!=0 );
77765  assert( pOp->p5==0 );
77766  r.pKeyInfo = pC->pKeyInfo;
77767  r.nField = (u16)pOp->p3;
77768  r.default_rc = 0;
77769  r.aMem = &aMem[pOp->p2];
77770#ifdef SQLITE_DEBUG
77771  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
77772#endif
77773  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
77774  if( rc==SQLITE_OK && res==0 ){
77775    rc = sqlite3BtreeDelete(pCrsr, 0);
77776  }
77777  assert( pC->deferredMoveto==0 );
77778  pC->cacheStatus = CACHE_STALE;
77779  break;
77780}
77781
77782/* Opcode: IdxRowid P1 P2 * * *
77783** Synopsis: r[P2]=rowid
77784**
77785** Write into register P2 an integer which is the last entry in the record at
77786** the end of the index key pointed to by cursor P1.  This integer should be
77787** the rowid of the table entry to which this index entry points.
77788**
77789** See also: Rowid, MakeRecord.
77790*/
77791case OP_IdxRowid: {              /* out2 */
77792  BtCursor *pCrsr;
77793  VdbeCursor *pC;
77794  i64 rowid;
77795
77796  pOut = out2Prerelease(p, pOp);
77797  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77798  pC = p->apCsr[pOp->p1];
77799  assert( pC!=0 );
77800  pCrsr = pC->pCursor;
77801  assert( pCrsr!=0 );
77802  pOut->flags = MEM_Null;
77803  assert( pC->isTable==0 );
77804  assert( pC->deferredMoveto==0 );
77805
77806  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
77807  ** out from under the cursor.  That will never happend for an IdxRowid
77808  ** opcode, hence the NEVER() arround the check of the return value.
77809  */
77810  rc = sqlite3VdbeCursorRestore(pC);
77811  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
77812
77813  if( !pC->nullRow ){
77814    rowid = 0;  /* Not needed.  Only used to silence a warning. */
77815    rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
77816    if( rc!=SQLITE_OK ){
77817      goto abort_due_to_error;
77818    }
77819    pOut->u.i = rowid;
77820    pOut->flags = MEM_Int;
77821  }
77822  break;
77823}
77824
77825/* Opcode: IdxGE P1 P2 P3 P4 P5
77826** Synopsis: key=r[P3@P4]
77827**
77828** The P4 register values beginning with P3 form an unpacked index
77829** key that omits the PRIMARY KEY.  Compare this key value against the index
77830** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
77831** fields at the end.
77832**
77833** If the P1 index entry is greater than or equal to the key value
77834** then jump to P2.  Otherwise fall through to the next instruction.
77835*/
77836/* Opcode: IdxGT P1 P2 P3 P4 P5
77837** Synopsis: key=r[P3@P4]
77838**
77839** The P4 register values beginning with P3 form an unpacked index
77840** key that omits the PRIMARY KEY.  Compare this key value against the index
77841** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
77842** fields at the end.
77843**
77844** If the P1 index entry is greater than the key value
77845** then jump to P2.  Otherwise fall through to the next instruction.
77846*/
77847/* Opcode: IdxLT P1 P2 P3 P4 P5
77848** Synopsis: key=r[P3@P4]
77849**
77850** The P4 register values beginning with P3 form an unpacked index
77851** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
77852** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
77853** ROWID on the P1 index.
77854**
77855** If the P1 index entry is less than the key value then jump to P2.
77856** Otherwise fall through to the next instruction.
77857*/
77858/* Opcode: IdxLE P1 P2 P3 P4 P5
77859** Synopsis: key=r[P3@P4]
77860**
77861** The P4 register values beginning with P3 form an unpacked index
77862** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
77863** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
77864** ROWID on the P1 index.
77865**
77866** If the P1 index entry is less than or equal to the key value then jump
77867** to P2. Otherwise fall through to the next instruction.
77868*/
77869case OP_IdxLE:          /* jump */
77870case OP_IdxGT:          /* jump */
77871case OP_IdxLT:          /* jump */
77872case OP_IdxGE:  {       /* jump */
77873  VdbeCursor *pC;
77874  int res;
77875  UnpackedRecord r;
77876
77877  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77878  pC = p->apCsr[pOp->p1];
77879  assert( pC!=0 );
77880  assert( pC->isOrdered );
77881  assert( pC->pCursor!=0);
77882  assert( pC->deferredMoveto==0 );
77883  assert( pOp->p5==0 || pOp->p5==1 );
77884  assert( pOp->p4type==P4_INT32 );
77885  r.pKeyInfo = pC->pKeyInfo;
77886  r.nField = (u16)pOp->p4.i;
77887  if( pOp->opcode<OP_IdxLT ){
77888    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
77889    r.default_rc = -1;
77890  }else{
77891    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
77892    r.default_rc = 0;
77893  }
77894  r.aMem = &aMem[pOp->p3];
77895#ifdef SQLITE_DEBUG
77896  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
77897#endif
77898  res = 0;  /* Not needed.  Only used to silence a warning. */
77899  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
77900  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
77901  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
77902    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
77903    res = -res;
77904  }else{
77905    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
77906    res++;
77907  }
77908  VdbeBranchTaken(res>0,2);
77909  if( res>0 ) goto jump_to_p2;
77910  break;
77911}
77912
77913/* Opcode: Destroy P1 P2 P3 * *
77914**
77915** Delete an entire database table or index whose root page in the database
77916** file is given by P1.
77917**
77918** The table being destroyed is in the main database file if P3==0.  If
77919** P3==1 then the table to be clear is in the auxiliary database file
77920** that is used to store tables create using CREATE TEMPORARY TABLE.
77921**
77922** If AUTOVACUUM is enabled then it is possible that another root page
77923** might be moved into the newly deleted root page in order to keep all
77924** root pages contiguous at the beginning of the database.  The former
77925** value of the root page that moved - its value before the move occurred -
77926** is stored in register P2.  If no page
77927** movement was required (because the table being dropped was already
77928** the last one in the database) then a zero is stored in register P2.
77929** If AUTOVACUUM is disabled then a zero is stored in register P2.
77930**
77931** See also: Clear
77932*/
77933case OP_Destroy: {     /* out2 */
77934  int iMoved;
77935  int iDb;
77936
77937  assert( p->readOnly==0 );
77938  pOut = out2Prerelease(p, pOp);
77939  pOut->flags = MEM_Null;
77940  if( db->nVdbeRead > db->nVDestroy+1 ){
77941    rc = SQLITE_LOCKED;
77942    p->errorAction = OE_Abort;
77943  }else{
77944    iDb = pOp->p3;
77945    assert( DbMaskTest(p->btreeMask, iDb) );
77946    iMoved = 0;  /* Not needed.  Only to silence a warning. */
77947    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
77948    pOut->flags = MEM_Int;
77949    pOut->u.i = iMoved;
77950#ifndef SQLITE_OMIT_AUTOVACUUM
77951    if( rc==SQLITE_OK && iMoved!=0 ){
77952      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
77953      /* All OP_Destroy operations occur on the same btree */
77954      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
77955      resetSchemaOnFault = iDb+1;
77956    }
77957#endif
77958  }
77959  break;
77960}
77961
77962/* Opcode: Clear P1 P2 P3
77963**
77964** Delete all contents of the database table or index whose root page
77965** in the database file is given by P1.  But, unlike Destroy, do not
77966** remove the table or index from the database file.
77967**
77968** The table being clear is in the main database file if P2==0.  If
77969** P2==1 then the table to be clear is in the auxiliary database file
77970** that is used to store tables create using CREATE TEMPORARY TABLE.
77971**
77972** If the P3 value is non-zero, then the table referred to must be an
77973** intkey table (an SQL table, not an index). In this case the row change
77974** count is incremented by the number of rows in the table being cleared.
77975** If P3 is greater than zero, then the value stored in register P3 is
77976** also incremented by the number of rows in the table being cleared.
77977**
77978** See also: Destroy
77979*/
77980case OP_Clear: {
77981  int nChange;
77982
77983  nChange = 0;
77984  assert( p->readOnly==0 );
77985  assert( DbMaskTest(p->btreeMask, pOp->p2) );
77986  rc = sqlite3BtreeClearTable(
77987      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
77988  );
77989  if( pOp->p3 ){
77990    p->nChange += nChange;
77991    if( pOp->p3>0 ){
77992      assert( memIsValid(&aMem[pOp->p3]) );
77993      memAboutToChange(p, &aMem[pOp->p3]);
77994      aMem[pOp->p3].u.i += nChange;
77995    }
77996  }
77997  break;
77998}
77999
78000/* Opcode: ResetSorter P1 * * * *
78001**
78002** Delete all contents from the ephemeral table or sorter
78003** that is open on cursor P1.
78004**
78005** This opcode only works for cursors used for sorting and
78006** opened with OP_OpenEphemeral or OP_SorterOpen.
78007*/
78008case OP_ResetSorter: {
78009  VdbeCursor *pC;
78010
78011  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
78012  pC = p->apCsr[pOp->p1];
78013  assert( pC!=0 );
78014  if( pC->pSorter ){
78015    sqlite3VdbeSorterReset(db, pC->pSorter);
78016  }else{
78017    assert( pC->isEphemeral );
78018    rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
78019  }
78020  break;
78021}
78022
78023/* Opcode: CreateTable P1 P2 * * *
78024** Synopsis: r[P2]=root iDb=P1
78025**
78026** Allocate a new table in the main database file if P1==0 or in the
78027** auxiliary database file if P1==1 or in an attached database if
78028** P1>1.  Write the root page number of the new table into
78029** register P2
78030**
78031** The difference between a table and an index is this:  A table must
78032** have a 4-byte integer key and can have arbitrary data.  An index
78033** has an arbitrary key but no data.
78034**
78035** See also: CreateIndex
78036*/
78037/* Opcode: CreateIndex P1 P2 * * *
78038** Synopsis: r[P2]=root iDb=P1
78039**
78040** Allocate a new index in the main database file if P1==0 or in the
78041** auxiliary database file if P1==1 or in an attached database if
78042** P1>1.  Write the root page number of the new table into
78043** register P2.
78044**
78045** See documentation on OP_CreateTable for additional information.
78046*/
78047case OP_CreateIndex:            /* out2 */
78048case OP_CreateTable: {          /* out2 */
78049  int pgno;
78050  int flags;
78051  Db *pDb;
78052
78053  pOut = out2Prerelease(p, pOp);
78054  pgno = 0;
78055  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78056  assert( DbMaskTest(p->btreeMask, pOp->p1) );
78057  assert( p->readOnly==0 );
78058  pDb = &db->aDb[pOp->p1];
78059  assert( pDb->pBt!=0 );
78060  if( pOp->opcode==OP_CreateTable ){
78061    /* flags = BTREE_INTKEY; */
78062    flags = BTREE_INTKEY;
78063  }else{
78064    flags = BTREE_BLOBKEY;
78065  }
78066  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
78067  pOut->u.i = pgno;
78068  break;
78069}
78070
78071/* Opcode: ParseSchema P1 * * P4 *
78072**
78073** Read and parse all entries from the SQLITE_MASTER table of database P1
78074** that match the WHERE clause P4.
78075**
78076** This opcode invokes the parser to create a new virtual machine,
78077** then runs the new virtual machine.  It is thus a re-entrant opcode.
78078*/
78079case OP_ParseSchema: {
78080  int iDb;
78081  const char *zMaster;
78082  char *zSql;
78083  InitData initData;
78084
78085  /* Any prepared statement that invokes this opcode will hold mutexes
78086  ** on every btree.  This is a prerequisite for invoking
78087  ** sqlite3InitCallback().
78088  */
78089#ifdef SQLITE_DEBUG
78090  for(iDb=0; iDb<db->nDb; iDb++){
78091    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78092  }
78093#endif
78094
78095  iDb = pOp->p1;
78096  assert( iDb>=0 && iDb<db->nDb );
78097  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
78098  /* Used to be a conditional */ {
78099    zMaster = SCHEMA_TABLE(iDb);
78100    initData.db = db;
78101    initData.iDb = pOp->p1;
78102    initData.pzErrMsg = &p->zErrMsg;
78103    zSql = sqlite3MPrintf(db,
78104       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
78105       db->aDb[iDb].zName, zMaster, pOp->p4.z);
78106    if( zSql==0 ){
78107      rc = SQLITE_NOMEM;
78108    }else{
78109      assert( db->init.busy==0 );
78110      db->init.busy = 1;
78111      initData.rc = SQLITE_OK;
78112      assert( !db->mallocFailed );
78113      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78114      if( rc==SQLITE_OK ) rc = initData.rc;
78115      sqlite3DbFree(db, zSql);
78116      db->init.busy = 0;
78117    }
78118  }
78119  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
78120  if( rc==SQLITE_NOMEM ){
78121    goto no_mem;
78122  }
78123  break;
78124}
78125
78126#if !defined(SQLITE_OMIT_ANALYZE)
78127/* Opcode: LoadAnalysis P1 * * * *
78128**
78129** Read the sqlite_stat1 table for database P1 and load the content
78130** of that table into the internal index hash table.  This will cause
78131** the analysis to be used when preparing all subsequent queries.
78132*/
78133case OP_LoadAnalysis: {
78134  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78135  rc = sqlite3AnalysisLoad(db, pOp->p1);
78136  break;
78137}
78138#endif /* !defined(SQLITE_OMIT_ANALYZE) */
78139
78140/* Opcode: DropTable P1 * * P4 *
78141**
78142** Remove the internal (in-memory) data structures that describe
78143** the table named P4 in database P1.  This is called after a table
78144** is dropped from disk (using the Destroy opcode) in order to keep
78145** the internal representation of the
78146** schema consistent with what is on disk.
78147*/
78148case OP_DropTable: {
78149  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
78150  break;
78151}
78152
78153/* Opcode: DropIndex P1 * * P4 *
78154**
78155** Remove the internal (in-memory) data structures that describe
78156** the index named P4 in database P1.  This is called after an index
78157** is dropped from disk (using the Destroy opcode)
78158** in order to keep the internal representation of the
78159** schema consistent with what is on disk.
78160*/
78161case OP_DropIndex: {
78162  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
78163  break;
78164}
78165
78166/* Opcode: DropTrigger P1 * * P4 *
78167**
78168** Remove the internal (in-memory) data structures that describe
78169** the trigger named P4 in database P1.  This is called after a trigger
78170** is dropped from disk (using the Destroy opcode) in order to keep
78171** the internal representation of the
78172** schema consistent with what is on disk.
78173*/
78174case OP_DropTrigger: {
78175  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
78176  break;
78177}
78178
78179
78180#ifndef SQLITE_OMIT_INTEGRITY_CHECK
78181/* Opcode: IntegrityCk P1 P2 P3 * P5
78182**
78183** Do an analysis of the currently open database.  Store in
78184** register P1 the text of an error message describing any problems.
78185** If no problems are found, store a NULL in register P1.
78186**
78187** The register P3 contains the maximum number of allowed errors.
78188** At most reg(P3) errors will be reported.
78189** In other words, the analysis stops as soon as reg(P1) errors are
78190** seen.  Reg(P1) is updated with the number of errors remaining.
78191**
78192** The root page numbers of all tables in the database are integer
78193** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
78194** total.
78195**
78196** If P5 is not zero, the check is done on the auxiliary database
78197** file, not the main database file.
78198**
78199** This opcode is used to implement the integrity_check pragma.
78200*/
78201case OP_IntegrityCk: {
78202  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
78203  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
78204  int j;          /* Loop counter */
78205  int nErr;       /* Number of errors reported */
78206  char *z;        /* Text of the error report */
78207  Mem *pnErr;     /* Register keeping track of errors remaining */
78208
78209  assert( p->bIsReader );
78210  nRoot = pOp->p2;
78211  assert( nRoot>0 );
78212  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
78213  if( aRoot==0 ) goto no_mem;
78214  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
78215  pnErr = &aMem[pOp->p3];
78216  assert( (pnErr->flags & MEM_Int)!=0 );
78217  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
78218  pIn1 = &aMem[pOp->p1];
78219  for(j=0; j<nRoot; j++){
78220    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
78221  }
78222  aRoot[j] = 0;
78223  assert( pOp->p5<db->nDb );
78224  assert( DbMaskTest(p->btreeMask, pOp->p5) );
78225  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
78226                                 (int)pnErr->u.i, &nErr);
78227  sqlite3DbFree(db, aRoot);
78228  pnErr->u.i -= nErr;
78229  sqlite3VdbeMemSetNull(pIn1);
78230  if( nErr==0 ){
78231    assert( z==0 );
78232  }else if( z==0 ){
78233    goto no_mem;
78234  }else{
78235    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
78236  }
78237  UPDATE_MAX_BLOBSIZE(pIn1);
78238  sqlite3VdbeChangeEncoding(pIn1, encoding);
78239  break;
78240}
78241#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
78242
78243/* Opcode: RowSetAdd P1 P2 * * *
78244** Synopsis:  rowset(P1)=r[P2]
78245**
78246** Insert the integer value held by register P2 into a boolean index
78247** held in register P1.
78248**
78249** An assertion fails if P2 is not an integer.
78250*/
78251case OP_RowSetAdd: {       /* in1, in2 */
78252  pIn1 = &aMem[pOp->p1];
78253  pIn2 = &aMem[pOp->p2];
78254  assert( (pIn2->flags & MEM_Int)!=0 );
78255  if( (pIn1->flags & MEM_RowSet)==0 ){
78256    sqlite3VdbeMemSetRowSet(pIn1);
78257    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
78258  }
78259  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
78260  break;
78261}
78262
78263/* Opcode: RowSetRead P1 P2 P3 * *
78264** Synopsis:  r[P3]=rowset(P1)
78265**
78266** Extract the smallest value from boolean index P1 and put that value into
78267** register P3.  Or, if boolean index P1 is initially empty, leave P3
78268** unchanged and jump to instruction P2.
78269*/
78270case OP_RowSetRead: {       /* jump, in1, out3 */
78271  i64 val;
78272
78273  pIn1 = &aMem[pOp->p1];
78274  if( (pIn1->flags & MEM_RowSet)==0
78275   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
78276  ){
78277    /* The boolean index is empty */
78278    sqlite3VdbeMemSetNull(pIn1);
78279    VdbeBranchTaken(1,2);
78280    goto jump_to_p2_and_check_for_interrupt;
78281  }else{
78282    /* A value was pulled from the index */
78283    VdbeBranchTaken(0,2);
78284    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
78285  }
78286  goto check_for_interrupt;
78287}
78288
78289/* Opcode: RowSetTest P1 P2 P3 P4
78290** Synopsis: if r[P3] in rowset(P1) goto P2
78291**
78292** Register P3 is assumed to hold a 64-bit integer value. If register P1
78293** contains a RowSet object and that RowSet object contains
78294** the value held in P3, jump to register P2. Otherwise, insert the
78295** integer in P3 into the RowSet and continue on to the
78296** next opcode.
78297**
78298** The RowSet object is optimized for the case where successive sets
78299** of integers, where each set contains no duplicates. Each set
78300** of values is identified by a unique P4 value. The first set
78301** must have P4==0, the final set P4=-1.  P4 must be either -1 or
78302** non-negative.  For non-negative values of P4 only the lower 4
78303** bits are significant.
78304**
78305** This allows optimizations: (a) when P4==0 there is no need to test
78306** the rowset object for P3, as it is guaranteed not to contain it,
78307** (b) when P4==-1 there is no need to insert the value, as it will
78308** never be tested for, and (c) when a value that is part of set X is
78309** inserted, there is no need to search to see if the same value was
78310** previously inserted as part of set X (only if it was previously
78311** inserted as part of some other set).
78312*/
78313case OP_RowSetTest: {                     /* jump, in1, in3 */
78314  int iSet;
78315  int exists;
78316
78317  pIn1 = &aMem[pOp->p1];
78318  pIn3 = &aMem[pOp->p3];
78319  iSet = pOp->p4.i;
78320  assert( pIn3->flags&MEM_Int );
78321
78322  /* If there is anything other than a rowset object in memory cell P1,
78323  ** delete it now and initialize P1 with an empty rowset
78324  */
78325  if( (pIn1->flags & MEM_RowSet)==0 ){
78326    sqlite3VdbeMemSetRowSet(pIn1);
78327    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
78328  }
78329
78330  assert( pOp->p4type==P4_INT32 );
78331  assert( iSet==-1 || iSet>=0 );
78332  if( iSet ){
78333    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
78334    VdbeBranchTaken(exists!=0,2);
78335    if( exists ) goto jump_to_p2;
78336  }
78337  if( iSet>=0 ){
78338    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
78339  }
78340  break;
78341}
78342
78343
78344#ifndef SQLITE_OMIT_TRIGGER
78345
78346/* Opcode: Program P1 P2 P3 P4 P5
78347**
78348** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
78349**
78350** P1 contains the address of the memory cell that contains the first memory
78351** cell in an array of values used as arguments to the sub-program. P2
78352** contains the address to jump to if the sub-program throws an IGNORE
78353** exception using the RAISE() function. Register P3 contains the address
78354** of a memory cell in this (the parent) VM that is used to allocate the
78355** memory required by the sub-vdbe at runtime.
78356**
78357** P4 is a pointer to the VM containing the trigger program.
78358**
78359** If P5 is non-zero, then recursive program invocation is enabled.
78360*/
78361case OP_Program: {        /* jump */
78362  int nMem;               /* Number of memory registers for sub-program */
78363  int nByte;              /* Bytes of runtime space required for sub-program */
78364  Mem *pRt;               /* Register to allocate runtime space */
78365  Mem *pMem;              /* Used to iterate through memory cells */
78366  Mem *pEnd;              /* Last memory cell in new array */
78367  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
78368  SubProgram *pProgram;   /* Sub-program to execute */
78369  void *t;                /* Token identifying trigger */
78370
78371  pProgram = pOp->p4.pProgram;
78372  pRt = &aMem[pOp->p3];
78373  assert( pProgram->nOp>0 );
78374
78375  /* If the p5 flag is clear, then recursive invocation of triggers is
78376  ** disabled for backwards compatibility (p5 is set if this sub-program
78377  ** is really a trigger, not a foreign key action, and the flag set
78378  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
78379  **
78380  ** It is recursive invocation of triggers, at the SQL level, that is
78381  ** disabled. In some cases a single trigger may generate more than one
78382  ** SubProgram (if the trigger may be executed with more than one different
78383  ** ON CONFLICT algorithm). SubProgram structures associated with a
78384  ** single trigger all have the same value for the SubProgram.token
78385  ** variable.  */
78386  if( pOp->p5 ){
78387    t = pProgram->token;
78388    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
78389    if( pFrame ) break;
78390  }
78391
78392  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
78393    rc = SQLITE_ERROR;
78394    sqlite3VdbeError(p, "too many levels of trigger recursion");
78395    break;
78396  }
78397
78398  /* Register pRt is used to store the memory required to save the state
78399  ** of the current program, and the memory required at runtime to execute
78400  ** the trigger program. If this trigger has been fired before, then pRt
78401  ** is already allocated. Otherwise, it must be initialized.  */
78402  if( (pRt->flags&MEM_Frame)==0 ){
78403    /* SubProgram.nMem is set to the number of memory cells used by the
78404    ** program stored in SubProgram.aOp. As well as these, one memory
78405    ** cell is required for each cursor used by the program. Set local
78406    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
78407    */
78408    nMem = pProgram->nMem + pProgram->nCsr;
78409    nByte = ROUND8(sizeof(VdbeFrame))
78410              + nMem * sizeof(Mem)
78411              + pProgram->nCsr * sizeof(VdbeCursor *)
78412              + pProgram->nOnce * sizeof(u8);
78413    pFrame = sqlite3DbMallocZero(db, nByte);
78414    if( !pFrame ){
78415      goto no_mem;
78416    }
78417    sqlite3VdbeMemRelease(pRt);
78418    pRt->flags = MEM_Frame;
78419    pRt->u.pFrame = pFrame;
78420
78421    pFrame->v = p;
78422    pFrame->nChildMem = nMem;
78423    pFrame->nChildCsr = pProgram->nCsr;
78424    pFrame->pc = (int)(pOp - aOp);
78425    pFrame->aMem = p->aMem;
78426    pFrame->nMem = p->nMem;
78427    pFrame->apCsr = p->apCsr;
78428    pFrame->nCursor = p->nCursor;
78429    pFrame->aOp = p->aOp;
78430    pFrame->nOp = p->nOp;
78431    pFrame->token = pProgram->token;
78432    pFrame->aOnceFlag = p->aOnceFlag;
78433    pFrame->nOnceFlag = p->nOnceFlag;
78434#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78435    pFrame->anExec = p->anExec;
78436#endif
78437
78438    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
78439    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
78440      pMem->flags = MEM_Undefined;
78441      pMem->db = db;
78442    }
78443  }else{
78444    pFrame = pRt->u.pFrame;
78445    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
78446    assert( pProgram->nCsr==pFrame->nChildCsr );
78447    assert( (int)(pOp - aOp)==pFrame->pc );
78448  }
78449
78450  p->nFrame++;
78451  pFrame->pParent = p->pFrame;
78452  pFrame->lastRowid = lastRowid;
78453  pFrame->nChange = p->nChange;
78454  pFrame->nDbChange = p->db->nChange;
78455  p->nChange = 0;
78456  p->pFrame = pFrame;
78457  p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
78458  p->nMem = pFrame->nChildMem;
78459  p->nCursor = (u16)pFrame->nChildCsr;
78460  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
78461  p->aOp = aOp = pProgram->aOp;
78462  p->nOp = pProgram->nOp;
78463  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
78464  p->nOnceFlag = pProgram->nOnce;
78465#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78466  p->anExec = 0;
78467#endif
78468  pOp = &aOp[-1];
78469  memset(p->aOnceFlag, 0, p->nOnceFlag);
78470
78471  break;
78472}
78473
78474/* Opcode: Param P1 P2 * * *
78475**
78476** This opcode is only ever present in sub-programs called via the
78477** OP_Program instruction. Copy a value currently stored in a memory
78478** cell of the calling (parent) frame to cell P2 in the current frames
78479** address space. This is used by trigger programs to access the new.*
78480** and old.* values.
78481**
78482** The address of the cell in the parent frame is determined by adding
78483** the value of the P1 argument to the value of the P1 argument to the
78484** calling OP_Program instruction.
78485*/
78486case OP_Param: {           /* out2 */
78487  VdbeFrame *pFrame;
78488  Mem *pIn;
78489  pOut = out2Prerelease(p, pOp);
78490  pFrame = p->pFrame;
78491  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
78492  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
78493  break;
78494}
78495
78496#endif /* #ifndef SQLITE_OMIT_TRIGGER */
78497
78498#ifndef SQLITE_OMIT_FOREIGN_KEY
78499/* Opcode: FkCounter P1 P2 * * *
78500** Synopsis: fkctr[P1]+=P2
78501**
78502** Increment a "constraint counter" by P2 (P2 may be negative or positive).
78503** If P1 is non-zero, the database constraint counter is incremented
78504** (deferred foreign key constraints). Otherwise, if P1 is zero, the
78505** statement counter is incremented (immediate foreign key constraints).
78506*/
78507case OP_FkCounter: {
78508  if( db->flags & SQLITE_DeferFKs ){
78509    db->nDeferredImmCons += pOp->p2;
78510  }else if( pOp->p1 ){
78511    db->nDeferredCons += pOp->p2;
78512  }else{
78513    p->nFkConstraint += pOp->p2;
78514  }
78515  break;
78516}
78517
78518/* Opcode: FkIfZero P1 P2 * * *
78519** Synopsis: if fkctr[P1]==0 goto P2
78520**
78521** This opcode tests if a foreign key constraint-counter is currently zero.
78522** If so, jump to instruction P2. Otherwise, fall through to the next
78523** instruction.
78524**
78525** If P1 is non-zero, then the jump is taken if the database constraint-counter
78526** is zero (the one that counts deferred constraint violations). If P1 is
78527** zero, the jump is taken if the statement constraint-counter is zero
78528** (immediate foreign key constraint violations).
78529*/
78530case OP_FkIfZero: {         /* jump */
78531  if( pOp->p1 ){
78532    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
78533    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
78534  }else{
78535    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
78536    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
78537  }
78538  break;
78539}
78540#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
78541
78542#ifndef SQLITE_OMIT_AUTOINCREMENT
78543/* Opcode: MemMax P1 P2 * * *
78544** Synopsis: r[P1]=max(r[P1],r[P2])
78545**
78546** P1 is a register in the root frame of this VM (the root frame is
78547** different from the current frame if this instruction is being executed
78548** within a sub-program). Set the value of register P1 to the maximum of
78549** its current value and the value in register P2.
78550**
78551** This instruction throws an error if the memory cell is not initially
78552** an integer.
78553*/
78554case OP_MemMax: {        /* in2 */
78555  VdbeFrame *pFrame;
78556  if( p->pFrame ){
78557    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
78558    pIn1 = &pFrame->aMem[pOp->p1];
78559  }else{
78560    pIn1 = &aMem[pOp->p1];
78561  }
78562  assert( memIsValid(pIn1) );
78563  sqlite3VdbeMemIntegerify(pIn1);
78564  pIn2 = &aMem[pOp->p2];
78565  sqlite3VdbeMemIntegerify(pIn2);
78566  if( pIn1->u.i<pIn2->u.i){
78567    pIn1->u.i = pIn2->u.i;
78568  }
78569  break;
78570}
78571#endif /* SQLITE_OMIT_AUTOINCREMENT */
78572
78573/* Opcode: IfPos P1 P2 P3 * *
78574** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
78575**
78576** Register P1 must contain an integer.
78577** If the value of register P1 is 1 or greater, subtract P3 from the
78578** value in P1 and jump to P2.
78579**
78580** If the initial value of register P1 is less than 1, then the
78581** value is unchanged and control passes through to the next instruction.
78582*/
78583case OP_IfPos: {        /* jump, in1 */
78584  pIn1 = &aMem[pOp->p1];
78585  assert( pIn1->flags&MEM_Int );
78586  VdbeBranchTaken( pIn1->u.i>0, 2);
78587  if( pIn1->u.i>0 ){
78588    pIn1->u.i -= pOp->p3;
78589    goto jump_to_p2;
78590  }
78591  break;
78592}
78593
78594/* Opcode: SetIfNotPos P1 P2 P3 * *
78595** Synopsis: if r[P1]<=0 then r[P2]=P3
78596**
78597** Register P1 must contain an integer.
78598** If the value of register P1 is not positive (if it is less than 1) then
78599** set the value of register P2 to be the integer P3.
78600*/
78601case OP_SetIfNotPos: {        /* in1, in2 */
78602  pIn1 = &aMem[pOp->p1];
78603  assert( pIn1->flags&MEM_Int );
78604  if( pIn1->u.i<=0 ){
78605    pOut = out2Prerelease(p, pOp);
78606    pOut->u.i = pOp->p3;
78607  }
78608  break;
78609}
78610
78611/* Opcode: IfNotZero P1 P2 P3 * *
78612** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
78613**
78614** Register P1 must contain an integer.  If the content of register P1 is
78615** initially nonzero, then subtract P3 from the value in register P1 and
78616** jump to P2.  If register P1 is initially zero, leave it unchanged
78617** and fall through.
78618*/
78619case OP_IfNotZero: {        /* jump, in1 */
78620  pIn1 = &aMem[pOp->p1];
78621  assert( pIn1->flags&MEM_Int );
78622  VdbeBranchTaken(pIn1->u.i<0, 2);
78623  if( pIn1->u.i ){
78624     pIn1->u.i -= pOp->p3;
78625     goto jump_to_p2;
78626  }
78627  break;
78628}
78629
78630/* Opcode: DecrJumpZero P1 P2 * * *
78631** Synopsis: if (--r[P1])==0 goto P2
78632**
78633** Register P1 must hold an integer.  Decrement the value in register P1
78634** then jump to P2 if the new value is exactly zero.
78635*/
78636case OP_DecrJumpZero: {      /* jump, in1 */
78637  pIn1 = &aMem[pOp->p1];
78638  assert( pIn1->flags&MEM_Int );
78639  pIn1->u.i--;
78640  VdbeBranchTaken(pIn1->u.i==0, 2);
78641  if( pIn1->u.i==0 ) goto jump_to_p2;
78642  break;
78643}
78644
78645
78646/* Opcode: JumpZeroIncr P1 P2 * * *
78647** Synopsis: if (r[P1]++)==0 ) goto P2
78648**
78649** The register P1 must contain an integer.  If register P1 is initially
78650** zero, then jump to P2.  Increment register P1 regardless of whether or
78651** not the jump is taken.
78652*/
78653case OP_JumpZeroIncr: {        /* jump, in1 */
78654  pIn1 = &aMem[pOp->p1];
78655  assert( pIn1->flags&MEM_Int );
78656  VdbeBranchTaken(pIn1->u.i==0, 2);
78657  if( (pIn1->u.i++)==0 ) goto jump_to_p2;
78658  break;
78659}
78660
78661/* Opcode: AggStep0 * P2 P3 P4 P5
78662** Synopsis: accum=r[P3] step(r[P2@P5])
78663**
78664** Execute the step function for an aggregate.  The
78665** function has P5 arguments.   P4 is a pointer to the FuncDef
78666** structure that specifies the function.  Register P3 is the
78667** accumulator.
78668**
78669** The P5 arguments are taken from register P2 and its
78670** successors.
78671*/
78672/* Opcode: AggStep * P2 P3 P4 P5
78673** Synopsis: accum=r[P3] step(r[P2@P5])
78674**
78675** Execute the step function for an aggregate.  The
78676** function has P5 arguments.   P4 is a pointer to an sqlite3_context
78677** object that is used to run the function.  Register P3 is
78678** as the accumulator.
78679**
78680** The P5 arguments are taken from register P2 and its
78681** successors.
78682**
78683** This opcode is initially coded as OP_AggStep0.  On first evaluation,
78684** the FuncDef stored in P4 is converted into an sqlite3_context and
78685** the opcode is changed.  In this way, the initialization of the
78686** sqlite3_context only happens once, instead of on each call to the
78687** step function.
78688*/
78689case OP_AggStep0: {
78690  int n;
78691  sqlite3_context *pCtx;
78692
78693  assert( pOp->p4type==P4_FUNCDEF );
78694  n = pOp->p5;
78695  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
78696  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
78697  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78698  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78699  if( pCtx==0 ) goto no_mem;
78700  pCtx->pMem = 0;
78701  pCtx->pFunc = pOp->p4.pFunc;
78702  pCtx->iOp = (int)(pOp - aOp);
78703  pCtx->pVdbe = p;
78704  pCtx->argc = n;
78705  pOp->p4type = P4_FUNCCTX;
78706  pOp->p4.pCtx = pCtx;
78707  pOp->opcode = OP_AggStep;
78708  /* Fall through into OP_AggStep */
78709}
78710case OP_AggStep: {
78711  int i;
78712  sqlite3_context *pCtx;
78713  Mem *pMem;
78714  Mem t;
78715
78716  assert( pOp->p4type==P4_FUNCCTX );
78717  pCtx = pOp->p4.pCtx;
78718  pMem = &aMem[pOp->p3];
78719
78720  /* If this function is inside of a trigger, the register array in aMem[]
78721  ** might change from one evaluation to the next.  The next block of code
78722  ** checks to see if the register array has changed, and if so it
78723  ** reinitializes the relavant parts of the sqlite3_context object */
78724  if( pCtx->pMem != pMem ){
78725    pCtx->pMem = pMem;
78726    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78727  }
78728
78729#ifdef SQLITE_DEBUG
78730  for(i=0; i<pCtx->argc; i++){
78731    assert( memIsValid(pCtx->argv[i]) );
78732    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78733  }
78734#endif
78735
78736  pMem->n++;
78737  sqlite3VdbeMemInit(&t, db, MEM_Null);
78738  pCtx->pOut = &t;
78739  pCtx->fErrorOrAux = 0;
78740  pCtx->skipFlag = 0;
78741  (pCtx->pFunc->xStep)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
78742  if( pCtx->fErrorOrAux ){
78743    if( pCtx->isError ){
78744      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
78745      rc = pCtx->isError;
78746    }
78747    sqlite3VdbeMemRelease(&t);
78748  }else{
78749    assert( t.flags==MEM_Null );
78750  }
78751  if( pCtx->skipFlag ){
78752    assert( pOp[-1].opcode==OP_CollSeq );
78753    i = pOp[-1].p1;
78754    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
78755  }
78756  break;
78757}
78758
78759/* Opcode: AggFinal P1 P2 * P4 *
78760** Synopsis: accum=r[P1] N=P2
78761**
78762** Execute the finalizer function for an aggregate.  P1 is
78763** the memory location that is the accumulator for the aggregate.
78764**
78765** P2 is the number of arguments that the step function takes and
78766** P4 is a pointer to the FuncDef for this function.  The P2
78767** argument is not used by this opcode.  It is only there to disambiguate
78768** functions that can take varying numbers of arguments.  The
78769** P4 argument is only needed for the degenerate case where
78770** the step function was not previously called.
78771*/
78772case OP_AggFinal: {
78773  Mem *pMem;
78774  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
78775  pMem = &aMem[pOp->p1];
78776  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
78777  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
78778  if( rc ){
78779    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
78780  }
78781  sqlite3VdbeChangeEncoding(pMem, encoding);
78782  UPDATE_MAX_BLOBSIZE(pMem);
78783  if( sqlite3VdbeMemTooBig(pMem) ){
78784    goto too_big;
78785  }
78786  break;
78787}
78788
78789#ifndef SQLITE_OMIT_WAL
78790/* Opcode: Checkpoint P1 P2 P3 * *
78791**
78792** Checkpoint database P1. This is a no-op if P1 is not currently in
78793** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
78794** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
78795** SQLITE_BUSY or not, respectively.  Write the number of pages in the
78796** WAL after the checkpoint into mem[P3+1] and the number of pages
78797** in the WAL that have been checkpointed after the checkpoint
78798** completes into mem[P3+2].  However on an error, mem[P3+1] and
78799** mem[P3+2] are initialized to -1.
78800*/
78801case OP_Checkpoint: {
78802  int i;                          /* Loop counter */
78803  int aRes[3];                    /* Results */
78804  Mem *pMem;                      /* Write results here */
78805
78806  assert( p->readOnly==0 );
78807  aRes[0] = 0;
78808  aRes[1] = aRes[2] = -1;
78809  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
78810       || pOp->p2==SQLITE_CHECKPOINT_FULL
78811       || pOp->p2==SQLITE_CHECKPOINT_RESTART
78812       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
78813  );
78814  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
78815  if( rc==SQLITE_BUSY ){
78816    rc = SQLITE_OK;
78817    aRes[0] = 1;
78818  }
78819  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
78820    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
78821  }
78822  break;
78823};
78824#endif
78825
78826#ifndef SQLITE_OMIT_PRAGMA
78827/* Opcode: JournalMode P1 P2 P3 * *
78828**
78829** Change the journal mode of database P1 to P3. P3 must be one of the
78830** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
78831** modes (delete, truncate, persist, off and memory), this is a simple
78832** operation. No IO is required.
78833**
78834** If changing into or out of WAL mode the procedure is more complicated.
78835**
78836** Write a string containing the final journal-mode to register P2.
78837*/
78838case OP_JournalMode: {    /* out2 */
78839  Btree *pBt;                     /* Btree to change journal mode of */
78840  Pager *pPager;                  /* Pager associated with pBt */
78841  int eNew;                       /* New journal mode */
78842  int eOld;                       /* The old journal mode */
78843#ifndef SQLITE_OMIT_WAL
78844  const char *zFilename;          /* Name of database file for pPager */
78845#endif
78846
78847  pOut = out2Prerelease(p, pOp);
78848  eNew = pOp->p3;
78849  assert( eNew==PAGER_JOURNALMODE_DELETE
78850       || eNew==PAGER_JOURNALMODE_TRUNCATE
78851       || eNew==PAGER_JOURNALMODE_PERSIST
78852       || eNew==PAGER_JOURNALMODE_OFF
78853       || eNew==PAGER_JOURNALMODE_MEMORY
78854       || eNew==PAGER_JOURNALMODE_WAL
78855       || eNew==PAGER_JOURNALMODE_QUERY
78856  );
78857  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78858  assert( p->readOnly==0 );
78859
78860  pBt = db->aDb[pOp->p1].pBt;
78861  pPager = sqlite3BtreePager(pBt);
78862  eOld = sqlite3PagerGetJournalMode(pPager);
78863  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
78864  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
78865
78866#ifndef SQLITE_OMIT_WAL
78867  zFilename = sqlite3PagerFilename(pPager, 1);
78868
78869  /* Do not allow a transition to journal_mode=WAL for a database
78870  ** in temporary storage or if the VFS does not support shared memory
78871  */
78872  if( eNew==PAGER_JOURNALMODE_WAL
78873   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
78874       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
78875  ){
78876    eNew = eOld;
78877  }
78878
78879  if( (eNew!=eOld)
78880   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
78881  ){
78882    if( !db->autoCommit || db->nVdbeRead>1 ){
78883      rc = SQLITE_ERROR;
78884      sqlite3VdbeError(p,
78885          "cannot change %s wal mode from within a transaction",
78886          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
78887      );
78888      break;
78889    }else{
78890
78891      if( eOld==PAGER_JOURNALMODE_WAL ){
78892        /* If leaving WAL mode, close the log file. If successful, the call
78893        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
78894        ** file. An EXCLUSIVE lock may still be held on the database file
78895        ** after a successful return.
78896        */
78897        rc = sqlite3PagerCloseWal(pPager);
78898        if( rc==SQLITE_OK ){
78899          sqlite3PagerSetJournalMode(pPager, eNew);
78900        }
78901      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
78902        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
78903        ** as an intermediate */
78904        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
78905      }
78906
78907      /* Open a transaction on the database file. Regardless of the journal
78908      ** mode, this transaction always uses a rollback journal.
78909      */
78910      assert( sqlite3BtreeIsInTrans(pBt)==0 );
78911      if( rc==SQLITE_OK ){
78912        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
78913      }
78914    }
78915  }
78916#endif /* ifndef SQLITE_OMIT_WAL */
78917
78918  if( rc ){
78919    eNew = eOld;
78920  }
78921  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
78922
78923  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78924  pOut->z = (char *)sqlite3JournalModename(eNew);
78925  pOut->n = sqlite3Strlen30(pOut->z);
78926  pOut->enc = SQLITE_UTF8;
78927  sqlite3VdbeChangeEncoding(pOut, encoding);
78928  break;
78929};
78930#endif /* SQLITE_OMIT_PRAGMA */
78931
78932#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
78933/* Opcode: Vacuum * * * * *
78934**
78935** Vacuum the entire database.  This opcode will cause other virtual
78936** machines to be created and run.  It may not be called from within
78937** a transaction.
78938*/
78939case OP_Vacuum: {
78940  assert( p->readOnly==0 );
78941  rc = sqlite3RunVacuum(&p->zErrMsg, db);
78942  break;
78943}
78944#endif
78945
78946#if !defined(SQLITE_OMIT_AUTOVACUUM)
78947/* Opcode: IncrVacuum P1 P2 * * *
78948**
78949** Perform a single step of the incremental vacuum procedure on
78950** the P1 database. If the vacuum has finished, jump to instruction
78951** P2. Otherwise, fall through to the next instruction.
78952*/
78953case OP_IncrVacuum: {        /* jump */
78954  Btree *pBt;
78955
78956  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78957  assert( DbMaskTest(p->btreeMask, pOp->p1) );
78958  assert( p->readOnly==0 );
78959  pBt = db->aDb[pOp->p1].pBt;
78960  rc = sqlite3BtreeIncrVacuum(pBt);
78961  VdbeBranchTaken(rc==SQLITE_DONE,2);
78962  if( rc==SQLITE_DONE ){
78963    rc = SQLITE_OK;
78964    goto jump_to_p2;
78965  }
78966  break;
78967}
78968#endif
78969
78970/* Opcode: Expire P1 * * * *
78971**
78972** Cause precompiled statements to expire.  When an expired statement
78973** is executed using sqlite3_step() it will either automatically
78974** reprepare itself (if it was originally created using sqlite3_prepare_v2())
78975** or it will fail with SQLITE_SCHEMA.
78976**
78977** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
78978** then only the currently executing statement is expired.
78979*/
78980case OP_Expire: {
78981  if( !pOp->p1 ){
78982    sqlite3ExpirePreparedStatements(db);
78983  }else{
78984    p->expired = 1;
78985  }
78986  break;
78987}
78988
78989#ifndef SQLITE_OMIT_SHARED_CACHE
78990/* Opcode: TableLock P1 P2 P3 P4 *
78991** Synopsis: iDb=P1 root=P2 write=P3
78992**
78993** Obtain a lock on a particular table. This instruction is only used when
78994** the shared-cache feature is enabled.
78995**
78996** P1 is the index of the database in sqlite3.aDb[] of the database
78997** on which the lock is acquired.  A readlock is obtained if P3==0 or
78998** a write lock if P3==1.
78999**
79000** P2 contains the root-page of the table to lock.
79001**
79002** P4 contains a pointer to the name of the table being locked. This is only
79003** used to generate an error message if the lock cannot be obtained.
79004*/
79005case OP_TableLock: {
79006  u8 isWriteLock = (u8)pOp->p3;
79007  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
79008    int p1 = pOp->p1;
79009    assert( p1>=0 && p1<db->nDb );
79010    assert( DbMaskTest(p->btreeMask, p1) );
79011    assert( isWriteLock==0 || isWriteLock==1 );
79012    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
79013    if( (rc&0xFF)==SQLITE_LOCKED ){
79014      const char *z = pOp->p4.z;
79015      sqlite3VdbeError(p, "database table is locked: %s", z);
79016    }
79017  }
79018  break;
79019}
79020#endif /* SQLITE_OMIT_SHARED_CACHE */
79021
79022#ifndef SQLITE_OMIT_VIRTUALTABLE
79023/* Opcode: VBegin * * * P4 *
79024**
79025** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
79026** xBegin method for that table.
79027**
79028** Also, whether or not P4 is set, check that this is not being called from
79029** within a callback to a virtual table xSync() method. If it is, the error
79030** code will be set to SQLITE_LOCKED.
79031*/
79032case OP_VBegin: {
79033  VTable *pVTab;
79034  pVTab = pOp->p4.pVtab;
79035  rc = sqlite3VtabBegin(db, pVTab);
79036  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
79037  break;
79038}
79039#endif /* SQLITE_OMIT_VIRTUALTABLE */
79040
79041#ifndef SQLITE_OMIT_VIRTUALTABLE
79042/* Opcode: VCreate P1 P2 * * *
79043**
79044** P2 is a register that holds the name of a virtual table in database
79045** P1. Call the xCreate method for that table.
79046*/
79047case OP_VCreate: {
79048  Mem sMem;          /* For storing the record being decoded */
79049  const char *zTab;  /* Name of the virtual table */
79050
79051  memset(&sMem, 0, sizeof(sMem));
79052  sMem.db = db;
79053  /* Because P2 is always a static string, it is impossible for the
79054  ** sqlite3VdbeMemCopy() to fail */
79055  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
79056  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
79057  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
79058  assert( rc==SQLITE_OK );
79059  zTab = (const char*)sqlite3_value_text(&sMem);
79060  assert( zTab || db->mallocFailed );
79061  if( zTab ){
79062    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
79063  }
79064  sqlite3VdbeMemRelease(&sMem);
79065  break;
79066}
79067#endif /* SQLITE_OMIT_VIRTUALTABLE */
79068
79069#ifndef SQLITE_OMIT_VIRTUALTABLE
79070/* Opcode: VDestroy P1 * * P4 *
79071**
79072** P4 is the name of a virtual table in database P1.  Call the xDestroy method
79073** of that table.
79074*/
79075case OP_VDestroy: {
79076  db->nVDestroy++;
79077  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
79078  db->nVDestroy--;
79079  break;
79080}
79081#endif /* SQLITE_OMIT_VIRTUALTABLE */
79082
79083#ifndef SQLITE_OMIT_VIRTUALTABLE
79084/* Opcode: VOpen P1 * * P4 *
79085**
79086** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79087** P1 is a cursor number.  This opcode opens a cursor to the virtual
79088** table and stores that cursor in P1.
79089*/
79090case OP_VOpen: {
79091  VdbeCursor *pCur;
79092  sqlite3_vtab_cursor *pVtabCursor;
79093  sqlite3_vtab *pVtab;
79094  const sqlite3_module *pModule;
79095
79096  assert( p->bIsReader );
79097  pCur = 0;
79098  pVtabCursor = 0;
79099  pVtab = pOp->p4.pVtab->pVtab;
79100  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
79101    rc = SQLITE_LOCKED;
79102    break;
79103  }
79104  pModule = pVtab->pModule;
79105  rc = pModule->xOpen(pVtab, &pVtabCursor);
79106  sqlite3VtabImportErrmsg(p, pVtab);
79107  if( SQLITE_OK==rc ){
79108    /* Initialize sqlite3_vtab_cursor base class */
79109    pVtabCursor->pVtab = pVtab;
79110
79111    /* Initialize vdbe cursor object */
79112    pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
79113    if( pCur ){
79114      pCur->pVtabCursor = pVtabCursor;
79115      pVtab->nRef++;
79116    }else{
79117      assert( db->mallocFailed );
79118      pModule->xClose(pVtabCursor);
79119      goto no_mem;
79120    }
79121  }
79122  break;
79123}
79124#endif /* SQLITE_OMIT_VIRTUALTABLE */
79125
79126#ifndef SQLITE_OMIT_VIRTUALTABLE
79127/* Opcode: VFilter P1 P2 P3 P4 *
79128** Synopsis: iplan=r[P3] zplan='P4'
79129**
79130** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
79131** the filtered result set is empty.
79132**
79133** P4 is either NULL or a string that was generated by the xBestIndex
79134** method of the module.  The interpretation of the P4 string is left
79135** to the module implementation.
79136**
79137** This opcode invokes the xFilter method on the virtual table specified
79138** by P1.  The integer query plan parameter to xFilter is stored in register
79139** P3. Register P3+1 stores the argc parameter to be passed to the
79140** xFilter method. Registers P3+2..P3+1+argc are the argc
79141** additional parameters which are passed to
79142** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
79143**
79144** A jump is made to P2 if the result set after filtering would be empty.
79145*/
79146case OP_VFilter: {   /* jump */
79147  int nArg;
79148  int iQuery;
79149  const sqlite3_module *pModule;
79150  Mem *pQuery;
79151  Mem *pArgc;
79152  sqlite3_vtab_cursor *pVtabCursor;
79153  sqlite3_vtab *pVtab;
79154  VdbeCursor *pCur;
79155  int res;
79156  int i;
79157  Mem **apArg;
79158
79159  pQuery = &aMem[pOp->p3];
79160  pArgc = &pQuery[1];
79161  pCur = p->apCsr[pOp->p1];
79162  assert( memIsValid(pQuery) );
79163  REGISTER_TRACE(pOp->p3, pQuery);
79164  assert( pCur->pVtabCursor );
79165  pVtabCursor = pCur->pVtabCursor;
79166  pVtab = pVtabCursor->pVtab;
79167  pModule = pVtab->pModule;
79168
79169  /* Grab the index number and argc parameters */
79170  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
79171  nArg = (int)pArgc->u.i;
79172  iQuery = (int)pQuery->u.i;
79173
79174  /* Invoke the xFilter method */
79175  res = 0;
79176  apArg = p->apArg;
79177  for(i = 0; i<nArg; i++){
79178    apArg[i] = &pArgc[i+1];
79179  }
79180  rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
79181  sqlite3VtabImportErrmsg(p, pVtab);
79182  if( rc==SQLITE_OK ){
79183    res = pModule->xEof(pVtabCursor);
79184  }
79185  pCur->nullRow = 0;
79186  VdbeBranchTaken(res!=0,2);
79187  if( res ) goto jump_to_p2;
79188  break;
79189}
79190#endif /* SQLITE_OMIT_VIRTUALTABLE */
79191
79192#ifndef SQLITE_OMIT_VIRTUALTABLE
79193/* Opcode: VColumn P1 P2 P3 * *
79194** Synopsis: r[P3]=vcolumn(P2)
79195**
79196** Store the value of the P2-th column of
79197** the row of the virtual-table that the
79198** P1 cursor is pointing to into register P3.
79199*/
79200case OP_VColumn: {
79201  sqlite3_vtab *pVtab;
79202  const sqlite3_module *pModule;
79203  Mem *pDest;
79204  sqlite3_context sContext;
79205
79206  VdbeCursor *pCur = p->apCsr[pOp->p1];
79207  assert( pCur->pVtabCursor );
79208  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
79209  pDest = &aMem[pOp->p3];
79210  memAboutToChange(p, pDest);
79211  if( pCur->nullRow ){
79212    sqlite3VdbeMemSetNull(pDest);
79213    break;
79214  }
79215  pVtab = pCur->pVtabCursor->pVtab;
79216  pModule = pVtab->pModule;
79217  assert( pModule->xColumn );
79218  memset(&sContext, 0, sizeof(sContext));
79219  sContext.pOut = pDest;
79220  MemSetTypeFlag(pDest, MEM_Null);
79221  rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
79222  sqlite3VtabImportErrmsg(p, pVtab);
79223  if( sContext.isError ){
79224    rc = sContext.isError;
79225  }
79226  sqlite3VdbeChangeEncoding(pDest, encoding);
79227  REGISTER_TRACE(pOp->p3, pDest);
79228  UPDATE_MAX_BLOBSIZE(pDest);
79229
79230  if( sqlite3VdbeMemTooBig(pDest) ){
79231    goto too_big;
79232  }
79233  break;
79234}
79235#endif /* SQLITE_OMIT_VIRTUALTABLE */
79236
79237#ifndef SQLITE_OMIT_VIRTUALTABLE
79238/* Opcode: VNext P1 P2 * * *
79239**
79240** Advance virtual table P1 to the next row in its result set and
79241** jump to instruction P2.  Or, if the virtual table has reached
79242** the end of its result set, then fall through to the next instruction.
79243*/
79244case OP_VNext: {   /* jump */
79245  sqlite3_vtab *pVtab;
79246  const sqlite3_module *pModule;
79247  int res;
79248  VdbeCursor *pCur;
79249
79250  res = 0;
79251  pCur = p->apCsr[pOp->p1];
79252  assert( pCur->pVtabCursor );
79253  if( pCur->nullRow ){
79254    break;
79255  }
79256  pVtab = pCur->pVtabCursor->pVtab;
79257  pModule = pVtab->pModule;
79258  assert( pModule->xNext );
79259
79260  /* Invoke the xNext() method of the module. There is no way for the
79261  ** underlying implementation to return an error if one occurs during
79262  ** xNext(). Instead, if an error occurs, true is returned (indicating that
79263  ** data is available) and the error code returned when xColumn or
79264  ** some other method is next invoked on the save virtual table cursor.
79265  */
79266  rc = pModule->xNext(pCur->pVtabCursor);
79267  sqlite3VtabImportErrmsg(p, pVtab);
79268  if( rc==SQLITE_OK ){
79269    res = pModule->xEof(pCur->pVtabCursor);
79270  }
79271  VdbeBranchTaken(!res,2);
79272  if( !res ){
79273    /* If there is data, jump to P2 */
79274    goto jump_to_p2_and_check_for_interrupt;
79275  }
79276  goto check_for_interrupt;
79277}
79278#endif /* SQLITE_OMIT_VIRTUALTABLE */
79279
79280#ifndef SQLITE_OMIT_VIRTUALTABLE
79281/* Opcode: VRename P1 * * P4 *
79282**
79283** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79284** This opcode invokes the corresponding xRename method. The value
79285** in register P1 is passed as the zName argument to the xRename method.
79286*/
79287case OP_VRename: {
79288  sqlite3_vtab *pVtab;
79289  Mem *pName;
79290
79291  pVtab = pOp->p4.pVtab->pVtab;
79292  pName = &aMem[pOp->p1];
79293  assert( pVtab->pModule->xRename );
79294  assert( memIsValid(pName) );
79295  assert( p->readOnly==0 );
79296  REGISTER_TRACE(pOp->p1, pName);
79297  assert( pName->flags & MEM_Str );
79298  testcase( pName->enc==SQLITE_UTF8 );
79299  testcase( pName->enc==SQLITE_UTF16BE );
79300  testcase( pName->enc==SQLITE_UTF16LE );
79301  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
79302  if( rc==SQLITE_OK ){
79303    rc = pVtab->pModule->xRename(pVtab, pName->z);
79304    sqlite3VtabImportErrmsg(p, pVtab);
79305    p->expired = 0;
79306  }
79307  break;
79308}
79309#endif
79310
79311#ifndef SQLITE_OMIT_VIRTUALTABLE
79312/* Opcode: VUpdate P1 P2 P3 P4 P5
79313** Synopsis: data=r[P3@P2]
79314**
79315** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79316** This opcode invokes the corresponding xUpdate method. P2 values
79317** are contiguous memory cells starting at P3 to pass to the xUpdate
79318** invocation. The value in register (P3+P2-1) corresponds to the
79319** p2th element of the argv array passed to xUpdate.
79320**
79321** The xUpdate method will do a DELETE or an INSERT or both.
79322** The argv[0] element (which corresponds to memory cell P3)
79323** is the rowid of a row to delete.  If argv[0] is NULL then no
79324** deletion occurs.  The argv[1] element is the rowid of the new
79325** row.  This can be NULL to have the virtual table select the new
79326** rowid for itself.  The subsequent elements in the array are
79327** the values of columns in the new row.
79328**
79329** If P2==1 then no insert is performed.  argv[0] is the rowid of
79330** a row to delete.
79331**
79332** P1 is a boolean flag. If it is set to true and the xUpdate call
79333** is successful, then the value returned by sqlite3_last_insert_rowid()
79334** is set to the value of the rowid for the row just inserted.
79335**
79336** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
79337** apply in the case of a constraint failure on an insert or update.
79338*/
79339case OP_VUpdate: {
79340  sqlite3_vtab *pVtab;
79341  const sqlite3_module *pModule;
79342  int nArg;
79343  int i;
79344  sqlite_int64 rowid;
79345  Mem **apArg;
79346  Mem *pX;
79347
79348  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
79349       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
79350  );
79351  assert( p->readOnly==0 );
79352  pVtab = pOp->p4.pVtab->pVtab;
79353  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
79354    rc = SQLITE_LOCKED;
79355    break;
79356  }
79357  pModule = pVtab->pModule;
79358  nArg = pOp->p2;
79359  assert( pOp->p4type==P4_VTAB );
79360  if( ALWAYS(pModule->xUpdate) ){
79361    u8 vtabOnConflict = db->vtabOnConflict;
79362    apArg = p->apArg;
79363    pX = &aMem[pOp->p3];
79364    for(i=0; i<nArg; i++){
79365      assert( memIsValid(pX) );
79366      memAboutToChange(p, pX);
79367      apArg[i] = pX;
79368      pX++;
79369    }
79370    db->vtabOnConflict = pOp->p5;
79371    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
79372    db->vtabOnConflict = vtabOnConflict;
79373    sqlite3VtabImportErrmsg(p, pVtab);
79374    if( rc==SQLITE_OK && pOp->p1 ){
79375      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
79376      db->lastRowid = lastRowid = rowid;
79377    }
79378    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
79379      if( pOp->p5==OE_Ignore ){
79380        rc = SQLITE_OK;
79381      }else{
79382        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
79383      }
79384    }else{
79385      p->nChange++;
79386    }
79387  }
79388  break;
79389}
79390#endif /* SQLITE_OMIT_VIRTUALTABLE */
79391
79392#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
79393/* Opcode: Pagecount P1 P2 * * *
79394**
79395** Write the current number of pages in database P1 to memory cell P2.
79396*/
79397case OP_Pagecount: {            /* out2 */
79398  pOut = out2Prerelease(p, pOp);
79399  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
79400  break;
79401}
79402#endif
79403
79404
79405#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
79406/* Opcode: MaxPgcnt P1 P2 P3 * *
79407**
79408** Try to set the maximum page count for database P1 to the value in P3.
79409** Do not let the maximum page count fall below the current page count and
79410** do not change the maximum page count value if P3==0.
79411**
79412** Store the maximum page count after the change in register P2.
79413*/
79414case OP_MaxPgcnt: {            /* out2 */
79415  unsigned int newMax;
79416  Btree *pBt;
79417
79418  pOut = out2Prerelease(p, pOp);
79419  pBt = db->aDb[pOp->p1].pBt;
79420  newMax = 0;
79421  if( pOp->p3 ){
79422    newMax = sqlite3BtreeLastPage(pBt);
79423    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
79424  }
79425  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
79426  break;
79427}
79428#endif
79429
79430
79431/* Opcode: Init * P2 * P4 *
79432** Synopsis:  Start at P2
79433**
79434** Programs contain a single instance of this opcode as the very first
79435** opcode.
79436**
79437** If tracing is enabled (by the sqlite3_trace()) interface, then
79438** the UTF-8 string contained in P4 is emitted on the trace callback.
79439** Or if P4 is blank, use the string returned by sqlite3_sql().
79440**
79441** If P2 is not zero, jump to instruction P2.
79442*/
79443case OP_Init: {          /* jump */
79444  char *zTrace;
79445  char *z;
79446
79447#ifndef SQLITE_OMIT_TRACE
79448  if( db->xTrace
79449   && !p->doingRerun
79450   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
79451  ){
79452    z = sqlite3VdbeExpandSql(p, zTrace);
79453    db->xTrace(db->pTraceArg, z);
79454    sqlite3DbFree(db, z);
79455  }
79456#ifdef SQLITE_USE_FCNTL_TRACE
79457  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
79458  if( zTrace ){
79459    int i;
79460    for(i=0; i<db->nDb; i++){
79461      if( DbMaskTest(p->btreeMask, i)==0 ) continue;
79462      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
79463    }
79464  }
79465#endif /* SQLITE_USE_FCNTL_TRACE */
79466#ifdef SQLITE_DEBUG
79467  if( (db->flags & SQLITE_SqlTrace)!=0
79468   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
79469  ){
79470    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
79471  }
79472#endif /* SQLITE_DEBUG */
79473#endif /* SQLITE_OMIT_TRACE */
79474  if( pOp->p2 ) goto jump_to_p2;
79475  break;
79476}
79477
79478
79479/* Opcode: Noop * * * * *
79480**
79481** Do nothing.  This instruction is often useful as a jump
79482** destination.
79483*/
79484/*
79485** The magic Explain opcode are only inserted when explain==2 (which
79486** is to say when the EXPLAIN QUERY PLAN syntax is used.)
79487** This opcode records information from the optimizer.  It is the
79488** the same as a no-op.  This opcodesnever appears in a real VM program.
79489*/
79490default: {          /* This is really OP_Noop and OP_Explain */
79491  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
79492  break;
79493}
79494
79495/*****************************************************************************
79496** The cases of the switch statement above this line should all be indented
79497** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
79498** readability.  From this point on down, the normal indentation rules are
79499** restored.
79500*****************************************************************************/
79501    }
79502
79503#ifdef VDBE_PROFILE
79504    {
79505      u64 endTime = sqlite3Hwtime();
79506      if( endTime>start ) pOrigOp->cycles += endTime - start;
79507      pOrigOp->cnt++;
79508    }
79509#endif
79510
79511    /* The following code adds nothing to the actual functionality
79512    ** of the program.  It is only here for testing and debugging.
79513    ** On the other hand, it does burn CPU cycles every time through
79514    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
79515    */
79516#ifndef NDEBUG
79517    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
79518
79519#ifdef SQLITE_DEBUG
79520    if( db->flags & SQLITE_VdbeTrace ){
79521      if( rc!=0 ) printf("rc=%d\n",rc);
79522      if( pOrigOp->opflags & (OPFLG_OUT2) ){
79523        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
79524      }
79525      if( pOrigOp->opflags & OPFLG_OUT3 ){
79526        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
79527      }
79528    }
79529#endif  /* SQLITE_DEBUG */
79530#endif  /* NDEBUG */
79531  }  /* The end of the for(;;) loop the loops through opcodes */
79532
79533  /* If we reach this point, it means that execution is finished with
79534  ** an error of some kind.
79535  */
79536vdbe_error_halt:
79537  assert( rc );
79538  p->rc = rc;
79539  testcase( sqlite3GlobalConfig.xLog!=0 );
79540  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
79541                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
79542  sqlite3VdbeHalt(p);
79543  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
79544  rc = SQLITE_ERROR;
79545  if( resetSchemaOnFault>0 ){
79546    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
79547  }
79548
79549  /* This is the only way out of this procedure.  We have to
79550  ** release the mutexes on btrees that were acquired at the
79551  ** top. */
79552vdbe_return:
79553  db->lastRowid = lastRowid;
79554  testcase( nVmStep>0 );
79555  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
79556  sqlite3VdbeLeave(p);
79557  return rc;
79558
79559  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
79560  ** is encountered.
79561  */
79562too_big:
79563  sqlite3VdbeError(p, "string or blob too big");
79564  rc = SQLITE_TOOBIG;
79565  goto vdbe_error_halt;
79566
79567  /* Jump to here if a malloc() fails.
79568  */
79569no_mem:
79570  db->mallocFailed = 1;
79571  sqlite3VdbeError(p, "out of memory");
79572  rc = SQLITE_NOMEM;
79573  goto vdbe_error_halt;
79574
79575  /* Jump to here for any other kind of fatal error.  The "rc" variable
79576  ** should hold the error number.
79577  */
79578abort_due_to_error:
79579  assert( p->zErrMsg==0 );
79580  if( db->mallocFailed ) rc = SQLITE_NOMEM;
79581  if( rc!=SQLITE_IOERR_NOMEM ){
79582    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
79583  }
79584  goto vdbe_error_halt;
79585
79586  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
79587  ** flag.
79588  */
79589abort_due_to_interrupt:
79590  assert( db->u1.isInterrupted );
79591  rc = SQLITE_INTERRUPT;
79592  p->rc = rc;
79593  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
79594  goto vdbe_error_halt;
79595}
79596
79597
79598/************** End of vdbe.c ************************************************/
79599/************** Begin file vdbeblob.c ****************************************/
79600/*
79601** 2007 May 1
79602**
79603** The author disclaims copyright to this source code.  In place of
79604** a legal notice, here is a blessing:
79605**
79606**    May you do good and not evil.
79607**    May you find forgiveness for yourself and forgive others.
79608**    May you share freely, never taking more than you give.
79609**
79610*************************************************************************
79611**
79612** This file contains code used to implement incremental BLOB I/O.
79613*/
79614
79615/* #include "sqliteInt.h" */
79616/* #include "vdbeInt.h" */
79617
79618#ifndef SQLITE_OMIT_INCRBLOB
79619
79620/*
79621** Valid sqlite3_blob* handles point to Incrblob structures.
79622*/
79623typedef struct Incrblob Incrblob;
79624struct Incrblob {
79625  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
79626  int nByte;              /* Size of open blob, in bytes */
79627  int iOffset;            /* Byte offset of blob in cursor data */
79628  int iCol;               /* Table column this handle is open on */
79629  BtCursor *pCsr;         /* Cursor pointing at blob row */
79630  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
79631  sqlite3 *db;            /* The associated database */
79632};
79633
79634
79635/*
79636** This function is used by both blob_open() and blob_reopen(). It seeks
79637** the b-tree cursor associated with blob handle p to point to row iRow.
79638** If successful, SQLITE_OK is returned and subsequent calls to
79639** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
79640**
79641** If an error occurs, or if the specified row does not exist or does not
79642** contain a value of type TEXT or BLOB in the column nominated when the
79643** blob handle was opened, then an error code is returned and *pzErr may
79644** be set to point to a buffer containing an error message. It is the
79645** responsibility of the caller to free the error message buffer using
79646** sqlite3DbFree().
79647**
79648** If an error does occur, then the b-tree cursor is closed. All subsequent
79649** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
79650** immediately return SQLITE_ABORT.
79651*/
79652static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
79653  int rc;                         /* Error code */
79654  char *zErr = 0;                 /* Error message */
79655  Vdbe *v = (Vdbe *)p->pStmt;
79656
79657  /* Set the value of the SQL statements only variable to integer iRow.
79658  ** This is done directly instead of using sqlite3_bind_int64() to avoid
79659  ** triggering asserts related to mutexes.
79660  */
79661  assert( v->aVar[0].flags&MEM_Int );
79662  v->aVar[0].u.i = iRow;
79663
79664  rc = sqlite3_step(p->pStmt);
79665  if( rc==SQLITE_ROW ){
79666    VdbeCursor *pC = v->apCsr[0];
79667    u32 type = pC->aType[p->iCol];
79668    if( type<12 ){
79669      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
79670          type==0?"null": type==7?"real": "integer"
79671      );
79672      rc = SQLITE_ERROR;
79673      sqlite3_finalize(p->pStmt);
79674      p->pStmt = 0;
79675    }else{
79676      p->iOffset = pC->aType[p->iCol + pC->nField];
79677      p->nByte = sqlite3VdbeSerialTypeLen(type);
79678      p->pCsr =  pC->pCursor;
79679      sqlite3BtreeIncrblobCursor(p->pCsr);
79680    }
79681  }
79682
79683  if( rc==SQLITE_ROW ){
79684    rc = SQLITE_OK;
79685  }else if( p->pStmt ){
79686    rc = sqlite3_finalize(p->pStmt);
79687    p->pStmt = 0;
79688    if( rc==SQLITE_OK ){
79689      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
79690      rc = SQLITE_ERROR;
79691    }else{
79692      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
79693    }
79694  }
79695
79696  assert( rc!=SQLITE_OK || zErr==0 );
79697  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
79698
79699  *pzErr = zErr;
79700  return rc;
79701}
79702
79703/*
79704** Open a blob handle.
79705*/
79706SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
79707  sqlite3* db,            /* The database connection */
79708  const char *zDb,        /* The attached database containing the blob */
79709  const char *zTable,     /* The table containing the blob */
79710  const char *zColumn,    /* The column containing the blob */
79711  sqlite_int64 iRow,      /* The row containing the glob */
79712  int flags,              /* True -> read/write access, false -> read-only */
79713  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
79714){
79715  int nAttempt = 0;
79716  int iCol;               /* Index of zColumn in row-record */
79717
79718  /* This VDBE program seeks a btree cursor to the identified
79719  ** db/table/row entry. The reason for using a vdbe program instead
79720  ** of writing code to use the b-tree layer directly is that the
79721  ** vdbe program will take advantage of the various transaction,
79722  ** locking and error handling infrastructure built into the vdbe.
79723  **
79724  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
79725  ** Code external to the Vdbe then "borrows" the b-tree cursor and
79726  ** uses it to implement the blob_read(), blob_write() and
79727  ** blob_bytes() functions.
79728  **
79729  ** The sqlite3_blob_close() function finalizes the vdbe program,
79730  ** which closes the b-tree cursor and (possibly) commits the
79731  ** transaction.
79732  */
79733  static const int iLn = VDBE_OFFSET_LINENO(4);
79734  static const VdbeOpList openBlob[] = {
79735    /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
79736    {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
79737    /* One of the following two instructions is replaced by an OP_Noop. */
79738    {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
79739    {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
79740    {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
79741    {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
79742    {OP_Column, 0, 0, 1},          /* 6  */
79743    {OP_ResultRow, 1, 0, 0},       /* 7  */
79744    {OP_Goto, 0, 4, 0},            /* 8  */
79745    {OP_Close, 0, 0, 0},           /* 9  */
79746    {OP_Halt, 0, 0, 0},            /* 10 */
79747  };
79748
79749  int rc = SQLITE_OK;
79750  char *zErr = 0;
79751  Table *pTab;
79752  Parse *pParse = 0;
79753  Incrblob *pBlob = 0;
79754
79755#ifdef SQLITE_ENABLE_API_ARMOR
79756  if( ppBlob==0 ){
79757    return SQLITE_MISUSE_BKPT;
79758  }
79759#endif
79760  *ppBlob = 0;
79761#ifdef SQLITE_ENABLE_API_ARMOR
79762  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
79763    return SQLITE_MISUSE_BKPT;
79764  }
79765#endif
79766  flags = !!flags;                /* flags = (flags ? 1 : 0); */
79767
79768  sqlite3_mutex_enter(db->mutex);
79769
79770  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
79771  if( !pBlob ) goto blob_open_out;
79772  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
79773  if( !pParse ) goto blob_open_out;
79774
79775  do {
79776    memset(pParse, 0, sizeof(Parse));
79777    pParse->db = db;
79778    sqlite3DbFree(db, zErr);
79779    zErr = 0;
79780
79781    sqlite3BtreeEnterAll(db);
79782    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
79783    if( pTab && IsVirtual(pTab) ){
79784      pTab = 0;
79785      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
79786    }
79787    if( pTab && !HasRowid(pTab) ){
79788      pTab = 0;
79789      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
79790    }
79791#ifndef SQLITE_OMIT_VIEW
79792    if( pTab && pTab->pSelect ){
79793      pTab = 0;
79794      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
79795    }
79796#endif
79797    if( !pTab ){
79798      if( pParse->zErrMsg ){
79799        sqlite3DbFree(db, zErr);
79800        zErr = pParse->zErrMsg;
79801        pParse->zErrMsg = 0;
79802      }
79803      rc = SQLITE_ERROR;
79804      sqlite3BtreeLeaveAll(db);
79805      goto blob_open_out;
79806    }
79807
79808    /* Now search pTab for the exact column. */
79809    for(iCol=0; iCol<pTab->nCol; iCol++) {
79810      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
79811        break;
79812      }
79813    }
79814    if( iCol==pTab->nCol ){
79815      sqlite3DbFree(db, zErr);
79816      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
79817      rc = SQLITE_ERROR;
79818      sqlite3BtreeLeaveAll(db);
79819      goto blob_open_out;
79820    }
79821
79822    /* If the value is being opened for writing, check that the
79823    ** column is not indexed, and that it is not part of a foreign key.
79824    ** It is against the rules to open a column to which either of these
79825    ** descriptions applies for writing.  */
79826    if( flags ){
79827      const char *zFault = 0;
79828      Index *pIdx;
79829#ifndef SQLITE_OMIT_FOREIGN_KEY
79830      if( db->flags&SQLITE_ForeignKeys ){
79831        /* Check that the column is not part of an FK child key definition. It
79832        ** is not necessary to check if it is part of a parent key, as parent
79833        ** key columns must be indexed. The check below will pick up this
79834        ** case.  */
79835        FKey *pFKey;
79836        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
79837          int j;
79838          for(j=0; j<pFKey->nCol; j++){
79839            if( pFKey->aCol[j].iFrom==iCol ){
79840              zFault = "foreign key";
79841            }
79842          }
79843        }
79844      }
79845#endif
79846      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79847        int j;
79848        for(j=0; j<pIdx->nKeyCol; j++){
79849          /* FIXME: Be smarter about indexes that use expressions */
79850          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
79851            zFault = "indexed";
79852          }
79853        }
79854      }
79855      if( zFault ){
79856        sqlite3DbFree(db, zErr);
79857        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
79858        rc = SQLITE_ERROR;
79859        sqlite3BtreeLeaveAll(db);
79860        goto blob_open_out;
79861      }
79862    }
79863
79864    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
79865    assert( pBlob->pStmt || db->mallocFailed );
79866    if( pBlob->pStmt ){
79867      Vdbe *v = (Vdbe *)pBlob->pStmt;
79868      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79869
79870
79871      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
79872                           pTab->pSchema->schema_cookie,
79873                           pTab->pSchema->iGeneration);
79874      sqlite3VdbeChangeP5(v, 1);
79875      sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
79876
79877      /* Make sure a mutex is held on the table to be accessed */
79878      sqlite3VdbeUsesBtree(v, iDb);
79879
79880      /* Configure the OP_TableLock instruction */
79881#ifdef SQLITE_OMIT_SHARED_CACHE
79882      sqlite3VdbeChangeToNoop(v, 1);
79883#else
79884      sqlite3VdbeChangeP1(v, 1, iDb);
79885      sqlite3VdbeChangeP2(v, 1, pTab->tnum);
79886      sqlite3VdbeChangeP3(v, 1, flags);
79887      sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
79888#endif
79889
79890      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
79891      ** parameter of the other to pTab->tnum.  */
79892      sqlite3VdbeChangeToNoop(v, 3 - flags);
79893      sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
79894      sqlite3VdbeChangeP3(v, 2 + flags, iDb);
79895
79896      /* Configure the number of columns. Configure the cursor to
79897      ** think that the table has one more column than it really
79898      ** does. An OP_Column to retrieve this imaginary column will
79899      ** always return an SQL NULL. This is useful because it means
79900      ** we can invoke OP_Column to fill in the vdbe cursors type
79901      ** and offset cache without causing any IO.
79902      */
79903      sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
79904      sqlite3VdbeChangeP2(v, 6, pTab->nCol);
79905      if( !db->mallocFailed ){
79906        pParse->nVar = 1;
79907        pParse->nMem = 1;
79908        pParse->nTab = 1;
79909        sqlite3VdbeMakeReady(v, pParse);
79910      }
79911    }
79912
79913    pBlob->flags = flags;
79914    pBlob->iCol = iCol;
79915    pBlob->db = db;
79916    sqlite3BtreeLeaveAll(db);
79917    if( db->mallocFailed ){
79918      goto blob_open_out;
79919    }
79920    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
79921    rc = blobSeekToRow(pBlob, iRow, &zErr);
79922  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
79923
79924blob_open_out:
79925  if( rc==SQLITE_OK && db->mallocFailed==0 ){
79926    *ppBlob = (sqlite3_blob *)pBlob;
79927  }else{
79928    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
79929    sqlite3DbFree(db, pBlob);
79930  }
79931  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
79932  sqlite3DbFree(db, zErr);
79933  sqlite3ParserReset(pParse);
79934  sqlite3StackFree(db, pParse);
79935  rc = sqlite3ApiExit(db, rc);
79936  sqlite3_mutex_leave(db->mutex);
79937  return rc;
79938}
79939
79940/*
79941** Close a blob handle that was previously created using
79942** sqlite3_blob_open().
79943*/
79944SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
79945  Incrblob *p = (Incrblob *)pBlob;
79946  int rc;
79947  sqlite3 *db;
79948
79949  if( p ){
79950    db = p->db;
79951    sqlite3_mutex_enter(db->mutex);
79952    rc = sqlite3_finalize(p->pStmt);
79953    sqlite3DbFree(db, p);
79954    sqlite3_mutex_leave(db->mutex);
79955  }else{
79956    rc = SQLITE_OK;
79957  }
79958  return rc;
79959}
79960
79961/*
79962** Perform a read or write operation on a blob
79963*/
79964static int blobReadWrite(
79965  sqlite3_blob *pBlob,
79966  void *z,
79967  int n,
79968  int iOffset,
79969  int (*xCall)(BtCursor*, u32, u32, void*)
79970){
79971  int rc;
79972  Incrblob *p = (Incrblob *)pBlob;
79973  Vdbe *v;
79974  sqlite3 *db;
79975
79976  if( p==0 ) return SQLITE_MISUSE_BKPT;
79977  db = p->db;
79978  sqlite3_mutex_enter(db->mutex);
79979  v = (Vdbe*)p->pStmt;
79980
79981  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
79982    /* Request is out of range. Return a transient error. */
79983    rc = SQLITE_ERROR;
79984  }else if( v==0 ){
79985    /* If there is no statement handle, then the blob-handle has
79986    ** already been invalidated. Return SQLITE_ABORT in this case.
79987    */
79988    rc = SQLITE_ABORT;
79989  }else{
79990    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
79991    ** returned, clean-up the statement handle.
79992    */
79993    assert( db == v->db );
79994    sqlite3BtreeEnterCursor(p->pCsr);
79995    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
79996    sqlite3BtreeLeaveCursor(p->pCsr);
79997    if( rc==SQLITE_ABORT ){
79998      sqlite3VdbeFinalize(v);
79999      p->pStmt = 0;
80000    }else{
80001      v->rc = rc;
80002    }
80003  }
80004  sqlite3Error(db, rc);
80005  rc = sqlite3ApiExit(db, rc);
80006  sqlite3_mutex_leave(db->mutex);
80007  return rc;
80008}
80009
80010/*
80011** Read data from a blob handle.
80012*/
80013SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
80014  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
80015}
80016
80017/*
80018** Write data to a blob handle.
80019*/
80020SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
80021  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
80022}
80023
80024/*
80025** Query a blob handle for the size of the data.
80026**
80027** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
80028** so no mutex is required for access.
80029*/
80030SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
80031  Incrblob *p = (Incrblob *)pBlob;
80032  return (p && p->pStmt) ? p->nByte : 0;
80033}
80034
80035/*
80036** Move an existing blob handle to point to a different row of the same
80037** database table.
80038**
80039** If an error occurs, or if the specified row does not exist or does not
80040** contain a blob or text value, then an error code is returned and the
80041** database handle error code and message set. If this happens, then all
80042** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
80043** immediately return SQLITE_ABORT.
80044*/
80045SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
80046  int rc;
80047  Incrblob *p = (Incrblob *)pBlob;
80048  sqlite3 *db;
80049
80050  if( p==0 ) return SQLITE_MISUSE_BKPT;
80051  db = p->db;
80052  sqlite3_mutex_enter(db->mutex);
80053
80054  if( p->pStmt==0 ){
80055    /* If there is no statement handle, then the blob-handle has
80056    ** already been invalidated. Return SQLITE_ABORT in this case.
80057    */
80058    rc = SQLITE_ABORT;
80059  }else{
80060    char *zErr;
80061    rc = blobSeekToRow(p, iRow, &zErr);
80062    if( rc!=SQLITE_OK ){
80063      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
80064      sqlite3DbFree(db, zErr);
80065    }
80066    assert( rc!=SQLITE_SCHEMA );
80067  }
80068
80069  rc = sqlite3ApiExit(db, rc);
80070  assert( rc==SQLITE_OK || p->pStmt==0 );
80071  sqlite3_mutex_leave(db->mutex);
80072  return rc;
80073}
80074
80075#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
80076
80077/************** End of vdbeblob.c ********************************************/
80078/************** Begin file vdbesort.c ****************************************/
80079/*
80080** 2011-07-09
80081**
80082** The author disclaims copyright to this source code.  In place of
80083** a legal notice, here is a blessing:
80084**
80085**    May you do good and not evil.
80086**    May you find forgiveness for yourself and forgive others.
80087**    May you share freely, never taking more than you give.
80088**
80089*************************************************************************
80090** This file contains code for the VdbeSorter object, used in concert with
80091** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
80092** or by SELECT statements with ORDER BY clauses that cannot be satisfied
80093** using indexes and without LIMIT clauses.
80094**
80095** The VdbeSorter object implements a multi-threaded external merge sort
80096** algorithm that is efficient even if the number of elements being sorted
80097** exceeds the available memory.
80098**
80099** Here is the (internal, non-API) interface between this module and the
80100** rest of the SQLite system:
80101**
80102**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
80103**
80104**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
80105**                                  object.  The row is a binary blob in the
80106**                                  OP_MakeRecord format that contains both
80107**                                  the ORDER BY key columns and result columns
80108**                                  in the case of a SELECT w/ ORDER BY, or
80109**                                  the complete record for an index entry
80110**                                  in the case of a CREATE INDEX.
80111**
80112**    sqlite3VdbeSorterRewind()     Sort all content previously added.
80113**                                  Position the read cursor on the
80114**                                  first sorted element.
80115**
80116**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
80117**                                  element.
80118**
80119**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
80120**                                  row currently under the read cursor.
80121**
80122**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
80123**                                  currently under the read cursor against
80124**                                  another binary blob X and report if
80125**                                  X is strictly less than the read cursor.
80126**                                  Used to enforce uniqueness in a
80127**                                  CREATE UNIQUE INDEX statement.
80128**
80129**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
80130**                                  all resources.
80131**
80132**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
80133**                                  is like Close() followed by Init() only
80134**                                  much faster.
80135**
80136** The interfaces above must be called in a particular order.  Write() can
80137** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
80138** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
80139**
80140**   Init()
80141**   for each record: Write()
80142**   Rewind()
80143**     Rowkey()/Compare()
80144**   Next()
80145**   Close()
80146**
80147** Algorithm:
80148**
80149** Records passed to the sorter via calls to Write() are initially held
80150** unsorted in main memory. Assuming the amount of memory used never exceeds
80151** a threshold, when Rewind() is called the set of records is sorted using
80152** an in-memory merge sort. In this case, no temporary files are required
80153** and subsequent calls to Rowkey(), Next() and Compare() read records
80154** directly from main memory.
80155**
80156** If the amount of space used to store records in main memory exceeds the
80157** threshold, then the set of records currently in memory are sorted and
80158** written to a temporary file in "Packed Memory Array" (PMA) format.
80159** A PMA created at this point is known as a "level-0 PMA". Higher levels
80160** of PMAs may be created by merging existing PMAs together - for example
80161** merging two or more level-0 PMAs together creates a level-1 PMA.
80162**
80163** The threshold for the amount of main memory to use before flushing
80164** records to a PMA is roughly the same as the limit configured for the
80165** page-cache of the main database. Specifically, the threshold is set to
80166** the value returned by "PRAGMA main.page_size" multipled by
80167** that returned by "PRAGMA main.cache_size", in bytes.
80168**
80169** If the sorter is running in single-threaded mode, then all PMAs generated
80170** are appended to a single temporary file. Or, if the sorter is running in
80171** multi-threaded mode then up to (N+1) temporary files may be opened, where
80172** N is the configured number of worker threads. In this case, instead of
80173** sorting the records and writing the PMA to a temporary file itself, the
80174** calling thread usually launches a worker thread to do so. Except, if
80175** there are already N worker threads running, the main thread does the work
80176** itself.
80177**
80178** The sorter is running in multi-threaded mode if (a) the library was built
80179** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
80180** than zero, and (b) worker threads have been enabled at runtime by calling
80181** "PRAGMA threads=N" with some value of N greater than 0.
80182**
80183** When Rewind() is called, any data remaining in memory is flushed to a
80184** final PMA. So at this point the data is stored in some number of sorted
80185** PMAs within temporary files on disk.
80186**
80187** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
80188** sorter is running in single-threaded mode, then these PMAs are merged
80189** incrementally as keys are retreived from the sorter by the VDBE.  The
80190** MergeEngine object, described in further detail below, performs this
80191** merge.
80192**
80193** Or, if running in multi-threaded mode, then a background thread is
80194** launched to merge the existing PMAs. Once the background thread has
80195** merged T bytes of data into a single sorted PMA, the main thread
80196** begins reading keys from that PMA while the background thread proceeds
80197** with merging the next T bytes of data. And so on.
80198**
80199** Parameter T is set to half the value of the memory threshold used
80200** by Write() above to determine when to create a new PMA.
80201**
80202** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
80203** Rewind() is called, then a hierarchy of incremental-merges is used.
80204** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
80205** disk are merged together. Then T bytes of data from the second set, and
80206** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
80207** PMAs at a time. This done is to improve locality.
80208**
80209** If running in multi-threaded mode and there are more than
80210** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
80211** than one background thread may be created. Specifically, there may be
80212** one background thread for each temporary file on disk, and one background
80213** thread to merge the output of each of the others to a single PMA for
80214** the main thread to read from.
80215*/
80216/* #include "sqliteInt.h" */
80217/* #include "vdbeInt.h" */
80218
80219/*
80220** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
80221** messages to stderr that may be helpful in understanding the performance
80222** characteristics of the sorter in multi-threaded mode.
80223*/
80224#if 0
80225# define SQLITE_DEBUG_SORTER_THREADS 1
80226#endif
80227
80228/*
80229** Hard-coded maximum amount of data to accumulate in memory before flushing
80230** to a level 0 PMA. The purpose of this limit is to prevent various integer
80231** overflows. 512MiB.
80232*/
80233#define SQLITE_MAX_PMASZ    (1<<29)
80234
80235/*
80236** Private objects used by the sorter
80237*/
80238typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
80239typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
80240typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
80241typedef struct SorterRecord SorterRecord;   /* A record being sorted */
80242typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
80243typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
80244typedef struct SorterList SorterList;       /* In-memory list of records */
80245typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
80246
80247/*
80248** A container for a temp file handle and the current amount of data
80249** stored in the file.
80250*/
80251struct SorterFile {
80252  sqlite3_file *pFd;              /* File handle */
80253  i64 iEof;                       /* Bytes of data stored in pFd */
80254};
80255
80256/*
80257** An in-memory list of objects to be sorted.
80258**
80259** If aMemory==0 then each object is allocated separately and the objects
80260** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
80261** are stored in the aMemory[] bulk memory, one right after the other, and
80262** are connected using SorterRecord.u.iNext.
80263*/
80264struct SorterList {
80265  SorterRecord *pList;            /* Linked list of records */
80266  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
80267  int szPMA;                      /* Size of pList as PMA in bytes */
80268};
80269
80270/*
80271** The MergeEngine object is used to combine two or more smaller PMAs into
80272** one big PMA using a merge operation.  Separate PMAs all need to be
80273** combined into one big PMA in order to be able to step through the sorted
80274** records in order.
80275**
80276** The aReadr[] array contains a PmaReader object for each of the PMAs being
80277** merged.  An aReadr[] object either points to a valid key or else is at EOF.
80278** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
80279** For the purposes of the paragraphs below, we assume that the array is
80280** actually N elements in size, where N is the smallest power of 2 greater
80281** to or equal to the number of PMAs being merged. The extra aReadr[] elements
80282** are treated as if they are empty (always at EOF).
80283**
80284** The aTree[] array is also N elements in size. The value of N is stored in
80285** the MergeEngine.nTree variable.
80286**
80287** The final (N/2) elements of aTree[] contain the results of comparing
80288** pairs of PMA keys together. Element i contains the result of
80289** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
80290** aTree element is set to the index of it.
80291**
80292** For the purposes of this comparison, EOF is considered greater than any
80293** other key value. If the keys are equal (only possible with two EOF
80294** values), it doesn't matter which index is stored.
80295**
80296** The (N/4) elements of aTree[] that precede the final (N/2) described
80297** above contains the index of the smallest of each block of 4 PmaReaders
80298** And so on. So that aTree[1] contains the index of the PmaReader that
80299** currently points to the smallest key value. aTree[0] is unused.
80300**
80301** Example:
80302**
80303**     aReadr[0] -> Banana
80304**     aReadr[1] -> Feijoa
80305**     aReadr[2] -> Elderberry
80306**     aReadr[3] -> Currant
80307**     aReadr[4] -> Grapefruit
80308**     aReadr[5] -> Apple
80309**     aReadr[6] -> Durian
80310**     aReadr[7] -> EOF
80311**
80312**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
80313**
80314** The current element is "Apple" (the value of the key indicated by
80315** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
80316** be advanced to the next key in its segment. Say the next key is
80317** "Eggplant":
80318**
80319**     aReadr[5] -> Eggplant
80320**
80321** The contents of aTree[] are updated first by comparing the new PmaReader
80322** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
80323** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
80324** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
80325** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
80326** so the value written into element 1 of the array is 0. As follows:
80327**
80328**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
80329**
80330** In other words, each time we advance to the next sorter element, log2(N)
80331** key comparison operations are required, where N is the number of segments
80332** being merged (rounded up to the next power of 2).
80333*/
80334struct MergeEngine {
80335  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
80336  SortSubtask *pTask;        /* Used by this thread only */
80337  int *aTree;                /* Current state of incremental merge */
80338  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
80339};
80340
80341/*
80342** This object represents a single thread of control in a sort operation.
80343** Exactly VdbeSorter.nTask instances of this object are allocated
80344** as part of each VdbeSorter object. Instances are never allocated any
80345** other way. VdbeSorter.nTask is set to the number of worker threads allowed
80346** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
80347** single-threaded operation, there is exactly one instance of this object
80348** and for multi-threaded operation there are two or more instances.
80349**
80350** Essentially, this structure contains all those fields of the VdbeSorter
80351** structure for which each thread requires a separate instance. For example,
80352** each thread requries its own UnpackedRecord object to unpack records in
80353** as part of comparison operations.
80354**
80355** Before a background thread is launched, variable bDone is set to 0. Then,
80356** right before it exits, the thread itself sets bDone to 1. This is used for
80357** two purposes:
80358**
80359**   1. When flushing the contents of memory to a level-0 PMA on disk, to
80360**      attempt to select a SortSubtask for which there is not already an
80361**      active background thread (since doing so causes the main thread
80362**      to block until it finishes).
80363**
80364**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
80365**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
80366**      block provoke debugging output.
80367**
80368** In both cases, the effects of the main thread seeing (bDone==0) even
80369** after the thread has finished are not dire. So we don't worry about
80370** memory barriers and such here.
80371*/
80372typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
80373struct SortSubtask {
80374  SQLiteThread *pThread;          /* Background thread, if any */
80375  int bDone;                      /* Set if thread is finished but not joined */
80376  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
80377  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
80378  SorterList list;                /* List for thread to write to a PMA */
80379  int nPMA;                       /* Number of PMAs currently in file */
80380  SorterCompare xCompare;         /* Compare function to use */
80381  SorterFile file;                /* Temp file for level-0 PMAs */
80382  SorterFile file2;               /* Space for other PMAs */
80383};
80384
80385
80386/*
80387** Main sorter structure. A single instance of this is allocated for each
80388** sorter cursor created by the VDBE.
80389**
80390** mxKeysize:
80391**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
80392**   this variable is updated so as to be set to the size on disk of the
80393**   largest record in the sorter.
80394*/
80395struct VdbeSorter {
80396  int mnPmaSize;                  /* Minimum PMA size, in bytes */
80397  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
80398  int mxKeysize;                  /* Largest serialized key seen so far */
80399  int pgsz;                       /* Main database page size */
80400  PmaReader *pReader;             /* Readr data from here after Rewind() */
80401  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
80402  sqlite3 *db;                    /* Database connection */
80403  KeyInfo *pKeyInfo;              /* How to compare records */
80404  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
80405  SorterList list;                /* List of in-memory records */
80406  int iMemory;                    /* Offset of free space in list.aMemory */
80407  int nMemory;                    /* Size of list.aMemory allocation in bytes */
80408  u8 bUsePMA;                     /* True if one or more PMAs created */
80409  u8 bUseThreads;                 /* True to use background threads */
80410  u8 iPrev;                       /* Previous thread used to flush PMA */
80411  u8 nTask;                       /* Size of aTask[] array */
80412  u8 typeMask;
80413  SortSubtask aTask[1];           /* One or more subtasks */
80414};
80415
80416#define SORTER_TYPE_INTEGER 0x01
80417#define SORTER_TYPE_TEXT    0x02
80418
80419/*
80420** An instance of the following object is used to read records out of a
80421** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
80422** aKey might point into aMap or into aBuffer.  If neither of those locations
80423** contain a contiguous representation of the key, then aAlloc is allocated
80424** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
80425**
80426** pFd==0 at EOF.
80427*/
80428struct PmaReader {
80429  i64 iReadOff;               /* Current read offset */
80430  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
80431  int nAlloc;                 /* Bytes of space at aAlloc */
80432  int nKey;                   /* Number of bytes in key */
80433  sqlite3_file *pFd;          /* File handle we are reading from */
80434  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
80435  u8 *aKey;                   /* Pointer to current key */
80436  u8 *aBuffer;                /* Current read buffer */
80437  int nBuffer;                /* Size of read buffer in bytes */
80438  u8 *aMap;                   /* Pointer to mapping of entire file */
80439  IncrMerger *pIncr;          /* Incremental merger */
80440};
80441
80442/*
80443** Normally, a PmaReader object iterates through an existing PMA stored
80444** within a temp file. However, if the PmaReader.pIncr variable points to
80445** an object of the following type, it may be used to iterate/merge through
80446** multiple PMAs simultaneously.
80447**
80448** There are two types of IncrMerger object - single (bUseThread==0) and
80449** multi-threaded (bUseThread==1).
80450**
80451** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
80452** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
80453** size. When the IncrMerger is initialized, it reads enough data from
80454** pMerger to populate aFile[0]. It then sets variables within the
80455** corresponding PmaReader object to read from that file and kicks off
80456** a background thread to populate aFile[1] with the next mxSz bytes of
80457** sorted record data from pMerger.
80458**
80459** When the PmaReader reaches the end of aFile[0], it blocks until the
80460** background thread has finished populating aFile[1]. It then exchanges
80461** the contents of the aFile[0] and aFile[1] variables within this structure,
80462** sets the PmaReader fields to read from the new aFile[0] and kicks off
80463** another background thread to populate the new aFile[1]. And so on, until
80464** the contents of pMerger are exhausted.
80465**
80466** A single-threaded IncrMerger does not open any temporary files of its
80467** own. Instead, it has exclusive access to mxSz bytes of space beginning
80468** at offset iStartOff of file pTask->file2. And instead of using a
80469** background thread to prepare data for the PmaReader, with a single
80470** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
80471** keys from pMerger by the calling thread whenever the PmaReader runs out
80472** of data.
80473*/
80474struct IncrMerger {
80475  SortSubtask *pTask;             /* Task that owns this merger */
80476  MergeEngine *pMerger;           /* Merge engine thread reads data from */
80477  i64 iStartOff;                  /* Offset to start writing file at */
80478  int mxSz;                       /* Maximum bytes of data to store */
80479  int bEof;                       /* Set to true when merge is finished */
80480  int bUseThread;                 /* True to use a bg thread for this object */
80481  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
80482};
80483
80484/*
80485** An instance of this object is used for writing a PMA.
80486**
80487** The PMA is written one record at a time.  Each record is of an arbitrary
80488** size.  But I/O is more efficient if it occurs in page-sized blocks where
80489** each block is aligned on a page boundary.  This object caches writes to
80490** the PMA so that aligned, page-size blocks are written.
80491*/
80492struct PmaWriter {
80493  int eFWErr;                     /* Non-zero if in an error state */
80494  u8 *aBuffer;                    /* Pointer to write buffer */
80495  int nBuffer;                    /* Size of write buffer in bytes */
80496  int iBufStart;                  /* First byte of buffer to write */
80497  int iBufEnd;                    /* Last byte of buffer to write */
80498  i64 iWriteOff;                  /* Offset of start of buffer in file */
80499  sqlite3_file *pFd;              /* File handle to write to */
80500};
80501
80502/*
80503** This object is the header on a single record while that record is being
80504** held in memory and prior to being written out as part of a PMA.
80505**
80506** How the linked list is connected depends on how memory is being managed
80507** by this module. If using a separate allocation for each in-memory record
80508** (VdbeSorter.list.aMemory==0), then the list is always connected using the
80509** SorterRecord.u.pNext pointers.
80510**
80511** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
80512** then while records are being accumulated the list is linked using the
80513** SorterRecord.u.iNext offset. This is because the aMemory[] array may
80514** be sqlite3Realloc()ed while records are being accumulated. Once the VM
80515** has finished passing records to the sorter, or when the in-memory buffer
80516** is full, the list is sorted. As part of the sorting process, it is
80517** converted to use the SorterRecord.u.pNext pointers. See function
80518** vdbeSorterSort() for details.
80519*/
80520struct SorterRecord {
80521  int nVal;                       /* Size of the record in bytes */
80522  union {
80523    SorterRecord *pNext;          /* Pointer to next record in list */
80524    int iNext;                    /* Offset within aMemory of next record */
80525  } u;
80526  /* The data for the record immediately follows this header */
80527};
80528
80529/* Return a pointer to the buffer containing the record data for SorterRecord
80530** object p. Should be used as if:
80531**
80532**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
80533*/
80534#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
80535
80536
80537/* Maximum number of PMAs that a single MergeEngine can merge */
80538#define SORTER_MAX_MERGE_COUNT 16
80539
80540static int vdbeIncrSwap(IncrMerger*);
80541static void vdbeIncrFree(IncrMerger *);
80542
80543/*
80544** Free all memory belonging to the PmaReader object passed as the
80545** argument. All structure fields are set to zero before returning.
80546*/
80547static void vdbePmaReaderClear(PmaReader *pReadr){
80548  sqlite3_free(pReadr->aAlloc);
80549  sqlite3_free(pReadr->aBuffer);
80550  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
80551  vdbeIncrFree(pReadr->pIncr);
80552  memset(pReadr, 0, sizeof(PmaReader));
80553}
80554
80555/*
80556** Read the next nByte bytes of data from the PMA p.
80557** If successful, set *ppOut to point to a buffer containing the data
80558** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
80559** error code.
80560**
80561** The buffer returned in *ppOut is only valid until the
80562** next call to this function.
80563*/
80564static int vdbePmaReadBlob(
80565  PmaReader *p,                   /* PmaReader from which to take the blob */
80566  int nByte,                      /* Bytes of data to read */
80567  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
80568){
80569  int iBuf;                       /* Offset within buffer to read from */
80570  int nAvail;                     /* Bytes of data available in buffer */
80571
80572  if( p->aMap ){
80573    *ppOut = &p->aMap[p->iReadOff];
80574    p->iReadOff += nByte;
80575    return SQLITE_OK;
80576  }
80577
80578  assert( p->aBuffer );
80579
80580  /* If there is no more data to be read from the buffer, read the next
80581  ** p->nBuffer bytes of data from the file into it. Or, if there are less
80582  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
80583  iBuf = p->iReadOff % p->nBuffer;
80584  if( iBuf==0 ){
80585    int nRead;                    /* Bytes to read from disk */
80586    int rc;                       /* sqlite3OsRead() return code */
80587
80588    /* Determine how many bytes of data to read. */
80589    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
80590      nRead = p->nBuffer;
80591    }else{
80592      nRead = (int)(p->iEof - p->iReadOff);
80593    }
80594    assert( nRead>0 );
80595
80596    /* Readr data from the file. Return early if an error occurs. */
80597    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
80598    assert( rc!=SQLITE_IOERR_SHORT_READ );
80599    if( rc!=SQLITE_OK ) return rc;
80600  }
80601  nAvail = p->nBuffer - iBuf;
80602
80603  if( nByte<=nAvail ){
80604    /* The requested data is available in the in-memory buffer. In this
80605    ** case there is no need to make a copy of the data, just return a
80606    ** pointer into the buffer to the caller.  */
80607    *ppOut = &p->aBuffer[iBuf];
80608    p->iReadOff += nByte;
80609  }else{
80610    /* The requested data is not all available in the in-memory buffer.
80611    ** In this case, allocate space at p->aAlloc[] to copy the requested
80612    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
80613    int nRem;                     /* Bytes remaining to copy */
80614
80615    /* Extend the p->aAlloc[] allocation if required. */
80616    if( p->nAlloc<nByte ){
80617      u8 *aNew;
80618      int nNew = MAX(128, p->nAlloc*2);
80619      while( nByte>nNew ) nNew = nNew*2;
80620      aNew = sqlite3Realloc(p->aAlloc, nNew);
80621      if( !aNew ) return SQLITE_NOMEM;
80622      p->nAlloc = nNew;
80623      p->aAlloc = aNew;
80624    }
80625
80626    /* Copy as much data as is available in the buffer into the start of
80627    ** p->aAlloc[].  */
80628    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
80629    p->iReadOff += nAvail;
80630    nRem = nByte - nAvail;
80631
80632    /* The following loop copies up to p->nBuffer bytes per iteration into
80633    ** the p->aAlloc[] buffer.  */
80634    while( nRem>0 ){
80635      int rc;                     /* vdbePmaReadBlob() return code */
80636      int nCopy;                  /* Number of bytes to copy */
80637      u8 *aNext;                  /* Pointer to buffer to copy data from */
80638
80639      nCopy = nRem;
80640      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
80641      rc = vdbePmaReadBlob(p, nCopy, &aNext);
80642      if( rc!=SQLITE_OK ) return rc;
80643      assert( aNext!=p->aAlloc );
80644      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
80645      nRem -= nCopy;
80646    }
80647
80648    *ppOut = p->aAlloc;
80649  }
80650
80651  return SQLITE_OK;
80652}
80653
80654/*
80655** Read a varint from the stream of data accessed by p. Set *pnOut to
80656** the value read.
80657*/
80658static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
80659  int iBuf;
80660
80661  if( p->aMap ){
80662    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
80663  }else{
80664    iBuf = p->iReadOff % p->nBuffer;
80665    if( iBuf && (p->nBuffer-iBuf)>=9 ){
80666      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
80667    }else{
80668      u8 aVarint[16], *a;
80669      int i = 0, rc;
80670      do{
80671        rc = vdbePmaReadBlob(p, 1, &a);
80672        if( rc ) return rc;
80673        aVarint[(i++)&0xf] = a[0];
80674      }while( (a[0]&0x80)!=0 );
80675      sqlite3GetVarint(aVarint, pnOut);
80676    }
80677  }
80678
80679  return SQLITE_OK;
80680}
80681
80682/*
80683** Attempt to memory map file pFile. If successful, set *pp to point to the
80684** new mapping and return SQLITE_OK. If the mapping is not attempted
80685** (because the file is too large or the VFS layer is configured not to use
80686** mmap), return SQLITE_OK and set *pp to NULL.
80687**
80688** Or, if an error occurs, return an SQLite error code. The final value of
80689** *pp is undefined in this case.
80690*/
80691static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
80692  int rc = SQLITE_OK;
80693  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
80694    sqlite3_file *pFd = pFile->pFd;
80695    if( pFd->pMethods->iVersion>=3 ){
80696      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
80697      testcase( rc!=SQLITE_OK );
80698    }
80699  }
80700  return rc;
80701}
80702
80703/*
80704** Attach PmaReader pReadr to file pFile (if it is not already attached to
80705** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
80706** if successful, or an SQLite error code if an error occurs.
80707*/
80708static int vdbePmaReaderSeek(
80709  SortSubtask *pTask,             /* Task context */
80710  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
80711  SorterFile *pFile,              /* Sorter file to read from */
80712  i64 iOff                        /* Offset in pFile */
80713){
80714  int rc = SQLITE_OK;
80715
80716  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
80717
80718  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
80719  if( pReadr->aMap ){
80720    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
80721    pReadr->aMap = 0;
80722  }
80723  pReadr->iReadOff = iOff;
80724  pReadr->iEof = pFile->iEof;
80725  pReadr->pFd = pFile->pFd;
80726
80727  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
80728  if( rc==SQLITE_OK && pReadr->aMap==0 ){
80729    int pgsz = pTask->pSorter->pgsz;
80730    int iBuf = pReadr->iReadOff % pgsz;
80731    if( pReadr->aBuffer==0 ){
80732      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
80733      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
80734      pReadr->nBuffer = pgsz;
80735    }
80736    if( rc==SQLITE_OK && iBuf ){
80737      int nRead = pgsz - iBuf;
80738      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
80739        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
80740      }
80741      rc = sqlite3OsRead(
80742          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
80743      );
80744      testcase( rc!=SQLITE_OK );
80745    }
80746  }
80747
80748  return rc;
80749}
80750
80751/*
80752** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
80753** no error occurs, or an SQLite error code if one does.
80754*/
80755static int vdbePmaReaderNext(PmaReader *pReadr){
80756  int rc = SQLITE_OK;             /* Return Code */
80757  u64 nRec = 0;                   /* Size of record in bytes */
80758
80759
80760  if( pReadr->iReadOff>=pReadr->iEof ){
80761    IncrMerger *pIncr = pReadr->pIncr;
80762    int bEof = 1;
80763    if( pIncr ){
80764      rc = vdbeIncrSwap(pIncr);
80765      if( rc==SQLITE_OK && pIncr->bEof==0 ){
80766        rc = vdbePmaReaderSeek(
80767            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
80768        );
80769        bEof = 0;
80770      }
80771    }
80772
80773    if( bEof ){
80774      /* This is an EOF condition */
80775      vdbePmaReaderClear(pReadr);
80776      testcase( rc!=SQLITE_OK );
80777      return rc;
80778    }
80779  }
80780
80781  if( rc==SQLITE_OK ){
80782    rc = vdbePmaReadVarint(pReadr, &nRec);
80783  }
80784  if( rc==SQLITE_OK ){
80785    pReadr->nKey = (int)nRec;
80786    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
80787    testcase( rc!=SQLITE_OK );
80788  }
80789
80790  return rc;
80791}
80792
80793/*
80794** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
80795** starting at offset iStart and ending at offset iEof-1. This function
80796** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
80797** PMA is empty).
80798**
80799** If the pnByte parameter is NULL, then it is assumed that the file
80800** contains a single PMA, and that that PMA omits the initial length varint.
80801*/
80802static int vdbePmaReaderInit(
80803  SortSubtask *pTask,             /* Task context */
80804  SorterFile *pFile,              /* Sorter file to read from */
80805  i64 iStart,                     /* Start offset in pFile */
80806  PmaReader *pReadr,              /* PmaReader to populate */
80807  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
80808){
80809  int rc;
80810
80811  assert( pFile->iEof>iStart );
80812  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
80813  assert( pReadr->aBuffer==0 );
80814  assert( pReadr->aMap==0 );
80815
80816  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
80817  if( rc==SQLITE_OK ){
80818    u64 nByte;                    /* Size of PMA in bytes */
80819    rc = vdbePmaReadVarint(pReadr, &nByte);
80820    pReadr->iEof = pReadr->iReadOff + nByte;
80821    *pnByte += nByte;
80822  }
80823
80824  if( rc==SQLITE_OK ){
80825    rc = vdbePmaReaderNext(pReadr);
80826  }
80827  return rc;
80828}
80829
80830/*
80831** A version of vdbeSorterCompare() that assumes that it has already been
80832** determined that the first field of key1 is equal to the first field of
80833** key2.
80834*/
80835static int vdbeSorterCompareTail(
80836  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80837  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80838  const void *pKey1, int nKey1,   /* Left side of comparison */
80839  const void *pKey2, int nKey2    /* Right side of comparison */
80840){
80841  UnpackedRecord *r2 = pTask->pUnpacked;
80842  if( *pbKey2Cached==0 ){
80843    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
80844    *pbKey2Cached = 1;
80845  }
80846  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
80847}
80848
80849/*
80850** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
80851** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
80852** used by the comparison. Return the result of the comparison.
80853**
80854** If IN/OUT parameter *pbKey2Cached is true when this function is called,
80855** it is assumed that (pTask->pUnpacked) contains the unpacked version
80856** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
80857** version of key2 and *pbKey2Cached set to true before returning.
80858**
80859** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
80860** to SQLITE_NOMEM.
80861*/
80862static int vdbeSorterCompare(
80863  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80864  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80865  const void *pKey1, int nKey1,   /* Left side of comparison */
80866  const void *pKey2, int nKey2    /* Right side of comparison */
80867){
80868  UnpackedRecord *r2 = pTask->pUnpacked;
80869  if( !*pbKey2Cached ){
80870    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
80871    *pbKey2Cached = 1;
80872  }
80873  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
80874}
80875
80876/*
80877** A specially optimized version of vdbeSorterCompare() that assumes that
80878** the first field of each key is a TEXT value and that the collation
80879** sequence to compare them with is BINARY.
80880*/
80881static int vdbeSorterCompareText(
80882  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80883  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80884  const void *pKey1, int nKey1,   /* Left side of comparison */
80885  const void *pKey2, int nKey2    /* Right side of comparison */
80886){
80887  const u8 * const p1 = (const u8 * const)pKey1;
80888  const u8 * const p2 = (const u8 * const)pKey2;
80889  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
80890  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
80891
80892  int n1;
80893  int n2;
80894  int res;
80895
80896  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
80897  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
80898  res = memcmp(v1, v2, MIN(n1, n2));
80899  if( res==0 ){
80900    res = n1 - n2;
80901  }
80902
80903  if( res==0 ){
80904    if( pTask->pSorter->pKeyInfo->nField>1 ){
80905      res = vdbeSorterCompareTail(
80906          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
80907      );
80908    }
80909  }else{
80910    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
80911      res = res * -1;
80912    }
80913  }
80914
80915  return res;
80916}
80917
80918/*
80919** A specially optimized version of vdbeSorterCompare() that assumes that
80920** the first field of each key is an INTEGER value.
80921*/
80922static int vdbeSorterCompareInt(
80923  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80924  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80925  const void *pKey1, int nKey1,   /* Left side of comparison */
80926  const void *pKey2, int nKey2    /* Right side of comparison */
80927){
80928  const u8 * const p1 = (const u8 * const)pKey1;
80929  const u8 * const p2 = (const u8 * const)pKey2;
80930  const int s1 = p1[1];                 /* Left hand serial type */
80931  const int s2 = p2[1];                 /* Right hand serial type */
80932  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
80933  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
80934  int res;                              /* Return value */
80935
80936  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
80937  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
80938
80939  if( s1>7 && s2>7 ){
80940    res = s1 - s2;
80941  }else{
80942    if( s1==s2 ){
80943      if( (*v1 ^ *v2) & 0x80 ){
80944        /* The two values have different signs */
80945        res = (*v1 & 0x80) ? -1 : +1;
80946      }else{
80947        /* The two values have the same sign. Compare using memcmp(). */
80948        static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
80949        int i;
80950        res = 0;
80951        for(i=0; i<aLen[s1]; i++){
80952          if( (res = v1[i] - v2[i]) ) break;
80953        }
80954      }
80955    }else{
80956      if( s2>7 ){
80957        res = +1;
80958      }else if( s1>7 ){
80959        res = -1;
80960      }else{
80961        res = s1 - s2;
80962      }
80963      assert( res!=0 );
80964
80965      if( res>0 ){
80966        if( *v1 & 0x80 ) res = -1;
80967      }else{
80968        if( *v2 & 0x80 ) res = +1;
80969      }
80970    }
80971  }
80972
80973  if( res==0 ){
80974    if( pTask->pSorter->pKeyInfo->nField>1 ){
80975      res = vdbeSorterCompareTail(
80976          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
80977      );
80978    }
80979  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
80980    res = res * -1;
80981  }
80982
80983  return res;
80984}
80985
80986/*
80987** Initialize the temporary index cursor just opened as a sorter cursor.
80988**
80989** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
80990** to determine the number of fields that should be compared from the
80991** records being sorted. However, if the value passed as argument nField
80992** is non-zero and the sorter is able to guarantee a stable sort, nField
80993** is used instead. This is used when sorting records for a CREATE INDEX
80994** statement. In this case, keys are always delivered to the sorter in
80995** order of the primary key, which happens to be make up the final part
80996** of the records being sorted. So if the sort is stable, there is never
80997** any reason to compare PK fields and they can be ignored for a small
80998** performance boost.
80999**
81000** The sorter can guarantee a stable sort when running in single-threaded
81001** mode, but not in multi-threaded mode.
81002**
81003** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
81004*/
81005SQLITE_PRIVATE int sqlite3VdbeSorterInit(
81006  sqlite3 *db,                    /* Database connection (for malloc()) */
81007  int nField,                     /* Number of key fields in each record */
81008  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
81009){
81010  int pgsz;                       /* Page size of main database */
81011  int i;                          /* Used to iterate through aTask[] */
81012  int mxCache;                    /* Cache size */
81013  VdbeSorter *pSorter;            /* The new sorter */
81014  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
81015  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
81016  int sz;                         /* Size of pSorter in bytes */
81017  int rc = SQLITE_OK;
81018#if SQLITE_MAX_WORKER_THREADS==0
81019# define nWorker 0
81020#else
81021  int nWorker;
81022#endif
81023
81024  /* Initialize the upper limit on the number of worker threads */
81025#if SQLITE_MAX_WORKER_THREADS>0
81026  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
81027    nWorker = 0;
81028  }else{
81029    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
81030  }
81031#endif
81032
81033  /* Do not allow the total number of threads (main thread + all workers)
81034  ** to exceed the maximum merge count */
81035#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
81036  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
81037    nWorker = SORTER_MAX_MERGE_COUNT-1;
81038  }
81039#endif
81040
81041  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
81042  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
81043  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
81044
81045  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
81046  pCsr->pSorter = pSorter;
81047  if( pSorter==0 ){
81048    rc = SQLITE_NOMEM;
81049  }else{
81050    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
81051    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
81052    pKeyInfo->db = 0;
81053    if( nField && nWorker==0 ){
81054      pKeyInfo->nXField += (pKeyInfo->nField - nField);
81055      pKeyInfo->nField = nField;
81056    }
81057    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
81058    pSorter->nTask = nWorker + 1;
81059    pSorter->iPrev = nWorker-1;
81060    pSorter->bUseThreads = (pSorter->nTask>1);
81061    pSorter->db = db;
81062    for(i=0; i<pSorter->nTask; i++){
81063      SortSubtask *pTask = &pSorter->aTask[i];
81064      pTask->pSorter = pSorter;
81065    }
81066
81067    if( !sqlite3TempInMemory(db) ){
81068      u32 szPma = sqlite3GlobalConfig.szPma;
81069      pSorter->mnPmaSize = szPma * pgsz;
81070      mxCache = db->aDb[0].pSchema->cache_size;
81071      if( mxCache<(int)szPma ) mxCache = (int)szPma;
81072      pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
81073
81074      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
81075      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
81076      ** large heap allocations.
81077      */
81078      if( sqlite3GlobalConfig.pScratch==0 ){
81079        assert( pSorter->iMemory==0 );
81080        pSorter->nMemory = pgsz;
81081        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
81082        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
81083      }
81084    }
81085
81086    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
81087     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
81088    ){
81089      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
81090    }
81091  }
81092
81093  return rc;
81094}
81095#undef nWorker   /* Defined at the top of this function */
81096
81097/*
81098** Free the list of sorted records starting at pRecord.
81099*/
81100static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
81101  SorterRecord *p;
81102  SorterRecord *pNext;
81103  for(p=pRecord; p; p=pNext){
81104    pNext = p->u.pNext;
81105    sqlite3DbFree(db, p);
81106  }
81107}
81108
81109/*
81110** Free all resources owned by the object indicated by argument pTask. All
81111** fields of *pTask are zeroed before returning.
81112*/
81113static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
81114  sqlite3DbFree(db, pTask->pUnpacked);
81115#if SQLITE_MAX_WORKER_THREADS>0
81116  /* pTask->list.aMemory can only be non-zero if it was handed memory
81117  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
81118  if( pTask->list.aMemory ){
81119    sqlite3_free(pTask->list.aMemory);
81120  }else
81121#endif
81122  {
81123    assert( pTask->list.aMemory==0 );
81124    vdbeSorterRecordFree(0, pTask->list.pList);
81125  }
81126  if( pTask->file.pFd ){
81127    sqlite3OsCloseFree(pTask->file.pFd);
81128  }
81129  if( pTask->file2.pFd ){
81130    sqlite3OsCloseFree(pTask->file2.pFd);
81131  }
81132  memset(pTask, 0, sizeof(SortSubtask));
81133}
81134
81135#ifdef SQLITE_DEBUG_SORTER_THREADS
81136static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
81137  i64 t;
81138  int iTask = (pTask - pTask->pSorter->aTask);
81139  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81140  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
81141}
81142static void vdbeSorterRewindDebug(const char *zEvent){
81143  i64 t;
81144  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
81145  fprintf(stderr, "%lld:X %s\n", t, zEvent);
81146}
81147static void vdbeSorterPopulateDebug(
81148  SortSubtask *pTask,
81149  const char *zEvent
81150){
81151  i64 t;
81152  int iTask = (pTask - pTask->pSorter->aTask);
81153  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81154  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
81155}
81156static void vdbeSorterBlockDebug(
81157  SortSubtask *pTask,
81158  int bBlocked,
81159  const char *zEvent
81160){
81161  if( bBlocked ){
81162    i64 t;
81163    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81164    fprintf(stderr, "%lld:main %s\n", t, zEvent);
81165  }
81166}
81167#else
81168# define vdbeSorterWorkDebug(x,y)
81169# define vdbeSorterRewindDebug(y)
81170# define vdbeSorterPopulateDebug(x,y)
81171# define vdbeSorterBlockDebug(x,y,z)
81172#endif
81173
81174#if SQLITE_MAX_WORKER_THREADS>0
81175/*
81176** Join thread pTask->thread.
81177*/
81178static int vdbeSorterJoinThread(SortSubtask *pTask){
81179  int rc = SQLITE_OK;
81180  if( pTask->pThread ){
81181#ifdef SQLITE_DEBUG_SORTER_THREADS
81182    int bDone = pTask->bDone;
81183#endif
81184    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
81185    vdbeSorterBlockDebug(pTask, !bDone, "enter");
81186    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
81187    vdbeSorterBlockDebug(pTask, !bDone, "exit");
81188    rc = SQLITE_PTR_TO_INT(pRet);
81189    assert( pTask->bDone==1 );
81190    pTask->bDone = 0;
81191    pTask->pThread = 0;
81192  }
81193  return rc;
81194}
81195
81196/*
81197** Launch a background thread to run xTask(pIn).
81198*/
81199static int vdbeSorterCreateThread(
81200  SortSubtask *pTask,             /* Thread will use this task object */
81201  void *(*xTask)(void*),          /* Routine to run in a separate thread */
81202  void *pIn                       /* Argument passed into xTask() */
81203){
81204  assert( pTask->pThread==0 && pTask->bDone==0 );
81205  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
81206}
81207
81208/*
81209** Join all outstanding threads launched by SorterWrite() to create
81210** level-0 PMAs.
81211*/
81212static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
81213  int rc = rcin;
81214  int i;
81215
81216  /* This function is always called by the main user thread.
81217  **
81218  ** If this function is being called after SorterRewind() has been called,
81219  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
81220  ** is currently attempt to join one of the other threads. To avoid a race
81221  ** condition where this thread also attempts to join the same object, join
81222  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
81223  for(i=pSorter->nTask-1; i>=0; i--){
81224    SortSubtask *pTask = &pSorter->aTask[i];
81225    int rc2 = vdbeSorterJoinThread(pTask);
81226    if( rc==SQLITE_OK ) rc = rc2;
81227  }
81228  return rc;
81229}
81230#else
81231# define vdbeSorterJoinAll(x,rcin) (rcin)
81232# define vdbeSorterJoinThread(pTask) SQLITE_OK
81233#endif
81234
81235/*
81236** Allocate a new MergeEngine object capable of handling up to
81237** nReader PmaReader inputs.
81238**
81239** nReader is automatically rounded up to the next power of two.
81240** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
81241*/
81242static MergeEngine *vdbeMergeEngineNew(int nReader){
81243  int N = 2;                      /* Smallest power of two >= nReader */
81244  int nByte;                      /* Total bytes of space to allocate */
81245  MergeEngine *pNew;              /* Pointer to allocated object to return */
81246
81247  assert( nReader<=SORTER_MAX_MERGE_COUNT );
81248
81249  while( N<nReader ) N += N;
81250  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
81251
81252  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
81253  if( pNew ){
81254    pNew->nTree = N;
81255    pNew->pTask = 0;
81256    pNew->aReadr = (PmaReader*)&pNew[1];
81257    pNew->aTree = (int*)&pNew->aReadr[N];
81258  }
81259  return pNew;
81260}
81261
81262/*
81263** Free the MergeEngine object passed as the only argument.
81264*/
81265static void vdbeMergeEngineFree(MergeEngine *pMerger){
81266  int i;
81267  if( pMerger ){
81268    for(i=0; i<pMerger->nTree; i++){
81269      vdbePmaReaderClear(&pMerger->aReadr[i]);
81270    }
81271  }
81272  sqlite3_free(pMerger);
81273}
81274
81275/*
81276** Free all resources associated with the IncrMerger object indicated by
81277** the first argument.
81278*/
81279static void vdbeIncrFree(IncrMerger *pIncr){
81280  if( pIncr ){
81281#if SQLITE_MAX_WORKER_THREADS>0
81282    if( pIncr->bUseThread ){
81283      vdbeSorterJoinThread(pIncr->pTask);
81284      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
81285      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
81286    }
81287#endif
81288    vdbeMergeEngineFree(pIncr->pMerger);
81289    sqlite3_free(pIncr);
81290  }
81291}
81292
81293/*
81294** Reset a sorting cursor back to its original empty state.
81295*/
81296SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
81297  int i;
81298  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
81299  assert( pSorter->bUseThreads || pSorter->pReader==0 );
81300#if SQLITE_MAX_WORKER_THREADS>0
81301  if( pSorter->pReader ){
81302    vdbePmaReaderClear(pSorter->pReader);
81303    sqlite3DbFree(db, pSorter->pReader);
81304    pSorter->pReader = 0;
81305  }
81306#endif
81307  vdbeMergeEngineFree(pSorter->pMerger);
81308  pSorter->pMerger = 0;
81309  for(i=0; i<pSorter->nTask; i++){
81310    SortSubtask *pTask = &pSorter->aTask[i];
81311    vdbeSortSubtaskCleanup(db, pTask);
81312    pTask->pSorter = pSorter;
81313  }
81314  if( pSorter->list.aMemory==0 ){
81315    vdbeSorterRecordFree(0, pSorter->list.pList);
81316  }
81317  pSorter->list.pList = 0;
81318  pSorter->list.szPMA = 0;
81319  pSorter->bUsePMA = 0;
81320  pSorter->iMemory = 0;
81321  pSorter->mxKeysize = 0;
81322  sqlite3DbFree(db, pSorter->pUnpacked);
81323  pSorter->pUnpacked = 0;
81324}
81325
81326/*
81327** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
81328*/
81329SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
81330  VdbeSorter *pSorter = pCsr->pSorter;
81331  if( pSorter ){
81332    sqlite3VdbeSorterReset(db, pSorter);
81333    sqlite3_free(pSorter->list.aMemory);
81334    sqlite3DbFree(db, pSorter);
81335    pCsr->pSorter = 0;
81336  }
81337}
81338
81339#if SQLITE_MAX_MMAP_SIZE>0
81340/*
81341** The first argument is a file-handle open on a temporary file. The file
81342** is guaranteed to be nByte bytes or smaller in size. This function
81343** attempts to extend the file to nByte bytes in size and to ensure that
81344** the VFS has memory mapped it.
81345**
81346** Whether or not the file does end up memory mapped of course depends on
81347** the specific VFS implementation.
81348*/
81349static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
81350  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
81351    void *p = 0;
81352    int chunksize = 4*1024;
81353    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
81354    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
81355    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
81356    sqlite3OsUnfetch(pFd, 0, p);
81357  }
81358}
81359#else
81360# define vdbeSorterExtendFile(x,y,z)
81361#endif
81362
81363/*
81364** Allocate space for a file-handle and open a temporary file. If successful,
81365** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
81366** Otherwise, set *ppFd to 0 and return an SQLite error code.
81367*/
81368static int vdbeSorterOpenTempFile(
81369  sqlite3 *db,                    /* Database handle doing sort */
81370  i64 nExtend,                    /* Attempt to extend file to this size */
81371  sqlite3_file **ppFd
81372){
81373  int rc;
81374  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
81375  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
81376      SQLITE_OPEN_TEMP_JOURNAL |
81377      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
81378      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
81379  );
81380  if( rc==SQLITE_OK ){
81381    i64 max = SQLITE_MAX_MMAP_SIZE;
81382    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
81383    if( nExtend>0 ){
81384      vdbeSorterExtendFile(db, *ppFd, nExtend);
81385    }
81386  }
81387  return rc;
81388}
81389
81390/*
81391** If it has not already been allocated, allocate the UnpackedRecord
81392** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
81393** if no allocation was required), or SQLITE_NOMEM otherwise.
81394*/
81395static int vdbeSortAllocUnpacked(SortSubtask *pTask){
81396  if( pTask->pUnpacked==0 ){
81397    char *pFree;
81398    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
81399        pTask->pSorter->pKeyInfo, 0, 0, &pFree
81400    );
81401    assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
81402    if( pFree==0 ) return SQLITE_NOMEM;
81403    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
81404    pTask->pUnpacked->errCode = 0;
81405  }
81406  return SQLITE_OK;
81407}
81408
81409
81410/*
81411** Merge the two sorted lists p1 and p2 into a single list.
81412** Set *ppOut to the head of the new list.
81413*/
81414static void vdbeSorterMerge(
81415  SortSubtask *pTask,             /* Calling thread context */
81416  SorterRecord *p1,               /* First list to merge */
81417  SorterRecord *p2,               /* Second list to merge */
81418  SorterRecord **ppOut            /* OUT: Head of merged list */
81419){
81420  SorterRecord *pFinal = 0;
81421  SorterRecord **pp = &pFinal;
81422  int bCached = 0;
81423
81424  while( p1 && p2 ){
81425    int res;
81426    res = pTask->xCompare(
81427        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
81428    );
81429
81430    if( res<=0 ){
81431      *pp = p1;
81432      pp = &p1->u.pNext;
81433      p1 = p1->u.pNext;
81434    }else{
81435      *pp = p2;
81436      pp = &p2->u.pNext;
81437      p2 = p2->u.pNext;
81438      bCached = 0;
81439    }
81440  }
81441  *pp = p1 ? p1 : p2;
81442  *ppOut = pFinal;
81443}
81444
81445/*
81446** Return the SorterCompare function to compare values collected by the
81447** sorter object passed as the only argument.
81448*/
81449static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
81450  if( p->typeMask==SORTER_TYPE_INTEGER ){
81451    return vdbeSorterCompareInt;
81452  }else if( p->typeMask==SORTER_TYPE_TEXT ){
81453    return vdbeSorterCompareText;
81454  }
81455  return vdbeSorterCompare;
81456}
81457
81458/*
81459** Sort the linked list of records headed at pTask->pList. Return
81460** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
81461** an error occurs.
81462*/
81463static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
81464  int i;
81465  SorterRecord **aSlot;
81466  SorterRecord *p;
81467  int rc;
81468
81469  rc = vdbeSortAllocUnpacked(pTask);
81470  if( rc!=SQLITE_OK ) return rc;
81471
81472  p = pList->pList;
81473  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
81474
81475  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
81476  if( !aSlot ){
81477    return SQLITE_NOMEM;
81478  }
81479
81480  while( p ){
81481    SorterRecord *pNext;
81482    if( pList->aMemory ){
81483      if( (u8*)p==pList->aMemory ){
81484        pNext = 0;
81485      }else{
81486        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
81487        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
81488      }
81489    }else{
81490      pNext = p->u.pNext;
81491    }
81492
81493    p->u.pNext = 0;
81494    for(i=0; aSlot[i]; i++){
81495      vdbeSorterMerge(pTask, p, aSlot[i], &p);
81496      aSlot[i] = 0;
81497    }
81498    aSlot[i] = p;
81499    p = pNext;
81500  }
81501
81502  p = 0;
81503  for(i=0; i<64; i++){
81504    vdbeSorterMerge(pTask, p, aSlot[i], &p);
81505  }
81506  pList->pList = p;
81507
81508  sqlite3_free(aSlot);
81509  assert( pTask->pUnpacked->errCode==SQLITE_OK
81510       || pTask->pUnpacked->errCode==SQLITE_NOMEM
81511  );
81512  return pTask->pUnpacked->errCode;
81513}
81514
81515/*
81516** Initialize a PMA-writer object.
81517*/
81518static void vdbePmaWriterInit(
81519  sqlite3_file *pFd,              /* File handle to write to */
81520  PmaWriter *p,                   /* Object to populate */
81521  int nBuf,                       /* Buffer size */
81522  i64 iStart                      /* Offset of pFd to begin writing at */
81523){
81524  memset(p, 0, sizeof(PmaWriter));
81525  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
81526  if( !p->aBuffer ){
81527    p->eFWErr = SQLITE_NOMEM;
81528  }else{
81529    p->iBufEnd = p->iBufStart = (iStart % nBuf);
81530    p->iWriteOff = iStart - p->iBufStart;
81531    p->nBuffer = nBuf;
81532    p->pFd = pFd;
81533  }
81534}
81535
81536/*
81537** Write nData bytes of data to the PMA. Return SQLITE_OK
81538** if successful, or an SQLite error code if an error occurs.
81539*/
81540static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
81541  int nRem = nData;
81542  while( nRem>0 && p->eFWErr==0 ){
81543    int nCopy = nRem;
81544    if( nCopy>(p->nBuffer - p->iBufEnd) ){
81545      nCopy = p->nBuffer - p->iBufEnd;
81546    }
81547
81548    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
81549    p->iBufEnd += nCopy;
81550    if( p->iBufEnd==p->nBuffer ){
81551      p->eFWErr = sqlite3OsWrite(p->pFd,
81552          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
81553          p->iWriteOff + p->iBufStart
81554      );
81555      p->iBufStart = p->iBufEnd = 0;
81556      p->iWriteOff += p->nBuffer;
81557    }
81558    assert( p->iBufEnd<p->nBuffer );
81559
81560    nRem -= nCopy;
81561  }
81562}
81563
81564/*
81565** Flush any buffered data to disk and clean up the PMA-writer object.
81566** The results of using the PMA-writer after this call are undefined.
81567** Return SQLITE_OK if flushing the buffered data succeeds or is not
81568** required. Otherwise, return an SQLite error code.
81569**
81570** Before returning, set *piEof to the offset immediately following the
81571** last byte written to the file.
81572*/
81573static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
81574  int rc;
81575  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
81576    p->eFWErr = sqlite3OsWrite(p->pFd,
81577        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
81578        p->iWriteOff + p->iBufStart
81579    );
81580  }
81581  *piEof = (p->iWriteOff + p->iBufEnd);
81582  sqlite3_free(p->aBuffer);
81583  rc = p->eFWErr;
81584  memset(p, 0, sizeof(PmaWriter));
81585  return rc;
81586}
81587
81588/*
81589** Write value iVal encoded as a varint to the PMA. Return
81590** SQLITE_OK if successful, or an SQLite error code if an error occurs.
81591*/
81592static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
81593  int nByte;
81594  u8 aByte[10];
81595  nByte = sqlite3PutVarint(aByte, iVal);
81596  vdbePmaWriteBlob(p, aByte, nByte);
81597}
81598
81599/*
81600** Write the current contents of in-memory linked-list pList to a level-0
81601** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
81602** successful, or an SQLite error code otherwise.
81603**
81604** The format of a PMA is:
81605**
81606**     * A varint. This varint contains the total number of bytes of content
81607**       in the PMA (not including the varint itself).
81608**
81609**     * One or more records packed end-to-end in order of ascending keys.
81610**       Each record consists of a varint followed by a blob of data (the
81611**       key). The varint is the number of bytes in the blob of data.
81612*/
81613static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
81614  sqlite3 *db = pTask->pSorter->db;
81615  int rc = SQLITE_OK;             /* Return code */
81616  PmaWriter writer;               /* Object used to write to the file */
81617
81618#ifdef SQLITE_DEBUG
81619  /* Set iSz to the expected size of file pTask->file after writing the PMA.
81620  ** This is used by an assert() statement at the end of this function.  */
81621  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
81622#endif
81623
81624  vdbeSorterWorkDebug(pTask, "enter");
81625  memset(&writer, 0, sizeof(PmaWriter));
81626  assert( pList->szPMA>0 );
81627
81628  /* If the first temporary PMA file has not been opened, open it now. */
81629  if( pTask->file.pFd==0 ){
81630    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
81631    assert( rc!=SQLITE_OK || pTask->file.pFd );
81632    assert( pTask->file.iEof==0 );
81633    assert( pTask->nPMA==0 );
81634  }
81635
81636  /* Try to get the file to memory map */
81637  if( rc==SQLITE_OK ){
81638    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
81639  }
81640
81641  /* Sort the list */
81642  if( rc==SQLITE_OK ){
81643    rc = vdbeSorterSort(pTask, pList);
81644  }
81645
81646  if( rc==SQLITE_OK ){
81647    SorterRecord *p;
81648    SorterRecord *pNext = 0;
81649
81650    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
81651                      pTask->file.iEof);
81652    pTask->nPMA++;
81653    vdbePmaWriteVarint(&writer, pList->szPMA);
81654    for(p=pList->pList; p; p=pNext){
81655      pNext = p->u.pNext;
81656      vdbePmaWriteVarint(&writer, p->nVal);
81657      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
81658      if( pList->aMemory==0 ) sqlite3_free(p);
81659    }
81660    pList->pList = p;
81661    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
81662  }
81663
81664  vdbeSorterWorkDebug(pTask, "exit");
81665  assert( rc!=SQLITE_OK || pList->pList==0 );
81666  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
81667  return rc;
81668}
81669
81670/*
81671** Advance the MergeEngine to its next entry.
81672** Set *pbEof to true there is no next entry because
81673** the MergeEngine has reached the end of all its inputs.
81674**
81675** Return SQLITE_OK if successful or an error code if an error occurs.
81676*/
81677static int vdbeMergeEngineStep(
81678  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
81679  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
81680){
81681  int rc;
81682  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
81683  SortSubtask *pTask = pMerger->pTask;
81684
81685  /* Advance the current PmaReader */
81686  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
81687
81688  /* Update contents of aTree[] */
81689  if( rc==SQLITE_OK ){
81690    int i;                      /* Index of aTree[] to recalculate */
81691    PmaReader *pReadr1;         /* First PmaReader to compare */
81692    PmaReader *pReadr2;         /* Second PmaReader to compare */
81693    int bCached = 0;
81694
81695    /* Find the first two PmaReaders to compare. The one that was just
81696    ** advanced (iPrev) and the one next to it in the array.  */
81697    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
81698    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
81699
81700    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
81701      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
81702      int iRes;
81703      if( pReadr1->pFd==0 ){
81704        iRes = +1;
81705      }else if( pReadr2->pFd==0 ){
81706        iRes = -1;
81707      }else{
81708        iRes = pTask->xCompare(pTask, &bCached,
81709            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
81710        );
81711      }
81712
81713      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
81714      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
81715      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
81716      ** pKey2 to point to the record belonging to pReadr2.
81717      **
81718      ** Alternatively, if pReadr2 contains the smaller of the two values,
81719      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
81720      ** was actually called above, then pTask->pUnpacked now contains
81721      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
81722      ** vdbeSorterCompare() from decoding pReadr2 again.
81723      **
81724      ** If the two values were equal, then the value from the oldest
81725      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
81726      ** is sorted from oldest to newest, so pReadr1 contains older values
81727      ** than pReadr2 iff (pReadr1<pReadr2).  */
81728      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
81729        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
81730        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
81731        bCached = 0;
81732      }else{
81733        if( pReadr1->pFd ) bCached = 0;
81734        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
81735        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
81736      }
81737    }
81738    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
81739  }
81740
81741  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
81742}
81743
81744#if SQLITE_MAX_WORKER_THREADS>0
81745/*
81746** The main routine for background threads that write level-0 PMAs.
81747*/
81748static void *vdbeSorterFlushThread(void *pCtx){
81749  SortSubtask *pTask = (SortSubtask*)pCtx;
81750  int rc;                         /* Return code */
81751  assert( pTask->bDone==0 );
81752  rc = vdbeSorterListToPMA(pTask, &pTask->list);
81753  pTask->bDone = 1;
81754  return SQLITE_INT_TO_PTR(rc);
81755}
81756#endif /* SQLITE_MAX_WORKER_THREADS>0 */
81757
81758/*
81759** Flush the current contents of VdbeSorter.list to a new PMA, possibly
81760** using a background thread.
81761*/
81762static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
81763#if SQLITE_MAX_WORKER_THREADS==0
81764  pSorter->bUsePMA = 1;
81765  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
81766#else
81767  int rc = SQLITE_OK;
81768  int i;
81769  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
81770  int nWorker = (pSorter->nTask-1);
81771
81772  /* Set the flag to indicate that at least one PMA has been written.
81773  ** Or will be, anyhow.  */
81774  pSorter->bUsePMA = 1;
81775
81776  /* Select a sub-task to sort and flush the current list of in-memory
81777  ** records to disk. If the sorter is running in multi-threaded mode,
81778  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
81779  ** the background thread from a sub-tasks previous turn is still running,
81780  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
81781  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
81782  ** sub-tasks are prefered as they use background threads - the final
81783  ** sub-task uses the main thread. */
81784  for(i=0; i<nWorker; i++){
81785    int iTest = (pSorter->iPrev + i + 1) % nWorker;
81786    pTask = &pSorter->aTask[iTest];
81787    if( pTask->bDone ){
81788      rc = vdbeSorterJoinThread(pTask);
81789    }
81790    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
81791  }
81792
81793  if( rc==SQLITE_OK ){
81794    if( i==nWorker ){
81795      /* Use the foreground thread for this operation */
81796      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
81797    }else{
81798      /* Launch a background thread for this operation */
81799      u8 *aMem = pTask->list.aMemory;
81800      void *pCtx = (void*)pTask;
81801
81802      assert( pTask->pThread==0 && pTask->bDone==0 );
81803      assert( pTask->list.pList==0 );
81804      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
81805
81806      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
81807      pTask->list = pSorter->list;
81808      pSorter->list.pList = 0;
81809      pSorter->list.szPMA = 0;
81810      if( aMem ){
81811        pSorter->list.aMemory = aMem;
81812        pSorter->nMemory = sqlite3MallocSize(aMem);
81813      }else if( pSorter->list.aMemory ){
81814        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
81815        if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
81816      }
81817
81818      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
81819    }
81820  }
81821
81822  return rc;
81823#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
81824}
81825
81826/*
81827** Add a record to the sorter.
81828*/
81829SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
81830  const VdbeCursor *pCsr,         /* Sorter cursor */
81831  Mem *pVal                       /* Memory cell containing record */
81832){
81833  VdbeSorter *pSorter = pCsr->pSorter;
81834  int rc = SQLITE_OK;             /* Return Code */
81835  SorterRecord *pNew;             /* New list element */
81836
81837  int bFlush;                     /* True to flush contents of memory to PMA */
81838  int nReq;                       /* Bytes of memory required */
81839  int nPMA;                       /* Bytes of PMA space required */
81840  int t;                          /* serial type of first record field */
81841
81842  getVarint32((const u8*)&pVal->z[1], t);
81843  if( t>0 && t<10 && t!=7 ){
81844    pSorter->typeMask &= SORTER_TYPE_INTEGER;
81845  }else if( t>10 && (t & 0x01) ){
81846    pSorter->typeMask &= SORTER_TYPE_TEXT;
81847  }else{
81848    pSorter->typeMask = 0;
81849  }
81850
81851  assert( pSorter );
81852
81853  /* Figure out whether or not the current contents of memory should be
81854  ** flushed to a PMA before continuing. If so, do so.
81855  **
81856  ** If using the single large allocation mode (pSorter->aMemory!=0), then
81857  ** flush the contents of memory to a new PMA if (a) at least one value is
81858  ** already in memory and (b) the new value will not fit in memory.
81859  **
81860  ** Or, if using separate allocations for each record, flush the contents
81861  ** of memory to a PMA if either of the following are true:
81862  **
81863  **   * The total memory allocated for the in-memory list is greater
81864  **     than (page-size * cache-size), or
81865  **
81866  **   * The total memory allocated for the in-memory list is greater
81867  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
81868  */
81869  nReq = pVal->n + sizeof(SorterRecord);
81870  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
81871  if( pSorter->mxPmaSize ){
81872    if( pSorter->list.aMemory ){
81873      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
81874    }else{
81875      bFlush = (
81876          (pSorter->list.szPMA > pSorter->mxPmaSize)
81877       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
81878      );
81879    }
81880    if( bFlush ){
81881      rc = vdbeSorterFlushPMA(pSorter);
81882      pSorter->list.szPMA = 0;
81883      pSorter->iMemory = 0;
81884      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
81885    }
81886  }
81887
81888  pSorter->list.szPMA += nPMA;
81889  if( nPMA>pSorter->mxKeysize ){
81890    pSorter->mxKeysize = nPMA;
81891  }
81892
81893  if( pSorter->list.aMemory ){
81894    int nMin = pSorter->iMemory + nReq;
81895
81896    if( nMin>pSorter->nMemory ){
81897      u8 *aNew;
81898      int nNew = pSorter->nMemory * 2;
81899      while( nNew < nMin ) nNew = nNew*2;
81900      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
81901      if( nNew < nMin ) nNew = nMin;
81902
81903      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
81904      if( !aNew ) return SQLITE_NOMEM;
81905      pSorter->list.pList = (SorterRecord*)(
81906          aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
81907      );
81908      pSorter->list.aMemory = aNew;
81909      pSorter->nMemory = nNew;
81910    }
81911
81912    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
81913    pSorter->iMemory += ROUND8(nReq);
81914    pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
81915  }else{
81916    pNew = (SorterRecord *)sqlite3Malloc(nReq);
81917    if( pNew==0 ){
81918      return SQLITE_NOMEM;
81919    }
81920    pNew->u.pNext = pSorter->list.pList;
81921  }
81922
81923  memcpy(SRVAL(pNew), pVal->z, pVal->n);
81924  pNew->nVal = pVal->n;
81925  pSorter->list.pList = pNew;
81926
81927  return rc;
81928}
81929
81930/*
81931** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
81932** of the data stored in aFile[1] is the same as that used by regular PMAs,
81933** except that the number-of-bytes varint is omitted from the start.
81934*/
81935static int vdbeIncrPopulate(IncrMerger *pIncr){
81936  int rc = SQLITE_OK;
81937  int rc2;
81938  i64 iStart = pIncr->iStartOff;
81939  SorterFile *pOut = &pIncr->aFile[1];
81940  SortSubtask *pTask = pIncr->pTask;
81941  MergeEngine *pMerger = pIncr->pMerger;
81942  PmaWriter writer;
81943  assert( pIncr->bEof==0 );
81944
81945  vdbeSorterPopulateDebug(pTask, "enter");
81946
81947  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
81948  while( rc==SQLITE_OK ){
81949    int dummy;
81950    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
81951    int nKey = pReader->nKey;
81952    i64 iEof = writer.iWriteOff + writer.iBufEnd;
81953
81954    /* Check if the output file is full or if the input has been exhausted.
81955    ** In either case exit the loop. */
81956    if( pReader->pFd==0 ) break;
81957    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
81958
81959    /* Write the next key to the output. */
81960    vdbePmaWriteVarint(&writer, nKey);
81961    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
81962    assert( pIncr->pMerger->pTask==pTask );
81963    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
81964  }
81965
81966  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
81967  if( rc==SQLITE_OK ) rc = rc2;
81968  vdbeSorterPopulateDebug(pTask, "exit");
81969  return rc;
81970}
81971
81972#if SQLITE_MAX_WORKER_THREADS>0
81973/*
81974** The main routine for background threads that populate aFile[1] of
81975** multi-threaded IncrMerger objects.
81976*/
81977static void *vdbeIncrPopulateThread(void *pCtx){
81978  IncrMerger *pIncr = (IncrMerger*)pCtx;
81979  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
81980  pIncr->pTask->bDone = 1;
81981  return pRet;
81982}
81983
81984/*
81985** Launch a background thread to populate aFile[1] of pIncr.
81986*/
81987static int vdbeIncrBgPopulate(IncrMerger *pIncr){
81988  void *p = (void*)pIncr;
81989  assert( pIncr->bUseThread );
81990  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
81991}
81992#endif
81993
81994/*
81995** This function is called when the PmaReader corresponding to pIncr has
81996** finished reading the contents of aFile[0]. Its purpose is to "refill"
81997** aFile[0] such that the PmaReader should start rereading it from the
81998** beginning.
81999**
82000** For single-threaded objects, this is accomplished by literally reading
82001** keys from pIncr->pMerger and repopulating aFile[0].
82002**
82003** For multi-threaded objects, all that is required is to wait until the
82004** background thread is finished (if it is not already) and then swap
82005** aFile[0] and aFile[1] in place. If the contents of pMerger have not
82006** been exhausted, this function also launches a new background thread
82007** to populate the new aFile[1].
82008**
82009** SQLITE_OK is returned on success, or an SQLite error code otherwise.
82010*/
82011static int vdbeIncrSwap(IncrMerger *pIncr){
82012  int rc = SQLITE_OK;
82013
82014#if SQLITE_MAX_WORKER_THREADS>0
82015  if( pIncr->bUseThread ){
82016    rc = vdbeSorterJoinThread(pIncr->pTask);
82017
82018    if( rc==SQLITE_OK ){
82019      SorterFile f0 = pIncr->aFile[0];
82020      pIncr->aFile[0] = pIncr->aFile[1];
82021      pIncr->aFile[1] = f0;
82022    }
82023
82024    if( rc==SQLITE_OK ){
82025      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
82026        pIncr->bEof = 1;
82027      }else{
82028        rc = vdbeIncrBgPopulate(pIncr);
82029      }
82030    }
82031  }else
82032#endif
82033  {
82034    rc = vdbeIncrPopulate(pIncr);
82035    pIncr->aFile[0] = pIncr->aFile[1];
82036    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
82037      pIncr->bEof = 1;
82038    }
82039  }
82040
82041  return rc;
82042}
82043
82044/*
82045** Allocate and return a new IncrMerger object to read data from pMerger.
82046**
82047** If an OOM condition is encountered, return NULL. In this case free the
82048** pMerger argument before returning.
82049*/
82050static int vdbeIncrMergerNew(
82051  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
82052  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
82053  IncrMerger **ppOut      /* Write the new IncrMerger here */
82054){
82055  int rc = SQLITE_OK;
82056  IncrMerger *pIncr = *ppOut = (IncrMerger*)
82057       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
82058  if( pIncr ){
82059    pIncr->pMerger = pMerger;
82060    pIncr->pTask = pTask;
82061    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
82062    pTask->file2.iEof += pIncr->mxSz;
82063  }else{
82064    vdbeMergeEngineFree(pMerger);
82065    rc = SQLITE_NOMEM;
82066  }
82067  return rc;
82068}
82069
82070#if SQLITE_MAX_WORKER_THREADS>0
82071/*
82072** Set the "use-threads" flag on object pIncr.
82073*/
82074static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
82075  pIncr->bUseThread = 1;
82076  pIncr->pTask->file2.iEof -= pIncr->mxSz;
82077}
82078#endif /* SQLITE_MAX_WORKER_THREADS>0 */
82079
82080
82081
82082/*
82083** Recompute pMerger->aTree[iOut] by comparing the next keys on the
82084** two PmaReaders that feed that entry.  Neither of the PmaReaders
82085** are advanced.  This routine merely does the comparison.
82086*/
82087static void vdbeMergeEngineCompare(
82088  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
82089  int iOut               /* Store the result in pMerger->aTree[iOut] */
82090){
82091  int i1;
82092  int i2;
82093  int iRes;
82094  PmaReader *p1;
82095  PmaReader *p2;
82096
82097  assert( iOut<pMerger->nTree && iOut>0 );
82098
82099  if( iOut>=(pMerger->nTree/2) ){
82100    i1 = (iOut - pMerger->nTree/2) * 2;
82101    i2 = i1 + 1;
82102  }else{
82103    i1 = pMerger->aTree[iOut*2];
82104    i2 = pMerger->aTree[iOut*2+1];
82105  }
82106
82107  p1 = &pMerger->aReadr[i1];
82108  p2 = &pMerger->aReadr[i2];
82109
82110  if( p1->pFd==0 ){
82111    iRes = i2;
82112  }else if( p2->pFd==0 ){
82113    iRes = i1;
82114  }else{
82115    SortSubtask *pTask = pMerger->pTask;
82116    int bCached = 0;
82117    int res;
82118    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
82119    res = pTask->xCompare(
82120        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
82121    );
82122    if( res<=0 ){
82123      iRes = i1;
82124    }else{
82125      iRes = i2;
82126    }
82127  }
82128
82129  pMerger->aTree[iOut] = iRes;
82130}
82131
82132/*
82133** Allowed values for the eMode parameter to vdbeMergeEngineInit()
82134** and vdbePmaReaderIncrMergeInit().
82135**
82136** Only INCRINIT_NORMAL is valid in single-threaded builds (when
82137** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
82138** when there exists one or more separate worker threads.
82139*/
82140#define INCRINIT_NORMAL 0
82141#define INCRINIT_TASK   1
82142#define INCRINIT_ROOT   2
82143
82144/*
82145** Forward reference required as the vdbeIncrMergeInit() and
82146** vdbePmaReaderIncrInit() routines are called mutually recursively when
82147** building a merge tree.
82148*/
82149static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
82150
82151/*
82152** Initialize the MergeEngine object passed as the second argument. Once this
82153** function returns, the first key of merged data may be read from the
82154** MergeEngine object in the usual fashion.
82155**
82156** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
82157** objects attached to the PmaReader objects that the merger reads from have
82158** already been populated, but that they have not yet populated aFile[0] and
82159** set the PmaReader objects up to read from it. In this case all that is
82160** required is to call vdbePmaReaderNext() on each PmaReader to point it at
82161** its first key.
82162**
82163** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
82164** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
82165** to pMerger.
82166**
82167** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82168*/
82169static int vdbeMergeEngineInit(
82170  SortSubtask *pTask,             /* Thread that will run pMerger */
82171  MergeEngine *pMerger,           /* MergeEngine to initialize */
82172  int eMode                       /* One of the INCRINIT_XXX constants */
82173){
82174  int rc = SQLITE_OK;             /* Return code */
82175  int i;                          /* For looping over PmaReader objects */
82176  int nTree = pMerger->nTree;
82177
82178  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
82179  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
82180
82181  /* Verify that the MergeEngine is assigned to a single thread */
82182  assert( pMerger->pTask==0 );
82183  pMerger->pTask = pTask;
82184
82185  for(i=0; i<nTree; i++){
82186    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
82187      /* PmaReaders should be normally initialized in order, as if they are
82188      ** reading from the same temp file this makes for more linear file IO.
82189      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
82190      ** in use it will block the vdbePmaReaderNext() call while it uses
82191      ** the main thread to fill its buffer. So calling PmaReaderNext()
82192      ** on this PmaReader before any of the multi-threaded PmaReaders takes
82193      ** better advantage of multi-processor hardware. */
82194      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
82195    }else{
82196      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
82197    }
82198    if( rc!=SQLITE_OK ) return rc;
82199  }
82200
82201  for(i=pMerger->nTree-1; i>0; i--){
82202    vdbeMergeEngineCompare(pMerger, i);
82203  }
82204  return pTask->pUnpacked->errCode;
82205}
82206
82207/*
82208** The PmaReader passed as the first argument is guaranteed to be an
82209** incremental-reader (pReadr->pIncr!=0). This function serves to open
82210** and/or initialize the temp file related fields of the IncrMerge
82211** object at (pReadr->pIncr).
82212**
82213** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
82214** in the sub-tree headed by pReadr are also initialized. Data is then
82215** loaded into the buffers belonging to pReadr and it is set to point to
82216** the first key in its range.
82217**
82218** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
82219** to be a multi-threaded PmaReader and this function is being called in a
82220** background thread. In this case all PmaReaders in the sub-tree are
82221** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
82222** pReadr is populated. However, pReadr itself is not set up to point
82223** to its first key. A call to vdbePmaReaderNext() is still required to do
82224** that.
82225**
82226** The reason this function does not call vdbePmaReaderNext() immediately
82227** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
82228** to block on thread (pTask->thread) before accessing aFile[1]. But, since
82229** this entire function is being run by thread (pTask->thread), that will
82230** lead to the current background thread attempting to join itself.
82231**
82232** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
82233** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
82234** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
82235** In this case vdbePmaReaderNext() is called on all child PmaReaders and
82236** the current PmaReader set to point to the first key in its range.
82237**
82238** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82239*/
82240static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
82241  int rc = SQLITE_OK;
82242  IncrMerger *pIncr = pReadr->pIncr;
82243  SortSubtask *pTask = pIncr->pTask;
82244  sqlite3 *db = pTask->pSorter->db;
82245
82246  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
82247  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
82248
82249  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
82250
82251  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
82252  ** requires two temp files to itself, whereas a single-threaded object
82253  ** only requires a region of pTask->file2. */
82254  if( rc==SQLITE_OK ){
82255    int mxSz = pIncr->mxSz;
82256#if SQLITE_MAX_WORKER_THREADS>0
82257    if( pIncr->bUseThread ){
82258      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
82259      if( rc==SQLITE_OK ){
82260        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
82261      }
82262    }else
82263#endif
82264    /*if( !pIncr->bUseThread )*/{
82265      if( pTask->file2.pFd==0 ){
82266        assert( pTask->file2.iEof>0 );
82267        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
82268        pTask->file2.iEof = 0;
82269      }
82270      if( rc==SQLITE_OK ){
82271        pIncr->aFile[1].pFd = pTask->file2.pFd;
82272        pIncr->iStartOff = pTask->file2.iEof;
82273        pTask->file2.iEof += mxSz;
82274      }
82275    }
82276  }
82277
82278#if SQLITE_MAX_WORKER_THREADS>0
82279  if( rc==SQLITE_OK && pIncr->bUseThread ){
82280    /* Use the current thread to populate aFile[1], even though this
82281    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
82282    ** then this function is already running in background thread
82283    ** pIncr->pTask->thread.
82284    **
82285    ** If this is the INCRINIT_ROOT object, then it is running in the
82286    ** main VDBE thread. But that is Ok, as that thread cannot return
82287    ** control to the VDBE or proceed with anything useful until the
82288    ** first results are ready from this merger object anyway.
82289    */
82290    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
82291    rc = vdbeIncrPopulate(pIncr);
82292  }
82293#endif
82294
82295  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
82296    rc = vdbePmaReaderNext(pReadr);
82297  }
82298
82299  return rc;
82300}
82301
82302#if SQLITE_MAX_WORKER_THREADS>0
82303/*
82304** The main routine for vdbePmaReaderIncrMergeInit() operations run in
82305** background threads.
82306*/
82307static void *vdbePmaReaderBgIncrInit(void *pCtx){
82308  PmaReader *pReader = (PmaReader*)pCtx;
82309  void *pRet = SQLITE_INT_TO_PTR(
82310                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
82311               );
82312  pReader->pIncr->pTask->bDone = 1;
82313  return pRet;
82314}
82315#endif
82316
82317/*
82318** If the PmaReader passed as the first argument is not an incremental-reader
82319** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
82320** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
82321** this routine to initialize the incremental merge.
82322**
82323** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
82324** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
82325** Or, if the IncrMerger is single threaded, the same function is called
82326** using the current thread.
82327*/
82328static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
82329  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
82330  int rc = SQLITE_OK;                  /* Return code */
82331  if( pIncr ){
82332#if SQLITE_MAX_WORKER_THREADS>0
82333    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
82334    if( pIncr->bUseThread ){
82335      void *pCtx = (void*)pReadr;
82336      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
82337    }else
82338#endif
82339    {
82340      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
82341    }
82342  }
82343  return rc;
82344}
82345
82346/*
82347** Allocate a new MergeEngine object to merge the contents of nPMA level-0
82348** PMAs from pTask->file. If no error occurs, set *ppOut to point to
82349** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
82350** to NULL and return an SQLite error code.
82351**
82352** When this function is called, *piOffset is set to the offset of the
82353** first PMA to read from pTask->file. Assuming no error occurs, it is
82354** set to the offset immediately following the last byte of the last
82355** PMA before returning. If an error does occur, then the final value of
82356** *piOffset is undefined.
82357*/
82358static int vdbeMergeEngineLevel0(
82359  SortSubtask *pTask,             /* Sorter task to read from */
82360  int nPMA,                       /* Number of PMAs to read */
82361  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
82362  MergeEngine **ppOut             /* OUT: New merge-engine */
82363){
82364  MergeEngine *pNew;              /* Merge engine to return */
82365  i64 iOff = *piOffset;
82366  int i;
82367  int rc = SQLITE_OK;
82368
82369  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
82370  if( pNew==0 ) rc = SQLITE_NOMEM;
82371
82372  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
82373    i64 nDummy;
82374    PmaReader *pReadr = &pNew->aReadr[i];
82375    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
82376    iOff = pReadr->iEof;
82377  }
82378
82379  if( rc!=SQLITE_OK ){
82380    vdbeMergeEngineFree(pNew);
82381    *ppOut = 0;
82382  }
82383  *piOffset = iOff;
82384  return rc;
82385}
82386
82387/*
82388** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
82389** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
82390**
82391** i.e.
82392**
82393**   nPMA<=16    -> TreeDepth() == 0
82394**   nPMA<=256   -> TreeDepth() == 1
82395**   nPMA<=65536 -> TreeDepth() == 2
82396*/
82397static int vdbeSorterTreeDepth(int nPMA){
82398  int nDepth = 0;
82399  i64 nDiv = SORTER_MAX_MERGE_COUNT;
82400  while( nDiv < (i64)nPMA ){
82401    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
82402    nDepth++;
82403  }
82404  return nDepth;
82405}
82406
82407/*
82408** pRoot is the root of an incremental merge-tree with depth nDepth (according
82409** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
82410** tree, counting from zero. This function adds pLeaf to the tree.
82411**
82412** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
82413** code is returned and pLeaf is freed.
82414*/
82415static int vdbeSorterAddToTree(
82416  SortSubtask *pTask,             /* Task context */
82417  int nDepth,                     /* Depth of tree according to TreeDepth() */
82418  int iSeq,                       /* Sequence number of leaf within tree */
82419  MergeEngine *pRoot,             /* Root of tree */
82420  MergeEngine *pLeaf              /* Leaf to add to tree */
82421){
82422  int rc = SQLITE_OK;
82423  int nDiv = 1;
82424  int i;
82425  MergeEngine *p = pRoot;
82426  IncrMerger *pIncr;
82427
82428  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
82429
82430  for(i=1; i<nDepth; i++){
82431    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
82432  }
82433
82434  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
82435    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
82436    PmaReader *pReadr = &p->aReadr[iIter];
82437
82438    if( pReadr->pIncr==0 ){
82439      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
82440      if( pNew==0 ){
82441        rc = SQLITE_NOMEM;
82442      }else{
82443        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
82444      }
82445    }
82446    if( rc==SQLITE_OK ){
82447      p = pReadr->pIncr->pMerger;
82448      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
82449    }
82450  }
82451
82452  if( rc==SQLITE_OK ){
82453    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
82454  }else{
82455    vdbeIncrFree(pIncr);
82456  }
82457  return rc;
82458}
82459
82460/*
82461** This function is called as part of a SorterRewind() operation on a sorter
82462** that has already written two or more level-0 PMAs to one or more temp
82463** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
82464** can be used to incrementally merge all PMAs on disk.
82465**
82466** If successful, SQLITE_OK is returned and *ppOut set to point to the
82467** MergeEngine object at the root of the tree before returning. Or, if an
82468** error occurs, an SQLite error code is returned and the final value
82469** of *ppOut is undefined.
82470*/
82471static int vdbeSorterMergeTreeBuild(
82472  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
82473  MergeEngine **ppOut        /* Write the MergeEngine here */
82474){
82475  MergeEngine *pMain = 0;
82476  int rc = SQLITE_OK;
82477  int iTask;
82478
82479#if SQLITE_MAX_WORKER_THREADS>0
82480  /* If the sorter uses more than one task, then create the top-level
82481  ** MergeEngine here. This MergeEngine will read data from exactly
82482  ** one PmaReader per sub-task.  */
82483  assert( pSorter->bUseThreads || pSorter->nTask==1 );
82484  if( pSorter->nTask>1 ){
82485    pMain = vdbeMergeEngineNew(pSorter->nTask);
82486    if( pMain==0 ) rc = SQLITE_NOMEM;
82487  }
82488#endif
82489
82490  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
82491    SortSubtask *pTask = &pSorter->aTask[iTask];
82492    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
82493    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
82494      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
82495      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
82496      i64 iReadOff = 0;
82497
82498      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
82499        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
82500      }else{
82501        int i;
82502        int iSeq = 0;
82503        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
82504        if( pRoot==0 ) rc = SQLITE_NOMEM;
82505        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
82506          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
82507          int nReader;              /* Number of level-0 PMAs to merge */
82508
82509          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
82510          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
82511          if( rc==SQLITE_OK ){
82512            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
82513          }
82514        }
82515      }
82516
82517      if( rc==SQLITE_OK ){
82518#if SQLITE_MAX_WORKER_THREADS>0
82519        if( pMain!=0 ){
82520          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
82521        }else
82522#endif
82523        {
82524          assert( pMain==0 );
82525          pMain = pRoot;
82526        }
82527      }else{
82528        vdbeMergeEngineFree(pRoot);
82529      }
82530    }
82531  }
82532
82533  if( rc!=SQLITE_OK ){
82534    vdbeMergeEngineFree(pMain);
82535    pMain = 0;
82536  }
82537  *ppOut = pMain;
82538  return rc;
82539}
82540
82541/*
82542** This function is called as part of an sqlite3VdbeSorterRewind() operation
82543** on a sorter that has written two or more PMAs to temporary files. It sets
82544** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
82545** (for multi-threaded sorters) so that it can be used to iterate through
82546** all records stored in the sorter.
82547**
82548** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82549*/
82550static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
82551  int rc;                         /* Return code */
82552  SortSubtask *pTask0 = &pSorter->aTask[0];
82553  MergeEngine *pMain = 0;
82554#if SQLITE_MAX_WORKER_THREADS
82555  sqlite3 *db = pTask0->pSorter->db;
82556  int i;
82557  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
82558  for(i=0; i<pSorter->nTask; i++){
82559    pSorter->aTask[i].xCompare = xCompare;
82560  }
82561#endif
82562
82563  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
82564  if( rc==SQLITE_OK ){
82565#if SQLITE_MAX_WORKER_THREADS
82566    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
82567    if( pSorter->bUseThreads ){
82568      int iTask;
82569      PmaReader *pReadr = 0;
82570      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
82571      rc = vdbeSortAllocUnpacked(pLast);
82572      if( rc==SQLITE_OK ){
82573        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
82574        pSorter->pReader = pReadr;
82575        if( pReadr==0 ) rc = SQLITE_NOMEM;
82576      }
82577      if( rc==SQLITE_OK ){
82578        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
82579        if( rc==SQLITE_OK ){
82580          vdbeIncrMergerSetThreads(pReadr->pIncr);
82581          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
82582            IncrMerger *pIncr;
82583            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
82584              vdbeIncrMergerSetThreads(pIncr);
82585              assert( pIncr->pTask!=pLast );
82586            }
82587          }
82588          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
82589            /* Check that:
82590            **
82591            **   a) The incremental merge object is configured to use the
82592            **      right task, and
82593            **   b) If it is using task (nTask-1), it is configured to run
82594            **      in single-threaded mode. This is important, as the
82595            **      root merge (INCRINIT_ROOT) will be using the same task
82596            **      object.
82597            */
82598            PmaReader *p = &pMain->aReadr[iTask];
82599            assert( p->pIncr==0 || (
82600                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
82601             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
82602            ));
82603            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
82604          }
82605        }
82606        pMain = 0;
82607      }
82608      if( rc==SQLITE_OK ){
82609        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
82610      }
82611    }else
82612#endif
82613    {
82614      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
82615      pSorter->pMerger = pMain;
82616      pMain = 0;
82617    }
82618  }
82619
82620  if( rc!=SQLITE_OK ){
82621    vdbeMergeEngineFree(pMain);
82622  }
82623  return rc;
82624}
82625
82626
82627/*
82628** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
82629** this function is called to prepare for iterating through the records
82630** in sorted order.
82631*/
82632SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
82633  VdbeSorter *pSorter = pCsr->pSorter;
82634  int rc = SQLITE_OK;             /* Return code */
82635
82636  assert( pSorter );
82637
82638  /* If no data has been written to disk, then do not do so now. Instead,
82639  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
82640  ** from the in-memory list.  */
82641  if( pSorter->bUsePMA==0 ){
82642    if( pSorter->list.pList ){
82643      *pbEof = 0;
82644      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
82645    }else{
82646      *pbEof = 1;
82647    }
82648    return rc;
82649  }
82650
82651  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
82652  ** function flushes the contents of memory to disk, it immediately always
82653  ** creates a new list consisting of a single key immediately afterwards.
82654  ** So the list is never empty at this point.  */
82655  assert( pSorter->list.pList );
82656  rc = vdbeSorterFlushPMA(pSorter);
82657
82658  /* Join all threads */
82659  rc = vdbeSorterJoinAll(pSorter, rc);
82660
82661  vdbeSorterRewindDebug("rewind");
82662
82663  /* Assuming no errors have occurred, set up a merger structure to
82664  ** incrementally read and merge all remaining PMAs.  */
82665  assert( pSorter->pReader==0 );
82666  if( rc==SQLITE_OK ){
82667    rc = vdbeSorterSetupMerge(pSorter);
82668    *pbEof = 0;
82669  }
82670
82671  vdbeSorterRewindDebug("rewinddone");
82672  return rc;
82673}
82674
82675/*
82676** Advance to the next element in the sorter.
82677*/
82678SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
82679  VdbeSorter *pSorter = pCsr->pSorter;
82680  int rc;                         /* Return code */
82681
82682  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
82683  if( pSorter->bUsePMA ){
82684    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
82685    assert( pSorter->bUseThreads==0 || pSorter->pReader );
82686    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
82687#if SQLITE_MAX_WORKER_THREADS>0
82688    if( pSorter->bUseThreads ){
82689      rc = vdbePmaReaderNext(pSorter->pReader);
82690      *pbEof = (pSorter->pReader->pFd==0);
82691    }else
82692#endif
82693    /*if( !pSorter->bUseThreads )*/ {
82694      assert( pSorter->pMerger!=0 );
82695      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
82696      rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
82697    }
82698  }else{
82699    SorterRecord *pFree = pSorter->list.pList;
82700    pSorter->list.pList = pFree->u.pNext;
82701    pFree->u.pNext = 0;
82702    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
82703    *pbEof = !pSorter->list.pList;
82704    rc = SQLITE_OK;
82705  }
82706  return rc;
82707}
82708
82709/*
82710** Return a pointer to a buffer owned by the sorter that contains the
82711** current key.
82712*/
82713static void *vdbeSorterRowkey(
82714  const VdbeSorter *pSorter,      /* Sorter object */
82715  int *pnKey                      /* OUT: Size of current key in bytes */
82716){
82717  void *pKey;
82718  if( pSorter->bUsePMA ){
82719    PmaReader *pReader;
82720#if SQLITE_MAX_WORKER_THREADS>0
82721    if( pSorter->bUseThreads ){
82722      pReader = pSorter->pReader;
82723    }else
82724#endif
82725    /*if( !pSorter->bUseThreads )*/{
82726      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
82727    }
82728    *pnKey = pReader->nKey;
82729    pKey = pReader->aKey;
82730  }else{
82731    *pnKey = pSorter->list.pList->nVal;
82732    pKey = SRVAL(pSorter->list.pList);
82733  }
82734  return pKey;
82735}
82736
82737/*
82738** Copy the current sorter key into the memory cell pOut.
82739*/
82740SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
82741  VdbeSorter *pSorter = pCsr->pSorter;
82742  void *pKey; int nKey;           /* Sorter key to copy into pOut */
82743
82744  pKey = vdbeSorterRowkey(pSorter, &nKey);
82745  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
82746    return SQLITE_NOMEM;
82747  }
82748  pOut->n = nKey;
82749  MemSetTypeFlag(pOut, MEM_Blob);
82750  memcpy(pOut->z, pKey, nKey);
82751
82752  return SQLITE_OK;
82753}
82754
82755/*
82756** Compare the key in memory cell pVal with the key that the sorter cursor
82757** passed as the first argument currently points to. For the purposes of
82758** the comparison, ignore the rowid field at the end of each record.
82759**
82760** If the sorter cursor key contains any NULL values, consider it to be
82761** less than pVal. Even if pVal also contains NULL values.
82762**
82763** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
82764** Otherwise, set *pRes to a negative, zero or positive value if the
82765** key in pVal is smaller than, equal to or larger than the current sorter
82766** key.
82767**
82768** This routine forms the core of the OP_SorterCompare opcode, which in
82769** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
82770*/
82771SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
82772  const VdbeCursor *pCsr,         /* Sorter cursor */
82773  Mem *pVal,                      /* Value to compare to current sorter key */
82774  int nKeyCol,                    /* Compare this many columns */
82775  int *pRes                       /* OUT: Result of comparison */
82776){
82777  VdbeSorter *pSorter = pCsr->pSorter;
82778  UnpackedRecord *r2 = pSorter->pUnpacked;
82779  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
82780  int i;
82781  void *pKey; int nKey;           /* Sorter key to compare pVal with */
82782
82783  if( r2==0 ){
82784    char *p;
82785    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
82786    assert( pSorter->pUnpacked==(UnpackedRecord*)p );
82787    if( r2==0 ) return SQLITE_NOMEM;
82788    r2->nField = nKeyCol;
82789  }
82790  assert( r2->nField==nKeyCol );
82791
82792  pKey = vdbeSorterRowkey(pSorter, &nKey);
82793  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
82794  for(i=0; i<nKeyCol; i++){
82795    if( r2->aMem[i].flags & MEM_Null ){
82796      *pRes = -1;
82797      return SQLITE_OK;
82798    }
82799  }
82800
82801  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
82802  return SQLITE_OK;
82803}
82804
82805/************** End of vdbesort.c ********************************************/
82806/************** Begin file journal.c *****************************************/
82807/*
82808** 2007 August 22
82809**
82810** The author disclaims copyright to this source code.  In place of
82811** a legal notice, here is a blessing:
82812**
82813**    May you do good and not evil.
82814**    May you find forgiveness for yourself and forgive others.
82815**    May you share freely, never taking more than you give.
82816**
82817*************************************************************************
82818**
82819** This file implements a special kind of sqlite3_file object used
82820** by SQLite to create journal files if the atomic-write optimization
82821** is enabled.
82822**
82823** The distinctive characteristic of this sqlite3_file is that the
82824** actual on disk file is created lazily. When the file is created,
82825** the caller specifies a buffer size for an in-memory buffer to
82826** be used to service read() and write() requests. The actual file
82827** on disk is not created or populated until either:
82828**
82829**   1) The in-memory representation grows too large for the allocated
82830**      buffer, or
82831**   2) The sqlite3JournalCreate() function is called.
82832*/
82833#ifdef SQLITE_ENABLE_ATOMIC_WRITE
82834/* #include "sqliteInt.h" */
82835
82836
82837/*
82838** A JournalFile object is a subclass of sqlite3_file used by
82839** as an open file handle for journal files.
82840*/
82841struct JournalFile {
82842  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
82843  int nBuf;                       /* Size of zBuf[] in bytes */
82844  char *zBuf;                     /* Space to buffer journal writes */
82845  int iSize;                      /* Amount of zBuf[] currently used */
82846  int flags;                      /* xOpen flags */
82847  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
82848  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
82849  const char *zJournal;           /* Name of the journal file */
82850};
82851typedef struct JournalFile JournalFile;
82852
82853/*
82854** If it does not already exists, create and populate the on-disk file
82855** for JournalFile p.
82856*/
82857static int createFile(JournalFile *p){
82858  int rc = SQLITE_OK;
82859  if( !p->pReal ){
82860    sqlite3_file *pReal = (sqlite3_file *)&p[1];
82861    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
82862    if( rc==SQLITE_OK ){
82863      p->pReal = pReal;
82864      if( p->iSize>0 ){
82865        assert(p->iSize<=p->nBuf);
82866        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
82867      }
82868      if( rc!=SQLITE_OK ){
82869        /* If an error occurred while writing to the file, close it before
82870        ** returning. This way, SQLite uses the in-memory journal data to
82871        ** roll back changes made to the internal page-cache before this
82872        ** function was called.  */
82873        sqlite3OsClose(pReal);
82874        p->pReal = 0;
82875      }
82876    }
82877  }
82878  return rc;
82879}
82880
82881/*
82882** Close the file.
82883*/
82884static int jrnlClose(sqlite3_file *pJfd){
82885  JournalFile *p = (JournalFile *)pJfd;
82886  if( p->pReal ){
82887    sqlite3OsClose(p->pReal);
82888  }
82889  sqlite3_free(p->zBuf);
82890  return SQLITE_OK;
82891}
82892
82893/*
82894** Read data from the file.
82895*/
82896static int jrnlRead(
82897  sqlite3_file *pJfd,    /* The journal file from which to read */
82898  void *zBuf,            /* Put the results here */
82899  int iAmt,              /* Number of bytes to read */
82900  sqlite_int64 iOfst     /* Begin reading at this offset */
82901){
82902  int rc = SQLITE_OK;
82903  JournalFile *p = (JournalFile *)pJfd;
82904  if( p->pReal ){
82905    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
82906  }else if( (iAmt+iOfst)>p->iSize ){
82907    rc = SQLITE_IOERR_SHORT_READ;
82908  }else{
82909    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
82910  }
82911  return rc;
82912}
82913
82914/*
82915** Write data to the file.
82916*/
82917static int jrnlWrite(
82918  sqlite3_file *pJfd,    /* The journal file into which to write */
82919  const void *zBuf,      /* Take data to be written from here */
82920  int iAmt,              /* Number of bytes to write */
82921  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
82922){
82923  int rc = SQLITE_OK;
82924  JournalFile *p = (JournalFile *)pJfd;
82925  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
82926    rc = createFile(p);
82927  }
82928  if( rc==SQLITE_OK ){
82929    if( p->pReal ){
82930      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
82931    }else{
82932      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
82933      if( p->iSize<(iOfst+iAmt) ){
82934        p->iSize = (iOfst+iAmt);
82935      }
82936    }
82937  }
82938  return rc;
82939}
82940
82941/*
82942** Truncate the file.
82943*/
82944static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
82945  int rc = SQLITE_OK;
82946  JournalFile *p = (JournalFile *)pJfd;
82947  if( p->pReal ){
82948    rc = sqlite3OsTruncate(p->pReal, size);
82949  }else if( size<p->iSize ){
82950    p->iSize = size;
82951  }
82952  return rc;
82953}
82954
82955/*
82956** Sync the file.
82957*/
82958static int jrnlSync(sqlite3_file *pJfd, int flags){
82959  int rc;
82960  JournalFile *p = (JournalFile *)pJfd;
82961  if( p->pReal ){
82962    rc = sqlite3OsSync(p->pReal, flags);
82963  }else{
82964    rc = SQLITE_OK;
82965  }
82966  return rc;
82967}
82968
82969/*
82970** Query the size of the file in bytes.
82971*/
82972static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
82973  int rc = SQLITE_OK;
82974  JournalFile *p = (JournalFile *)pJfd;
82975  if( p->pReal ){
82976    rc = sqlite3OsFileSize(p->pReal, pSize);
82977  }else{
82978    *pSize = (sqlite_int64) p->iSize;
82979  }
82980  return rc;
82981}
82982
82983/*
82984** Table of methods for JournalFile sqlite3_file object.
82985*/
82986static struct sqlite3_io_methods JournalFileMethods = {
82987  1,             /* iVersion */
82988  jrnlClose,     /* xClose */
82989  jrnlRead,      /* xRead */
82990  jrnlWrite,     /* xWrite */
82991  jrnlTruncate,  /* xTruncate */
82992  jrnlSync,      /* xSync */
82993  jrnlFileSize,  /* xFileSize */
82994  0,             /* xLock */
82995  0,             /* xUnlock */
82996  0,             /* xCheckReservedLock */
82997  0,             /* xFileControl */
82998  0,             /* xSectorSize */
82999  0,             /* xDeviceCharacteristics */
83000  0,             /* xShmMap */
83001  0,             /* xShmLock */
83002  0,             /* xShmBarrier */
83003  0              /* xShmUnmap */
83004};
83005
83006/*
83007** Open a journal file.
83008*/
83009SQLITE_PRIVATE int sqlite3JournalOpen(
83010  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
83011  const char *zName,         /* Name of the journal file */
83012  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
83013  int flags,                 /* Opening flags */
83014  int nBuf                   /* Bytes buffered before opening the file */
83015){
83016  JournalFile *p = (JournalFile *)pJfd;
83017  memset(p, 0, sqlite3JournalSize(pVfs));
83018  if( nBuf>0 ){
83019    p->zBuf = sqlite3MallocZero(nBuf);
83020    if( !p->zBuf ){
83021      return SQLITE_NOMEM;
83022    }
83023  }else{
83024    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
83025  }
83026  p->pMethod = &JournalFileMethods;
83027  p->nBuf = nBuf;
83028  p->flags = flags;
83029  p->zJournal = zName;
83030  p->pVfs = pVfs;
83031  return SQLITE_OK;
83032}
83033
83034/*
83035** If the argument p points to a JournalFile structure, and the underlying
83036** file has not yet been created, create it now.
83037*/
83038SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
83039  if( p->pMethods!=&JournalFileMethods ){
83040    return SQLITE_OK;
83041  }
83042  return createFile((JournalFile *)p);
83043}
83044
83045/*
83046** The file-handle passed as the only argument is guaranteed to be an open
83047** file. It may or may not be of class JournalFile. If the file is a
83048** JournalFile, and the underlying file on disk has not yet been opened,
83049** return 0. Otherwise, return 1.
83050*/
83051SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
83052  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
83053}
83054
83055/*
83056** Return the number of bytes required to store a JournalFile that uses vfs
83057** pVfs to create the underlying on-disk files.
83058*/
83059SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
83060  return (pVfs->szOsFile+sizeof(JournalFile));
83061}
83062#endif
83063
83064/************** End of journal.c *********************************************/
83065/************** Begin file memjournal.c **************************************/
83066/*
83067** 2008 October 7
83068**
83069** The author disclaims copyright to this source code.  In place of
83070** a legal notice, here is a blessing:
83071**
83072**    May you do good and not evil.
83073**    May you find forgiveness for yourself and forgive others.
83074**    May you share freely, never taking more than you give.
83075**
83076*************************************************************************
83077**
83078** This file contains code use to implement an in-memory rollback journal.
83079** The in-memory rollback journal is used to journal transactions for
83080** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
83081*/
83082/* #include "sqliteInt.h" */
83083
83084/* Forward references to internal structures */
83085typedef struct MemJournal MemJournal;
83086typedef struct FilePoint FilePoint;
83087typedef struct FileChunk FileChunk;
83088
83089/* Space to hold the rollback journal is allocated in increments of
83090** this many bytes.
83091**
83092** The size chosen is a little less than a power of two.  That way,
83093** the FileChunk object will have a size that almost exactly fills
83094** a power-of-two allocation.  This minimizes wasted space in power-of-two
83095** memory allocators.
83096*/
83097#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
83098
83099/*
83100** The rollback journal is composed of a linked list of these structures.
83101*/
83102struct FileChunk {
83103  FileChunk *pNext;               /* Next chunk in the journal */
83104  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
83105};
83106
83107/*
83108** An instance of this object serves as a cursor into the rollback journal.
83109** The cursor can be either for reading or writing.
83110*/
83111struct FilePoint {
83112  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
83113  FileChunk *pChunk;              /* Specific chunk into which cursor points */
83114};
83115
83116/*
83117** This subclass is a subclass of sqlite3_file.  Each open memory-journal
83118** is an instance of this class.
83119*/
83120struct MemJournal {
83121  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
83122  FileChunk *pFirst;              /* Head of in-memory chunk-list */
83123  FilePoint endpoint;             /* Pointer to the end of the file */
83124  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
83125};
83126
83127/*
83128** Read data from the in-memory journal file.  This is the implementation
83129** of the sqlite3_vfs.xRead method.
83130*/
83131static int memjrnlRead(
83132  sqlite3_file *pJfd,    /* The journal file from which to read */
83133  void *zBuf,            /* Put the results here */
83134  int iAmt,              /* Number of bytes to read */
83135  sqlite_int64 iOfst     /* Begin reading at this offset */
83136){
83137  MemJournal *p = (MemJournal *)pJfd;
83138  u8 *zOut = zBuf;
83139  int nRead = iAmt;
83140  int iChunkOffset;
83141  FileChunk *pChunk;
83142
83143  /* SQLite never tries to read past the end of a rollback journal file */
83144  assert( iOfst+iAmt<=p->endpoint.iOffset );
83145
83146  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
83147    sqlite3_int64 iOff = 0;
83148    for(pChunk=p->pFirst;
83149        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
83150        pChunk=pChunk->pNext
83151    ){
83152      iOff += JOURNAL_CHUNKSIZE;
83153    }
83154  }else{
83155    pChunk = p->readpoint.pChunk;
83156  }
83157
83158  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
83159  do {
83160    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
83161    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
83162    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
83163    zOut += nCopy;
83164    nRead -= iSpace;
83165    iChunkOffset = 0;
83166  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
83167  p->readpoint.iOffset = iOfst+iAmt;
83168  p->readpoint.pChunk = pChunk;
83169
83170  return SQLITE_OK;
83171}
83172
83173/*
83174** Write data to the file.
83175*/
83176static int memjrnlWrite(
83177  sqlite3_file *pJfd,    /* The journal file into which to write */
83178  const void *zBuf,      /* Take data to be written from here */
83179  int iAmt,              /* Number of bytes to write */
83180  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
83181){
83182  MemJournal *p = (MemJournal *)pJfd;
83183  int nWrite = iAmt;
83184  u8 *zWrite = (u8 *)zBuf;
83185
83186  /* An in-memory journal file should only ever be appended to. Random
83187  ** access writes are not required by sqlite.
83188  */
83189  assert( iOfst==p->endpoint.iOffset );
83190  UNUSED_PARAMETER(iOfst);
83191
83192  while( nWrite>0 ){
83193    FileChunk *pChunk = p->endpoint.pChunk;
83194    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
83195    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
83196
83197    if( iChunkOffset==0 ){
83198      /* New chunk is required to extend the file. */
83199      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
83200      if( !pNew ){
83201        return SQLITE_IOERR_NOMEM;
83202      }
83203      pNew->pNext = 0;
83204      if( pChunk ){
83205        assert( p->pFirst );
83206        pChunk->pNext = pNew;
83207      }else{
83208        assert( !p->pFirst );
83209        p->pFirst = pNew;
83210      }
83211      p->endpoint.pChunk = pNew;
83212    }
83213
83214    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
83215    zWrite += iSpace;
83216    nWrite -= iSpace;
83217    p->endpoint.iOffset += iSpace;
83218  }
83219
83220  return SQLITE_OK;
83221}
83222
83223/*
83224** Truncate the file.
83225*/
83226static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
83227  MemJournal *p = (MemJournal *)pJfd;
83228  FileChunk *pChunk;
83229  assert(size==0);
83230  UNUSED_PARAMETER(size);
83231  pChunk = p->pFirst;
83232  while( pChunk ){
83233    FileChunk *pTmp = pChunk;
83234    pChunk = pChunk->pNext;
83235    sqlite3_free(pTmp);
83236  }
83237  sqlite3MemJournalOpen(pJfd);
83238  return SQLITE_OK;
83239}
83240
83241/*
83242** Close the file.
83243*/
83244static int memjrnlClose(sqlite3_file *pJfd){
83245  memjrnlTruncate(pJfd, 0);
83246  return SQLITE_OK;
83247}
83248
83249
83250/*
83251** Sync the file.
83252**
83253** Syncing an in-memory journal is a no-op.  And, in fact, this routine
83254** is never called in a working implementation.  This implementation
83255** exists purely as a contingency, in case some malfunction in some other
83256** part of SQLite causes Sync to be called by mistake.
83257*/
83258static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
83259  UNUSED_PARAMETER2(NotUsed, NotUsed2);
83260  return SQLITE_OK;
83261}
83262
83263/*
83264** Query the size of the file in bytes.
83265*/
83266static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
83267  MemJournal *p = (MemJournal *)pJfd;
83268  *pSize = (sqlite_int64) p->endpoint.iOffset;
83269  return SQLITE_OK;
83270}
83271
83272/*
83273** Table of methods for MemJournal sqlite3_file object.
83274*/
83275static const struct sqlite3_io_methods MemJournalMethods = {
83276  1,                /* iVersion */
83277  memjrnlClose,     /* xClose */
83278  memjrnlRead,      /* xRead */
83279  memjrnlWrite,     /* xWrite */
83280  memjrnlTruncate,  /* xTruncate */
83281  memjrnlSync,      /* xSync */
83282  memjrnlFileSize,  /* xFileSize */
83283  0,                /* xLock */
83284  0,                /* xUnlock */
83285  0,                /* xCheckReservedLock */
83286  0,                /* xFileControl */
83287  0,                /* xSectorSize */
83288  0,                /* xDeviceCharacteristics */
83289  0,                /* xShmMap */
83290  0,                /* xShmLock */
83291  0,                /* xShmBarrier */
83292  0,                /* xShmUnmap */
83293  0,                /* xFetch */
83294  0                 /* xUnfetch */
83295};
83296
83297/*
83298** Open a journal file.
83299*/
83300SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
83301  MemJournal *p = (MemJournal *)pJfd;
83302  assert( EIGHT_BYTE_ALIGNMENT(p) );
83303  memset(p, 0, sqlite3MemJournalSize());
83304  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
83305}
83306
83307/*
83308** Return true if the file-handle passed as an argument is
83309** an in-memory journal
83310*/
83311SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
83312  return pJfd->pMethods==&MemJournalMethods;
83313}
83314
83315/*
83316** Return the number of bytes required to store a MemJournal file descriptor.
83317*/
83318SQLITE_PRIVATE int sqlite3MemJournalSize(void){
83319  return sizeof(MemJournal);
83320}
83321
83322/************** End of memjournal.c ******************************************/
83323/************** Begin file walker.c ******************************************/
83324/*
83325** 2008 August 16
83326**
83327** The author disclaims copyright to this source code.  In place of
83328** a legal notice, here is a blessing:
83329**
83330**    May you do good and not evil.
83331**    May you find forgiveness for yourself and forgive others.
83332**    May you share freely, never taking more than you give.
83333**
83334*************************************************************************
83335** This file contains routines used for walking the parser tree for
83336** an SQL statement.
83337*/
83338/* #include "sqliteInt.h" */
83339/* #include <stdlib.h> */
83340/* #include <string.h> */
83341
83342
83343/*
83344** Walk an expression tree.  Invoke the callback once for each node
83345** of the expression, while descending.  (In other words, the callback
83346** is invoked before visiting children.)
83347**
83348** The return value from the callback should be one of the WRC_*
83349** constants to specify how to proceed with the walk.
83350**
83351**    WRC_Continue      Continue descending down the tree.
83352**
83353**    WRC_Prune         Do not descend into child nodes.  But allow
83354**                      the walk to continue with sibling nodes.
83355**
83356**    WRC_Abort         Do no more callbacks.  Unwind the stack and
83357**                      return the top-level walk call.
83358**
83359** The return value from this routine is WRC_Abort to abandon the tree walk
83360** and WRC_Continue to continue.
83361*/
83362SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
83363  int rc;
83364  if( pExpr==0 ) return WRC_Continue;
83365  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
83366  testcase( ExprHasProperty(pExpr, EP_Reduced) );
83367  rc = pWalker->xExprCallback(pWalker, pExpr);
83368  if( rc==WRC_Continue
83369              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
83370    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
83371    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
83372    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
83373      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
83374    }else{
83375      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
83376    }
83377  }
83378  return rc & WRC_Abort;
83379}
83380
83381/*
83382** Call sqlite3WalkExpr() for every expression in list p or until
83383** an abort request is seen.
83384*/
83385SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
83386  int i;
83387  struct ExprList_item *pItem;
83388  if( p ){
83389    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
83390      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
83391    }
83392  }
83393  return WRC_Continue;
83394}
83395
83396/*
83397** Walk all expressions associated with SELECT statement p.  Do
83398** not invoke the SELECT callback on p, but do (of course) invoke
83399** any expr callbacks and SELECT callbacks that come from subqueries.
83400** Return WRC_Abort or WRC_Continue.
83401*/
83402SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
83403  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
83404  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
83405  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
83406  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
83407  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
83408  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
83409  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
83410  return WRC_Continue;
83411}
83412
83413/*
83414** Walk the parse trees associated with all subqueries in the
83415** FROM clause of SELECT statement p.  Do not invoke the select
83416** callback on p, but do invoke it on each FROM clause subquery
83417** and on any subqueries further down in the tree.  Return
83418** WRC_Abort or WRC_Continue;
83419*/
83420SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
83421  SrcList *pSrc;
83422  int i;
83423  struct SrcList_item *pItem;
83424
83425  pSrc = p->pSrc;
83426  if( ALWAYS(pSrc) ){
83427    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
83428      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
83429        return WRC_Abort;
83430      }
83431      if( pItem->fg.isTabFunc
83432       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
83433      ){
83434        return WRC_Abort;
83435      }
83436    }
83437  }
83438  return WRC_Continue;
83439}
83440
83441/*
83442** Call sqlite3WalkExpr() for every expression in Select statement p.
83443** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
83444** on the compound select chain, p->pPrior.
83445**
83446** If it is not NULL, the xSelectCallback() callback is invoked before
83447** the walk of the expressions and FROM clause. The xSelectCallback2()
83448** method, if it is not NULL, is invoked following the walk of the
83449** expressions and FROM clause.
83450**
83451** Return WRC_Continue under normal conditions.  Return WRC_Abort if
83452** there is an abort request.
83453**
83454** If the Walker does not have an xSelectCallback() then this routine
83455** is a no-op returning WRC_Continue.
83456*/
83457SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
83458  int rc;
83459  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
83460    return WRC_Continue;
83461  }
83462  rc = WRC_Continue;
83463  pWalker->walkerDepth++;
83464  while( p ){
83465    if( pWalker->xSelectCallback ){
83466       rc = pWalker->xSelectCallback(pWalker, p);
83467       if( rc ) break;
83468    }
83469    if( sqlite3WalkSelectExpr(pWalker, p)
83470     || sqlite3WalkSelectFrom(pWalker, p)
83471    ){
83472      pWalker->walkerDepth--;
83473      return WRC_Abort;
83474    }
83475    if( pWalker->xSelectCallback2 ){
83476      pWalker->xSelectCallback2(pWalker, p);
83477    }
83478    p = p->pPrior;
83479  }
83480  pWalker->walkerDepth--;
83481  return rc & WRC_Abort;
83482}
83483
83484/************** End of walker.c **********************************************/
83485/************** Begin file resolve.c *****************************************/
83486/*
83487** 2008 August 18
83488**
83489** The author disclaims copyright to this source code.  In place of
83490** a legal notice, here is a blessing:
83491**
83492**    May you do good and not evil.
83493**    May you find forgiveness for yourself and forgive others.
83494**    May you share freely, never taking more than you give.
83495**
83496*************************************************************************
83497**
83498** This file contains routines used for walking the parser tree and
83499** resolve all identifiers by associating them with a particular
83500** table and column.
83501*/
83502/* #include "sqliteInt.h" */
83503/* #include <stdlib.h> */
83504/* #include <string.h> */
83505
83506/*
83507** Walk the expression tree pExpr and increase the aggregate function
83508** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
83509** This needs to occur when copying a TK_AGG_FUNCTION node from an
83510** outer query into an inner subquery.
83511**
83512** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
83513** is a helper function - a callback for the tree walker.
83514*/
83515static int incrAggDepth(Walker *pWalker, Expr *pExpr){
83516  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
83517  return WRC_Continue;
83518}
83519static void incrAggFunctionDepth(Expr *pExpr, int N){
83520  if( N>0 ){
83521    Walker w;
83522    memset(&w, 0, sizeof(w));
83523    w.xExprCallback = incrAggDepth;
83524    w.u.n = N;
83525    sqlite3WalkExpr(&w, pExpr);
83526  }
83527}
83528
83529/*
83530** Turn the pExpr expression into an alias for the iCol-th column of the
83531** result set in pEList.
83532**
83533** If the reference is followed by a COLLATE operator, then make sure
83534** the COLLATE operator is preserved.  For example:
83535**
83536**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
83537**
83538** Should be transformed into:
83539**
83540**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
83541**
83542** The nSubquery parameter specifies how many levels of subquery the
83543** alias is removed from the original expression.  The usual value is
83544** zero but it might be more if the alias is contained within a subquery
83545** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
83546** structures must be increased by the nSubquery amount.
83547*/
83548static void resolveAlias(
83549  Parse *pParse,         /* Parsing context */
83550  ExprList *pEList,      /* A result set */
83551  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
83552  Expr *pExpr,           /* Transform this into an alias to the result set */
83553  const char *zType,     /* "GROUP" or "ORDER" or "" */
83554  int nSubquery          /* Number of subqueries that the label is moving */
83555){
83556  Expr *pOrig;           /* The iCol-th column of the result set */
83557  Expr *pDup;            /* Copy of pOrig */
83558  sqlite3 *db;           /* The database connection */
83559
83560  assert( iCol>=0 && iCol<pEList->nExpr );
83561  pOrig = pEList->a[iCol].pExpr;
83562  assert( pOrig!=0 );
83563  db = pParse->db;
83564  pDup = sqlite3ExprDup(db, pOrig, 0);
83565  if( pDup==0 ) return;
83566  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
83567  if( pExpr->op==TK_COLLATE ){
83568    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
83569  }
83570  ExprSetProperty(pDup, EP_Alias);
83571
83572  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
83573  ** prevents ExprDelete() from deleting the Expr structure itself,
83574  ** allowing it to be repopulated by the memcpy() on the following line.
83575  ** The pExpr->u.zToken might point into memory that will be freed by the
83576  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
83577  ** make a copy of the token before doing the sqlite3DbFree().
83578  */
83579  ExprSetProperty(pExpr, EP_Static);
83580  sqlite3ExprDelete(db, pExpr);
83581  memcpy(pExpr, pDup, sizeof(*pExpr));
83582  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
83583    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
83584    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
83585    pExpr->flags |= EP_MemToken;
83586  }
83587  sqlite3DbFree(db, pDup);
83588}
83589
83590
83591/*
83592** Return TRUE if the name zCol occurs anywhere in the USING clause.
83593**
83594** Return FALSE if the USING clause is NULL or if it does not contain
83595** zCol.
83596*/
83597static int nameInUsingClause(IdList *pUsing, const char *zCol){
83598  if( pUsing ){
83599    int k;
83600    for(k=0; k<pUsing->nId; k++){
83601      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
83602    }
83603  }
83604  return 0;
83605}
83606
83607/*
83608** Subqueries stores the original database, table and column names for their
83609** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
83610** Check to see if the zSpan given to this routine matches the zDb, zTab,
83611** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
83612** match anything.
83613*/
83614SQLITE_PRIVATE int sqlite3MatchSpanName(
83615  const char *zSpan,
83616  const char *zCol,
83617  const char *zTab,
83618  const char *zDb
83619){
83620  int n;
83621  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
83622  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
83623    return 0;
83624  }
83625  zSpan += n+1;
83626  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
83627  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
83628    return 0;
83629  }
83630  zSpan += n+1;
83631  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
83632    return 0;
83633  }
83634  return 1;
83635}
83636
83637/*
83638** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
83639** that name in the set of source tables in pSrcList and make the pExpr
83640** expression node refer back to that source column.  The following changes
83641** are made to pExpr:
83642**
83643**    pExpr->iDb           Set the index in db->aDb[] of the database X
83644**                         (even if X is implied).
83645**    pExpr->iTable        Set to the cursor number for the table obtained
83646**                         from pSrcList.
83647**    pExpr->pTab          Points to the Table structure of X.Y (even if
83648**                         X and/or Y are implied.)
83649**    pExpr->iColumn       Set to the column number within the table.
83650**    pExpr->op            Set to TK_COLUMN.
83651**    pExpr->pLeft         Any expression this points to is deleted
83652**    pExpr->pRight        Any expression this points to is deleted.
83653**
83654** The zDb variable is the name of the database (the "X").  This value may be
83655** NULL meaning that name is of the form Y.Z or Z.  Any available database
83656** can be used.  The zTable variable is the name of the table (the "Y").  This
83657** value can be NULL if zDb is also NULL.  If zTable is NULL it
83658** means that the form of the name is Z and that columns from any table
83659** can be used.
83660**
83661** If the name cannot be resolved unambiguously, leave an error message
83662** in pParse and return WRC_Abort.  Return WRC_Prune on success.
83663*/
83664static int lookupName(
83665  Parse *pParse,       /* The parsing context */
83666  const char *zDb,     /* Name of the database containing table, or NULL */
83667  const char *zTab,    /* Name of table containing column, or NULL */
83668  const char *zCol,    /* Name of the column. */
83669  NameContext *pNC,    /* The name context used to resolve the name */
83670  Expr *pExpr          /* Make this EXPR node point to the selected column */
83671){
83672  int i, j;                         /* Loop counters */
83673  int cnt = 0;                      /* Number of matching column names */
83674  int cntTab = 0;                   /* Number of matching table names */
83675  int nSubquery = 0;                /* How many levels of subquery */
83676  sqlite3 *db = pParse->db;         /* The database connection */
83677  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
83678  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
83679  NameContext *pTopNC = pNC;        /* First namecontext in the list */
83680  Schema *pSchema = 0;              /* Schema of the expression */
83681  int isTrigger = 0;                /* True if resolved to a trigger column */
83682  Table *pTab = 0;                  /* Table hold the row */
83683  Column *pCol;                     /* A column of pTab */
83684
83685  assert( pNC );     /* the name context cannot be NULL. */
83686  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
83687  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
83688
83689  /* Initialize the node to no-match */
83690  pExpr->iTable = -1;
83691  pExpr->pTab = 0;
83692  ExprSetVVAProperty(pExpr, EP_NoReduce);
83693
83694  /* Translate the schema name in zDb into a pointer to the corresponding
83695  ** schema.  If not found, pSchema will remain NULL and nothing will match
83696  ** resulting in an appropriate error message toward the end of this routine
83697  */
83698  if( zDb ){
83699    testcase( pNC->ncFlags & NC_PartIdx );
83700    testcase( pNC->ncFlags & NC_IsCheck );
83701    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
83702      /* Silently ignore database qualifiers inside CHECK constraints and
83703      ** partial indices.  Do not raise errors because that might break
83704      ** legacy and because it does not hurt anything to just ignore the
83705      ** database name. */
83706      zDb = 0;
83707    }else{
83708      for(i=0; i<db->nDb; i++){
83709        assert( db->aDb[i].zName );
83710        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
83711          pSchema = db->aDb[i].pSchema;
83712          break;
83713        }
83714      }
83715    }
83716  }
83717
83718  /* Start at the inner-most context and move outward until a match is found */
83719  while( pNC && cnt==0 ){
83720    ExprList *pEList;
83721    SrcList *pSrcList = pNC->pSrcList;
83722
83723    if( pSrcList ){
83724      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
83725        pTab = pItem->pTab;
83726        assert( pTab!=0 && pTab->zName!=0 );
83727        assert( pTab->nCol>0 );
83728        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
83729          int hit = 0;
83730          pEList = pItem->pSelect->pEList;
83731          for(j=0; j<pEList->nExpr; j++){
83732            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
83733              cnt++;
83734              cntTab = 2;
83735              pMatch = pItem;
83736              pExpr->iColumn = j;
83737              hit = 1;
83738            }
83739          }
83740          if( hit || zTab==0 ) continue;
83741        }
83742        if( zDb && pTab->pSchema!=pSchema ){
83743          continue;
83744        }
83745        if( zTab ){
83746          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
83747          assert( zTabName!=0 );
83748          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
83749            continue;
83750          }
83751        }
83752        if( 0==(cntTab++) ){
83753          pMatch = pItem;
83754        }
83755        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
83756          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
83757            /* If there has been exactly one prior match and this match
83758            ** is for the right-hand table of a NATURAL JOIN or is in a
83759            ** USING clause, then skip this match.
83760            */
83761            if( cnt==1 ){
83762              if( pItem->fg.jointype & JT_NATURAL ) continue;
83763              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
83764            }
83765            cnt++;
83766            pMatch = pItem;
83767            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
83768            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
83769            break;
83770          }
83771        }
83772      }
83773      if( pMatch ){
83774        pExpr->iTable = pMatch->iCursor;
83775        pExpr->pTab = pMatch->pTab;
83776        /* RIGHT JOIN not (yet) supported */
83777        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
83778        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
83779          ExprSetProperty(pExpr, EP_CanBeNull);
83780        }
83781        pSchema = pExpr->pTab->pSchema;
83782      }
83783    } /* if( pSrcList ) */
83784
83785#ifndef SQLITE_OMIT_TRIGGER
83786    /* If we have not already resolved the name, then maybe
83787    ** it is a new.* or old.* trigger argument reference
83788    */
83789    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
83790      int op = pParse->eTriggerOp;
83791      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
83792      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
83793        pExpr->iTable = 1;
83794        pTab = pParse->pTriggerTab;
83795      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
83796        pExpr->iTable = 0;
83797        pTab = pParse->pTriggerTab;
83798      }else{
83799        pTab = 0;
83800      }
83801
83802      if( pTab ){
83803        int iCol;
83804        pSchema = pTab->pSchema;
83805        cntTab++;
83806        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
83807          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
83808            if( iCol==pTab->iPKey ){
83809              iCol = -1;
83810            }
83811            break;
83812          }
83813        }
83814        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
83815          /* IMP: R-51414-32910 */
83816          /* IMP: R-44911-55124 */
83817          iCol = -1;
83818        }
83819        if( iCol<pTab->nCol ){
83820          cnt++;
83821          if( iCol<0 ){
83822            pExpr->affinity = SQLITE_AFF_INTEGER;
83823          }else if( pExpr->iTable==0 ){
83824            testcase( iCol==31 );
83825            testcase( iCol==32 );
83826            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
83827          }else{
83828            testcase( iCol==31 );
83829            testcase( iCol==32 );
83830            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
83831          }
83832          pExpr->iColumn = (i16)iCol;
83833          pExpr->pTab = pTab;
83834          isTrigger = 1;
83835        }
83836      }
83837    }
83838#endif /* !defined(SQLITE_OMIT_TRIGGER) */
83839
83840    /*
83841    ** Perhaps the name is a reference to the ROWID
83842    */
83843    if( cnt==0
83844     && cntTab==1
83845     && pMatch
83846     && (pNC->ncFlags & NC_IdxExpr)==0
83847     && sqlite3IsRowid(zCol)
83848     && VisibleRowid(pMatch->pTab)
83849    ){
83850      cnt = 1;
83851      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
83852      pExpr->affinity = SQLITE_AFF_INTEGER;
83853    }
83854
83855    /*
83856    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
83857    ** might refer to an result-set alias.  This happens, for example, when
83858    ** we are resolving names in the WHERE clause of the following command:
83859    **
83860    **     SELECT a+b AS x FROM table WHERE x<10;
83861    **
83862    ** In cases like this, replace pExpr with a copy of the expression that
83863    ** forms the result set entry ("a+b" in the example) and return immediately.
83864    ** Note that the expression in the result set should have already been
83865    ** resolved by the time the WHERE clause is resolved.
83866    **
83867    ** The ability to use an output result-set column in the WHERE, GROUP BY,
83868    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
83869    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
83870    ** is supported for backwards compatibility only. Hence, we issue a warning
83871    ** on sqlite3_log() whenever the capability is used.
83872    */
83873    if( (pEList = pNC->pEList)!=0
83874     && zTab==0
83875     && cnt==0
83876    ){
83877      for(j=0; j<pEList->nExpr; j++){
83878        char *zAs = pEList->a[j].zName;
83879        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
83880          Expr *pOrig;
83881          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
83882          assert( pExpr->x.pList==0 );
83883          assert( pExpr->x.pSelect==0 );
83884          pOrig = pEList->a[j].pExpr;
83885          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
83886            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
83887            return WRC_Abort;
83888          }
83889          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
83890          cnt = 1;
83891          pMatch = 0;
83892          assert( zTab==0 && zDb==0 );
83893          goto lookupname_end;
83894        }
83895      }
83896    }
83897
83898    /* Advance to the next name context.  The loop will exit when either
83899    ** we have a match (cnt>0) or when we run out of name contexts.
83900    */
83901    if( cnt==0 ){
83902      pNC = pNC->pNext;
83903      nSubquery++;
83904    }
83905  }
83906
83907  /*
83908  ** If X and Y are NULL (in other words if only the column name Z is
83909  ** supplied) and the value of Z is enclosed in double-quotes, then
83910  ** Z is a string literal if it doesn't match any column names.  In that
83911  ** case, we need to return right away and not make any changes to
83912  ** pExpr.
83913  **
83914  ** Because no reference was made to outer contexts, the pNC->nRef
83915  ** fields are not changed in any context.
83916  */
83917  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
83918    pExpr->op = TK_STRING;
83919    pExpr->pTab = 0;
83920    return WRC_Prune;
83921  }
83922
83923  /*
83924  ** cnt==0 means there was not match.  cnt>1 means there were two or
83925  ** more matches.  Either way, we have an error.
83926  */
83927  if( cnt!=1 ){
83928    const char *zErr;
83929    zErr = cnt==0 ? "no such column" : "ambiguous column name";
83930    if( zDb ){
83931      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
83932    }else if( zTab ){
83933      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
83934    }else{
83935      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
83936    }
83937    pParse->checkSchema = 1;
83938    pTopNC->nErr++;
83939  }
83940
83941  /* If a column from a table in pSrcList is referenced, then record
83942  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
83943  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
83944  ** column number is greater than the number of bits in the bitmask
83945  ** then set the high-order bit of the bitmask.
83946  */
83947  if( pExpr->iColumn>=0 && pMatch!=0 ){
83948    int n = pExpr->iColumn;
83949    testcase( n==BMS-1 );
83950    if( n>=BMS ){
83951      n = BMS-1;
83952    }
83953    assert( pMatch->iCursor==pExpr->iTable );
83954    pMatch->colUsed |= ((Bitmask)1)<<n;
83955  }
83956
83957  /* Clean up and return
83958  */
83959  sqlite3ExprDelete(db, pExpr->pLeft);
83960  pExpr->pLeft = 0;
83961  sqlite3ExprDelete(db, pExpr->pRight);
83962  pExpr->pRight = 0;
83963  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
83964lookupname_end:
83965  if( cnt==1 ){
83966    assert( pNC!=0 );
83967    if( !ExprHasProperty(pExpr, EP_Alias) ){
83968      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
83969    }
83970    /* Increment the nRef value on all name contexts from TopNC up to
83971    ** the point where the name matched. */
83972    for(;;){
83973      assert( pTopNC!=0 );
83974      pTopNC->nRef++;
83975      if( pTopNC==pNC ) break;
83976      pTopNC = pTopNC->pNext;
83977    }
83978    return WRC_Prune;
83979  } else {
83980    return WRC_Abort;
83981  }
83982}
83983
83984/*
83985** Allocate and return a pointer to an expression to load the column iCol
83986** from datasource iSrc in SrcList pSrc.
83987*/
83988SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
83989  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
83990  if( p ){
83991    struct SrcList_item *pItem = &pSrc->a[iSrc];
83992    p->pTab = pItem->pTab;
83993    p->iTable = pItem->iCursor;
83994    if( p->pTab->iPKey==iCol ){
83995      p->iColumn = -1;
83996    }else{
83997      p->iColumn = (ynVar)iCol;
83998      testcase( iCol==BMS );
83999      testcase( iCol==BMS-1 );
84000      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
84001    }
84002    ExprSetProperty(p, EP_Resolved);
84003  }
84004  return p;
84005}
84006
84007/*
84008** Report an error that an expression is not valid for some set of
84009** pNC->ncFlags values determined by validMask.
84010*/
84011static void notValid(
84012  Parse *pParse,       /* Leave error message here */
84013  NameContext *pNC,    /* The name context */
84014  const char *zMsg,    /* Type of error */
84015  int validMask        /* Set of contexts for which prohibited */
84016){
84017  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
84018  if( (pNC->ncFlags & validMask)!=0 ){
84019    const char *zIn = "partial index WHERE clauses";
84020    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
84021#ifndef SQLITE_OMIT_CHECK
84022    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
84023#endif
84024    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
84025  }
84026}
84027
84028/*
84029** Expression p should encode a floating point value between 1.0 and 0.0.
84030** Return 1024 times this value.  Or return -1 if p is not a floating point
84031** value between 1.0 and 0.0.
84032*/
84033static int exprProbability(Expr *p){
84034  double r = -1.0;
84035  if( p->op!=TK_FLOAT ) return -1;
84036  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
84037  assert( r>=0.0 );
84038  if( r>1.0 ) return -1;
84039  return (int)(r*134217728.0);
84040}
84041
84042/*
84043** This routine is callback for sqlite3WalkExpr().
84044**
84045** Resolve symbolic names into TK_COLUMN operators for the current
84046** node in the expression tree.  Return 0 to continue the search down
84047** the tree or 2 to abort the tree walk.
84048**
84049** This routine also does error checking and name resolution for
84050** function names.  The operator for aggregate functions is changed
84051** to TK_AGG_FUNCTION.
84052*/
84053static int resolveExprStep(Walker *pWalker, Expr *pExpr){
84054  NameContext *pNC;
84055  Parse *pParse;
84056
84057  pNC = pWalker->u.pNC;
84058  assert( pNC!=0 );
84059  pParse = pNC->pParse;
84060  assert( pParse==pWalker->pParse );
84061
84062  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
84063  ExprSetProperty(pExpr, EP_Resolved);
84064#ifndef NDEBUG
84065  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
84066    SrcList *pSrcList = pNC->pSrcList;
84067    int i;
84068    for(i=0; i<pNC->pSrcList->nSrc; i++){
84069      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
84070    }
84071  }
84072#endif
84073  switch( pExpr->op ){
84074
84075#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
84076    /* The special operator TK_ROW means use the rowid for the first
84077    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
84078    ** clause processing on UPDATE and DELETE statements.
84079    */
84080    case TK_ROW: {
84081      SrcList *pSrcList = pNC->pSrcList;
84082      struct SrcList_item *pItem;
84083      assert( pSrcList && pSrcList->nSrc==1 );
84084      pItem = pSrcList->a;
84085      pExpr->op = TK_COLUMN;
84086      pExpr->pTab = pItem->pTab;
84087      pExpr->iTable = pItem->iCursor;
84088      pExpr->iColumn = -1;
84089      pExpr->affinity = SQLITE_AFF_INTEGER;
84090      break;
84091    }
84092#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
84093          && !defined(SQLITE_OMIT_SUBQUERY) */
84094
84095    /* A lone identifier is the name of a column.
84096    */
84097    case TK_ID: {
84098      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
84099    }
84100
84101    /* A table name and column name:     ID.ID
84102    ** Or a database, table and column:  ID.ID.ID
84103    */
84104    case TK_DOT: {
84105      const char *zColumn;
84106      const char *zTable;
84107      const char *zDb;
84108      Expr *pRight;
84109
84110      /* if( pSrcList==0 ) break; */
84111      notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
84112      /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
84113      pRight = pExpr->pRight;
84114      if( pRight->op==TK_ID ){
84115        zDb = 0;
84116        zTable = pExpr->pLeft->u.zToken;
84117        zColumn = pRight->u.zToken;
84118      }else{
84119        assert( pRight->op==TK_DOT );
84120        zDb = pExpr->pLeft->u.zToken;
84121        zTable = pRight->pLeft->u.zToken;
84122        zColumn = pRight->pRight->u.zToken;
84123      }
84124      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
84125    }
84126
84127    /* Resolve function names
84128    */
84129    case TK_FUNCTION: {
84130      ExprList *pList = pExpr->x.pList;    /* The argument list */
84131      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
84132      int no_such_func = 0;       /* True if no such function exists */
84133      int wrong_num_args = 0;     /* True if wrong number of arguments */
84134      int is_agg = 0;             /* True if is an aggregate function */
84135      int auth;                   /* Authorization to use the function */
84136      int nId;                    /* Number of characters in function name */
84137      const char *zId;            /* The function name. */
84138      FuncDef *pDef;              /* Information about the function */
84139      u8 enc = ENC(pParse->db);   /* The database encoding */
84140
84141      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84142      notValid(pParse, pNC, "functions", NC_PartIdx);
84143      zId = pExpr->u.zToken;
84144      nId = sqlite3Strlen30(zId);
84145      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
84146      if( pDef==0 ){
84147        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
84148        if( pDef==0 ){
84149          no_such_func = 1;
84150        }else{
84151          wrong_num_args = 1;
84152        }
84153      }else{
84154        is_agg = pDef->xFunc==0;
84155        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
84156          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
84157          if( n==2 ){
84158            pExpr->iTable = exprProbability(pList->a[1].pExpr);
84159            if( pExpr->iTable<0 ){
84160              sqlite3ErrorMsg(pParse,
84161                "second argument to likelihood() must be a "
84162                "constant between 0.0 and 1.0");
84163              pNC->nErr++;
84164            }
84165          }else{
84166            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
84167            ** equivalent to likelihood(X, 0.0625).
84168            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
84169            ** short-hand for likelihood(X,0.0625).
84170            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
84171            ** for likelihood(X,0.9375).
84172            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
84173            ** to likelihood(X,0.9375). */
84174            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
84175            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
84176          }
84177        }
84178#ifndef SQLITE_OMIT_AUTHORIZATION
84179        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
84180        if( auth!=SQLITE_OK ){
84181          if( auth==SQLITE_DENY ){
84182            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
84183                                    pDef->zName);
84184            pNC->nErr++;
84185          }
84186          pExpr->op = TK_NULL;
84187          return WRC_Prune;
84188        }
84189#endif
84190        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
84191          /* For the purposes of the EP_ConstFunc flag, date and time
84192          ** functions and other functions that change slowly are considered
84193          ** constant because they are constant for the duration of one query */
84194          ExprSetProperty(pExpr,EP_ConstFunc);
84195        }
84196        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
84197          /* Date/time functions that use 'now', and other functions like
84198          ** sqlite_version() that might change over time cannot be used
84199          ** in an index. */
84200          notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
84201        }
84202      }
84203      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
84204        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
84205        pNC->nErr++;
84206        is_agg = 0;
84207      }else if( no_such_func && pParse->db->init.busy==0 ){
84208        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
84209        pNC->nErr++;
84210      }else if( wrong_num_args ){
84211        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
84212             nId, zId);
84213        pNC->nErr++;
84214      }
84215      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
84216      sqlite3WalkExprList(pWalker, pList);
84217      if( is_agg ){
84218        NameContext *pNC2 = pNC;
84219        pExpr->op = TK_AGG_FUNCTION;
84220        pExpr->op2 = 0;
84221        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
84222          pExpr->op2++;
84223          pNC2 = pNC2->pNext;
84224        }
84225        assert( pDef!=0 );
84226        if( pNC2 ){
84227          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
84228          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
84229          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
84230
84231        }
84232        pNC->ncFlags |= NC_AllowAgg;
84233      }
84234      /* FIX ME:  Compute pExpr->affinity based on the expected return
84235      ** type of the function
84236      */
84237      return WRC_Prune;
84238    }
84239#ifndef SQLITE_OMIT_SUBQUERY
84240    case TK_SELECT:
84241    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
84242#endif
84243    case TK_IN: {
84244      testcase( pExpr->op==TK_IN );
84245      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84246        int nRef = pNC->nRef;
84247        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
84248        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
84249        assert( pNC->nRef>=nRef );
84250        if( nRef!=pNC->nRef ){
84251          ExprSetProperty(pExpr, EP_VarSelect);
84252        }
84253      }
84254      break;
84255    }
84256    case TK_VARIABLE: {
84257      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
84258      break;
84259    }
84260  }
84261  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
84262}
84263
84264/*
84265** pEList is a list of expressions which are really the result set of the
84266** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
84267** This routine checks to see if pE is a simple identifier which corresponds
84268** to the AS-name of one of the terms of the expression list.  If it is,
84269** this routine return an integer between 1 and N where N is the number of
84270** elements in pEList, corresponding to the matching entry.  If there is
84271** no match, or if pE is not a simple identifier, then this routine
84272** return 0.
84273**
84274** pEList has been resolved.  pE has not.
84275*/
84276static int resolveAsName(
84277  Parse *pParse,     /* Parsing context for error messages */
84278  ExprList *pEList,  /* List of expressions to scan */
84279  Expr *pE           /* Expression we are trying to match */
84280){
84281  int i;             /* Loop counter */
84282
84283  UNUSED_PARAMETER(pParse);
84284
84285  if( pE->op==TK_ID ){
84286    char *zCol = pE->u.zToken;
84287    for(i=0; i<pEList->nExpr; i++){
84288      char *zAs = pEList->a[i].zName;
84289      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
84290        return i+1;
84291      }
84292    }
84293  }
84294  return 0;
84295}
84296
84297/*
84298** pE is a pointer to an expression which is a single term in the
84299** ORDER BY of a compound SELECT.  The expression has not been
84300** name resolved.
84301**
84302** At the point this routine is called, we already know that the
84303** ORDER BY term is not an integer index into the result set.  That
84304** case is handled by the calling routine.
84305**
84306** Attempt to match pE against result set columns in the left-most
84307** SELECT statement.  Return the index i of the matching column,
84308** as an indication to the caller that it should sort by the i-th column.
84309** The left-most column is 1.  In other words, the value returned is the
84310** same integer value that would be used in the SQL statement to indicate
84311** the column.
84312**
84313** If there is no match, return 0.  Return -1 if an error occurs.
84314*/
84315static int resolveOrderByTermToExprList(
84316  Parse *pParse,     /* Parsing context for error messages */
84317  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
84318  Expr *pE           /* The specific ORDER BY term */
84319){
84320  int i;             /* Loop counter */
84321  ExprList *pEList;  /* The columns of the result set */
84322  NameContext nc;    /* Name context for resolving pE */
84323  sqlite3 *db;       /* Database connection */
84324  int rc;            /* Return code from subprocedures */
84325  u8 savedSuppErr;   /* Saved value of db->suppressErr */
84326
84327  assert( sqlite3ExprIsInteger(pE, &i)==0 );
84328  pEList = pSelect->pEList;
84329
84330  /* Resolve all names in the ORDER BY term expression
84331  */
84332  memset(&nc, 0, sizeof(nc));
84333  nc.pParse = pParse;
84334  nc.pSrcList = pSelect->pSrc;
84335  nc.pEList = pEList;
84336  nc.ncFlags = NC_AllowAgg;
84337  nc.nErr = 0;
84338  db = pParse->db;
84339  savedSuppErr = db->suppressErr;
84340  db->suppressErr = 1;
84341  rc = sqlite3ResolveExprNames(&nc, pE);
84342  db->suppressErr = savedSuppErr;
84343  if( rc ) return 0;
84344
84345  /* Try to match the ORDER BY expression against an expression
84346  ** in the result set.  Return an 1-based index of the matching
84347  ** result-set entry.
84348  */
84349  for(i=0; i<pEList->nExpr; i++){
84350    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
84351      return i+1;
84352    }
84353  }
84354
84355  /* If no match, return 0. */
84356  return 0;
84357}
84358
84359/*
84360** Generate an ORDER BY or GROUP BY term out-of-range error.
84361*/
84362static void resolveOutOfRangeError(
84363  Parse *pParse,         /* The error context into which to write the error */
84364  const char *zType,     /* "ORDER" or "GROUP" */
84365  int i,                 /* The index (1-based) of the term out of range */
84366  int mx                 /* Largest permissible value of i */
84367){
84368  sqlite3ErrorMsg(pParse,
84369    "%r %s BY term out of range - should be "
84370    "between 1 and %d", i, zType, mx);
84371}
84372
84373/*
84374** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
84375** each term of the ORDER BY clause is a constant integer between 1
84376** and N where N is the number of columns in the compound SELECT.
84377**
84378** ORDER BY terms that are already an integer between 1 and N are
84379** unmodified.  ORDER BY terms that are integers outside the range of
84380** 1 through N generate an error.  ORDER BY terms that are expressions
84381** are matched against result set expressions of compound SELECT
84382** beginning with the left-most SELECT and working toward the right.
84383** At the first match, the ORDER BY expression is transformed into
84384** the integer column number.
84385**
84386** Return the number of errors seen.
84387*/
84388static int resolveCompoundOrderBy(
84389  Parse *pParse,        /* Parsing context.  Leave error messages here */
84390  Select *pSelect       /* The SELECT statement containing the ORDER BY */
84391){
84392  int i;
84393  ExprList *pOrderBy;
84394  ExprList *pEList;
84395  sqlite3 *db;
84396  int moreToDo = 1;
84397
84398  pOrderBy = pSelect->pOrderBy;
84399  if( pOrderBy==0 ) return 0;
84400  db = pParse->db;
84401#if SQLITE_MAX_COLUMN
84402  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
84403    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
84404    return 1;
84405  }
84406#endif
84407  for(i=0; i<pOrderBy->nExpr; i++){
84408    pOrderBy->a[i].done = 0;
84409  }
84410  pSelect->pNext = 0;
84411  while( pSelect->pPrior ){
84412    pSelect->pPrior->pNext = pSelect;
84413    pSelect = pSelect->pPrior;
84414  }
84415  while( pSelect && moreToDo ){
84416    struct ExprList_item *pItem;
84417    moreToDo = 0;
84418    pEList = pSelect->pEList;
84419    assert( pEList!=0 );
84420    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84421      int iCol = -1;
84422      Expr *pE, *pDup;
84423      if( pItem->done ) continue;
84424      pE = sqlite3ExprSkipCollate(pItem->pExpr);
84425      if( sqlite3ExprIsInteger(pE, &iCol) ){
84426        if( iCol<=0 || iCol>pEList->nExpr ){
84427          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
84428          return 1;
84429        }
84430      }else{
84431        iCol = resolveAsName(pParse, pEList, pE);
84432        if( iCol==0 ){
84433          pDup = sqlite3ExprDup(db, pE, 0);
84434          if( !db->mallocFailed ){
84435            assert(pDup);
84436            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
84437          }
84438          sqlite3ExprDelete(db, pDup);
84439        }
84440      }
84441      if( iCol>0 ){
84442        /* Convert the ORDER BY term into an integer column number iCol,
84443        ** taking care to preserve the COLLATE clause if it exists */
84444        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
84445        if( pNew==0 ) return 1;
84446        pNew->flags |= EP_IntValue;
84447        pNew->u.iValue = iCol;
84448        if( pItem->pExpr==pE ){
84449          pItem->pExpr = pNew;
84450        }else{
84451          Expr *pParent = pItem->pExpr;
84452          assert( pParent->op==TK_COLLATE );
84453          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
84454          assert( pParent->pLeft==pE );
84455          pParent->pLeft = pNew;
84456        }
84457        sqlite3ExprDelete(db, pE);
84458        pItem->u.x.iOrderByCol = (u16)iCol;
84459        pItem->done = 1;
84460      }else{
84461        moreToDo = 1;
84462      }
84463    }
84464    pSelect = pSelect->pNext;
84465  }
84466  for(i=0; i<pOrderBy->nExpr; i++){
84467    if( pOrderBy->a[i].done==0 ){
84468      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
84469            "column in the result set", i+1);
84470      return 1;
84471    }
84472  }
84473  return 0;
84474}
84475
84476/*
84477** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
84478** the SELECT statement pSelect.  If any term is reference to a
84479** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
84480** field) then convert that term into a copy of the corresponding result set
84481** column.
84482**
84483** If any errors are detected, add an error message to pParse and
84484** return non-zero.  Return zero if no errors are seen.
84485*/
84486SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
84487  Parse *pParse,        /* Parsing context.  Leave error messages here */
84488  Select *pSelect,      /* The SELECT statement containing the clause */
84489  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
84490  const char *zType     /* "ORDER" or "GROUP" */
84491){
84492  int i;
84493  sqlite3 *db = pParse->db;
84494  ExprList *pEList;
84495  struct ExprList_item *pItem;
84496
84497  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
84498#if SQLITE_MAX_COLUMN
84499  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
84500    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
84501    return 1;
84502  }
84503#endif
84504  pEList = pSelect->pEList;
84505  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
84506  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84507    if( pItem->u.x.iOrderByCol ){
84508      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
84509        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
84510        return 1;
84511      }
84512      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
84513                   zType,0);
84514    }
84515  }
84516  return 0;
84517}
84518
84519/*
84520** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
84521** The Name context of the SELECT statement is pNC.  zType is either
84522** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
84523**
84524** This routine resolves each term of the clause into an expression.
84525** If the order-by term is an integer I between 1 and N (where N is the
84526** number of columns in the result set of the SELECT) then the expression
84527** in the resolution is a copy of the I-th result-set expression.  If
84528** the order-by term is an identifier that corresponds to the AS-name of
84529** a result-set expression, then the term resolves to a copy of the
84530** result-set expression.  Otherwise, the expression is resolved in
84531** the usual way - using sqlite3ResolveExprNames().
84532**
84533** This routine returns the number of errors.  If errors occur, then
84534** an appropriate error message might be left in pParse.  (OOM errors
84535** excepted.)
84536*/
84537static int resolveOrderGroupBy(
84538  NameContext *pNC,     /* The name context of the SELECT statement */
84539  Select *pSelect,      /* The SELECT statement holding pOrderBy */
84540  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
84541  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
84542){
84543  int i, j;                      /* Loop counters */
84544  int iCol;                      /* Column number */
84545  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
84546  Parse *pParse;                 /* Parsing context */
84547  int nResult;                   /* Number of terms in the result set */
84548
84549  if( pOrderBy==0 ) return 0;
84550  nResult = pSelect->pEList->nExpr;
84551  pParse = pNC->pParse;
84552  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84553    Expr *pE = pItem->pExpr;
84554    Expr *pE2 = sqlite3ExprSkipCollate(pE);
84555    if( zType[0]!='G' ){
84556      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
84557      if( iCol>0 ){
84558        /* If an AS-name match is found, mark this ORDER BY column as being
84559        ** a copy of the iCol-th result-set column.  The subsequent call to
84560        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
84561        ** copy of the iCol-th result-set expression. */
84562        pItem->u.x.iOrderByCol = (u16)iCol;
84563        continue;
84564      }
84565    }
84566    if( sqlite3ExprIsInteger(pE2, &iCol) ){
84567      /* The ORDER BY term is an integer constant.  Again, set the column
84568      ** number so that sqlite3ResolveOrderGroupBy() will convert the
84569      ** order-by term to a copy of the result-set expression */
84570      if( iCol<1 || iCol>0xffff ){
84571        resolveOutOfRangeError(pParse, zType, i+1, nResult);
84572        return 1;
84573      }
84574      pItem->u.x.iOrderByCol = (u16)iCol;
84575      continue;
84576    }
84577
84578    /* Otherwise, treat the ORDER BY term as an ordinary expression */
84579    pItem->u.x.iOrderByCol = 0;
84580    if( sqlite3ResolveExprNames(pNC, pE) ){
84581      return 1;
84582    }
84583    for(j=0; j<pSelect->pEList->nExpr; j++){
84584      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
84585        pItem->u.x.iOrderByCol = j+1;
84586      }
84587    }
84588  }
84589  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
84590}
84591
84592/*
84593** Resolve names in the SELECT statement p and all of its descendants.
84594*/
84595static int resolveSelectStep(Walker *pWalker, Select *p){
84596  NameContext *pOuterNC;  /* Context that contains this SELECT */
84597  NameContext sNC;        /* Name context of this SELECT */
84598  int isCompound;         /* True if p is a compound select */
84599  int nCompound;          /* Number of compound terms processed so far */
84600  Parse *pParse;          /* Parsing context */
84601  int i;                  /* Loop counter */
84602  ExprList *pGroupBy;     /* The GROUP BY clause */
84603  Select *pLeftmost;      /* Left-most of SELECT of a compound */
84604  sqlite3 *db;            /* Database connection */
84605
84606
84607  assert( p!=0 );
84608  if( p->selFlags & SF_Resolved ){
84609    return WRC_Prune;
84610  }
84611  pOuterNC = pWalker->u.pNC;
84612  pParse = pWalker->pParse;
84613  db = pParse->db;
84614
84615  /* Normally sqlite3SelectExpand() will be called first and will have
84616  ** already expanded this SELECT.  However, if this is a subquery within
84617  ** an expression, sqlite3ResolveExprNames() will be called without a
84618  ** prior call to sqlite3SelectExpand().  When that happens, let
84619  ** sqlite3SelectPrep() do all of the processing for this SELECT.
84620  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
84621  ** this routine in the correct order.
84622  */
84623  if( (p->selFlags & SF_Expanded)==0 ){
84624    sqlite3SelectPrep(pParse, p, pOuterNC);
84625    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
84626  }
84627
84628  isCompound = p->pPrior!=0;
84629  nCompound = 0;
84630  pLeftmost = p;
84631  while( p ){
84632    assert( (p->selFlags & SF_Expanded)!=0 );
84633    assert( (p->selFlags & SF_Resolved)==0 );
84634    p->selFlags |= SF_Resolved;
84635
84636    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
84637    ** are not allowed to refer to any names, so pass an empty NameContext.
84638    */
84639    memset(&sNC, 0, sizeof(sNC));
84640    sNC.pParse = pParse;
84641    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
84642        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
84643      return WRC_Abort;
84644    }
84645
84646    /* If the SF_Converted flags is set, then this Select object was
84647    ** was created by the convertCompoundSelectToSubquery() function.
84648    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
84649    ** as if it were part of the sub-query, not the parent. This block
84650    ** moves the pOrderBy down to the sub-query. It will be moved back
84651    ** after the names have been resolved.  */
84652    if( p->selFlags & SF_Converted ){
84653      Select *pSub = p->pSrc->a[0].pSelect;
84654      assert( p->pSrc->nSrc==1 && p->pOrderBy );
84655      assert( pSub->pPrior && pSub->pOrderBy==0 );
84656      pSub->pOrderBy = p->pOrderBy;
84657      p->pOrderBy = 0;
84658    }
84659
84660    /* Recursively resolve names in all subqueries
84661    */
84662    for(i=0; i<p->pSrc->nSrc; i++){
84663      struct SrcList_item *pItem = &p->pSrc->a[i];
84664      if( pItem->pSelect ){
84665        NameContext *pNC;         /* Used to iterate name contexts */
84666        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
84667        const char *zSavedContext = pParse->zAuthContext;
84668
84669        /* Count the total number of references to pOuterNC and all of its
84670        ** parent contexts. After resolving references to expressions in
84671        ** pItem->pSelect, check if this value has changed. If so, then
84672        ** SELECT statement pItem->pSelect must be correlated. Set the
84673        ** pItem->fg.isCorrelated flag if this is the case. */
84674        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
84675
84676        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
84677        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
84678        pParse->zAuthContext = zSavedContext;
84679        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
84680
84681        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
84682        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
84683        pItem->fg.isCorrelated = (nRef!=0);
84684      }
84685    }
84686
84687    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
84688    ** resolve the result-set expression list.
84689    */
84690    sNC.ncFlags = NC_AllowAgg;
84691    sNC.pSrcList = p->pSrc;
84692    sNC.pNext = pOuterNC;
84693
84694    /* Resolve names in the result set. */
84695    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
84696
84697    /* If there are no aggregate functions in the result-set, and no GROUP BY
84698    ** expression, do not allow aggregates in any of the other expressions.
84699    */
84700    assert( (p->selFlags & SF_Aggregate)==0 );
84701    pGroupBy = p->pGroupBy;
84702    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
84703      assert( NC_MinMaxAgg==SF_MinMaxAgg );
84704      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
84705    }else{
84706      sNC.ncFlags &= ~NC_AllowAgg;
84707    }
84708
84709    /* If a HAVING clause is present, then there must be a GROUP BY clause.
84710    */
84711    if( p->pHaving && !pGroupBy ){
84712      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
84713      return WRC_Abort;
84714    }
84715
84716    /* Add the output column list to the name-context before parsing the
84717    ** other expressions in the SELECT statement. This is so that
84718    ** expressions in the WHERE clause (etc.) can refer to expressions by
84719    ** aliases in the result set.
84720    **
84721    ** Minor point: If this is the case, then the expression will be
84722    ** re-evaluated for each reference to it.
84723    */
84724    sNC.pEList = p->pEList;
84725    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
84726    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
84727
84728    /* Resolve names in table-valued-function arguments */
84729    for(i=0; i<p->pSrc->nSrc; i++){
84730      struct SrcList_item *pItem = &p->pSrc->a[i];
84731      if( pItem->fg.isTabFunc
84732       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
84733      ){
84734        return WRC_Abort;
84735      }
84736    }
84737
84738    /* The ORDER BY and GROUP BY clauses may not refer to terms in
84739    ** outer queries
84740    */
84741    sNC.pNext = 0;
84742    sNC.ncFlags |= NC_AllowAgg;
84743
84744    /* If this is a converted compound query, move the ORDER BY clause from
84745    ** the sub-query back to the parent query. At this point each term
84746    ** within the ORDER BY clause has been transformed to an integer value.
84747    ** These integers will be replaced by copies of the corresponding result
84748    ** set expressions by the call to resolveOrderGroupBy() below.  */
84749    if( p->selFlags & SF_Converted ){
84750      Select *pSub = p->pSrc->a[0].pSelect;
84751      p->pOrderBy = pSub->pOrderBy;
84752      pSub->pOrderBy = 0;
84753    }
84754
84755    /* Process the ORDER BY clause for singleton SELECT statements.
84756    ** The ORDER BY clause for compounds SELECT statements is handled
84757    ** below, after all of the result-sets for all of the elements of
84758    ** the compound have been resolved.
84759    **
84760    ** If there is an ORDER BY clause on a term of a compound-select other
84761    ** than the right-most term, then that is a syntax error.  But the error
84762    ** is not detected until much later, and so we need to go ahead and
84763    ** resolve those symbols on the incorrect ORDER BY for consistency.
84764    */
84765    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
84766     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
84767    ){
84768      return WRC_Abort;
84769    }
84770    if( db->mallocFailed ){
84771      return WRC_Abort;
84772    }
84773
84774    /* Resolve the GROUP BY clause.  At the same time, make sure
84775    ** the GROUP BY clause does not contain aggregate functions.
84776    */
84777    if( pGroupBy ){
84778      struct ExprList_item *pItem;
84779
84780      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
84781        return WRC_Abort;
84782      }
84783      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
84784        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
84785          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
84786              "the GROUP BY clause");
84787          return WRC_Abort;
84788        }
84789      }
84790    }
84791
84792    /* If this is part of a compound SELECT, check that it has the right
84793    ** number of expressions in the select list. */
84794    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
84795      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
84796      return WRC_Abort;
84797    }
84798
84799    /* Advance to the next term of the compound
84800    */
84801    p = p->pPrior;
84802    nCompound++;
84803  }
84804
84805  /* Resolve the ORDER BY on a compound SELECT after all terms of
84806  ** the compound have been resolved.
84807  */
84808  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
84809    return WRC_Abort;
84810  }
84811
84812  return WRC_Prune;
84813}
84814
84815/*
84816** This routine walks an expression tree and resolves references to
84817** table columns and result-set columns.  At the same time, do error
84818** checking on function usage and set a flag if any aggregate functions
84819** are seen.
84820**
84821** To resolve table columns references we look for nodes (or subtrees) of the
84822** form X.Y.Z or Y.Z or just Z where
84823**
84824**      X:   The name of a database.  Ex:  "main" or "temp" or
84825**           the symbolic name assigned to an ATTACH-ed database.
84826**
84827**      Y:   The name of a table in a FROM clause.  Or in a trigger
84828**           one of the special names "old" or "new".
84829**
84830**      Z:   The name of a column in table Y.
84831**
84832** The node at the root of the subtree is modified as follows:
84833**
84834**    Expr.op        Changed to TK_COLUMN
84835**    Expr.pTab      Points to the Table object for X.Y
84836**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
84837**    Expr.iTable    The VDBE cursor number for X.Y
84838**
84839**
84840** To resolve result-set references, look for expression nodes of the
84841** form Z (with no X and Y prefix) where the Z matches the right-hand
84842** size of an AS clause in the result-set of a SELECT.  The Z expression
84843** is replaced by a copy of the left-hand side of the result-set expression.
84844** Table-name and function resolution occurs on the substituted expression
84845** tree.  For example, in:
84846**
84847**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
84848**
84849** The "x" term of the order by is replaced by "a+b" to render:
84850**
84851**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
84852**
84853** Function calls are checked to make sure that the function is
84854** defined and that the correct number of arguments are specified.
84855** If the function is an aggregate function, then the NC_HasAgg flag is
84856** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
84857** If an expression contains aggregate functions then the EP_Agg
84858** property on the expression is set.
84859**
84860** An error message is left in pParse if anything is amiss.  The number
84861** if errors is returned.
84862*/
84863SQLITE_PRIVATE int sqlite3ResolveExprNames(
84864  NameContext *pNC,       /* Namespace to resolve expressions in. */
84865  Expr *pExpr             /* The expression to be analyzed. */
84866){
84867  u16 savedHasAgg;
84868  Walker w;
84869
84870  if( pExpr==0 ) return 0;
84871#if SQLITE_MAX_EXPR_DEPTH>0
84872  {
84873    Parse *pParse = pNC->pParse;
84874    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
84875      return 1;
84876    }
84877    pParse->nHeight += pExpr->nHeight;
84878  }
84879#endif
84880  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
84881  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
84882  memset(&w, 0, sizeof(w));
84883  w.xExprCallback = resolveExprStep;
84884  w.xSelectCallback = resolveSelectStep;
84885  w.pParse = pNC->pParse;
84886  w.u.pNC = pNC;
84887  sqlite3WalkExpr(&w, pExpr);
84888#if SQLITE_MAX_EXPR_DEPTH>0
84889  pNC->pParse->nHeight -= pExpr->nHeight;
84890#endif
84891  if( pNC->nErr>0 || w.pParse->nErr>0 ){
84892    ExprSetProperty(pExpr, EP_Error);
84893  }
84894  if( pNC->ncFlags & NC_HasAgg ){
84895    ExprSetProperty(pExpr, EP_Agg);
84896  }
84897  pNC->ncFlags |= savedHasAgg;
84898  return ExprHasProperty(pExpr, EP_Error);
84899}
84900
84901/*
84902** Resolve all names for all expression in an expression list.  This is
84903** just like sqlite3ResolveExprNames() except that it works for an expression
84904** list rather than a single expression.
84905*/
84906SQLITE_PRIVATE int sqlite3ResolveExprListNames(
84907  NameContext *pNC,       /* Namespace to resolve expressions in. */
84908  ExprList *pList         /* The expression list to be analyzed. */
84909){
84910  int i;
84911  assert( pList!=0 );
84912  for(i=0; i<pList->nExpr; i++){
84913    if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
84914  }
84915  return WRC_Continue;
84916}
84917
84918/*
84919** Resolve all names in all expressions of a SELECT and in all
84920** decendents of the SELECT, including compounds off of p->pPrior,
84921** subqueries in expressions, and subqueries used as FROM clause
84922** terms.
84923**
84924** See sqlite3ResolveExprNames() for a description of the kinds of
84925** transformations that occur.
84926**
84927** All SELECT statements should have been expanded using
84928** sqlite3SelectExpand() prior to invoking this routine.
84929*/
84930SQLITE_PRIVATE void sqlite3ResolveSelectNames(
84931  Parse *pParse,         /* The parser context */
84932  Select *p,             /* The SELECT statement being coded. */
84933  NameContext *pOuterNC  /* Name context for parent SELECT statement */
84934){
84935  Walker w;
84936
84937  assert( p!=0 );
84938  memset(&w, 0, sizeof(w));
84939  w.xExprCallback = resolveExprStep;
84940  w.xSelectCallback = resolveSelectStep;
84941  w.pParse = pParse;
84942  w.u.pNC = pOuterNC;
84943  sqlite3WalkSelect(&w, p);
84944}
84945
84946/*
84947** Resolve names in expressions that can only reference a single table:
84948**
84949**    *   CHECK constraints
84950**    *   WHERE clauses on partial indices
84951**
84952** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
84953** is set to -1 and the Expr.iColumn value is set to the column number.
84954**
84955** Any errors cause an error message to be set in pParse.
84956*/
84957SQLITE_PRIVATE void sqlite3ResolveSelfReference(
84958  Parse *pParse,      /* Parsing context */
84959  Table *pTab,        /* The table being referenced */
84960  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
84961  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
84962  ExprList *pList     /* Expression list to resolve.  May be NUL. */
84963){
84964  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
84965  NameContext sNC;                /* Name context for pParse->pNewTable */
84966
84967  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
84968  memset(&sNC, 0, sizeof(sNC));
84969  memset(&sSrc, 0, sizeof(sSrc));
84970  sSrc.nSrc = 1;
84971  sSrc.a[0].zName = pTab->zName;
84972  sSrc.a[0].pTab = pTab;
84973  sSrc.a[0].iCursor = -1;
84974  sNC.pParse = pParse;
84975  sNC.pSrcList = &sSrc;
84976  sNC.ncFlags = type;
84977  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
84978  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
84979}
84980
84981/************** End of resolve.c *********************************************/
84982/************** Begin file expr.c ********************************************/
84983/*
84984** 2001 September 15
84985**
84986** The author disclaims copyright to this source code.  In place of
84987** a legal notice, here is a blessing:
84988**
84989**    May you do good and not evil.
84990**    May you find forgiveness for yourself and forgive others.
84991**    May you share freely, never taking more than you give.
84992**
84993*************************************************************************
84994** This file contains routines used for analyzing expressions and
84995** for generating VDBE code that evaluates expressions in SQLite.
84996*/
84997/* #include "sqliteInt.h" */
84998
84999/*
85000** Return the 'affinity' of the expression pExpr if any.
85001**
85002** If pExpr is a column, a reference to a column via an 'AS' alias,
85003** or a sub-select with a column as the return value, then the
85004** affinity of that column is returned. Otherwise, 0x00 is returned,
85005** indicating no affinity for the expression.
85006**
85007** i.e. the WHERE clause expressions in the following statements all
85008** have an affinity:
85009**
85010** CREATE TABLE t1(a);
85011** SELECT * FROM t1 WHERE a;
85012** SELECT a AS b FROM t1 WHERE b;
85013** SELECT * FROM t1 WHERE (select a from t1);
85014*/
85015SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
85016  int op;
85017  pExpr = sqlite3ExprSkipCollate(pExpr);
85018  if( pExpr->flags & EP_Generic ) return 0;
85019  op = pExpr->op;
85020  if( op==TK_SELECT ){
85021    assert( pExpr->flags&EP_xIsSelect );
85022    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
85023  }
85024#ifndef SQLITE_OMIT_CAST
85025  if( op==TK_CAST ){
85026    assert( !ExprHasProperty(pExpr, EP_IntValue) );
85027    return sqlite3AffinityType(pExpr->u.zToken, 0);
85028  }
85029#endif
85030  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
85031   && pExpr->pTab!=0
85032  ){
85033    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
85034    ** a TK_COLUMN but was previously evaluated and cached in a register */
85035    int j = pExpr->iColumn;
85036    if( j<0 ) return SQLITE_AFF_INTEGER;
85037    assert( pExpr->pTab && j<pExpr->pTab->nCol );
85038    return pExpr->pTab->aCol[j].affinity;
85039  }
85040  return pExpr->affinity;
85041}
85042
85043/*
85044** Set the collating sequence for expression pExpr to be the collating
85045** sequence named by pToken.   Return a pointer to a new Expr node that
85046** implements the COLLATE operator.
85047**
85048** If a memory allocation error occurs, that fact is recorded in pParse->db
85049** and the pExpr parameter is returned unchanged.
85050*/
85051SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
85052  Parse *pParse,           /* Parsing context */
85053  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
85054  const Token *pCollName,  /* Name of collating sequence */
85055  int dequote              /* True to dequote pCollName */
85056){
85057  if( pCollName->n>0 ){
85058    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
85059    if( pNew ){
85060      pNew->pLeft = pExpr;
85061      pNew->flags |= EP_Collate|EP_Skip;
85062      pExpr = pNew;
85063    }
85064  }
85065  return pExpr;
85066}
85067SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
85068  Token s;
85069  assert( zC!=0 );
85070  s.z = zC;
85071  s.n = sqlite3Strlen30(s.z);
85072  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
85073}
85074
85075/*
85076** Skip over any TK_COLLATE operators and any unlikely()
85077** or likelihood() function at the root of an expression.
85078*/
85079SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
85080  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
85081    if( ExprHasProperty(pExpr, EP_Unlikely) ){
85082      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85083      assert( pExpr->x.pList->nExpr>0 );
85084      assert( pExpr->op==TK_FUNCTION );
85085      pExpr = pExpr->x.pList->a[0].pExpr;
85086    }else{
85087      assert( pExpr->op==TK_COLLATE );
85088      pExpr = pExpr->pLeft;
85089    }
85090  }
85091  return pExpr;
85092}
85093
85094/*
85095** Return the collation sequence for the expression pExpr. If
85096** there is no defined collating sequence, return NULL.
85097**
85098** The collating sequence might be determined by a COLLATE operator
85099** or by the presence of a column with a defined collating sequence.
85100** COLLATE operators take first precedence.  Left operands take
85101** precedence over right operands.
85102*/
85103SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
85104  sqlite3 *db = pParse->db;
85105  CollSeq *pColl = 0;
85106  Expr *p = pExpr;
85107  while( p ){
85108    int op = p->op;
85109    if( p->flags & EP_Generic ) break;
85110    if( op==TK_CAST || op==TK_UPLUS ){
85111      p = p->pLeft;
85112      continue;
85113    }
85114    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
85115      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
85116      break;
85117    }
85118    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
85119          || op==TK_REGISTER || op==TK_TRIGGER)
85120     && p->pTab!=0
85121    ){
85122      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
85123      ** a TK_COLUMN but was previously evaluated and cached in a register */
85124      int j = p->iColumn;
85125      if( j>=0 ){
85126        const char *zColl = p->pTab->aCol[j].zColl;
85127        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
85128      }
85129      break;
85130    }
85131    if( p->flags & EP_Collate ){
85132      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
85133        p = p->pLeft;
85134      }else{
85135        Expr *pNext  = p->pRight;
85136        /* The Expr.x union is never used at the same time as Expr.pRight */
85137        assert( p->x.pList==0 || p->pRight==0 );
85138        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
85139        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
85140        ** least one EP_Collate. Thus the following two ALWAYS. */
85141        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
85142          int i;
85143          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
85144            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
85145              pNext = p->x.pList->a[i].pExpr;
85146              break;
85147            }
85148          }
85149        }
85150        p = pNext;
85151      }
85152    }else{
85153      break;
85154    }
85155  }
85156  if( sqlite3CheckCollSeq(pParse, pColl) ){
85157    pColl = 0;
85158  }
85159  return pColl;
85160}
85161
85162/*
85163** pExpr is an operand of a comparison operator.  aff2 is the
85164** type affinity of the other operand.  This routine returns the
85165** type affinity that should be used for the comparison operator.
85166*/
85167SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
85168  char aff1 = sqlite3ExprAffinity(pExpr);
85169  if( aff1 && aff2 ){
85170    /* Both sides of the comparison are columns. If one has numeric
85171    ** affinity, use that. Otherwise use no affinity.
85172    */
85173    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
85174      return SQLITE_AFF_NUMERIC;
85175    }else{
85176      return SQLITE_AFF_BLOB;
85177    }
85178  }else if( !aff1 && !aff2 ){
85179    /* Neither side of the comparison is a column.  Compare the
85180    ** results directly.
85181    */
85182    return SQLITE_AFF_BLOB;
85183  }else{
85184    /* One side is a column, the other is not. Use the columns affinity. */
85185    assert( aff1==0 || aff2==0 );
85186    return (aff1 + aff2);
85187  }
85188}
85189
85190/*
85191** pExpr is a comparison operator.  Return the type affinity that should
85192** be applied to both operands prior to doing the comparison.
85193*/
85194static char comparisonAffinity(Expr *pExpr){
85195  char aff;
85196  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
85197          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
85198          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
85199  assert( pExpr->pLeft );
85200  aff = sqlite3ExprAffinity(pExpr->pLeft);
85201  if( pExpr->pRight ){
85202    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
85203  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
85204    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
85205  }else if( !aff ){
85206    aff = SQLITE_AFF_BLOB;
85207  }
85208  return aff;
85209}
85210
85211/*
85212** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
85213** idx_affinity is the affinity of an indexed column. Return true
85214** if the index with affinity idx_affinity may be used to implement
85215** the comparison in pExpr.
85216*/
85217SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
85218  char aff = comparisonAffinity(pExpr);
85219  switch( aff ){
85220    case SQLITE_AFF_BLOB:
85221      return 1;
85222    case SQLITE_AFF_TEXT:
85223      return idx_affinity==SQLITE_AFF_TEXT;
85224    default:
85225      return sqlite3IsNumericAffinity(idx_affinity);
85226  }
85227}
85228
85229/*
85230** Return the P5 value that should be used for a binary comparison
85231** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
85232*/
85233static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
85234  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
85235  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
85236  return aff;
85237}
85238
85239/*
85240** Return a pointer to the collation sequence that should be used by
85241** a binary comparison operator comparing pLeft and pRight.
85242**
85243** If the left hand expression has a collating sequence type, then it is
85244** used. Otherwise the collation sequence for the right hand expression
85245** is used, or the default (BINARY) if neither expression has a collating
85246** type.
85247**
85248** Argument pRight (but not pLeft) may be a null pointer. In this case,
85249** it is not considered.
85250*/
85251SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
85252  Parse *pParse,
85253  Expr *pLeft,
85254  Expr *pRight
85255){
85256  CollSeq *pColl;
85257  assert( pLeft );
85258  if( pLeft->flags & EP_Collate ){
85259    pColl = sqlite3ExprCollSeq(pParse, pLeft);
85260  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
85261    pColl = sqlite3ExprCollSeq(pParse, pRight);
85262  }else{
85263    pColl = sqlite3ExprCollSeq(pParse, pLeft);
85264    if( !pColl ){
85265      pColl = sqlite3ExprCollSeq(pParse, pRight);
85266    }
85267  }
85268  return pColl;
85269}
85270
85271/*
85272** Generate code for a comparison operator.
85273*/
85274static int codeCompare(
85275  Parse *pParse,    /* The parsing (and code generating) context */
85276  Expr *pLeft,      /* The left operand */
85277  Expr *pRight,     /* The right operand */
85278  int opcode,       /* The comparison opcode */
85279  int in1, int in2, /* Register holding operands */
85280  int dest,         /* Jump here if true.  */
85281  int jumpIfNull    /* If true, jump if either operand is NULL */
85282){
85283  int p5;
85284  int addr;
85285  CollSeq *p4;
85286
85287  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
85288  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
85289  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
85290                           (void*)p4, P4_COLLSEQ);
85291  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
85292  return addr;
85293}
85294
85295#if SQLITE_MAX_EXPR_DEPTH>0
85296/*
85297** Check that argument nHeight is less than or equal to the maximum
85298** expression depth allowed. If it is not, leave an error message in
85299** pParse.
85300*/
85301SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
85302  int rc = SQLITE_OK;
85303  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
85304  if( nHeight>mxHeight ){
85305    sqlite3ErrorMsg(pParse,
85306       "Expression tree is too large (maximum depth %d)", mxHeight
85307    );
85308    rc = SQLITE_ERROR;
85309  }
85310  return rc;
85311}
85312
85313/* The following three functions, heightOfExpr(), heightOfExprList()
85314** and heightOfSelect(), are used to determine the maximum height
85315** of any expression tree referenced by the structure passed as the
85316** first argument.
85317**
85318** If this maximum height is greater than the current value pointed
85319** to by pnHeight, the second parameter, then set *pnHeight to that
85320** value.
85321*/
85322static void heightOfExpr(Expr *p, int *pnHeight){
85323  if( p ){
85324    if( p->nHeight>*pnHeight ){
85325      *pnHeight = p->nHeight;
85326    }
85327  }
85328}
85329static void heightOfExprList(ExprList *p, int *pnHeight){
85330  if( p ){
85331    int i;
85332    for(i=0; i<p->nExpr; i++){
85333      heightOfExpr(p->a[i].pExpr, pnHeight);
85334    }
85335  }
85336}
85337static void heightOfSelect(Select *p, int *pnHeight){
85338  if( p ){
85339    heightOfExpr(p->pWhere, pnHeight);
85340    heightOfExpr(p->pHaving, pnHeight);
85341    heightOfExpr(p->pLimit, pnHeight);
85342    heightOfExpr(p->pOffset, pnHeight);
85343    heightOfExprList(p->pEList, pnHeight);
85344    heightOfExprList(p->pGroupBy, pnHeight);
85345    heightOfExprList(p->pOrderBy, pnHeight);
85346    heightOfSelect(p->pPrior, pnHeight);
85347  }
85348}
85349
85350/*
85351** Set the Expr.nHeight variable in the structure passed as an
85352** argument. An expression with no children, Expr.pList or
85353** Expr.pSelect member has a height of 1. Any other expression
85354** has a height equal to the maximum height of any other
85355** referenced Expr plus one.
85356**
85357** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
85358** if appropriate.
85359*/
85360static void exprSetHeight(Expr *p){
85361  int nHeight = 0;
85362  heightOfExpr(p->pLeft, &nHeight);
85363  heightOfExpr(p->pRight, &nHeight);
85364  if( ExprHasProperty(p, EP_xIsSelect) ){
85365    heightOfSelect(p->x.pSelect, &nHeight);
85366  }else if( p->x.pList ){
85367    heightOfExprList(p->x.pList, &nHeight);
85368    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
85369  }
85370  p->nHeight = nHeight + 1;
85371}
85372
85373/*
85374** Set the Expr.nHeight variable using the exprSetHeight() function. If
85375** the height is greater than the maximum allowed expression depth,
85376** leave an error in pParse.
85377**
85378** Also propagate all EP_Propagate flags from the Expr.x.pList into
85379** Expr.flags.
85380*/
85381SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
85382  if( pParse->nErr ) return;
85383  exprSetHeight(p);
85384  sqlite3ExprCheckHeight(pParse, p->nHeight);
85385}
85386
85387/*
85388** Return the maximum height of any expression tree referenced
85389** by the select statement passed as an argument.
85390*/
85391SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
85392  int nHeight = 0;
85393  heightOfSelect(p, &nHeight);
85394  return nHeight;
85395}
85396#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
85397/*
85398** Propagate all EP_Propagate flags from the Expr.x.pList into
85399** Expr.flags.
85400*/
85401SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
85402  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
85403    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
85404  }
85405}
85406#define exprSetHeight(y)
85407#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
85408
85409/*
85410** This routine is the core allocator for Expr nodes.
85411**
85412** Construct a new expression node and return a pointer to it.  Memory
85413** for this node and for the pToken argument is a single allocation
85414** obtained from sqlite3DbMalloc().  The calling function
85415** is responsible for making sure the node eventually gets freed.
85416**
85417** If dequote is true, then the token (if it exists) is dequoted.
85418** If dequote is false, no dequoting is performed.  The deQuote
85419** parameter is ignored if pToken is NULL or if the token does not
85420** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
85421** then the EP_DblQuoted flag is set on the expression node.
85422**
85423** Special case:  If op==TK_INTEGER and pToken points to a string that
85424** can be translated into a 32-bit integer, then the token is not
85425** stored in u.zToken.  Instead, the integer values is written
85426** into u.iValue and the EP_IntValue flag is set.  No extra storage
85427** is allocated to hold the integer text and the dequote flag is ignored.
85428*/
85429SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
85430  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
85431  int op,                 /* Expression opcode */
85432  const Token *pToken,    /* Token argument.  Might be NULL */
85433  int dequote             /* True to dequote */
85434){
85435  Expr *pNew;
85436  int nExtra = 0;
85437  int iValue = 0;
85438
85439  if( pToken ){
85440    if( op!=TK_INTEGER || pToken->z==0
85441          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
85442      nExtra = pToken->n+1;
85443      assert( iValue>=0 );
85444    }
85445  }
85446  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
85447  if( pNew ){
85448    pNew->op = (u8)op;
85449    pNew->iAgg = -1;
85450    if( pToken ){
85451      if( nExtra==0 ){
85452        pNew->flags |= EP_IntValue;
85453        pNew->u.iValue = iValue;
85454      }else{
85455        int c;
85456        pNew->u.zToken = (char*)&pNew[1];
85457        assert( pToken->z!=0 || pToken->n==0 );
85458        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
85459        pNew->u.zToken[pToken->n] = 0;
85460        if( dequote && nExtra>=3
85461             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
85462          sqlite3Dequote(pNew->u.zToken);
85463          if( c=='"' ) pNew->flags |= EP_DblQuoted;
85464        }
85465      }
85466    }
85467#if SQLITE_MAX_EXPR_DEPTH>0
85468    pNew->nHeight = 1;
85469#endif
85470  }
85471  return pNew;
85472}
85473
85474/*
85475** Allocate a new expression node from a zero-terminated token that has
85476** already been dequoted.
85477*/
85478SQLITE_PRIVATE Expr *sqlite3Expr(
85479  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
85480  int op,                 /* Expression opcode */
85481  const char *zToken      /* Token argument.  Might be NULL */
85482){
85483  Token x;
85484  x.z = zToken;
85485  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
85486  return sqlite3ExprAlloc(db, op, &x, 0);
85487}
85488
85489/*
85490** Attach subtrees pLeft and pRight to the Expr node pRoot.
85491**
85492** If pRoot==NULL that means that a memory allocation error has occurred.
85493** In that case, delete the subtrees pLeft and pRight.
85494*/
85495SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
85496  sqlite3 *db,
85497  Expr *pRoot,
85498  Expr *pLeft,
85499  Expr *pRight
85500){
85501  if( pRoot==0 ){
85502    assert( db->mallocFailed );
85503    sqlite3ExprDelete(db, pLeft);
85504    sqlite3ExprDelete(db, pRight);
85505  }else{
85506    if( pRight ){
85507      pRoot->pRight = pRight;
85508      pRoot->flags |= EP_Propagate & pRight->flags;
85509    }
85510    if( pLeft ){
85511      pRoot->pLeft = pLeft;
85512      pRoot->flags |= EP_Propagate & pLeft->flags;
85513    }
85514    exprSetHeight(pRoot);
85515  }
85516}
85517
85518/*
85519** Allocate an Expr node which joins as many as two subtrees.
85520**
85521** One or both of the subtrees can be NULL.  Return a pointer to the new
85522** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
85523** free the subtrees and return NULL.
85524*/
85525SQLITE_PRIVATE Expr *sqlite3PExpr(
85526  Parse *pParse,          /* Parsing context */
85527  int op,                 /* Expression opcode */
85528  Expr *pLeft,            /* Left operand */
85529  Expr *pRight,           /* Right operand */
85530  const Token *pToken     /* Argument token */
85531){
85532  Expr *p;
85533  if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
85534    /* Take advantage of short-circuit false optimization for AND */
85535    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
85536  }else{
85537    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
85538    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
85539  }
85540  if( p ) {
85541    sqlite3ExprCheckHeight(pParse, p->nHeight);
85542  }
85543  return p;
85544}
85545
85546/*
85547** If the expression is always either TRUE or FALSE (respectively),
85548** then return 1.  If one cannot determine the truth value of the
85549** expression at compile-time return 0.
85550**
85551** This is an optimization.  If is OK to return 0 here even if
85552** the expression really is always false or false (a false negative).
85553** But it is a bug to return 1 if the expression might have different
85554** boolean values in different circumstances (a false positive.)
85555**
85556** Note that if the expression is part of conditional for a
85557** LEFT JOIN, then we cannot determine at compile-time whether or not
85558** is it true or false, so always return 0.
85559*/
85560static int exprAlwaysTrue(Expr *p){
85561  int v = 0;
85562  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
85563  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
85564  return v!=0;
85565}
85566static int exprAlwaysFalse(Expr *p){
85567  int v = 0;
85568  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
85569  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
85570  return v==0;
85571}
85572
85573/*
85574** Join two expressions using an AND operator.  If either expression is
85575** NULL, then just return the other expression.
85576**
85577** If one side or the other of the AND is known to be false, then instead
85578** of returning an AND expression, just return a constant expression with
85579** a value of false.
85580*/
85581SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
85582  if( pLeft==0 ){
85583    return pRight;
85584  }else if( pRight==0 ){
85585    return pLeft;
85586  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
85587    sqlite3ExprDelete(db, pLeft);
85588    sqlite3ExprDelete(db, pRight);
85589    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
85590  }else{
85591    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
85592    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
85593    return pNew;
85594  }
85595}
85596
85597/*
85598** Construct a new expression node for a function with multiple
85599** arguments.
85600*/
85601SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
85602  Expr *pNew;
85603  sqlite3 *db = pParse->db;
85604  assert( pToken );
85605  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
85606  if( pNew==0 ){
85607    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
85608    return 0;
85609  }
85610  pNew->x.pList = pList;
85611  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
85612  sqlite3ExprSetHeightAndFlags(pParse, pNew);
85613  return pNew;
85614}
85615
85616/*
85617** Assign a variable number to an expression that encodes a wildcard
85618** in the original SQL statement.
85619**
85620** Wildcards consisting of a single "?" are assigned the next sequential
85621** variable number.
85622**
85623** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
85624** sure "nnn" is not too be to avoid a denial of service attack when
85625** the SQL statement comes from an external source.
85626**
85627** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
85628** as the previous instance of the same wildcard.  Or if this is the first
85629** instance of the wildcard, the next sequential variable number is
85630** assigned.
85631*/
85632SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
85633  sqlite3 *db = pParse->db;
85634  const char *z;
85635
85636  if( pExpr==0 ) return;
85637  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
85638  z = pExpr->u.zToken;
85639  assert( z!=0 );
85640  assert( z[0]!=0 );
85641  if( z[1]==0 ){
85642    /* Wildcard of the form "?".  Assign the next variable number */
85643    assert( z[0]=='?' );
85644    pExpr->iColumn = (ynVar)(++pParse->nVar);
85645  }else{
85646    ynVar x = 0;
85647    u32 n = sqlite3Strlen30(z);
85648    if( z[0]=='?' ){
85649      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
85650      ** use it as the variable number */
85651      i64 i;
85652      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
85653      pExpr->iColumn = x = (ynVar)i;
85654      testcase( i==0 );
85655      testcase( i==1 );
85656      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
85657      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
85658      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
85659        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
85660            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
85661        x = 0;
85662      }
85663      if( i>pParse->nVar ){
85664        pParse->nVar = (int)i;
85665      }
85666    }else{
85667      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
85668      ** number as the prior appearance of the same name, or if the name
85669      ** has never appeared before, reuse the same variable number
85670      */
85671      ynVar i;
85672      for(i=0; i<pParse->nzVar; i++){
85673        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
85674          pExpr->iColumn = x = (ynVar)i+1;
85675          break;
85676        }
85677      }
85678      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
85679    }
85680    if( x>0 ){
85681      if( x>pParse->nzVar ){
85682        char **a;
85683        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
85684        if( a==0 ) return;  /* Error reported through db->mallocFailed */
85685        pParse->azVar = a;
85686        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
85687        pParse->nzVar = x;
85688      }
85689      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
85690        sqlite3DbFree(db, pParse->azVar[x-1]);
85691        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
85692      }
85693    }
85694  }
85695  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
85696    sqlite3ErrorMsg(pParse, "too many SQL variables");
85697  }
85698}
85699
85700/*
85701** Recursively delete an expression tree.
85702*/
85703SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
85704  if( p==0 ) return;
85705  /* Sanity check: Assert that the IntValue is non-negative if it exists */
85706  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
85707  if( !ExprHasProperty(p, EP_TokenOnly) ){
85708    /* The Expr.x union is never used at the same time as Expr.pRight */
85709    assert( p->x.pList==0 || p->pRight==0 );
85710    sqlite3ExprDelete(db, p->pLeft);
85711    sqlite3ExprDelete(db, p->pRight);
85712    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
85713    if( ExprHasProperty(p, EP_xIsSelect) ){
85714      sqlite3SelectDelete(db, p->x.pSelect);
85715    }else{
85716      sqlite3ExprListDelete(db, p->x.pList);
85717    }
85718  }
85719  if( !ExprHasProperty(p, EP_Static) ){
85720    sqlite3DbFree(db, p);
85721  }
85722}
85723
85724/*
85725** Return the number of bytes allocated for the expression structure
85726** passed as the first argument. This is always one of EXPR_FULLSIZE,
85727** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
85728*/
85729static int exprStructSize(Expr *p){
85730  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
85731  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
85732  return EXPR_FULLSIZE;
85733}
85734
85735/*
85736** The dupedExpr*Size() routines each return the number of bytes required
85737** to store a copy of an expression or expression tree.  They differ in
85738** how much of the tree is measured.
85739**
85740**     dupedExprStructSize()     Size of only the Expr structure
85741**     dupedExprNodeSize()       Size of Expr + space for token
85742**     dupedExprSize()           Expr + token + subtree components
85743**
85744***************************************************************************
85745**
85746** The dupedExprStructSize() function returns two values OR-ed together:
85747** (1) the space required for a copy of the Expr structure only and
85748** (2) the EP_xxx flags that indicate what the structure size should be.
85749** The return values is always one of:
85750**
85751**      EXPR_FULLSIZE
85752**      EXPR_REDUCEDSIZE   | EP_Reduced
85753**      EXPR_TOKENONLYSIZE | EP_TokenOnly
85754**
85755** The size of the structure can be found by masking the return value
85756** of this routine with 0xfff.  The flags can be found by masking the
85757** return value with EP_Reduced|EP_TokenOnly.
85758**
85759** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
85760** (unreduced) Expr objects as they or originally constructed by the parser.
85761** During expression analysis, extra information is computed and moved into
85762** later parts of teh Expr object and that extra information might get chopped
85763** off if the expression is reduced.  Note also that it does not work to
85764** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
85765** to reduce a pristine expression tree from the parser.  The implementation
85766** of dupedExprStructSize() contain multiple assert() statements that attempt
85767** to enforce this constraint.
85768*/
85769static int dupedExprStructSize(Expr *p, int flags){
85770  int nSize;
85771  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
85772  assert( EXPR_FULLSIZE<=0xfff );
85773  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
85774  if( 0==(flags&EXPRDUP_REDUCE) ){
85775    nSize = EXPR_FULLSIZE;
85776  }else{
85777    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
85778    assert( !ExprHasProperty(p, EP_FromJoin) );
85779    assert( !ExprHasProperty(p, EP_MemToken) );
85780    assert( !ExprHasProperty(p, EP_NoReduce) );
85781    if( p->pLeft || p->x.pList ){
85782      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
85783    }else{
85784      assert( p->pRight==0 );
85785      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
85786    }
85787  }
85788  return nSize;
85789}
85790
85791/*
85792** This function returns the space in bytes required to store the copy
85793** of the Expr structure and a copy of the Expr.u.zToken string (if that
85794** string is defined.)
85795*/
85796static int dupedExprNodeSize(Expr *p, int flags){
85797  int nByte = dupedExprStructSize(p, flags) & 0xfff;
85798  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
85799    nByte += sqlite3Strlen30(p->u.zToken)+1;
85800  }
85801  return ROUND8(nByte);
85802}
85803
85804/*
85805** Return the number of bytes required to create a duplicate of the
85806** expression passed as the first argument. The second argument is a
85807** mask containing EXPRDUP_XXX flags.
85808**
85809** The value returned includes space to create a copy of the Expr struct
85810** itself and the buffer referred to by Expr.u.zToken, if any.
85811**
85812** If the EXPRDUP_REDUCE flag is set, then the return value includes
85813** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
85814** and Expr.pRight variables (but not for any structures pointed to or
85815** descended from the Expr.x.pList or Expr.x.pSelect variables).
85816*/
85817static int dupedExprSize(Expr *p, int flags){
85818  int nByte = 0;
85819  if( p ){
85820    nByte = dupedExprNodeSize(p, flags);
85821    if( flags&EXPRDUP_REDUCE ){
85822      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
85823    }
85824  }
85825  return nByte;
85826}
85827
85828/*
85829** This function is similar to sqlite3ExprDup(), except that if pzBuffer
85830** is not NULL then *pzBuffer is assumed to point to a buffer large enough
85831** to store the copy of expression p, the copies of p->u.zToken
85832** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
85833** if any. Before returning, *pzBuffer is set to the first byte past the
85834** portion of the buffer copied into by this function.
85835*/
85836static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
85837  Expr *pNew = 0;                      /* Value to return */
85838  if( p ){
85839    const int isReduced = (flags&EXPRDUP_REDUCE);
85840    u8 *zAlloc;
85841    u32 staticFlag = 0;
85842
85843    assert( pzBuffer==0 || isReduced );
85844
85845    /* Figure out where to write the new Expr structure. */
85846    if( pzBuffer ){
85847      zAlloc = *pzBuffer;
85848      staticFlag = EP_Static;
85849    }else{
85850      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
85851    }
85852    pNew = (Expr *)zAlloc;
85853
85854    if( pNew ){
85855      /* Set nNewSize to the size allocated for the structure pointed to
85856      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
85857      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
85858      ** by the copy of the p->u.zToken string (if any).
85859      */
85860      const unsigned nStructSize = dupedExprStructSize(p, flags);
85861      const int nNewSize = nStructSize & 0xfff;
85862      int nToken;
85863      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
85864        nToken = sqlite3Strlen30(p->u.zToken) + 1;
85865      }else{
85866        nToken = 0;
85867      }
85868      if( isReduced ){
85869        assert( ExprHasProperty(p, EP_Reduced)==0 );
85870        memcpy(zAlloc, p, nNewSize);
85871      }else{
85872        int nSize = exprStructSize(p);
85873        memcpy(zAlloc, p, nSize);
85874        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
85875      }
85876
85877      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
85878      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
85879      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
85880      pNew->flags |= staticFlag;
85881
85882      /* Copy the p->u.zToken string, if any. */
85883      if( nToken ){
85884        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
85885        memcpy(zToken, p->u.zToken, nToken);
85886      }
85887
85888      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
85889        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
85890        if( ExprHasProperty(p, EP_xIsSelect) ){
85891          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
85892        }else{
85893          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
85894        }
85895      }
85896
85897      /* Fill in pNew->pLeft and pNew->pRight. */
85898      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
85899        zAlloc += dupedExprNodeSize(p, flags);
85900        if( ExprHasProperty(pNew, EP_Reduced) ){
85901          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
85902          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
85903        }
85904        if( pzBuffer ){
85905          *pzBuffer = zAlloc;
85906        }
85907      }else{
85908        if( !ExprHasProperty(p, EP_TokenOnly) ){
85909          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
85910          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
85911        }
85912      }
85913
85914    }
85915  }
85916  return pNew;
85917}
85918
85919/*
85920** Create and return a deep copy of the object passed as the second
85921** argument. If an OOM condition is encountered, NULL is returned
85922** and the db->mallocFailed flag set.
85923*/
85924#ifndef SQLITE_OMIT_CTE
85925static With *withDup(sqlite3 *db, With *p){
85926  With *pRet = 0;
85927  if( p ){
85928    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
85929    pRet = sqlite3DbMallocZero(db, nByte);
85930    if( pRet ){
85931      int i;
85932      pRet->nCte = p->nCte;
85933      for(i=0; i<p->nCte; i++){
85934        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
85935        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
85936        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
85937      }
85938    }
85939  }
85940  return pRet;
85941}
85942#else
85943# define withDup(x,y) 0
85944#endif
85945
85946/*
85947** The following group of routines make deep copies of expressions,
85948** expression lists, ID lists, and select statements.  The copies can
85949** be deleted (by being passed to their respective ...Delete() routines)
85950** without effecting the originals.
85951**
85952** The expression list, ID, and source lists return by sqlite3ExprListDup(),
85953** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
85954** by subsequent calls to sqlite*ListAppend() routines.
85955**
85956** Any tables that the SrcList might point to are not duplicated.
85957**
85958** The flags parameter contains a combination of the EXPRDUP_XXX flags.
85959** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
85960** truncated version of the usual Expr structure that will be stored as
85961** part of the in-memory representation of the database schema.
85962*/
85963SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
85964  return exprDup(db, p, flags, 0);
85965}
85966SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
85967  ExprList *pNew;
85968  struct ExprList_item *pItem, *pOldItem;
85969  int i;
85970  if( p==0 ) return 0;
85971  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
85972  if( pNew==0 ) return 0;
85973  pNew->nExpr = i = p->nExpr;
85974  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
85975  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
85976  if( pItem==0 ){
85977    sqlite3DbFree(db, pNew);
85978    return 0;
85979  }
85980  pOldItem = p->a;
85981  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
85982    Expr *pOldExpr = pOldItem->pExpr;
85983    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
85984    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
85985    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
85986    pItem->sortOrder = pOldItem->sortOrder;
85987    pItem->done = 0;
85988    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
85989    pItem->u = pOldItem->u;
85990  }
85991  return pNew;
85992}
85993
85994/*
85995** If cursors, triggers, views and subqueries are all omitted from
85996** the build, then none of the following routines, except for
85997** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
85998** called with a NULL argument.
85999*/
86000#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
86001 || !defined(SQLITE_OMIT_SUBQUERY)
86002SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
86003  SrcList *pNew;
86004  int i;
86005  int nByte;
86006  if( p==0 ) return 0;
86007  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
86008  pNew = sqlite3DbMallocRaw(db, nByte );
86009  if( pNew==0 ) return 0;
86010  pNew->nSrc = pNew->nAlloc = p->nSrc;
86011  for(i=0; i<p->nSrc; i++){
86012    struct SrcList_item *pNewItem = &pNew->a[i];
86013    struct SrcList_item *pOldItem = &p->a[i];
86014    Table *pTab;
86015    pNewItem->pSchema = pOldItem->pSchema;
86016    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
86017    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
86018    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
86019    pNewItem->fg = pOldItem->fg;
86020    pNewItem->iCursor = pOldItem->iCursor;
86021    pNewItem->addrFillSub = pOldItem->addrFillSub;
86022    pNewItem->regReturn = pOldItem->regReturn;
86023    if( pNewItem->fg.isIndexedBy ){
86024      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
86025    }
86026    pNewItem->pIBIndex = pOldItem->pIBIndex;
86027    if( pNewItem->fg.isTabFunc ){
86028      pNewItem->u1.pFuncArg =
86029          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
86030    }
86031    pTab = pNewItem->pTab = pOldItem->pTab;
86032    if( pTab ){
86033      pTab->nRef++;
86034    }
86035    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
86036    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
86037    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
86038    pNewItem->colUsed = pOldItem->colUsed;
86039  }
86040  return pNew;
86041}
86042SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
86043  IdList *pNew;
86044  int i;
86045  if( p==0 ) return 0;
86046  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
86047  if( pNew==0 ) return 0;
86048  pNew->nId = p->nId;
86049  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
86050  if( pNew->a==0 ){
86051    sqlite3DbFree(db, pNew);
86052    return 0;
86053  }
86054  /* Note that because the size of the allocation for p->a[] is not
86055  ** necessarily a power of two, sqlite3IdListAppend() may not be called
86056  ** on the duplicate created by this function. */
86057  for(i=0; i<p->nId; i++){
86058    struct IdList_item *pNewItem = &pNew->a[i];
86059    struct IdList_item *pOldItem = &p->a[i];
86060    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
86061    pNewItem->idx = pOldItem->idx;
86062  }
86063  return pNew;
86064}
86065SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
86066  Select *pNew, *pPrior;
86067  if( p==0 ) return 0;
86068  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
86069  if( pNew==0 ) return 0;
86070  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
86071  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
86072  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
86073  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
86074  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
86075  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
86076  pNew->op = p->op;
86077  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
86078  if( pPrior ) pPrior->pNext = pNew;
86079  pNew->pNext = 0;
86080  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
86081  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
86082  pNew->iLimit = 0;
86083  pNew->iOffset = 0;
86084  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
86085  pNew->addrOpenEphm[0] = -1;
86086  pNew->addrOpenEphm[1] = -1;
86087  pNew->nSelectRow = p->nSelectRow;
86088  pNew->pWith = withDup(db, p->pWith);
86089  sqlite3SelectSetName(pNew, p->zSelName);
86090  return pNew;
86091}
86092#else
86093SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
86094  assert( p==0 );
86095  return 0;
86096}
86097#endif
86098
86099
86100/*
86101** Add a new element to the end of an expression list.  If pList is
86102** initially NULL, then create a new expression list.
86103**
86104** If a memory allocation error occurs, the entire list is freed and
86105** NULL is returned.  If non-NULL is returned, then it is guaranteed
86106** that the new entry was successfully appended.
86107*/
86108SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
86109  Parse *pParse,          /* Parsing context */
86110  ExprList *pList,        /* List to which to append. Might be NULL */
86111  Expr *pExpr             /* Expression to be appended. Might be NULL */
86112){
86113  sqlite3 *db = pParse->db;
86114  if( pList==0 ){
86115    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
86116    if( pList==0 ){
86117      goto no_mem;
86118    }
86119    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
86120    if( pList->a==0 ) goto no_mem;
86121  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
86122    struct ExprList_item *a;
86123    assert( pList->nExpr>0 );
86124    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
86125    if( a==0 ){
86126      goto no_mem;
86127    }
86128    pList->a = a;
86129  }
86130  assert( pList->a!=0 );
86131  if( 1 ){
86132    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
86133    memset(pItem, 0, sizeof(*pItem));
86134    pItem->pExpr = pExpr;
86135  }
86136  return pList;
86137
86138no_mem:
86139  /* Avoid leaking memory if malloc has failed. */
86140  sqlite3ExprDelete(db, pExpr);
86141  sqlite3ExprListDelete(db, pList);
86142  return 0;
86143}
86144
86145/*
86146** Set the sort order for the last element on the given ExprList.
86147*/
86148SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
86149  if( p==0 ) return;
86150  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
86151  assert( p->nExpr>0 );
86152  if( iSortOrder<0 ){
86153    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
86154    return;
86155  }
86156  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
86157}
86158
86159/*
86160** Set the ExprList.a[].zName element of the most recently added item
86161** on the expression list.
86162**
86163** pList might be NULL following an OOM error.  But pName should never be
86164** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
86165** is set.
86166*/
86167SQLITE_PRIVATE void sqlite3ExprListSetName(
86168  Parse *pParse,          /* Parsing context */
86169  ExprList *pList,        /* List to which to add the span. */
86170  Token *pName,           /* Name to be added */
86171  int dequote             /* True to cause the name to be dequoted */
86172){
86173  assert( pList!=0 || pParse->db->mallocFailed!=0 );
86174  if( pList ){
86175    struct ExprList_item *pItem;
86176    assert( pList->nExpr>0 );
86177    pItem = &pList->a[pList->nExpr-1];
86178    assert( pItem->zName==0 );
86179    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
86180    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
86181  }
86182}
86183
86184/*
86185** Set the ExprList.a[].zSpan element of the most recently added item
86186** on the expression list.
86187**
86188** pList might be NULL following an OOM error.  But pSpan should never be
86189** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
86190** is set.
86191*/
86192SQLITE_PRIVATE void sqlite3ExprListSetSpan(
86193  Parse *pParse,          /* Parsing context */
86194  ExprList *pList,        /* List to which to add the span. */
86195  ExprSpan *pSpan         /* The span to be added */
86196){
86197  sqlite3 *db = pParse->db;
86198  assert( pList!=0 || db->mallocFailed!=0 );
86199  if( pList ){
86200    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
86201    assert( pList->nExpr>0 );
86202    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
86203    sqlite3DbFree(db, pItem->zSpan);
86204    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
86205                                    (int)(pSpan->zEnd - pSpan->zStart));
86206  }
86207}
86208
86209/*
86210** If the expression list pEList contains more than iLimit elements,
86211** leave an error message in pParse.
86212*/
86213SQLITE_PRIVATE void sqlite3ExprListCheckLength(
86214  Parse *pParse,
86215  ExprList *pEList,
86216  const char *zObject
86217){
86218  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
86219  testcase( pEList && pEList->nExpr==mx );
86220  testcase( pEList && pEList->nExpr==mx+1 );
86221  if( pEList && pEList->nExpr>mx ){
86222    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
86223  }
86224}
86225
86226/*
86227** Delete an entire expression list.
86228*/
86229SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
86230  int i;
86231  struct ExprList_item *pItem;
86232  if( pList==0 ) return;
86233  assert( pList->a!=0 || pList->nExpr==0 );
86234  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
86235    sqlite3ExprDelete(db, pItem->pExpr);
86236    sqlite3DbFree(db, pItem->zName);
86237    sqlite3DbFree(db, pItem->zSpan);
86238  }
86239  sqlite3DbFree(db, pList->a);
86240  sqlite3DbFree(db, pList);
86241}
86242
86243/*
86244** Return the bitwise-OR of all Expr.flags fields in the given
86245** ExprList.
86246*/
86247SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
86248  int i;
86249  u32 m = 0;
86250  if( pList ){
86251    for(i=0; i<pList->nExpr; i++){
86252       Expr *pExpr = pList->a[i].pExpr;
86253       if( ALWAYS(pExpr) ) m |= pExpr->flags;
86254    }
86255  }
86256  return m;
86257}
86258
86259/*
86260** These routines are Walker callbacks used to check expressions to
86261** see if they are "constant" for some definition of constant.  The
86262** Walker.eCode value determines the type of "constant" we are looking
86263** for.
86264**
86265** These callback routines are used to implement the following:
86266**
86267**     sqlite3ExprIsConstant()                  pWalker->eCode==1
86268**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
86269**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
86270**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
86271**
86272** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
86273** is found to not be a constant.
86274**
86275** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
86276** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
86277** an existing schema and 4 when processing a new statement.  A bound
86278** parameter raises an error for new statements, but is silently converted
86279** to NULL for existing schemas.  This allows sqlite_master tables that
86280** contain a bound parameter because they were generated by older versions
86281** of SQLite to be parsed by newer versions of SQLite without raising a
86282** malformed schema error.
86283*/
86284static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
86285
86286  /* If pWalker->eCode is 2 then any term of the expression that comes from
86287  ** the ON or USING clauses of a left join disqualifies the expression
86288  ** from being considered constant. */
86289  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
86290    pWalker->eCode = 0;
86291    return WRC_Abort;
86292  }
86293
86294  switch( pExpr->op ){
86295    /* Consider functions to be constant if all their arguments are constant
86296    ** and either pWalker->eCode==4 or 5 or the function has the
86297    ** SQLITE_FUNC_CONST flag. */
86298    case TK_FUNCTION:
86299      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
86300        return WRC_Continue;
86301      }else{
86302        pWalker->eCode = 0;
86303        return WRC_Abort;
86304      }
86305    case TK_ID:
86306    case TK_COLUMN:
86307    case TK_AGG_FUNCTION:
86308    case TK_AGG_COLUMN:
86309      testcase( pExpr->op==TK_ID );
86310      testcase( pExpr->op==TK_COLUMN );
86311      testcase( pExpr->op==TK_AGG_FUNCTION );
86312      testcase( pExpr->op==TK_AGG_COLUMN );
86313      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
86314        return WRC_Continue;
86315      }else{
86316        pWalker->eCode = 0;
86317        return WRC_Abort;
86318      }
86319    case TK_VARIABLE:
86320      if( pWalker->eCode==5 ){
86321        /* Silently convert bound parameters that appear inside of CREATE
86322        ** statements into a NULL when parsing the CREATE statement text out
86323        ** of the sqlite_master table */
86324        pExpr->op = TK_NULL;
86325      }else if( pWalker->eCode==4 ){
86326        /* A bound parameter in a CREATE statement that originates from
86327        ** sqlite3_prepare() causes an error */
86328        pWalker->eCode = 0;
86329        return WRC_Abort;
86330      }
86331      /* Fall through */
86332    default:
86333      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
86334      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
86335      return WRC_Continue;
86336  }
86337}
86338static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
86339  UNUSED_PARAMETER(NotUsed);
86340  pWalker->eCode = 0;
86341  return WRC_Abort;
86342}
86343static int exprIsConst(Expr *p, int initFlag, int iCur){
86344  Walker w;
86345  memset(&w, 0, sizeof(w));
86346  w.eCode = initFlag;
86347  w.xExprCallback = exprNodeIsConstant;
86348  w.xSelectCallback = selectNodeIsConstant;
86349  w.u.iCur = iCur;
86350  sqlite3WalkExpr(&w, p);
86351  return w.eCode;
86352}
86353
86354/*
86355** Walk an expression tree.  Return non-zero if the expression is constant
86356** and 0 if it involves variables or function calls.
86357**
86358** For the purposes of this function, a double-quoted string (ex: "abc")
86359** is considered a variable but a single-quoted string (ex: 'abc') is
86360** a constant.
86361*/
86362SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
86363  return exprIsConst(p, 1, 0);
86364}
86365
86366/*
86367** Walk an expression tree.  Return non-zero if the expression is constant
86368** that does no originate from the ON or USING clauses of a join.
86369** Return 0 if it involves variables or function calls or terms from
86370** an ON or USING clause.
86371*/
86372SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
86373  return exprIsConst(p, 2, 0);
86374}
86375
86376/*
86377** Walk an expression tree.  Return non-zero if the expression is constant
86378** for any single row of the table with cursor iCur.  In other words, the
86379** expression must not refer to any non-deterministic function nor any
86380** table other than iCur.
86381*/
86382SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
86383  return exprIsConst(p, 3, iCur);
86384}
86385
86386/*
86387** Walk an expression tree.  Return non-zero if the expression is constant
86388** or a function call with constant arguments.  Return and 0 if there
86389** are any variables.
86390**
86391** For the purposes of this function, a double-quoted string (ex: "abc")
86392** is considered a variable but a single-quoted string (ex: 'abc') is
86393** a constant.
86394*/
86395SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
86396  assert( isInit==0 || isInit==1 );
86397  return exprIsConst(p, 4+isInit, 0);
86398}
86399
86400/*
86401** If the expression p codes a constant integer that is small enough
86402** to fit in a 32-bit integer, return 1 and put the value of the integer
86403** in *pValue.  If the expression is not an integer or if it is too big
86404** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
86405*/
86406SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
86407  int rc = 0;
86408
86409  /* If an expression is an integer literal that fits in a signed 32-bit
86410  ** integer, then the EP_IntValue flag will have already been set */
86411  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
86412           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
86413
86414  if( p->flags & EP_IntValue ){
86415    *pValue = p->u.iValue;
86416    return 1;
86417  }
86418  switch( p->op ){
86419    case TK_UPLUS: {
86420      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
86421      break;
86422    }
86423    case TK_UMINUS: {
86424      int v;
86425      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
86426        assert( v!=(-2147483647-1) );
86427        *pValue = -v;
86428        rc = 1;
86429      }
86430      break;
86431    }
86432    default: break;
86433  }
86434  return rc;
86435}
86436
86437/*
86438** Return FALSE if there is no chance that the expression can be NULL.
86439**
86440** If the expression might be NULL or if the expression is too complex
86441** to tell return TRUE.
86442**
86443** This routine is used as an optimization, to skip OP_IsNull opcodes
86444** when we know that a value cannot be NULL.  Hence, a false positive
86445** (returning TRUE when in fact the expression can never be NULL) might
86446** be a small performance hit but is otherwise harmless.  On the other
86447** hand, a false negative (returning FALSE when the result could be NULL)
86448** will likely result in an incorrect answer.  So when in doubt, return
86449** TRUE.
86450*/
86451SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
86452  u8 op;
86453  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
86454  op = p->op;
86455  if( op==TK_REGISTER ) op = p->op2;
86456  switch( op ){
86457    case TK_INTEGER:
86458    case TK_STRING:
86459    case TK_FLOAT:
86460    case TK_BLOB:
86461      return 0;
86462    case TK_COLUMN:
86463      assert( p->pTab!=0 );
86464      return ExprHasProperty(p, EP_CanBeNull) ||
86465             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
86466    default:
86467      return 1;
86468  }
86469}
86470
86471/*
86472** Return TRUE if the given expression is a constant which would be
86473** unchanged by OP_Affinity with the affinity given in the second
86474** argument.
86475**
86476** This routine is used to determine if the OP_Affinity operation
86477** can be omitted.  When in doubt return FALSE.  A false negative
86478** is harmless.  A false positive, however, can result in the wrong
86479** answer.
86480*/
86481SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
86482  u8 op;
86483  if( aff==SQLITE_AFF_BLOB ) return 1;
86484  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
86485  op = p->op;
86486  if( op==TK_REGISTER ) op = p->op2;
86487  switch( op ){
86488    case TK_INTEGER: {
86489      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
86490    }
86491    case TK_FLOAT: {
86492      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
86493    }
86494    case TK_STRING: {
86495      return aff==SQLITE_AFF_TEXT;
86496    }
86497    case TK_BLOB: {
86498      return 1;
86499    }
86500    case TK_COLUMN: {
86501      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
86502      return p->iColumn<0
86503          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
86504    }
86505    default: {
86506      return 0;
86507    }
86508  }
86509}
86510
86511/*
86512** Return TRUE if the given string is a row-id column name.
86513*/
86514SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
86515  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
86516  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
86517  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
86518  return 0;
86519}
86520
86521/*
86522** Return true if we are able to the IN operator optimization on a
86523** query of the form
86524**
86525**       x IN (SELECT ...)
86526**
86527** Where the SELECT... clause is as specified by the parameter to this
86528** routine.
86529**
86530** The Select object passed in has already been preprocessed and no
86531** errors have been found.
86532*/
86533#ifndef SQLITE_OMIT_SUBQUERY
86534static int isCandidateForInOpt(Select *p){
86535  SrcList *pSrc;
86536  ExprList *pEList;
86537  Table *pTab;
86538  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
86539  if( p->pPrior ) return 0;              /* Not a compound SELECT */
86540  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
86541    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
86542    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
86543    return 0; /* No DISTINCT keyword and no aggregate functions */
86544  }
86545  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
86546  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
86547  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
86548  if( p->pWhere ) return 0;              /* Has no WHERE clause */
86549  pSrc = p->pSrc;
86550  assert( pSrc!=0 );
86551  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
86552  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
86553  pTab = pSrc->a[0].pTab;
86554  if( NEVER(pTab==0) ) return 0;
86555  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
86556  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
86557  pEList = p->pEList;
86558  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
86559  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
86560  return 1;
86561}
86562#endif /* SQLITE_OMIT_SUBQUERY */
86563
86564/*
86565** Code an OP_Once instruction and allocate space for its flag. Return the
86566** address of the new instruction.
86567*/
86568SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
86569  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
86570  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
86571}
86572
86573/*
86574** Generate code that checks the left-most column of index table iCur to see if
86575** it contains any NULL entries.  Cause the register at regHasNull to be set
86576** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
86577** to be set to NULL if iCur contains one or more NULL values.
86578*/
86579static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
86580  int addr1;
86581  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
86582  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
86583  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
86584  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
86585  VdbeComment((v, "first_entry_in(%d)", iCur));
86586  sqlite3VdbeJumpHere(v, addr1);
86587}
86588
86589
86590#ifndef SQLITE_OMIT_SUBQUERY
86591/*
86592** The argument is an IN operator with a list (not a subquery) on the
86593** right-hand side.  Return TRUE if that list is constant.
86594*/
86595static int sqlite3InRhsIsConstant(Expr *pIn){
86596  Expr *pLHS;
86597  int res;
86598  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
86599  pLHS = pIn->pLeft;
86600  pIn->pLeft = 0;
86601  res = sqlite3ExprIsConstant(pIn);
86602  pIn->pLeft = pLHS;
86603  return res;
86604}
86605#endif
86606
86607/*
86608** This function is used by the implementation of the IN (...) operator.
86609** The pX parameter is the expression on the RHS of the IN operator, which
86610** might be either a list of expressions or a subquery.
86611**
86612** The job of this routine is to find or create a b-tree object that can
86613** be used either to test for membership in the RHS set or to iterate through
86614** all members of the RHS set, skipping duplicates.
86615**
86616** A cursor is opened on the b-tree object that is the RHS of the IN operator
86617** and pX->iTable is set to the index of that cursor.
86618**
86619** The returned value of this function indicates the b-tree type, as follows:
86620**
86621**   IN_INDEX_ROWID      - The cursor was opened on a database table.
86622**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
86623**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
86624**   IN_INDEX_EPH        - The cursor was opened on a specially created and
86625**                         populated epheremal table.
86626**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
86627**                         implemented as a sequence of comparisons.
86628**
86629** An existing b-tree might be used if the RHS expression pX is a simple
86630** subquery such as:
86631**
86632**     SELECT <column> FROM <table>
86633**
86634** If the RHS of the IN operator is a list or a more complex subquery, then
86635** an ephemeral table might need to be generated from the RHS and then
86636** pX->iTable made to point to the ephemeral table instead of an
86637** existing table.
86638**
86639** The inFlags parameter must contain exactly one of the bits
86640** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
86641** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
86642** fast membership test.  When the IN_INDEX_LOOP bit is set, the
86643** IN index will be used to loop over all values of the RHS of the
86644** IN operator.
86645**
86646** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
86647** through the set members) then the b-tree must not contain duplicates.
86648** An epheremal table must be used unless the selected <column> is guaranteed
86649** to be unique - either because it is an INTEGER PRIMARY KEY or it
86650** has a UNIQUE constraint or UNIQUE index.
86651**
86652** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
86653** for fast set membership tests) then an epheremal table must
86654** be used unless <column> is an INTEGER PRIMARY KEY or an index can
86655** be found with <column> as its left-most column.
86656**
86657** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
86658** if the RHS of the IN operator is a list (not a subquery) then this
86659** routine might decide that creating an ephemeral b-tree for membership
86660** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
86661** calling routine should implement the IN operator using a sequence
86662** of Eq or Ne comparison operations.
86663**
86664** When the b-tree is being used for membership tests, the calling function
86665** might need to know whether or not the RHS side of the IN operator
86666** contains a NULL.  If prRhsHasNull is not a NULL pointer and
86667** if there is any chance that the (...) might contain a NULL value at
86668** runtime, then a register is allocated and the register number written
86669** to *prRhsHasNull. If there is no chance that the (...) contains a
86670** NULL value, then *prRhsHasNull is left unchanged.
86671**
86672** If a register is allocated and its location stored in *prRhsHasNull, then
86673** the value in that register will be NULL if the b-tree contains one or more
86674** NULL values, and it will be some non-NULL value if the b-tree contains no
86675** NULL values.
86676*/
86677#ifndef SQLITE_OMIT_SUBQUERY
86678SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
86679  Select *p;                            /* SELECT to the right of IN operator */
86680  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
86681  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
86682  int mustBeUnique;                     /* True if RHS must be unique */
86683  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
86684
86685  assert( pX->op==TK_IN );
86686  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
86687
86688  /* Check to see if an existing table or index can be used to
86689  ** satisfy the query.  This is preferable to generating a new
86690  ** ephemeral table.
86691  */
86692  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
86693  if( pParse->nErr==0 && isCandidateForInOpt(p) ){
86694    sqlite3 *db = pParse->db;              /* Database connection */
86695    Table *pTab;                           /* Table <table>. */
86696    Expr *pExpr;                           /* Expression <column> */
86697    i16 iCol;                              /* Index of column <column> */
86698    i16 iDb;                               /* Database idx for pTab */
86699
86700    assert( p );                        /* Because of isCandidateForInOpt(p) */
86701    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
86702    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
86703    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
86704    pTab = p->pSrc->a[0].pTab;
86705    pExpr = p->pEList->a[0].pExpr;
86706    iCol = (i16)pExpr->iColumn;
86707
86708    /* Code an OP_Transaction and OP_TableLock for <table>. */
86709    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86710    sqlite3CodeVerifySchema(pParse, iDb);
86711    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
86712
86713    /* This function is only called from two places. In both cases the vdbe
86714    ** has already been allocated. So assume sqlite3GetVdbe() is always
86715    ** successful here.
86716    */
86717    assert(v);
86718    if( iCol<0 ){
86719      int iAddr = sqlite3CodeOnce(pParse);
86720      VdbeCoverage(v);
86721
86722      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
86723      eType = IN_INDEX_ROWID;
86724
86725      sqlite3VdbeJumpHere(v, iAddr);
86726    }else{
86727      Index *pIdx;                         /* Iterator variable */
86728
86729      /* The collation sequence used by the comparison. If an index is to
86730      ** be used in place of a temp-table, it must be ordered according
86731      ** to this collation sequence.  */
86732      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
86733
86734      /* Check that the affinity that will be used to perform the
86735      ** comparison is the same as the affinity of the column. If
86736      ** it is not, it is not possible to use any index.
86737      */
86738      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
86739
86740      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
86741        if( (pIdx->aiColumn[0]==iCol)
86742         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
86743         && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
86744        ){
86745          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
86746          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
86747          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
86748          VdbeComment((v, "%s", pIdx->zName));
86749          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
86750          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
86751
86752          if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
86753            *prRhsHasNull = ++pParse->nMem;
86754            sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
86755          }
86756          sqlite3VdbeJumpHere(v, iAddr);
86757        }
86758      }
86759    }
86760  }
86761
86762  /* If no preexisting index is available for the IN clause
86763  ** and IN_INDEX_NOOP is an allowed reply
86764  ** and the RHS of the IN operator is a list, not a subquery
86765  ** and the RHS is not contant or has two or fewer terms,
86766  ** then it is not worth creating an ephemeral table to evaluate
86767  ** the IN operator so return IN_INDEX_NOOP.
86768  */
86769  if( eType==0
86770   && (inFlags & IN_INDEX_NOOP_OK)
86771   && !ExprHasProperty(pX, EP_xIsSelect)
86772   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
86773  ){
86774    eType = IN_INDEX_NOOP;
86775  }
86776
86777
86778  if( eType==0 ){
86779    /* Could not find an existing table or index to use as the RHS b-tree.
86780    ** We will have to generate an ephemeral table to do the job.
86781    */
86782    u32 savedNQueryLoop = pParse->nQueryLoop;
86783    int rMayHaveNull = 0;
86784    eType = IN_INDEX_EPH;
86785    if( inFlags & IN_INDEX_LOOP ){
86786      pParse->nQueryLoop = 0;
86787      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
86788        eType = IN_INDEX_ROWID;
86789      }
86790    }else if( prRhsHasNull ){
86791      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
86792    }
86793    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
86794    pParse->nQueryLoop = savedNQueryLoop;
86795  }else{
86796    pX->iTable = iTab;
86797  }
86798  return eType;
86799}
86800#endif
86801
86802/*
86803** Generate code for scalar subqueries used as a subquery expression, EXISTS,
86804** or IN operators.  Examples:
86805**
86806**     (SELECT a FROM b)          -- subquery
86807**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
86808**     x IN (4,5,11)              -- IN operator with list on right-hand side
86809**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
86810**
86811** The pExpr parameter describes the expression that contains the IN
86812** operator or subquery.
86813**
86814** If parameter isRowid is non-zero, then expression pExpr is guaranteed
86815** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
86816** to some integer key column of a table B-Tree. In this case, use an
86817** intkey B-Tree to store the set of IN(...) values instead of the usual
86818** (slower) variable length keys B-Tree.
86819**
86820** If rMayHaveNull is non-zero, that means that the operation is an IN
86821** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
86822** All this routine does is initialize the register given by rMayHaveNull
86823** to NULL.  Calling routines will take care of changing this register
86824** value to non-NULL if the RHS is NULL-free.
86825**
86826** For a SELECT or EXISTS operator, return the register that holds the
86827** result.  For IN operators or if an error occurs, the return value is 0.
86828*/
86829#ifndef SQLITE_OMIT_SUBQUERY
86830SQLITE_PRIVATE int sqlite3CodeSubselect(
86831  Parse *pParse,          /* Parsing context */
86832  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
86833  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
86834  int isRowid             /* If true, LHS of IN operator is a rowid */
86835){
86836  int jmpIfDynamic = -1;                      /* One-time test address */
86837  int rReg = 0;                           /* Register storing resulting */
86838  Vdbe *v = sqlite3GetVdbe(pParse);
86839  if( NEVER(v==0) ) return 0;
86840  sqlite3ExprCachePush(pParse);
86841
86842  /* This code must be run in its entirety every time it is encountered
86843  ** if any of the following is true:
86844  **
86845  **    *  The right-hand side is a correlated subquery
86846  **    *  The right-hand side is an expression list containing variables
86847  **    *  We are inside a trigger
86848  **
86849  ** If all of the above are false, then we can run this code just once
86850  ** save the results, and reuse the same result on subsequent invocations.
86851  */
86852  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
86853    jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
86854  }
86855
86856#ifndef SQLITE_OMIT_EXPLAIN
86857  if( pParse->explain==2 ){
86858    char *zMsg = sqlite3MPrintf(
86859        pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
86860        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
86861    );
86862    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
86863  }
86864#endif
86865
86866  switch( pExpr->op ){
86867    case TK_IN: {
86868      char affinity;              /* Affinity of the LHS of the IN */
86869      int addr;                   /* Address of OP_OpenEphemeral instruction */
86870      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
86871      KeyInfo *pKeyInfo = 0;      /* Key information */
86872
86873      affinity = sqlite3ExprAffinity(pLeft);
86874
86875      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
86876      ** expression it is handled the same way.  An ephemeral table is
86877      ** filled with single-field index keys representing the results
86878      ** from the SELECT or the <exprlist>.
86879      **
86880      ** If the 'x' expression is a column value, or the SELECT...
86881      ** statement returns a column value, then the affinity of that
86882      ** column is used to build the index keys. If both 'x' and the
86883      ** SELECT... statement are columns, then numeric affinity is used
86884      ** if either column has NUMERIC or INTEGER affinity. If neither
86885      ** 'x' nor the SELECT... statement are columns, then numeric affinity
86886      ** is used.
86887      */
86888      pExpr->iTable = pParse->nTab++;
86889      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
86890      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
86891
86892      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
86893        /* Case 1:     expr IN (SELECT ...)
86894        **
86895        ** Generate code to write the results of the select into the temporary
86896        ** table allocated and opened above.
86897        */
86898        Select *pSelect = pExpr->x.pSelect;
86899        SelectDest dest;
86900        ExprList *pEList;
86901
86902        assert( !isRowid );
86903        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
86904        dest.affSdst = (u8)affinity;
86905        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
86906        pSelect->iLimit = 0;
86907        testcase( pSelect->selFlags & SF_Distinct );
86908        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
86909        if( sqlite3Select(pParse, pSelect, &dest) ){
86910          sqlite3KeyInfoUnref(pKeyInfo);
86911          return 0;
86912        }
86913        pEList = pSelect->pEList;
86914        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
86915        assert( pEList!=0 );
86916        assert( pEList->nExpr>0 );
86917        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
86918        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
86919                                                         pEList->a[0].pExpr);
86920      }else if( ALWAYS(pExpr->x.pList!=0) ){
86921        /* Case 2:     expr IN (exprlist)
86922        **
86923        ** For each expression, build an index key from the evaluation and
86924        ** store it in the temporary table. If <expr> is a column, then use
86925        ** that columns affinity when building index keys. If <expr> is not
86926        ** a column, use numeric affinity.
86927        */
86928        int i;
86929        ExprList *pList = pExpr->x.pList;
86930        struct ExprList_item *pItem;
86931        int r1, r2, r3;
86932
86933        if( !affinity ){
86934          affinity = SQLITE_AFF_BLOB;
86935        }
86936        if( pKeyInfo ){
86937          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
86938          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
86939        }
86940
86941        /* Loop through each expression in <exprlist>. */
86942        r1 = sqlite3GetTempReg(pParse);
86943        r2 = sqlite3GetTempReg(pParse);
86944        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
86945        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
86946          Expr *pE2 = pItem->pExpr;
86947          int iValToIns;
86948
86949          /* If the expression is not constant then we will need to
86950          ** disable the test that was generated above that makes sure
86951          ** this code only executes once.  Because for a non-constant
86952          ** expression we need to rerun this code each time.
86953          */
86954          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
86955            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
86956            jmpIfDynamic = -1;
86957          }
86958
86959          /* Evaluate the expression and insert it into the temp table */
86960          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
86961            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
86962          }else{
86963            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
86964            if( isRowid ){
86965              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
86966                                sqlite3VdbeCurrentAddr(v)+2);
86967              VdbeCoverage(v);
86968              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
86969            }else{
86970              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
86971              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
86972              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
86973            }
86974          }
86975        }
86976        sqlite3ReleaseTempReg(pParse, r1);
86977        sqlite3ReleaseTempReg(pParse, r2);
86978      }
86979      if( pKeyInfo ){
86980        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
86981      }
86982      break;
86983    }
86984
86985    case TK_EXISTS:
86986    case TK_SELECT:
86987    default: {
86988      /* If this has to be a scalar SELECT.  Generate code to put the
86989      ** value of this select in a memory cell and record the number
86990      ** of the memory cell in iColumn.  If this is an EXISTS, write
86991      ** an integer 0 (not exists) or 1 (exists) into a memory cell
86992      ** and record that memory cell in iColumn.
86993      */
86994      Select *pSel;                         /* SELECT statement to encode */
86995      SelectDest dest;                      /* How to deal with SELECt result */
86996
86997      testcase( pExpr->op==TK_EXISTS );
86998      testcase( pExpr->op==TK_SELECT );
86999      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
87000
87001      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
87002      pSel = pExpr->x.pSelect;
87003      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
87004      if( pExpr->op==TK_SELECT ){
87005        dest.eDest = SRT_Mem;
87006        dest.iSdst = dest.iSDParm;
87007        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
87008        VdbeComment((v, "Init subquery result"));
87009      }else{
87010        dest.eDest = SRT_Exists;
87011        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
87012        VdbeComment((v, "Init EXISTS result"));
87013      }
87014      sqlite3ExprDelete(pParse->db, pSel->pLimit);
87015      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
87016                                  &sqlite3IntTokens[1]);
87017      pSel->iLimit = 0;
87018      pSel->selFlags &= ~SF_MultiValue;
87019      if( sqlite3Select(pParse, pSel, &dest) ){
87020        return 0;
87021      }
87022      rReg = dest.iSDParm;
87023      ExprSetVVAProperty(pExpr, EP_NoReduce);
87024      break;
87025    }
87026  }
87027
87028  if( rHasNullFlag ){
87029    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
87030  }
87031
87032  if( jmpIfDynamic>=0 ){
87033    sqlite3VdbeJumpHere(v, jmpIfDynamic);
87034  }
87035  sqlite3ExprCachePop(pParse);
87036
87037  return rReg;
87038}
87039#endif /* SQLITE_OMIT_SUBQUERY */
87040
87041#ifndef SQLITE_OMIT_SUBQUERY
87042/*
87043** Generate code for an IN expression.
87044**
87045**      x IN (SELECT ...)
87046**      x IN (value, value, ...)
87047**
87048** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
87049** is an array of zero or more values.  The expression is true if the LHS is
87050** contained within the RHS.  The value of the expression is unknown (NULL)
87051** if the LHS is NULL or if the LHS is not contained within the RHS and the
87052** RHS contains one or more NULL values.
87053**
87054** This routine generates code that jumps to destIfFalse if the LHS is not
87055** contained within the RHS.  If due to NULLs we cannot determine if the LHS
87056** is contained in the RHS then jump to destIfNull.  If the LHS is contained
87057** within the RHS then fall through.
87058*/
87059static void sqlite3ExprCodeIN(
87060  Parse *pParse,        /* Parsing and code generating context */
87061  Expr *pExpr,          /* The IN expression */
87062  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
87063  int destIfNull        /* Jump here if the results are unknown due to NULLs */
87064){
87065  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
87066  char affinity;        /* Comparison affinity to use */
87067  int eType;            /* Type of the RHS */
87068  int r1;               /* Temporary use register */
87069  Vdbe *v;              /* Statement under construction */
87070
87071  /* Compute the RHS.   After this step, the table with cursor
87072  ** pExpr->iTable will contains the values that make up the RHS.
87073  */
87074  v = pParse->pVdbe;
87075  assert( v!=0 );       /* OOM detected prior to this routine */
87076  VdbeNoopComment((v, "begin IN expr"));
87077  eType = sqlite3FindInIndex(pParse, pExpr,
87078                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
87079                             destIfFalse==destIfNull ? 0 : &rRhsHasNull);
87080
87081  /* Figure out the affinity to use to create a key from the results
87082  ** of the expression. affinityStr stores a static string suitable for
87083  ** P4 of OP_MakeRecord.
87084  */
87085  affinity = comparisonAffinity(pExpr);
87086
87087  /* Code the LHS, the <expr> from "<expr> IN (...)".
87088  */
87089  sqlite3ExprCachePush(pParse);
87090  r1 = sqlite3GetTempReg(pParse);
87091  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
87092
87093  /* If sqlite3FindInIndex() did not find or create an index that is
87094  ** suitable for evaluating the IN operator, then evaluate using a
87095  ** sequence of comparisons.
87096  */
87097  if( eType==IN_INDEX_NOOP ){
87098    ExprList *pList = pExpr->x.pList;
87099    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87100    int labelOk = sqlite3VdbeMakeLabel(v);
87101    int r2, regToFree;
87102    int regCkNull = 0;
87103    int ii;
87104    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87105    if( destIfNull!=destIfFalse ){
87106      regCkNull = sqlite3GetTempReg(pParse);
87107      sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
87108    }
87109    for(ii=0; ii<pList->nExpr; ii++){
87110      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
87111      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
87112        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
87113      }
87114      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
87115        sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
87116                          (void*)pColl, P4_COLLSEQ);
87117        VdbeCoverageIf(v, ii<pList->nExpr-1);
87118        VdbeCoverageIf(v, ii==pList->nExpr-1);
87119        sqlite3VdbeChangeP5(v, affinity);
87120      }else{
87121        assert( destIfNull==destIfFalse );
87122        sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
87123                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
87124        sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
87125      }
87126      sqlite3ReleaseTempReg(pParse, regToFree);
87127    }
87128    if( regCkNull ){
87129      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
87130      sqlite3VdbeGoto(v, destIfFalse);
87131    }
87132    sqlite3VdbeResolveLabel(v, labelOk);
87133    sqlite3ReleaseTempReg(pParse, regCkNull);
87134  }else{
87135
87136    /* If the LHS is NULL, then the result is either false or NULL depending
87137    ** on whether the RHS is empty or not, respectively.
87138    */
87139    if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
87140      if( destIfNull==destIfFalse ){
87141        /* Shortcut for the common case where the false and NULL outcomes are
87142        ** the same. */
87143        sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
87144      }else{
87145        int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
87146        sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
87147        VdbeCoverage(v);
87148        sqlite3VdbeGoto(v, destIfNull);
87149        sqlite3VdbeJumpHere(v, addr1);
87150      }
87151    }
87152
87153    if( eType==IN_INDEX_ROWID ){
87154      /* In this case, the RHS is the ROWID of table b-tree
87155      */
87156      sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
87157      sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
87158      VdbeCoverage(v);
87159    }else{
87160      /* In this case, the RHS is an index b-tree.
87161      */
87162      sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
87163
87164      /* If the set membership test fails, then the result of the
87165      ** "x IN (...)" expression must be either 0 or NULL. If the set
87166      ** contains no NULL values, then the result is 0. If the set
87167      ** contains one or more NULL values, then the result of the
87168      ** expression is also NULL.
87169      */
87170      assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
87171      if( rRhsHasNull==0 ){
87172        /* This branch runs if it is known at compile time that the RHS
87173        ** cannot contain NULL values. This happens as the result
87174        ** of a "NOT NULL" constraint in the database schema.
87175        **
87176        ** Also run this branch if NULL is equivalent to FALSE
87177        ** for this particular IN operator.
87178        */
87179        sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
87180        VdbeCoverage(v);
87181      }else{
87182        /* In this branch, the RHS of the IN might contain a NULL and
87183        ** the presence of a NULL on the RHS makes a difference in the
87184        ** outcome.
87185        */
87186        int addr1;
87187
87188        /* First check to see if the LHS is contained in the RHS.  If so,
87189        ** then the answer is TRUE the presence of NULLs in the RHS does
87190        ** not matter.  If the LHS is not contained in the RHS, then the
87191        ** answer is NULL if the RHS contains NULLs and the answer is
87192        ** FALSE if the RHS is NULL-free.
87193        */
87194        addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
87195        VdbeCoverage(v);
87196        sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
87197        VdbeCoverage(v);
87198        sqlite3VdbeGoto(v, destIfFalse);
87199        sqlite3VdbeJumpHere(v, addr1);
87200      }
87201    }
87202  }
87203  sqlite3ReleaseTempReg(pParse, r1);
87204  sqlite3ExprCachePop(pParse);
87205  VdbeComment((v, "end IN expr"));
87206}
87207#endif /* SQLITE_OMIT_SUBQUERY */
87208
87209#ifndef SQLITE_OMIT_FLOATING_POINT
87210/*
87211** Generate an instruction that will put the floating point
87212** value described by z[0..n-1] into register iMem.
87213**
87214** The z[] string will probably not be zero-terminated.  But the
87215** z[n] character is guaranteed to be something that does not look
87216** like the continuation of the number.
87217*/
87218static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
87219  if( ALWAYS(z!=0) ){
87220    double value;
87221    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
87222    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
87223    if( negateFlag ) value = -value;
87224    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
87225  }
87226}
87227#endif
87228
87229
87230/*
87231** Generate an instruction that will put the integer describe by
87232** text z[0..n-1] into register iMem.
87233**
87234** Expr.u.zToken is always UTF8 and zero-terminated.
87235*/
87236static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
87237  Vdbe *v = pParse->pVdbe;
87238  if( pExpr->flags & EP_IntValue ){
87239    int i = pExpr->u.iValue;
87240    assert( i>=0 );
87241    if( negFlag ) i = -i;
87242    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
87243  }else{
87244    int c;
87245    i64 value;
87246    const char *z = pExpr->u.zToken;
87247    assert( z!=0 );
87248    c = sqlite3DecOrHexToI64(z, &value);
87249    if( c==0 || (c==2 && negFlag) ){
87250      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
87251      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
87252    }else{
87253#ifdef SQLITE_OMIT_FLOATING_POINT
87254      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
87255#else
87256#ifndef SQLITE_OMIT_HEX_INTEGER
87257      if( sqlite3_strnicmp(z,"0x",2)==0 ){
87258        sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
87259      }else
87260#endif
87261      {
87262        codeReal(v, z, negFlag, iMem);
87263      }
87264#endif
87265    }
87266  }
87267}
87268
87269/*
87270** Clear a cache entry.
87271*/
87272static void cacheEntryClear(Parse *pParse, struct yColCache *p){
87273  if( p->tempReg ){
87274    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
87275      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
87276    }
87277    p->tempReg = 0;
87278  }
87279}
87280
87281
87282/*
87283** Record in the column cache that a particular column from a
87284** particular table is stored in a particular register.
87285*/
87286SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
87287  int i;
87288  int minLru;
87289  int idxLru;
87290  struct yColCache *p;
87291
87292  /* Unless an error has occurred, register numbers are always positive. */
87293  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
87294  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
87295
87296  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
87297  ** for testing only - to verify that SQLite always gets the same answer
87298  ** with and without the column cache.
87299  */
87300  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
87301
87302  /* First replace any existing entry.
87303  **
87304  ** Actually, the way the column cache is currently used, we are guaranteed
87305  ** that the object will never already be in cache.  Verify this guarantee.
87306  */
87307#ifndef NDEBUG
87308  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87309    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
87310  }
87311#endif
87312
87313  /* Find an empty slot and replace it */
87314  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87315    if( p->iReg==0 ){
87316      p->iLevel = pParse->iCacheLevel;
87317      p->iTable = iTab;
87318      p->iColumn = iCol;
87319      p->iReg = iReg;
87320      p->tempReg = 0;
87321      p->lru = pParse->iCacheCnt++;
87322      return;
87323    }
87324  }
87325
87326  /* Replace the last recently used */
87327  minLru = 0x7fffffff;
87328  idxLru = -1;
87329  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87330    if( p->lru<minLru ){
87331      idxLru = i;
87332      minLru = p->lru;
87333    }
87334  }
87335  if( ALWAYS(idxLru>=0) ){
87336    p = &pParse->aColCache[idxLru];
87337    p->iLevel = pParse->iCacheLevel;
87338    p->iTable = iTab;
87339    p->iColumn = iCol;
87340    p->iReg = iReg;
87341    p->tempReg = 0;
87342    p->lru = pParse->iCacheCnt++;
87343    return;
87344  }
87345}
87346
87347/*
87348** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
87349** Purge the range of registers from the column cache.
87350*/
87351SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
87352  int i;
87353  int iLast = iReg + nReg - 1;
87354  struct yColCache *p;
87355  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87356    int r = p->iReg;
87357    if( r>=iReg && r<=iLast ){
87358      cacheEntryClear(pParse, p);
87359      p->iReg = 0;
87360    }
87361  }
87362}
87363
87364/*
87365** Remember the current column cache context.  Any new entries added
87366** added to the column cache after this call are removed when the
87367** corresponding pop occurs.
87368*/
87369SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
87370  pParse->iCacheLevel++;
87371#ifdef SQLITE_DEBUG
87372  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87373    printf("PUSH to %d\n", pParse->iCacheLevel);
87374  }
87375#endif
87376}
87377
87378/*
87379** Remove from the column cache any entries that were added since the
87380** the previous sqlite3ExprCachePush operation.  In other words, restore
87381** the cache to the state it was in prior the most recent Push.
87382*/
87383SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
87384  int i;
87385  struct yColCache *p;
87386  assert( pParse->iCacheLevel>=1 );
87387  pParse->iCacheLevel--;
87388#ifdef SQLITE_DEBUG
87389  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87390    printf("POP  to %d\n", pParse->iCacheLevel);
87391  }
87392#endif
87393  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87394    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
87395      cacheEntryClear(pParse, p);
87396      p->iReg = 0;
87397    }
87398  }
87399}
87400
87401/*
87402** When a cached column is reused, make sure that its register is
87403** no longer available as a temp register.  ticket #3879:  that same
87404** register might be in the cache in multiple places, so be sure to
87405** get them all.
87406*/
87407static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
87408  int i;
87409  struct yColCache *p;
87410  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87411    if( p->iReg==iReg ){
87412      p->tempReg = 0;
87413    }
87414  }
87415}
87416
87417/* Generate code that will load into register regOut a value that is
87418** appropriate for the iIdxCol-th column of index pIdx.
87419*/
87420SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
87421  Parse *pParse,  /* The parsing context */
87422  Index *pIdx,    /* The index whose column is to be loaded */
87423  int iTabCur,    /* Cursor pointing to a table row */
87424  int iIdxCol,    /* The column of the index to be loaded */
87425  int regOut      /* Store the index column value in this register */
87426){
87427  i16 iTabCol = pIdx->aiColumn[iIdxCol];
87428  if( iTabCol==XN_EXPR ){
87429    assert( pIdx->aColExpr );
87430    assert( pIdx->aColExpr->nExpr>iIdxCol );
87431    pParse->iSelfTab = iTabCur;
87432    sqlite3ExprCode(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
87433  }else{
87434    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
87435                                    iTabCol, regOut);
87436  }
87437}
87438
87439/*
87440** Generate code to extract the value of the iCol-th column of a table.
87441*/
87442SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
87443  Vdbe *v,        /* The VDBE under construction */
87444  Table *pTab,    /* The table containing the value */
87445  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
87446  int iCol,       /* Index of the column to extract */
87447  int regOut      /* Extract the value into this register */
87448){
87449  if( iCol<0 || iCol==pTab->iPKey ){
87450    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
87451  }else{
87452    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
87453    int x = iCol;
87454    if( !HasRowid(pTab) ){
87455      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
87456    }
87457    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
87458  }
87459  if( iCol>=0 ){
87460    sqlite3ColumnDefault(v, pTab, iCol, regOut);
87461  }
87462}
87463
87464/*
87465** Generate code that will extract the iColumn-th column from
87466** table pTab and store the column value in a register.  An effort
87467** is made to store the column value in register iReg, but this is
87468** not guaranteed.  The location of the column value is returned.
87469**
87470** There must be an open cursor to pTab in iTable when this routine
87471** is called.  If iColumn<0 then code is generated that extracts the rowid.
87472*/
87473SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
87474  Parse *pParse,   /* Parsing and code generating context */
87475  Table *pTab,     /* Description of the table we are reading from */
87476  int iColumn,     /* Index of the table column */
87477  int iTable,      /* The cursor pointing to the table */
87478  int iReg,        /* Store results here */
87479  u8 p5            /* P5 value for OP_Column */
87480){
87481  Vdbe *v = pParse->pVdbe;
87482  int i;
87483  struct yColCache *p;
87484
87485  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87486    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
87487      p->lru = pParse->iCacheCnt++;
87488      sqlite3ExprCachePinRegister(pParse, p->iReg);
87489      return p->iReg;
87490    }
87491  }
87492  assert( v!=0 );
87493  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
87494  if( p5 ){
87495    sqlite3VdbeChangeP5(v, p5);
87496  }else{
87497    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
87498  }
87499  return iReg;
87500}
87501
87502/*
87503** Clear all column cache entries.
87504*/
87505SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
87506  int i;
87507  struct yColCache *p;
87508
87509#if SQLITE_DEBUG
87510  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87511    printf("CLEAR\n");
87512  }
87513#endif
87514  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87515    if( p->iReg ){
87516      cacheEntryClear(pParse, p);
87517      p->iReg = 0;
87518    }
87519  }
87520}
87521
87522/*
87523** Record the fact that an affinity change has occurred on iCount
87524** registers starting with iStart.
87525*/
87526SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
87527  sqlite3ExprCacheRemove(pParse, iStart, iCount);
87528}
87529
87530/*
87531** Generate code to move content from registers iFrom...iFrom+nReg-1
87532** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
87533*/
87534SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
87535  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
87536  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
87537  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
87538}
87539
87540#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
87541/*
87542** Return true if any register in the range iFrom..iTo (inclusive)
87543** is used as part of the column cache.
87544**
87545** This routine is used within assert() and testcase() macros only
87546** and does not appear in a normal build.
87547*/
87548static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
87549  int i;
87550  struct yColCache *p;
87551  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87552    int r = p->iReg;
87553    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
87554  }
87555  return 0;
87556}
87557#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
87558
87559/*
87560** Convert an expression node to a TK_REGISTER
87561*/
87562static void exprToRegister(Expr *p, int iReg){
87563  p->op2 = p->op;
87564  p->op = TK_REGISTER;
87565  p->iTable = iReg;
87566  ExprClearProperty(p, EP_Skip);
87567}
87568
87569/*
87570** Generate code into the current Vdbe to evaluate the given
87571** expression.  Attempt to store the results in register "target".
87572** Return the register where results are stored.
87573**
87574** With this routine, there is no guarantee that results will
87575** be stored in target.  The result might be stored in some other
87576** register if it is convenient to do so.  The calling function
87577** must check the return code and move the results to the desired
87578** register.
87579*/
87580SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
87581  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
87582  int op;                   /* The opcode being coded */
87583  int inReg = target;       /* Results stored in register inReg */
87584  int regFree1 = 0;         /* If non-zero free this temporary register */
87585  int regFree2 = 0;         /* If non-zero free this temporary register */
87586  int r1, r2, r3, r4;       /* Various register numbers */
87587  sqlite3 *db = pParse->db; /* The database connection */
87588  Expr tempX;               /* Temporary expression node */
87589
87590  assert( target>0 && target<=pParse->nMem );
87591  if( v==0 ){
87592    assert( pParse->db->mallocFailed );
87593    return 0;
87594  }
87595
87596  if( pExpr==0 ){
87597    op = TK_NULL;
87598  }else{
87599    op = pExpr->op;
87600  }
87601  switch( op ){
87602    case TK_AGG_COLUMN: {
87603      AggInfo *pAggInfo = pExpr->pAggInfo;
87604      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
87605      if( !pAggInfo->directMode ){
87606        assert( pCol->iMem>0 );
87607        inReg = pCol->iMem;
87608        break;
87609      }else if( pAggInfo->useSortingIdx ){
87610        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
87611                              pCol->iSorterColumn, target);
87612        break;
87613      }
87614      /* Otherwise, fall thru into the TK_COLUMN case */
87615    }
87616    case TK_COLUMN: {
87617      int iTab = pExpr->iTable;
87618      if( iTab<0 ){
87619        if( pParse->ckBase>0 ){
87620          /* Generating CHECK constraints or inserting into partial index */
87621          inReg = pExpr->iColumn + pParse->ckBase;
87622          break;
87623        }else{
87624          /* Coding an expression that is part of an index where column names
87625          ** in the index refer to the table to which the index belongs */
87626          iTab = pParse->iSelfTab;
87627        }
87628      }
87629      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
87630                               pExpr->iColumn, iTab, target,
87631                               pExpr->op2);
87632      break;
87633    }
87634    case TK_INTEGER: {
87635      codeInteger(pParse, pExpr, 0, target);
87636      break;
87637    }
87638#ifndef SQLITE_OMIT_FLOATING_POINT
87639    case TK_FLOAT: {
87640      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87641      codeReal(v, pExpr->u.zToken, 0, target);
87642      break;
87643    }
87644#endif
87645    case TK_STRING: {
87646      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87647      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
87648      break;
87649    }
87650    case TK_NULL: {
87651      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
87652      break;
87653    }
87654#ifndef SQLITE_OMIT_BLOB_LITERAL
87655    case TK_BLOB: {
87656      int n;
87657      const char *z;
87658      char *zBlob;
87659      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87660      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
87661      assert( pExpr->u.zToken[1]=='\'' );
87662      z = &pExpr->u.zToken[2];
87663      n = sqlite3Strlen30(z) - 1;
87664      assert( z[n]=='\'' );
87665      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
87666      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
87667      break;
87668    }
87669#endif
87670    case TK_VARIABLE: {
87671      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87672      assert( pExpr->u.zToken!=0 );
87673      assert( pExpr->u.zToken[0]!=0 );
87674      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
87675      if( pExpr->u.zToken[1]!=0 ){
87676        assert( pExpr->u.zToken[0]=='?'
87677             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
87678        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
87679      }
87680      break;
87681    }
87682    case TK_REGISTER: {
87683      inReg = pExpr->iTable;
87684      break;
87685    }
87686#ifndef SQLITE_OMIT_CAST
87687    case TK_CAST: {
87688      /* Expressions of the form:   CAST(pLeft AS token) */
87689      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
87690      if( inReg!=target ){
87691        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
87692        inReg = target;
87693      }
87694      sqlite3VdbeAddOp2(v, OP_Cast, target,
87695                        sqlite3AffinityType(pExpr->u.zToken, 0));
87696      testcase( usedAsColumnCache(pParse, inReg, inReg) );
87697      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
87698      break;
87699    }
87700#endif /* SQLITE_OMIT_CAST */
87701    case TK_LT:
87702    case TK_LE:
87703    case TK_GT:
87704    case TK_GE:
87705    case TK_NE:
87706    case TK_EQ: {
87707      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87708      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87709      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
87710                  r1, r2, inReg, SQLITE_STOREP2);
87711      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
87712      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
87713      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
87714      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
87715      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
87716      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
87717      testcase( regFree1==0 );
87718      testcase( regFree2==0 );
87719      break;
87720    }
87721    case TK_IS:
87722    case TK_ISNOT: {
87723      testcase( op==TK_IS );
87724      testcase( op==TK_ISNOT );
87725      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87726      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87727      op = (op==TK_IS) ? TK_EQ : TK_NE;
87728      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
87729                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
87730      VdbeCoverageIf(v, op==TK_EQ);
87731      VdbeCoverageIf(v, op==TK_NE);
87732      testcase( regFree1==0 );
87733      testcase( regFree2==0 );
87734      break;
87735    }
87736    case TK_AND:
87737    case TK_OR:
87738    case TK_PLUS:
87739    case TK_STAR:
87740    case TK_MINUS:
87741    case TK_REM:
87742    case TK_BITAND:
87743    case TK_BITOR:
87744    case TK_SLASH:
87745    case TK_LSHIFT:
87746    case TK_RSHIFT:
87747    case TK_CONCAT: {
87748      assert( TK_AND==OP_And );            testcase( op==TK_AND );
87749      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
87750      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
87751      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
87752      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
87753      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
87754      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
87755      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
87756      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
87757      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
87758      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
87759      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87760      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87761      sqlite3VdbeAddOp3(v, op, r2, r1, target);
87762      testcase( regFree1==0 );
87763      testcase( regFree2==0 );
87764      break;
87765    }
87766    case TK_UMINUS: {
87767      Expr *pLeft = pExpr->pLeft;
87768      assert( pLeft );
87769      if( pLeft->op==TK_INTEGER ){
87770        codeInteger(pParse, pLeft, 1, target);
87771#ifndef SQLITE_OMIT_FLOATING_POINT
87772      }else if( pLeft->op==TK_FLOAT ){
87773        assert( !ExprHasProperty(pExpr, EP_IntValue) );
87774        codeReal(v, pLeft->u.zToken, 1, target);
87775#endif
87776      }else{
87777        tempX.op = TK_INTEGER;
87778        tempX.flags = EP_IntValue|EP_TokenOnly;
87779        tempX.u.iValue = 0;
87780        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
87781        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
87782        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
87783        testcase( regFree2==0 );
87784      }
87785      inReg = target;
87786      break;
87787    }
87788    case TK_BITNOT:
87789    case TK_NOT: {
87790      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
87791      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
87792      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87793      testcase( regFree1==0 );
87794      inReg = target;
87795      sqlite3VdbeAddOp2(v, op, r1, inReg);
87796      break;
87797    }
87798    case TK_ISNULL:
87799    case TK_NOTNULL: {
87800      int addr;
87801      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
87802      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
87803      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
87804      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87805      testcase( regFree1==0 );
87806      addr = sqlite3VdbeAddOp1(v, op, r1);
87807      VdbeCoverageIf(v, op==TK_ISNULL);
87808      VdbeCoverageIf(v, op==TK_NOTNULL);
87809      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
87810      sqlite3VdbeJumpHere(v, addr);
87811      break;
87812    }
87813    case TK_AGG_FUNCTION: {
87814      AggInfo *pInfo = pExpr->pAggInfo;
87815      if( pInfo==0 ){
87816        assert( !ExprHasProperty(pExpr, EP_IntValue) );
87817        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
87818      }else{
87819        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
87820      }
87821      break;
87822    }
87823    case TK_FUNCTION: {
87824      ExprList *pFarg;       /* List of function arguments */
87825      int nFarg;             /* Number of function arguments */
87826      FuncDef *pDef;         /* The function definition object */
87827      int nId;               /* Length of the function name in bytes */
87828      const char *zId;       /* The function name */
87829      u32 constMask = 0;     /* Mask of function arguments that are constant */
87830      int i;                 /* Loop counter */
87831      u8 enc = ENC(db);      /* The text encoding used by this database */
87832      CollSeq *pColl = 0;    /* A collating sequence */
87833
87834      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87835      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
87836        pFarg = 0;
87837      }else{
87838        pFarg = pExpr->x.pList;
87839      }
87840      nFarg = pFarg ? pFarg->nExpr : 0;
87841      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87842      zId = pExpr->u.zToken;
87843      nId = sqlite3Strlen30(zId);
87844      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
87845      if( pDef==0 || pDef->xFunc==0 ){
87846        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
87847        break;
87848      }
87849
87850      /* Attempt a direct implementation of the built-in COALESCE() and
87851      ** IFNULL() functions.  This avoids unnecessary evaluation of
87852      ** arguments past the first non-NULL argument.
87853      */
87854      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
87855        int endCoalesce = sqlite3VdbeMakeLabel(v);
87856        assert( nFarg>=2 );
87857        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
87858        for(i=1; i<nFarg; i++){
87859          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
87860          VdbeCoverage(v);
87861          sqlite3ExprCacheRemove(pParse, target, 1);
87862          sqlite3ExprCachePush(pParse);
87863          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
87864          sqlite3ExprCachePop(pParse);
87865        }
87866        sqlite3VdbeResolveLabel(v, endCoalesce);
87867        break;
87868      }
87869
87870      /* The UNLIKELY() function is a no-op.  The result is the value
87871      ** of the first argument.
87872      */
87873      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
87874        assert( nFarg>=1 );
87875        inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
87876        break;
87877      }
87878
87879      for(i=0; i<nFarg; i++){
87880        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
87881          testcase( i==31 );
87882          constMask |= MASKBIT32(i);
87883        }
87884        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
87885          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
87886        }
87887      }
87888      if( pFarg ){
87889        if( constMask ){
87890          r1 = pParse->nMem+1;
87891          pParse->nMem += nFarg;
87892        }else{
87893          r1 = sqlite3GetTempRange(pParse, nFarg);
87894        }
87895
87896        /* For length() and typeof() functions with a column argument,
87897        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
87898        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
87899        ** loading.
87900        */
87901        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
87902          u8 exprOp;
87903          assert( nFarg==1 );
87904          assert( pFarg->a[0].pExpr!=0 );
87905          exprOp = pFarg->a[0].pExpr->op;
87906          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
87907            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
87908            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
87909            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
87910            pFarg->a[0].pExpr->op2 =
87911                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
87912          }
87913        }
87914
87915        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
87916        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
87917                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
87918        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
87919      }else{
87920        r1 = 0;
87921      }
87922#ifndef SQLITE_OMIT_VIRTUALTABLE
87923      /* Possibly overload the function if the first argument is
87924      ** a virtual table column.
87925      **
87926      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
87927      ** second argument, not the first, as the argument to test to
87928      ** see if it is a column in a virtual table.  This is done because
87929      ** the left operand of infix functions (the operand we want to
87930      ** control overloading) ends up as the second argument to the
87931      ** function.  The expression "A glob B" is equivalent to
87932      ** "glob(B,A).  We want to use the A in "A glob B" to test
87933      ** for function overloading.  But we use the B term in "glob(B,A)".
87934      */
87935      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
87936        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
87937      }else if( nFarg>0 ){
87938        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
87939      }
87940#endif
87941      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
87942        if( !pColl ) pColl = db->pDfltColl;
87943        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
87944      }
87945      sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
87946                        (char*)pDef, P4_FUNCDEF);
87947      sqlite3VdbeChangeP5(v, (u8)nFarg);
87948      if( nFarg && constMask==0 ){
87949        sqlite3ReleaseTempRange(pParse, r1, nFarg);
87950      }
87951      break;
87952    }
87953#ifndef SQLITE_OMIT_SUBQUERY
87954    case TK_EXISTS:
87955    case TK_SELECT: {
87956      testcase( op==TK_EXISTS );
87957      testcase( op==TK_SELECT );
87958      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
87959      break;
87960    }
87961    case TK_IN: {
87962      int destIfFalse = sqlite3VdbeMakeLabel(v);
87963      int destIfNull = sqlite3VdbeMakeLabel(v);
87964      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
87965      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
87966      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
87967      sqlite3VdbeResolveLabel(v, destIfFalse);
87968      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
87969      sqlite3VdbeResolveLabel(v, destIfNull);
87970      break;
87971    }
87972#endif /* SQLITE_OMIT_SUBQUERY */
87973
87974
87975    /*
87976    **    x BETWEEN y AND z
87977    **
87978    ** This is equivalent to
87979    **
87980    **    x>=y AND x<=z
87981    **
87982    ** X is stored in pExpr->pLeft.
87983    ** Y is stored in pExpr->pList->a[0].pExpr.
87984    ** Z is stored in pExpr->pList->a[1].pExpr.
87985    */
87986    case TK_BETWEEN: {
87987      Expr *pLeft = pExpr->pLeft;
87988      struct ExprList_item *pLItem = pExpr->x.pList->a;
87989      Expr *pRight = pLItem->pExpr;
87990
87991      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
87992      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
87993      testcase( regFree1==0 );
87994      testcase( regFree2==0 );
87995      r3 = sqlite3GetTempReg(pParse);
87996      r4 = sqlite3GetTempReg(pParse);
87997      codeCompare(pParse, pLeft, pRight, OP_Ge,
87998                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
87999      pLItem++;
88000      pRight = pLItem->pExpr;
88001      sqlite3ReleaseTempReg(pParse, regFree2);
88002      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
88003      testcase( regFree2==0 );
88004      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
88005      VdbeCoverage(v);
88006      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
88007      sqlite3ReleaseTempReg(pParse, r3);
88008      sqlite3ReleaseTempReg(pParse, r4);
88009      break;
88010    }
88011    case TK_COLLATE:
88012    case TK_UPLUS: {
88013      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
88014      break;
88015    }
88016
88017    case TK_TRIGGER: {
88018      /* If the opcode is TK_TRIGGER, then the expression is a reference
88019      ** to a column in the new.* or old.* pseudo-tables available to
88020      ** trigger programs. In this case Expr.iTable is set to 1 for the
88021      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
88022      ** is set to the column of the pseudo-table to read, or to -1 to
88023      ** read the rowid field.
88024      **
88025      ** The expression is implemented using an OP_Param opcode. The p1
88026      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
88027      ** to reference another column of the old.* pseudo-table, where
88028      ** i is the index of the column. For a new.rowid reference, p1 is
88029      ** set to (n+1), where n is the number of columns in each pseudo-table.
88030      ** For a reference to any other column in the new.* pseudo-table, p1
88031      ** is set to (n+2+i), where n and i are as defined previously. For
88032      ** example, if the table on which triggers are being fired is
88033      ** declared as:
88034      **
88035      **   CREATE TABLE t1(a, b);
88036      **
88037      ** Then p1 is interpreted as follows:
88038      **
88039      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
88040      **   p1==1   ->    old.a         p1==4   ->    new.a
88041      **   p1==2   ->    old.b         p1==5   ->    new.b
88042      */
88043      Table *pTab = pExpr->pTab;
88044      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
88045
88046      assert( pExpr->iTable==0 || pExpr->iTable==1 );
88047      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
88048      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
88049      assert( p1>=0 && p1<(pTab->nCol*2+2) );
88050
88051      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
88052      VdbeComment((v, "%s.%s -> $%d",
88053        (pExpr->iTable ? "new" : "old"),
88054        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
88055        target
88056      ));
88057
88058#ifndef SQLITE_OMIT_FLOATING_POINT
88059      /* If the column has REAL affinity, it may currently be stored as an
88060      ** integer. Use OP_RealAffinity to make sure it is really real.
88061      **
88062      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
88063      ** floating point when extracting it from the record.  */
88064      if( pExpr->iColumn>=0
88065       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
88066      ){
88067        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
88068      }
88069#endif
88070      break;
88071    }
88072
88073
88074    /*
88075    ** Form A:
88076    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
88077    **
88078    ** Form B:
88079    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
88080    **
88081    ** Form A is can be transformed into the equivalent form B as follows:
88082    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
88083    **        WHEN x=eN THEN rN ELSE y END
88084    **
88085    ** X (if it exists) is in pExpr->pLeft.
88086    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
88087    ** odd.  The Y is also optional.  If the number of elements in x.pList
88088    ** is even, then Y is omitted and the "otherwise" result is NULL.
88089    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
88090    **
88091    ** The result of the expression is the Ri for the first matching Ei,
88092    ** or if there is no matching Ei, the ELSE term Y, or if there is
88093    ** no ELSE term, NULL.
88094    */
88095    default: assert( op==TK_CASE ); {
88096      int endLabel;                     /* GOTO label for end of CASE stmt */
88097      int nextCase;                     /* GOTO label for next WHEN clause */
88098      int nExpr;                        /* 2x number of WHEN terms */
88099      int i;                            /* Loop counter */
88100      ExprList *pEList;                 /* List of WHEN terms */
88101      struct ExprList_item *aListelem;  /* Array of WHEN terms */
88102      Expr opCompare;                   /* The X==Ei expression */
88103      Expr *pX;                         /* The X expression */
88104      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
88105      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
88106
88107      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
88108      assert(pExpr->x.pList->nExpr > 0);
88109      pEList = pExpr->x.pList;
88110      aListelem = pEList->a;
88111      nExpr = pEList->nExpr;
88112      endLabel = sqlite3VdbeMakeLabel(v);
88113      if( (pX = pExpr->pLeft)!=0 ){
88114        tempX = *pX;
88115        testcase( pX->op==TK_COLUMN );
88116        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
88117        testcase( regFree1==0 );
88118        opCompare.op = TK_EQ;
88119        opCompare.pLeft = &tempX;
88120        pTest = &opCompare;
88121        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
88122        ** The value in regFree1 might get SCopy-ed into the file result.
88123        ** So make sure that the regFree1 register is not reused for other
88124        ** purposes and possibly overwritten.  */
88125        regFree1 = 0;
88126      }
88127      for(i=0; i<nExpr-1; i=i+2){
88128        sqlite3ExprCachePush(pParse);
88129        if( pX ){
88130          assert( pTest!=0 );
88131          opCompare.pRight = aListelem[i].pExpr;
88132        }else{
88133          pTest = aListelem[i].pExpr;
88134        }
88135        nextCase = sqlite3VdbeMakeLabel(v);
88136        testcase( pTest->op==TK_COLUMN );
88137        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
88138        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
88139        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
88140        sqlite3VdbeGoto(v, endLabel);
88141        sqlite3ExprCachePop(pParse);
88142        sqlite3VdbeResolveLabel(v, nextCase);
88143      }
88144      if( (nExpr&1)!=0 ){
88145        sqlite3ExprCachePush(pParse);
88146        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
88147        sqlite3ExprCachePop(pParse);
88148      }else{
88149        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
88150      }
88151      assert( db->mallocFailed || pParse->nErr>0
88152           || pParse->iCacheLevel==iCacheLevel );
88153      sqlite3VdbeResolveLabel(v, endLabel);
88154      break;
88155    }
88156#ifndef SQLITE_OMIT_TRIGGER
88157    case TK_RAISE: {
88158      assert( pExpr->affinity==OE_Rollback
88159           || pExpr->affinity==OE_Abort
88160           || pExpr->affinity==OE_Fail
88161           || pExpr->affinity==OE_Ignore
88162      );
88163      if( !pParse->pTriggerTab ){
88164        sqlite3ErrorMsg(pParse,
88165                       "RAISE() may only be used within a trigger-program");
88166        return 0;
88167      }
88168      if( pExpr->affinity==OE_Abort ){
88169        sqlite3MayAbort(pParse);
88170      }
88171      assert( !ExprHasProperty(pExpr, EP_IntValue) );
88172      if( pExpr->affinity==OE_Ignore ){
88173        sqlite3VdbeAddOp4(
88174            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
88175        VdbeCoverage(v);
88176      }else{
88177        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
88178                              pExpr->affinity, pExpr->u.zToken, 0, 0);
88179      }
88180
88181      break;
88182    }
88183#endif
88184  }
88185  sqlite3ReleaseTempReg(pParse, regFree1);
88186  sqlite3ReleaseTempReg(pParse, regFree2);
88187  return inReg;
88188}
88189
88190/*
88191** Factor out the code of the given expression to initialization time.
88192*/
88193SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
88194  Parse *pParse,    /* Parsing context */
88195  Expr *pExpr,      /* The expression to code when the VDBE initializes */
88196  int regDest,      /* Store the value in this register */
88197  u8 reusable       /* True if this expression is reusable */
88198){
88199  ExprList *p;
88200  assert( ConstFactorOk(pParse) );
88201  p = pParse->pConstExpr;
88202  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
88203  p = sqlite3ExprListAppend(pParse, p, pExpr);
88204  if( p ){
88205     struct ExprList_item *pItem = &p->a[p->nExpr-1];
88206     pItem->u.iConstExprReg = regDest;
88207     pItem->reusable = reusable;
88208  }
88209  pParse->pConstExpr = p;
88210}
88211
88212/*
88213** Generate code to evaluate an expression and store the results
88214** into a register.  Return the register number where the results
88215** are stored.
88216**
88217** If the register is a temporary register that can be deallocated,
88218** then write its number into *pReg.  If the result register is not
88219** a temporary, then set *pReg to zero.
88220**
88221** If pExpr is a constant, then this routine might generate this
88222** code to fill the register in the initialization section of the
88223** VDBE program, in order to factor it out of the evaluation loop.
88224*/
88225SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
88226  int r2;
88227  pExpr = sqlite3ExprSkipCollate(pExpr);
88228  if( ConstFactorOk(pParse)
88229   && pExpr->op!=TK_REGISTER
88230   && sqlite3ExprIsConstantNotJoin(pExpr)
88231  ){
88232    ExprList *p = pParse->pConstExpr;
88233    int i;
88234    *pReg  = 0;
88235    if( p ){
88236      struct ExprList_item *pItem;
88237      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
88238        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
88239          return pItem->u.iConstExprReg;
88240        }
88241      }
88242    }
88243    r2 = ++pParse->nMem;
88244    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
88245  }else{
88246    int r1 = sqlite3GetTempReg(pParse);
88247    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
88248    if( r2==r1 ){
88249      *pReg = r1;
88250    }else{
88251      sqlite3ReleaseTempReg(pParse, r1);
88252      *pReg = 0;
88253    }
88254  }
88255  return r2;
88256}
88257
88258/*
88259** Generate code that will evaluate expression pExpr and store the
88260** results in register target.  The results are guaranteed to appear
88261** in register target.
88262*/
88263SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
88264  int inReg;
88265
88266  assert( target>0 && target<=pParse->nMem );
88267  if( pExpr && pExpr->op==TK_REGISTER ){
88268    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
88269  }else{
88270    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
88271    assert( pParse->pVdbe || pParse->db->mallocFailed );
88272    if( inReg!=target && pParse->pVdbe ){
88273      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
88274    }
88275  }
88276}
88277
88278/*
88279** Generate code that will evaluate expression pExpr and store the
88280** results in register target.  The results are guaranteed to appear
88281** in register target.  If the expression is constant, then this routine
88282** might choose to code the expression at initialization time.
88283*/
88284SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
88285  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
88286    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
88287  }else{
88288    sqlite3ExprCode(pParse, pExpr, target);
88289  }
88290}
88291
88292/*
88293** Generate code that evaluates the given expression and puts the result
88294** in register target.
88295**
88296** Also make a copy of the expression results into another "cache" register
88297** and modify the expression so that the next time it is evaluated,
88298** the result is a copy of the cache register.
88299**
88300** This routine is used for expressions that are used multiple
88301** times.  They are evaluated once and the results of the expression
88302** are reused.
88303*/
88304SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
88305  Vdbe *v = pParse->pVdbe;
88306  int iMem;
88307
88308  assert( target>0 );
88309  assert( pExpr->op!=TK_REGISTER );
88310  sqlite3ExprCode(pParse, pExpr, target);
88311  iMem = ++pParse->nMem;
88312  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
88313  exprToRegister(pExpr, iMem);
88314}
88315
88316/*
88317** Generate code that pushes the value of every element of the given
88318** expression list into a sequence of registers beginning at target.
88319**
88320** Return the number of elements evaluated.
88321**
88322** The SQLITE_ECEL_DUP flag prevents the arguments from being
88323** filled using OP_SCopy.  OP_Copy must be used instead.
88324**
88325** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
88326** factored out into initialization code.
88327*/
88328SQLITE_PRIVATE int sqlite3ExprCodeExprList(
88329  Parse *pParse,     /* Parsing context */
88330  ExprList *pList,   /* The expression list to be coded */
88331  int target,        /* Where to write results */
88332  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
88333  u8 flags           /* SQLITE_ECEL_* flags */
88334){
88335  struct ExprList_item *pItem;
88336  int i, j, n;
88337  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
88338  Vdbe *v = pParse->pVdbe;
88339  assert( pList!=0 );
88340  assert( target>0 );
88341  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
88342  n = pList->nExpr;
88343  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
88344  for(pItem=pList->a, i=0; i<n; i++, pItem++){
88345    Expr *pExpr = pItem->pExpr;
88346    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
88347      sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
88348    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
88349      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
88350    }else{
88351      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
88352      if( inReg!=target+i ){
88353        VdbeOp *pOp;
88354        if( copyOp==OP_Copy
88355         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
88356         && pOp->p1+pOp->p3+1==inReg
88357         && pOp->p2+pOp->p3+1==target+i
88358        ){
88359          pOp->p3++;
88360        }else{
88361          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
88362        }
88363      }
88364    }
88365  }
88366  return n;
88367}
88368
88369/*
88370** Generate code for a BETWEEN operator.
88371**
88372**    x BETWEEN y AND z
88373**
88374** The above is equivalent to
88375**
88376**    x>=y AND x<=z
88377**
88378** Code it as such, taking care to do the common subexpression
88379** elimination of x.
88380*/
88381static void exprCodeBetween(
88382  Parse *pParse,    /* Parsing and code generating context */
88383  Expr *pExpr,      /* The BETWEEN expression */
88384  int dest,         /* Jump here if the jump is taken */
88385  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
88386  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
88387){
88388  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
88389  Expr compLeft;    /* The  x>=y  term */
88390  Expr compRight;   /* The  x<=z  term */
88391  Expr exprX;       /* The  x  subexpression */
88392  int regFree1 = 0; /* Temporary use register */
88393
88394  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88395  exprX = *pExpr->pLeft;
88396  exprAnd.op = TK_AND;
88397  exprAnd.pLeft = &compLeft;
88398  exprAnd.pRight = &compRight;
88399  compLeft.op = TK_GE;
88400  compLeft.pLeft = &exprX;
88401  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
88402  compRight.op = TK_LE;
88403  compRight.pLeft = &exprX;
88404  compRight.pRight = pExpr->x.pList->a[1].pExpr;
88405  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
88406  if( jumpIfTrue ){
88407    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
88408  }else{
88409    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
88410  }
88411  sqlite3ReleaseTempReg(pParse, regFree1);
88412
88413  /* Ensure adequate test coverage */
88414  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
88415  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
88416  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
88417  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
88418  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
88419  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
88420  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
88421  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
88422}
88423
88424/*
88425** Generate code for a boolean expression such that a jump is made
88426** to the label "dest" if the expression is true but execution
88427** continues straight thru if the expression is false.
88428**
88429** If the expression evaluates to NULL (neither true nor false), then
88430** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
88431**
88432** This code depends on the fact that certain token values (ex: TK_EQ)
88433** are the same as opcode values (ex: OP_Eq) that implement the corresponding
88434** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
88435** the make process cause these values to align.  Assert()s in the code
88436** below verify that the numbers are aligned correctly.
88437*/
88438SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
88439  Vdbe *v = pParse->pVdbe;
88440  int op = 0;
88441  int regFree1 = 0;
88442  int regFree2 = 0;
88443  int r1, r2;
88444
88445  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
88446  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
88447  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
88448  op = pExpr->op;
88449  switch( op ){
88450    case TK_AND: {
88451      int d2 = sqlite3VdbeMakeLabel(v);
88452      testcase( jumpIfNull==0 );
88453      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
88454      sqlite3ExprCachePush(pParse);
88455      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
88456      sqlite3VdbeResolveLabel(v, d2);
88457      sqlite3ExprCachePop(pParse);
88458      break;
88459    }
88460    case TK_OR: {
88461      testcase( jumpIfNull==0 );
88462      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
88463      sqlite3ExprCachePush(pParse);
88464      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
88465      sqlite3ExprCachePop(pParse);
88466      break;
88467    }
88468    case TK_NOT: {
88469      testcase( jumpIfNull==0 );
88470      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
88471      break;
88472    }
88473    case TK_LT:
88474    case TK_LE:
88475    case TK_GT:
88476    case TK_GE:
88477    case TK_NE:
88478    case TK_EQ: {
88479      testcase( jumpIfNull==0 );
88480      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88481      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88482      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88483                  r1, r2, dest, jumpIfNull);
88484      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
88485      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
88486      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
88487      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
88488      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
88489      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
88490      testcase( regFree1==0 );
88491      testcase( regFree2==0 );
88492      break;
88493    }
88494    case TK_IS:
88495    case TK_ISNOT: {
88496      testcase( op==TK_IS );
88497      testcase( op==TK_ISNOT );
88498      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88499      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88500      op = (op==TK_IS) ? TK_EQ : TK_NE;
88501      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88502                  r1, r2, dest, SQLITE_NULLEQ);
88503      VdbeCoverageIf(v, op==TK_EQ);
88504      VdbeCoverageIf(v, op==TK_NE);
88505      testcase( regFree1==0 );
88506      testcase( regFree2==0 );
88507      break;
88508    }
88509    case TK_ISNULL:
88510    case TK_NOTNULL: {
88511      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
88512      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
88513      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88514      sqlite3VdbeAddOp2(v, op, r1, dest);
88515      VdbeCoverageIf(v, op==TK_ISNULL);
88516      VdbeCoverageIf(v, op==TK_NOTNULL);
88517      testcase( regFree1==0 );
88518      break;
88519    }
88520    case TK_BETWEEN: {
88521      testcase( jumpIfNull==0 );
88522      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
88523      break;
88524    }
88525#ifndef SQLITE_OMIT_SUBQUERY
88526    case TK_IN: {
88527      int destIfFalse = sqlite3VdbeMakeLabel(v);
88528      int destIfNull = jumpIfNull ? dest : destIfFalse;
88529      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
88530      sqlite3VdbeGoto(v, dest);
88531      sqlite3VdbeResolveLabel(v, destIfFalse);
88532      break;
88533    }
88534#endif
88535    default: {
88536      if( exprAlwaysTrue(pExpr) ){
88537        sqlite3VdbeGoto(v, dest);
88538      }else if( exprAlwaysFalse(pExpr) ){
88539        /* No-op */
88540      }else{
88541        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
88542        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
88543        VdbeCoverage(v);
88544        testcase( regFree1==0 );
88545        testcase( jumpIfNull==0 );
88546      }
88547      break;
88548    }
88549  }
88550  sqlite3ReleaseTempReg(pParse, regFree1);
88551  sqlite3ReleaseTempReg(pParse, regFree2);
88552}
88553
88554/*
88555** Generate code for a boolean expression such that a jump is made
88556** to the label "dest" if the expression is false but execution
88557** continues straight thru if the expression is true.
88558**
88559** If the expression evaluates to NULL (neither true nor false) then
88560** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
88561** is 0.
88562*/
88563SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
88564  Vdbe *v = pParse->pVdbe;
88565  int op = 0;
88566  int regFree1 = 0;
88567  int regFree2 = 0;
88568  int r1, r2;
88569
88570  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
88571  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
88572  if( pExpr==0 )    return;
88573
88574  /* The value of pExpr->op and op are related as follows:
88575  **
88576  **       pExpr->op            op
88577  **       ---------          ----------
88578  **       TK_ISNULL          OP_NotNull
88579  **       TK_NOTNULL         OP_IsNull
88580  **       TK_NE              OP_Eq
88581  **       TK_EQ              OP_Ne
88582  **       TK_GT              OP_Le
88583  **       TK_LE              OP_Gt
88584  **       TK_GE              OP_Lt
88585  **       TK_LT              OP_Ge
88586  **
88587  ** For other values of pExpr->op, op is undefined and unused.
88588  ** The value of TK_ and OP_ constants are arranged such that we
88589  ** can compute the mapping above using the following expression.
88590  ** Assert()s verify that the computation is correct.
88591  */
88592  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
88593
88594  /* Verify correct alignment of TK_ and OP_ constants
88595  */
88596  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
88597  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
88598  assert( pExpr->op!=TK_NE || op==OP_Eq );
88599  assert( pExpr->op!=TK_EQ || op==OP_Ne );
88600  assert( pExpr->op!=TK_LT || op==OP_Ge );
88601  assert( pExpr->op!=TK_LE || op==OP_Gt );
88602  assert( pExpr->op!=TK_GT || op==OP_Le );
88603  assert( pExpr->op!=TK_GE || op==OP_Lt );
88604
88605  switch( pExpr->op ){
88606    case TK_AND: {
88607      testcase( jumpIfNull==0 );
88608      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
88609      sqlite3ExprCachePush(pParse);
88610      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
88611      sqlite3ExprCachePop(pParse);
88612      break;
88613    }
88614    case TK_OR: {
88615      int d2 = sqlite3VdbeMakeLabel(v);
88616      testcase( jumpIfNull==0 );
88617      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
88618      sqlite3ExprCachePush(pParse);
88619      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
88620      sqlite3VdbeResolveLabel(v, d2);
88621      sqlite3ExprCachePop(pParse);
88622      break;
88623    }
88624    case TK_NOT: {
88625      testcase( jumpIfNull==0 );
88626      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
88627      break;
88628    }
88629    case TK_LT:
88630    case TK_LE:
88631    case TK_GT:
88632    case TK_GE:
88633    case TK_NE:
88634    case TK_EQ: {
88635      testcase( jumpIfNull==0 );
88636      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88637      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88638      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88639                  r1, r2, dest, jumpIfNull);
88640      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
88641      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
88642      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
88643      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
88644      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
88645      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
88646      testcase( regFree1==0 );
88647      testcase( regFree2==0 );
88648      break;
88649    }
88650    case TK_IS:
88651    case TK_ISNOT: {
88652      testcase( pExpr->op==TK_IS );
88653      testcase( pExpr->op==TK_ISNOT );
88654      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88655      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88656      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
88657      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88658                  r1, r2, dest, SQLITE_NULLEQ);
88659      VdbeCoverageIf(v, op==TK_EQ);
88660      VdbeCoverageIf(v, op==TK_NE);
88661      testcase( regFree1==0 );
88662      testcase( regFree2==0 );
88663      break;
88664    }
88665    case TK_ISNULL:
88666    case TK_NOTNULL: {
88667      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88668      sqlite3VdbeAddOp2(v, op, r1, dest);
88669      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
88670      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
88671      testcase( regFree1==0 );
88672      break;
88673    }
88674    case TK_BETWEEN: {
88675      testcase( jumpIfNull==0 );
88676      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
88677      break;
88678    }
88679#ifndef SQLITE_OMIT_SUBQUERY
88680    case TK_IN: {
88681      if( jumpIfNull ){
88682        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
88683      }else{
88684        int destIfNull = sqlite3VdbeMakeLabel(v);
88685        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
88686        sqlite3VdbeResolveLabel(v, destIfNull);
88687      }
88688      break;
88689    }
88690#endif
88691    default: {
88692      if( exprAlwaysFalse(pExpr) ){
88693        sqlite3VdbeGoto(v, dest);
88694      }else if( exprAlwaysTrue(pExpr) ){
88695        /* no-op */
88696      }else{
88697        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
88698        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
88699        VdbeCoverage(v);
88700        testcase( regFree1==0 );
88701        testcase( jumpIfNull==0 );
88702      }
88703      break;
88704    }
88705  }
88706  sqlite3ReleaseTempReg(pParse, regFree1);
88707  sqlite3ReleaseTempReg(pParse, regFree2);
88708}
88709
88710/*
88711** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
88712** code generation, and that copy is deleted after code generation. This
88713** ensures that the original pExpr is unchanged.
88714*/
88715SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
88716  sqlite3 *db = pParse->db;
88717  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
88718  if( db->mallocFailed==0 ){
88719    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
88720  }
88721  sqlite3ExprDelete(db, pCopy);
88722}
88723
88724
88725/*
88726** Do a deep comparison of two expression trees.  Return 0 if the two
88727** expressions are completely identical.  Return 1 if they differ only
88728** by a COLLATE operator at the top level.  Return 2 if there are differences
88729** other than the top-level COLLATE operator.
88730**
88731** If any subelement of pB has Expr.iTable==(-1) then it is allowed
88732** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
88733**
88734** The pA side might be using TK_REGISTER.  If that is the case and pB is
88735** not using TK_REGISTER but is otherwise equivalent, then still return 0.
88736**
88737** Sometimes this routine will return 2 even if the two expressions
88738** really are equivalent.  If we cannot prove that the expressions are
88739** identical, we return 2 just to be safe.  So if this routine
88740** returns 2, then you do not really know for certain if the two
88741** expressions are the same.  But if you get a 0 or 1 return, then you
88742** can be sure the expressions are the same.  In the places where
88743** this routine is used, it does not hurt to get an extra 2 - that
88744** just might result in some slightly slower code.  But returning
88745** an incorrect 0 or 1 could lead to a malfunction.
88746*/
88747SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
88748  u32 combinedFlags;
88749  if( pA==0 || pB==0 ){
88750    return pB==pA ? 0 : 2;
88751  }
88752  combinedFlags = pA->flags | pB->flags;
88753  if( combinedFlags & EP_IntValue ){
88754    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
88755      return 0;
88756    }
88757    return 2;
88758  }
88759  if( pA->op!=pB->op ){
88760    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
88761      return 1;
88762    }
88763    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
88764      return 1;
88765    }
88766    return 2;
88767  }
88768  if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
88769    if( pA->op==TK_FUNCTION ){
88770      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
88771    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
88772      return pA->op==TK_COLLATE ? 1 : 2;
88773    }
88774  }
88775  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
88776  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
88777    if( combinedFlags & EP_xIsSelect ) return 2;
88778    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
88779    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
88780    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
88781    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
88782      if( pA->iColumn!=pB->iColumn ) return 2;
88783      if( pA->iTable!=pB->iTable
88784       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
88785    }
88786  }
88787  return 0;
88788}
88789
88790/*
88791** Compare two ExprList objects.  Return 0 if they are identical and
88792** non-zero if they differ in any way.
88793**
88794** If any subelement of pB has Expr.iTable==(-1) then it is allowed
88795** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
88796**
88797** This routine might return non-zero for equivalent ExprLists.  The
88798** only consequence will be disabled optimizations.  But this routine
88799** must never return 0 if the two ExprList objects are different, or
88800** a malfunction will result.
88801**
88802** Two NULL pointers are considered to be the same.  But a NULL pointer
88803** always differs from a non-NULL pointer.
88804*/
88805SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
88806  int i;
88807  if( pA==0 && pB==0 ) return 0;
88808  if( pA==0 || pB==0 ) return 1;
88809  if( pA->nExpr!=pB->nExpr ) return 1;
88810  for(i=0; i<pA->nExpr; i++){
88811    Expr *pExprA = pA->a[i].pExpr;
88812    Expr *pExprB = pB->a[i].pExpr;
88813    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
88814    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
88815  }
88816  return 0;
88817}
88818
88819/*
88820** Return true if we can prove the pE2 will always be true if pE1 is
88821** true.  Return false if we cannot complete the proof or if pE2 might
88822** be false.  Examples:
88823**
88824**     pE1: x==5       pE2: x==5             Result: true
88825**     pE1: x>0        pE2: x==5             Result: false
88826**     pE1: x=21       pE2: x=21 OR y=43     Result: true
88827**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
88828**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
88829**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
88830**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
88831**
88832** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
88833** Expr.iTable<0 then assume a table number given by iTab.
88834**
88835** When in doubt, return false.  Returning true might give a performance
88836** improvement.  Returning false might cause a performance reduction, but
88837** it will always give the correct answer and is hence always safe.
88838*/
88839SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
88840  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
88841    return 1;
88842  }
88843  if( pE2->op==TK_OR
88844   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
88845             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
88846  ){
88847    return 1;
88848  }
88849  if( pE2->op==TK_NOTNULL
88850   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
88851   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
88852  ){
88853    return 1;
88854  }
88855  return 0;
88856}
88857
88858/*
88859** An instance of the following structure is used by the tree walker
88860** to count references to table columns in the arguments of an
88861** aggregate function, in order to implement the
88862** sqlite3FunctionThisSrc() routine.
88863*/
88864struct SrcCount {
88865  SrcList *pSrc;   /* One particular FROM clause in a nested query */
88866  int nThis;       /* Number of references to columns in pSrcList */
88867  int nOther;      /* Number of references to columns in other FROM clauses */
88868};
88869
88870/*
88871** Count the number of references to columns.
88872*/
88873static int exprSrcCount(Walker *pWalker, Expr *pExpr){
88874  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
88875  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
88876  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
88877  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
88878  ** NEVER() will need to be removed. */
88879  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
88880    int i;
88881    struct SrcCount *p = pWalker->u.pSrcCount;
88882    SrcList *pSrc = p->pSrc;
88883    int nSrc = pSrc ? pSrc->nSrc : 0;
88884    for(i=0; i<nSrc; i++){
88885      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
88886    }
88887    if( i<nSrc ){
88888      p->nThis++;
88889    }else{
88890      p->nOther++;
88891    }
88892  }
88893  return WRC_Continue;
88894}
88895
88896/*
88897** Determine if any of the arguments to the pExpr Function reference
88898** pSrcList.  Return true if they do.  Also return true if the function
88899** has no arguments or has only constant arguments.  Return false if pExpr
88900** references columns but not columns of tables found in pSrcList.
88901*/
88902SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
88903  Walker w;
88904  struct SrcCount cnt;
88905  assert( pExpr->op==TK_AGG_FUNCTION );
88906  memset(&w, 0, sizeof(w));
88907  w.xExprCallback = exprSrcCount;
88908  w.u.pSrcCount = &cnt;
88909  cnt.pSrc = pSrcList;
88910  cnt.nThis = 0;
88911  cnt.nOther = 0;
88912  sqlite3WalkExprList(&w, pExpr->x.pList);
88913  return cnt.nThis>0 || cnt.nOther==0;
88914}
88915
88916/*
88917** Add a new element to the pAggInfo->aCol[] array.  Return the index of
88918** the new element.  Return a negative number if malloc fails.
88919*/
88920static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
88921  int i;
88922  pInfo->aCol = sqlite3ArrayAllocate(
88923       db,
88924       pInfo->aCol,
88925       sizeof(pInfo->aCol[0]),
88926       &pInfo->nColumn,
88927       &i
88928  );
88929  return i;
88930}
88931
88932/*
88933** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
88934** the new element.  Return a negative number if malloc fails.
88935*/
88936static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
88937  int i;
88938  pInfo->aFunc = sqlite3ArrayAllocate(
88939       db,
88940       pInfo->aFunc,
88941       sizeof(pInfo->aFunc[0]),
88942       &pInfo->nFunc,
88943       &i
88944  );
88945  return i;
88946}
88947
88948/*
88949** This is the xExprCallback for a tree walker.  It is used to
88950** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
88951** for additional information.
88952*/
88953static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
88954  int i;
88955  NameContext *pNC = pWalker->u.pNC;
88956  Parse *pParse = pNC->pParse;
88957  SrcList *pSrcList = pNC->pSrcList;
88958  AggInfo *pAggInfo = pNC->pAggInfo;
88959
88960  switch( pExpr->op ){
88961    case TK_AGG_COLUMN:
88962    case TK_COLUMN: {
88963      testcase( pExpr->op==TK_AGG_COLUMN );
88964      testcase( pExpr->op==TK_COLUMN );
88965      /* Check to see if the column is in one of the tables in the FROM
88966      ** clause of the aggregate query */
88967      if( ALWAYS(pSrcList!=0) ){
88968        struct SrcList_item *pItem = pSrcList->a;
88969        for(i=0; i<pSrcList->nSrc; i++, pItem++){
88970          struct AggInfo_col *pCol;
88971          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88972          if( pExpr->iTable==pItem->iCursor ){
88973            /* If we reach this point, it means that pExpr refers to a table
88974            ** that is in the FROM clause of the aggregate query.
88975            **
88976            ** Make an entry for the column in pAggInfo->aCol[] if there
88977            ** is not an entry there already.
88978            */
88979            int k;
88980            pCol = pAggInfo->aCol;
88981            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
88982              if( pCol->iTable==pExpr->iTable &&
88983                  pCol->iColumn==pExpr->iColumn ){
88984                break;
88985              }
88986            }
88987            if( (k>=pAggInfo->nColumn)
88988             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
88989            ){
88990              pCol = &pAggInfo->aCol[k];
88991              pCol->pTab = pExpr->pTab;
88992              pCol->iTable = pExpr->iTable;
88993              pCol->iColumn = pExpr->iColumn;
88994              pCol->iMem = ++pParse->nMem;
88995              pCol->iSorterColumn = -1;
88996              pCol->pExpr = pExpr;
88997              if( pAggInfo->pGroupBy ){
88998                int j, n;
88999                ExprList *pGB = pAggInfo->pGroupBy;
89000                struct ExprList_item *pTerm = pGB->a;
89001                n = pGB->nExpr;
89002                for(j=0; j<n; j++, pTerm++){
89003                  Expr *pE = pTerm->pExpr;
89004                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
89005                      pE->iColumn==pExpr->iColumn ){
89006                    pCol->iSorterColumn = j;
89007                    break;
89008                  }
89009                }
89010              }
89011              if( pCol->iSorterColumn<0 ){
89012                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
89013              }
89014            }
89015            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
89016            ** because it was there before or because we just created it).
89017            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
89018            ** pAggInfo->aCol[] entry.
89019            */
89020            ExprSetVVAProperty(pExpr, EP_NoReduce);
89021            pExpr->pAggInfo = pAggInfo;
89022            pExpr->op = TK_AGG_COLUMN;
89023            pExpr->iAgg = (i16)k;
89024            break;
89025          } /* endif pExpr->iTable==pItem->iCursor */
89026        } /* end loop over pSrcList */
89027      }
89028      return WRC_Prune;
89029    }
89030    case TK_AGG_FUNCTION: {
89031      if( (pNC->ncFlags & NC_InAggFunc)==0
89032       && pWalker->walkerDepth==pExpr->op2
89033      ){
89034        /* Check to see if pExpr is a duplicate of another aggregate
89035        ** function that is already in the pAggInfo structure
89036        */
89037        struct AggInfo_func *pItem = pAggInfo->aFunc;
89038        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
89039          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
89040            break;
89041          }
89042        }
89043        if( i>=pAggInfo->nFunc ){
89044          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
89045          */
89046          u8 enc = ENC(pParse->db);
89047          i = addAggInfoFunc(pParse->db, pAggInfo);
89048          if( i>=0 ){
89049            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89050            pItem = &pAggInfo->aFunc[i];
89051            pItem->pExpr = pExpr;
89052            pItem->iMem = ++pParse->nMem;
89053            assert( !ExprHasProperty(pExpr, EP_IntValue) );
89054            pItem->pFunc = sqlite3FindFunction(pParse->db,
89055                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
89056                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
89057            if( pExpr->flags & EP_Distinct ){
89058              pItem->iDistinct = pParse->nTab++;
89059            }else{
89060              pItem->iDistinct = -1;
89061            }
89062          }
89063        }
89064        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
89065        */
89066        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
89067        ExprSetVVAProperty(pExpr, EP_NoReduce);
89068        pExpr->iAgg = (i16)i;
89069        pExpr->pAggInfo = pAggInfo;
89070        return WRC_Prune;
89071      }else{
89072        return WRC_Continue;
89073      }
89074    }
89075  }
89076  return WRC_Continue;
89077}
89078static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
89079  UNUSED_PARAMETER(pWalker);
89080  UNUSED_PARAMETER(pSelect);
89081  return WRC_Continue;
89082}
89083
89084/*
89085** Analyze the pExpr expression looking for aggregate functions and
89086** for variables that need to be added to AggInfo object that pNC->pAggInfo
89087** points to.  Additional entries are made on the AggInfo object as
89088** necessary.
89089**
89090** This routine should only be called after the expression has been
89091** analyzed by sqlite3ResolveExprNames().
89092*/
89093SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
89094  Walker w;
89095  memset(&w, 0, sizeof(w));
89096  w.xExprCallback = analyzeAggregate;
89097  w.xSelectCallback = analyzeAggregatesInSelect;
89098  w.u.pNC = pNC;
89099  assert( pNC->pSrcList!=0 );
89100  sqlite3WalkExpr(&w, pExpr);
89101}
89102
89103/*
89104** Call sqlite3ExprAnalyzeAggregates() for every expression in an
89105** expression list.  Return the number of errors.
89106**
89107** If an error is found, the analysis is cut short.
89108*/
89109SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
89110  struct ExprList_item *pItem;
89111  int i;
89112  if( pList ){
89113    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
89114      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
89115    }
89116  }
89117}
89118
89119/*
89120** Allocate a single new register for use to hold some intermediate result.
89121*/
89122SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
89123  if( pParse->nTempReg==0 ){
89124    return ++pParse->nMem;
89125  }
89126  return pParse->aTempReg[--pParse->nTempReg];
89127}
89128
89129/*
89130** Deallocate a register, making available for reuse for some other
89131** purpose.
89132**
89133** If a register is currently being used by the column cache, then
89134** the deallocation is deferred until the column cache line that uses
89135** the register becomes stale.
89136*/
89137SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
89138  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
89139    int i;
89140    struct yColCache *p;
89141    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89142      if( p->iReg==iReg ){
89143        p->tempReg = 1;
89144        return;
89145      }
89146    }
89147    pParse->aTempReg[pParse->nTempReg++] = iReg;
89148  }
89149}
89150
89151/*
89152** Allocate or deallocate a block of nReg consecutive registers
89153*/
89154SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
89155  int i, n;
89156  i = pParse->iRangeReg;
89157  n = pParse->nRangeReg;
89158  if( nReg<=n ){
89159    assert( !usedAsColumnCache(pParse, i, i+n-1) );
89160    pParse->iRangeReg += nReg;
89161    pParse->nRangeReg -= nReg;
89162  }else{
89163    i = pParse->nMem+1;
89164    pParse->nMem += nReg;
89165  }
89166  return i;
89167}
89168SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
89169  sqlite3ExprCacheRemove(pParse, iReg, nReg);
89170  if( nReg>pParse->nRangeReg ){
89171    pParse->nRangeReg = nReg;
89172    pParse->iRangeReg = iReg;
89173  }
89174}
89175
89176/*
89177** Mark all temporary registers as being unavailable for reuse.
89178*/
89179SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
89180  pParse->nTempReg = 0;
89181  pParse->nRangeReg = 0;
89182}
89183
89184/************** End of expr.c ************************************************/
89185/************** Begin file alter.c *******************************************/
89186/*
89187** 2005 February 15
89188**
89189** The author disclaims copyright to this source code.  In place of
89190** a legal notice, here is a blessing:
89191**
89192**    May you do good and not evil.
89193**    May you find forgiveness for yourself and forgive others.
89194**    May you share freely, never taking more than you give.
89195**
89196*************************************************************************
89197** This file contains C code routines that used to generate VDBE code
89198** that implements the ALTER TABLE command.
89199*/
89200/* #include "sqliteInt.h" */
89201
89202/*
89203** The code in this file only exists if we are not omitting the
89204** ALTER TABLE logic from the build.
89205*/
89206#ifndef SQLITE_OMIT_ALTERTABLE
89207
89208
89209/*
89210** This function is used by SQL generated to implement the
89211** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
89212** CREATE INDEX command. The second is a table name. The table name in
89213** the CREATE TABLE or CREATE INDEX statement is replaced with the third
89214** argument and the result returned. Examples:
89215**
89216** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
89217**     -> 'CREATE TABLE def(a, b, c)'
89218**
89219** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
89220**     -> 'CREATE INDEX i ON def(a, b, c)'
89221*/
89222static void renameTableFunc(
89223  sqlite3_context *context,
89224  int NotUsed,
89225  sqlite3_value **argv
89226){
89227  unsigned char const *zSql = sqlite3_value_text(argv[0]);
89228  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
89229
89230  int token;
89231  Token tname;
89232  unsigned char const *zCsr = zSql;
89233  int len = 0;
89234  char *zRet;
89235
89236  sqlite3 *db = sqlite3_context_db_handle(context);
89237
89238  UNUSED_PARAMETER(NotUsed);
89239
89240  /* The principle used to locate the table name in the CREATE TABLE
89241  ** statement is that the table name is the first non-space token that
89242  ** is immediately followed by a TK_LP or TK_USING token.
89243  */
89244  if( zSql ){
89245    do {
89246      if( !*zCsr ){
89247        /* Ran out of input before finding an opening bracket. Return NULL. */
89248        return;
89249      }
89250
89251      /* Store the token that zCsr points to in tname. */
89252      tname.z = (char*)zCsr;
89253      tname.n = len;
89254
89255      /* Advance zCsr to the next token. Store that token type in 'token',
89256      ** and its length in 'len' (to be used next iteration of this loop).
89257      */
89258      do {
89259        zCsr += len;
89260        len = sqlite3GetToken(zCsr, &token);
89261      } while( token==TK_SPACE );
89262      assert( len>0 );
89263    } while( token!=TK_LP && token!=TK_USING );
89264
89265    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
89266       zSql, zTableName, tname.z+tname.n);
89267    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
89268  }
89269}
89270
89271/*
89272** This C function implements an SQL user function that is used by SQL code
89273** generated by the ALTER TABLE ... RENAME command to modify the definition
89274** of any foreign key constraints that use the table being renamed as the
89275** parent table. It is passed three arguments:
89276**
89277**   1) The complete text of the CREATE TABLE statement being modified,
89278**   2) The old name of the table being renamed, and
89279**   3) The new name of the table being renamed.
89280**
89281** It returns the new CREATE TABLE statement. For example:
89282**
89283**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
89284**       -> 'CREATE TABLE t1(a REFERENCES t3)'
89285*/
89286#ifndef SQLITE_OMIT_FOREIGN_KEY
89287static void renameParentFunc(
89288  sqlite3_context *context,
89289  int NotUsed,
89290  sqlite3_value **argv
89291){
89292  sqlite3 *db = sqlite3_context_db_handle(context);
89293  char *zOutput = 0;
89294  char *zResult;
89295  unsigned char const *zInput = sqlite3_value_text(argv[0]);
89296  unsigned char const *zOld = sqlite3_value_text(argv[1]);
89297  unsigned char const *zNew = sqlite3_value_text(argv[2]);
89298
89299  unsigned const char *z;         /* Pointer to token */
89300  int n;                          /* Length of token z */
89301  int token;                      /* Type of token */
89302
89303  UNUSED_PARAMETER(NotUsed);
89304  if( zInput==0 || zOld==0 ) return;
89305  for(z=zInput; *z; z=z+n){
89306    n = sqlite3GetToken(z, &token);
89307    if( token==TK_REFERENCES ){
89308      char *zParent;
89309      do {
89310        z += n;
89311        n = sqlite3GetToken(z, &token);
89312      }while( token==TK_SPACE );
89313
89314      if( token==TK_ILLEGAL ) break;
89315      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
89316      if( zParent==0 ) break;
89317      sqlite3Dequote(zParent);
89318      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
89319        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
89320            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
89321        );
89322        sqlite3DbFree(db, zOutput);
89323        zOutput = zOut;
89324        zInput = &z[n];
89325      }
89326      sqlite3DbFree(db, zParent);
89327    }
89328  }
89329
89330  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
89331  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
89332  sqlite3DbFree(db, zOutput);
89333}
89334#endif
89335
89336#ifndef SQLITE_OMIT_TRIGGER
89337/* This function is used by SQL generated to implement the
89338** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
89339** statement. The second is a table name. The table name in the CREATE
89340** TRIGGER statement is replaced with the third argument and the result
89341** returned. This is analagous to renameTableFunc() above, except for CREATE
89342** TRIGGER, not CREATE INDEX and CREATE TABLE.
89343*/
89344static void renameTriggerFunc(
89345  sqlite3_context *context,
89346  int NotUsed,
89347  sqlite3_value **argv
89348){
89349  unsigned char const *zSql = sqlite3_value_text(argv[0]);
89350  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
89351
89352  int token;
89353  Token tname;
89354  int dist = 3;
89355  unsigned char const *zCsr = zSql;
89356  int len = 0;
89357  char *zRet;
89358  sqlite3 *db = sqlite3_context_db_handle(context);
89359
89360  UNUSED_PARAMETER(NotUsed);
89361
89362  /* The principle used to locate the table name in the CREATE TRIGGER
89363  ** statement is that the table name is the first token that is immediately
89364  ** preceded by either TK_ON or TK_DOT and immediately followed by one
89365  ** of TK_WHEN, TK_BEGIN or TK_FOR.
89366  */
89367  if( zSql ){
89368    do {
89369
89370      if( !*zCsr ){
89371        /* Ran out of input before finding the table name. Return NULL. */
89372        return;
89373      }
89374
89375      /* Store the token that zCsr points to in tname. */
89376      tname.z = (char*)zCsr;
89377      tname.n = len;
89378
89379      /* Advance zCsr to the next token. Store that token type in 'token',
89380      ** and its length in 'len' (to be used next iteration of this loop).
89381      */
89382      do {
89383        zCsr += len;
89384        len = sqlite3GetToken(zCsr, &token);
89385      }while( token==TK_SPACE );
89386      assert( len>0 );
89387
89388      /* Variable 'dist' stores the number of tokens read since the most
89389      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
89390      ** token is read and 'dist' equals 2, the condition stated above
89391      ** to be met.
89392      **
89393      ** Note that ON cannot be a database, table or column name, so
89394      ** there is no need to worry about syntax like
89395      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
89396      */
89397      dist++;
89398      if( token==TK_DOT || token==TK_ON ){
89399        dist = 0;
89400      }
89401    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
89402
89403    /* Variable tname now contains the token that is the old table-name
89404    ** in the CREATE TRIGGER statement.
89405    */
89406    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
89407       zSql, zTableName, tname.z+tname.n);
89408    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
89409  }
89410}
89411#endif   /* !SQLITE_OMIT_TRIGGER */
89412
89413/*
89414** Register built-in functions used to help implement ALTER TABLE
89415*/
89416SQLITE_PRIVATE void sqlite3AlterFunctions(void){
89417  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
89418    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
89419#ifndef SQLITE_OMIT_TRIGGER
89420    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
89421#endif
89422#ifndef SQLITE_OMIT_FOREIGN_KEY
89423    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
89424#endif
89425  };
89426  int i;
89427  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89428  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
89429
89430  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
89431    sqlite3FuncDefInsert(pHash, &aFunc[i]);
89432  }
89433}
89434
89435/*
89436** This function is used to create the text of expressions of the form:
89437**
89438**   name=<constant1> OR name=<constant2> OR ...
89439**
89440** If argument zWhere is NULL, then a pointer string containing the text
89441** "name=<constant>" is returned, where <constant> is the quoted version
89442** of the string passed as argument zConstant. The returned buffer is
89443** allocated using sqlite3DbMalloc(). It is the responsibility of the
89444** caller to ensure that it is eventually freed.
89445**
89446** If argument zWhere is not NULL, then the string returned is
89447** "<where> OR name=<constant>", where <where> is the contents of zWhere.
89448** In this case zWhere is passed to sqlite3DbFree() before returning.
89449**
89450*/
89451static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
89452  char *zNew;
89453  if( !zWhere ){
89454    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
89455  }else{
89456    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
89457    sqlite3DbFree(db, zWhere);
89458  }
89459  return zNew;
89460}
89461
89462#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89463/*
89464** Generate the text of a WHERE expression which can be used to select all
89465** tables that have foreign key constraints that refer to table pTab (i.e.
89466** constraints for which pTab is the parent table) from the sqlite_master
89467** table.
89468*/
89469static char *whereForeignKeys(Parse *pParse, Table *pTab){
89470  FKey *p;
89471  char *zWhere = 0;
89472  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89473    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
89474  }
89475  return zWhere;
89476}
89477#endif
89478
89479/*
89480** Generate the text of a WHERE expression which can be used to select all
89481** temporary triggers on table pTab from the sqlite_temp_master table. If
89482** table pTab has no temporary triggers, or is itself stored in the
89483** temporary database, NULL is returned.
89484*/
89485static char *whereTempTriggers(Parse *pParse, Table *pTab){
89486  Trigger *pTrig;
89487  char *zWhere = 0;
89488  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
89489
89490  /* If the table is not located in the temp-db (in which case NULL is
89491  ** returned, loop through the tables list of triggers. For each trigger
89492  ** that is not part of the temp-db schema, add a clause to the WHERE
89493  ** expression being built up in zWhere.
89494  */
89495  if( pTab->pSchema!=pTempSchema ){
89496    sqlite3 *db = pParse->db;
89497    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
89498      if( pTrig->pSchema==pTempSchema ){
89499        zWhere = whereOrName(db, zWhere, pTrig->zName);
89500      }
89501    }
89502  }
89503  if( zWhere ){
89504    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
89505    sqlite3DbFree(pParse->db, zWhere);
89506    zWhere = zNew;
89507  }
89508  return zWhere;
89509}
89510
89511/*
89512** Generate code to drop and reload the internal representation of table
89513** pTab from the database, including triggers and temporary triggers.
89514** Argument zName is the name of the table in the database schema at
89515** the time the generated code is executed. This can be different from
89516** pTab->zName if this function is being called to code part of an
89517** "ALTER TABLE RENAME TO" statement.
89518*/
89519static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
89520  Vdbe *v;
89521  char *zWhere;
89522  int iDb;                   /* Index of database containing pTab */
89523#ifndef SQLITE_OMIT_TRIGGER
89524  Trigger *pTrig;
89525#endif
89526
89527  v = sqlite3GetVdbe(pParse);
89528  if( NEVER(v==0) ) return;
89529  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89530  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89531  assert( iDb>=0 );
89532
89533#ifndef SQLITE_OMIT_TRIGGER
89534  /* Drop any table triggers from the internal schema. */
89535  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
89536    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
89537    assert( iTrigDb==iDb || iTrigDb==1 );
89538    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
89539  }
89540#endif
89541
89542  /* Drop the table and index from the internal schema.  */
89543  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
89544
89545  /* Reload the table, index and permanent trigger schemas. */
89546  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
89547  if( !zWhere ) return;
89548  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
89549
89550#ifndef SQLITE_OMIT_TRIGGER
89551  /* Now, if the table is not stored in the temp database, reload any temp
89552  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
89553  */
89554  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
89555    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
89556  }
89557#endif
89558}
89559
89560/*
89561** Parameter zName is the name of a table that is about to be altered
89562** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
89563** If the table is a system table, this function leaves an error message
89564** in pParse->zErr (system tables may not be altered) and returns non-zero.
89565**
89566** Or, if zName is not a system table, zero is returned.
89567*/
89568static int isSystemTable(Parse *pParse, const char *zName){
89569  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
89570    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
89571    return 1;
89572  }
89573  return 0;
89574}
89575
89576/*
89577** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
89578** command.
89579*/
89580SQLITE_PRIVATE void sqlite3AlterRenameTable(
89581  Parse *pParse,            /* Parser context. */
89582  SrcList *pSrc,            /* The table to rename. */
89583  Token *pName              /* The new table name. */
89584){
89585  int iDb;                  /* Database that contains the table */
89586  char *zDb;                /* Name of database iDb */
89587  Table *pTab;              /* Table being renamed */
89588  char *zName = 0;          /* NULL-terminated version of pName */
89589  sqlite3 *db = pParse->db; /* Database connection */
89590  int nTabName;             /* Number of UTF-8 characters in zTabName */
89591  const char *zTabName;     /* Original name of the table */
89592  Vdbe *v;
89593#ifndef SQLITE_OMIT_TRIGGER
89594  char *zWhere = 0;         /* Where clause to locate temp triggers */
89595#endif
89596  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
89597  int savedDbFlags;         /* Saved value of db->flags */
89598
89599  savedDbFlags = db->flags;
89600  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
89601  assert( pSrc->nSrc==1 );
89602  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89603
89604  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
89605  if( !pTab ) goto exit_rename_table;
89606  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89607  zDb = db->aDb[iDb].zName;
89608  db->flags |= SQLITE_PreferBuiltin;
89609
89610  /* Get a NULL terminated version of the new table name. */
89611  zName = sqlite3NameFromToken(db, pName);
89612  if( !zName ) goto exit_rename_table;
89613
89614  /* Check that a table or index named 'zName' does not already exist
89615  ** in database iDb. If so, this is an error.
89616  */
89617  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
89618    sqlite3ErrorMsg(pParse,
89619        "there is already another table or index with this name: %s", zName);
89620    goto exit_rename_table;
89621  }
89622
89623  /* Make sure it is not a system table being altered, or a reserved name
89624  ** that the table is being renamed to.
89625  */
89626  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
89627    goto exit_rename_table;
89628  }
89629  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
89630    exit_rename_table;
89631  }
89632
89633#ifndef SQLITE_OMIT_VIEW
89634  if( pTab->pSelect ){
89635    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
89636    goto exit_rename_table;
89637  }
89638#endif
89639
89640#ifndef SQLITE_OMIT_AUTHORIZATION
89641  /* Invoke the authorization callback. */
89642  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
89643    goto exit_rename_table;
89644  }
89645#endif
89646
89647#ifndef SQLITE_OMIT_VIRTUALTABLE
89648  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89649    goto exit_rename_table;
89650  }
89651  if( IsVirtual(pTab) ){
89652    pVTab = sqlite3GetVTable(db, pTab);
89653    if( pVTab->pVtab->pModule->xRename==0 ){
89654      pVTab = 0;
89655    }
89656  }
89657#endif
89658
89659  /* Begin a transaction for database iDb.
89660  ** Then modify the schema cookie (since the ALTER TABLE modifies the
89661  ** schema). Open a statement transaction if the table is a virtual
89662  ** table.
89663  */
89664  v = sqlite3GetVdbe(pParse);
89665  if( v==0 ){
89666    goto exit_rename_table;
89667  }
89668  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
89669  sqlite3ChangeCookie(pParse, iDb);
89670
89671  /* If this is a virtual table, invoke the xRename() function if
89672  ** one is defined. The xRename() callback will modify the names
89673  ** of any resources used by the v-table implementation (including other
89674  ** SQLite tables) that are identified by the name of the virtual table.
89675  */
89676#ifndef SQLITE_OMIT_VIRTUALTABLE
89677  if( pVTab ){
89678    int i = ++pParse->nMem;
89679    sqlite3VdbeLoadString(v, i, zName);
89680    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
89681    sqlite3MayAbort(pParse);
89682  }
89683#endif
89684
89685  /* figure out how many UTF-8 characters are in zName */
89686  zTabName = pTab->zName;
89687  nTabName = sqlite3Utf8CharLen(zTabName, -1);
89688
89689#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89690  if( db->flags&SQLITE_ForeignKeys ){
89691    /* If foreign-key support is enabled, rewrite the CREATE TABLE
89692    ** statements corresponding to all child tables of foreign key constraints
89693    ** for which the renamed table is the parent table.  */
89694    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
89695      sqlite3NestedParse(pParse,
89696          "UPDATE \"%w\".%s SET "
89697              "sql = sqlite_rename_parent(sql, %Q, %Q) "
89698              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
89699      sqlite3DbFree(db, zWhere);
89700    }
89701  }
89702#endif
89703
89704  /* Modify the sqlite_master table to use the new table name. */
89705  sqlite3NestedParse(pParse,
89706      "UPDATE %Q.%s SET "
89707#ifdef SQLITE_OMIT_TRIGGER
89708          "sql = sqlite_rename_table(sql, %Q), "
89709#else
89710          "sql = CASE "
89711            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
89712            "ELSE sqlite_rename_table(sql, %Q) END, "
89713#endif
89714          "tbl_name = %Q, "
89715          "name = CASE "
89716            "WHEN type='table' THEN %Q "
89717            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
89718             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
89719            "ELSE name END "
89720      "WHERE tbl_name=%Q COLLATE nocase AND "
89721          "(type='table' OR type='index' OR type='trigger');",
89722      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
89723#ifndef SQLITE_OMIT_TRIGGER
89724      zName,
89725#endif
89726      zName, nTabName, zTabName
89727  );
89728
89729#ifndef SQLITE_OMIT_AUTOINCREMENT
89730  /* If the sqlite_sequence table exists in this database, then update
89731  ** it with the new table name.
89732  */
89733  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
89734    sqlite3NestedParse(pParse,
89735        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
89736        zDb, zName, pTab->zName);
89737  }
89738#endif
89739
89740#ifndef SQLITE_OMIT_TRIGGER
89741  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
89742  ** table. Don't do this if the table being ALTERed is itself located in
89743  ** the temp database.
89744  */
89745  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
89746    sqlite3NestedParse(pParse,
89747        "UPDATE sqlite_temp_master SET "
89748            "sql = sqlite_rename_trigger(sql, %Q), "
89749            "tbl_name = %Q "
89750            "WHERE %s;", zName, zName, zWhere);
89751    sqlite3DbFree(db, zWhere);
89752  }
89753#endif
89754
89755#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89756  if( db->flags&SQLITE_ForeignKeys ){
89757    FKey *p;
89758    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89759      Table *pFrom = p->pFrom;
89760      if( pFrom!=pTab ){
89761        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
89762      }
89763    }
89764  }
89765#endif
89766
89767  /* Drop and reload the internal table schema. */
89768  reloadTableSchema(pParse, pTab, zName);
89769
89770exit_rename_table:
89771  sqlite3SrcListDelete(db, pSrc);
89772  sqlite3DbFree(db, zName);
89773  db->flags = savedDbFlags;
89774}
89775
89776
89777/*
89778** Generate code to make sure the file format number is at least minFormat.
89779** The generated code will increase the file format number if necessary.
89780*/
89781SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
89782  Vdbe *v;
89783  v = sqlite3GetVdbe(pParse);
89784  /* The VDBE should have been allocated before this routine is called.
89785  ** If that allocation failed, we would have quit before reaching this
89786  ** point */
89787  if( ALWAYS(v) ){
89788    int r1 = sqlite3GetTempReg(pParse);
89789    int r2 = sqlite3GetTempReg(pParse);
89790    int addr1;
89791    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
89792    sqlite3VdbeUsesBtree(v, iDb);
89793    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
89794    addr1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
89795    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
89796    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
89797    sqlite3VdbeJumpHere(v, addr1);
89798    sqlite3ReleaseTempReg(pParse, r1);
89799    sqlite3ReleaseTempReg(pParse, r2);
89800  }
89801}
89802
89803/*
89804** This function is called after an "ALTER TABLE ... ADD" statement
89805** has been parsed. Argument pColDef contains the text of the new
89806** column definition.
89807**
89808** The Table structure pParse->pNewTable was extended to include
89809** the new column during parsing.
89810*/
89811SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
89812  Table *pNew;              /* Copy of pParse->pNewTable */
89813  Table *pTab;              /* Table being altered */
89814  int iDb;                  /* Database number */
89815  const char *zDb;          /* Database name */
89816  const char *zTab;         /* Table name */
89817  char *zCol;               /* Null-terminated column definition */
89818  Column *pCol;             /* The new column */
89819  Expr *pDflt;              /* Default value for the new column */
89820  sqlite3 *db;              /* The database connection; */
89821
89822  db = pParse->db;
89823  if( pParse->nErr || db->mallocFailed ) return;
89824  pNew = pParse->pNewTable;
89825  assert( pNew );
89826
89827  assert( sqlite3BtreeHoldsAllMutexes(db) );
89828  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
89829  zDb = db->aDb[iDb].zName;
89830  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
89831  pCol = &pNew->aCol[pNew->nCol-1];
89832  pDflt = pCol->pDflt;
89833  pTab = sqlite3FindTable(db, zTab, zDb);
89834  assert( pTab );
89835
89836#ifndef SQLITE_OMIT_AUTHORIZATION
89837  /* Invoke the authorization callback. */
89838  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
89839    return;
89840  }
89841#endif
89842
89843  /* If the default value for the new column was specified with a
89844  ** literal NULL, then set pDflt to 0. This simplifies checking
89845  ** for an SQL NULL default below.
89846  */
89847  if( pDflt && pDflt->op==TK_NULL ){
89848    pDflt = 0;
89849  }
89850
89851  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
89852  ** If there is a NOT NULL constraint, then the default value for the
89853  ** column must not be NULL.
89854  */
89855  if( pCol->colFlags & COLFLAG_PRIMKEY ){
89856    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
89857    return;
89858  }
89859  if( pNew->pIndex ){
89860    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
89861    return;
89862  }
89863  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
89864    sqlite3ErrorMsg(pParse,
89865        "Cannot add a REFERENCES column with non-NULL default value");
89866    return;
89867  }
89868  if( pCol->notNull && !pDflt ){
89869    sqlite3ErrorMsg(pParse,
89870        "Cannot add a NOT NULL column with default value NULL");
89871    return;
89872  }
89873
89874  /* Ensure the default expression is something that sqlite3ValueFromExpr()
89875  ** can handle (i.e. not CURRENT_TIME etc.)
89876  */
89877  if( pDflt ){
89878    sqlite3_value *pVal = 0;
89879    int rc;
89880    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
89881    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
89882    if( rc!=SQLITE_OK ){
89883      db->mallocFailed = 1;
89884      return;
89885    }
89886    if( !pVal ){
89887      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
89888      return;
89889    }
89890    sqlite3ValueFree(pVal);
89891  }
89892
89893  /* Modify the CREATE TABLE statement. */
89894  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
89895  if( zCol ){
89896    char *zEnd = &zCol[pColDef->n-1];
89897    int savedDbFlags = db->flags;
89898    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
89899      *zEnd-- = '\0';
89900    }
89901    db->flags |= SQLITE_PreferBuiltin;
89902    sqlite3NestedParse(pParse,
89903        "UPDATE \"%w\".%s SET "
89904          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
89905        "WHERE type = 'table' AND name = %Q",
89906      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
89907      zTab
89908    );
89909    sqlite3DbFree(db, zCol);
89910    db->flags = savedDbFlags;
89911  }
89912
89913  /* If the default value of the new column is NULL, then set the file
89914  ** format to 2. If the default value of the new column is not NULL,
89915  ** the file format becomes 3.
89916  */
89917  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
89918
89919  /* Reload the schema of the modified table. */
89920  reloadTableSchema(pParse, pTab, pTab->zName);
89921}
89922
89923/*
89924** This function is called by the parser after the table-name in
89925** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
89926** pSrc is the full-name of the table being altered.
89927**
89928** This routine makes a (partial) copy of the Table structure
89929** for the table being altered and sets Parse.pNewTable to point
89930** to it. Routines called by the parser as the column definition
89931** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
89932** the copy. The copy of the Table structure is deleted by tokenize.c
89933** after parsing is finished.
89934**
89935** Routine sqlite3AlterFinishAddColumn() will be called to complete
89936** coding the "ALTER TABLE ... ADD" statement.
89937*/
89938SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
89939  Table *pNew;
89940  Table *pTab;
89941  Vdbe *v;
89942  int iDb;
89943  int i;
89944  int nAlloc;
89945  sqlite3 *db = pParse->db;
89946
89947  /* Look up the table being altered. */
89948  assert( pParse->pNewTable==0 );
89949  assert( sqlite3BtreeHoldsAllMutexes(db) );
89950  if( db->mallocFailed ) goto exit_begin_add_column;
89951  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
89952  if( !pTab ) goto exit_begin_add_column;
89953
89954#ifndef SQLITE_OMIT_VIRTUALTABLE
89955  if( IsVirtual(pTab) ){
89956    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
89957    goto exit_begin_add_column;
89958  }
89959#endif
89960
89961  /* Make sure this is not an attempt to ALTER a view. */
89962  if( pTab->pSelect ){
89963    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
89964    goto exit_begin_add_column;
89965  }
89966  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
89967    goto exit_begin_add_column;
89968  }
89969
89970  assert( pTab->addColOffset>0 );
89971  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89972
89973  /* Put a copy of the Table struct in Parse.pNewTable for the
89974  ** sqlite3AddColumn() function and friends to modify.  But modify
89975  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
89976  ** prefix, we insure that the name will not collide with an existing
89977  ** table because user table are not allowed to have the "sqlite_"
89978  ** prefix on their name.
89979  */
89980  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
89981  if( !pNew ) goto exit_begin_add_column;
89982  pParse->pNewTable = pNew;
89983  pNew->nRef = 1;
89984  pNew->nCol = pTab->nCol;
89985  assert( pNew->nCol>0 );
89986  nAlloc = (((pNew->nCol-1)/8)*8)+8;
89987  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
89988  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
89989  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
89990  if( !pNew->aCol || !pNew->zName ){
89991    db->mallocFailed = 1;
89992    goto exit_begin_add_column;
89993  }
89994  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
89995  for(i=0; i<pNew->nCol; i++){
89996    Column *pCol = &pNew->aCol[i];
89997    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
89998    pCol->zColl = 0;
89999    pCol->zType = 0;
90000    pCol->pDflt = 0;
90001    pCol->zDflt = 0;
90002  }
90003  pNew->pSchema = db->aDb[iDb].pSchema;
90004  pNew->addColOffset = pTab->addColOffset;
90005  pNew->nRef = 1;
90006
90007  /* Begin a transaction and increment the schema cookie.  */
90008  sqlite3BeginWriteOperation(pParse, 0, iDb);
90009  v = sqlite3GetVdbe(pParse);
90010  if( !v ) goto exit_begin_add_column;
90011  sqlite3ChangeCookie(pParse, iDb);
90012
90013exit_begin_add_column:
90014  sqlite3SrcListDelete(db, pSrc);
90015  return;
90016}
90017#endif  /* SQLITE_ALTER_TABLE */
90018
90019/************** End of alter.c ***********************************************/
90020/************** Begin file analyze.c *****************************************/
90021/*
90022** 2005-07-08
90023**
90024** The author disclaims copyright to this source code.  In place of
90025** a legal notice, here is a blessing:
90026**
90027**    May you do good and not evil.
90028**    May you find forgiveness for yourself and forgive others.
90029**    May you share freely, never taking more than you give.
90030**
90031*************************************************************************
90032** This file contains code associated with the ANALYZE command.
90033**
90034** The ANALYZE command gather statistics about the content of tables
90035** and indices.  These statistics are made available to the query planner
90036** to help it make better decisions about how to perform queries.
90037**
90038** The following system tables are or have been supported:
90039**
90040**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
90041**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
90042**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
90043**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
90044**
90045** Additional tables might be added in future releases of SQLite.
90046** The sqlite_stat2 table is not created or used unless the SQLite version
90047** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
90048** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
90049** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
90050** created and used by SQLite versions 3.7.9 and later and with
90051** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
90052** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
90053** version of sqlite_stat3 and is only available when compiled with
90054** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
90055** not possible to enable both STAT3 and STAT4 at the same time.  If they
90056** are both enabled, then STAT4 takes precedence.
90057**
90058** For most applications, sqlite_stat1 provides all the statistics required
90059** for the query planner to make good choices.
90060**
90061** Format of sqlite_stat1:
90062**
90063** There is normally one row per index, with the index identified by the
90064** name in the idx column.  The tbl column is the name of the table to
90065** which the index belongs.  In each such row, the stat column will be
90066** a string consisting of a list of integers.  The first integer in this
90067** list is the number of rows in the index.  (This is the same as the
90068** number of rows in the table, except for partial indices.)  The second
90069** integer is the average number of rows in the index that have the same
90070** value in the first column of the index.  The third integer is the average
90071** number of rows in the index that have the same value for the first two
90072** columns.  The N-th integer (for N>1) is the average number of rows in
90073** the index which have the same value for the first N-1 columns.  For
90074** a K-column index, there will be K+1 integers in the stat column.  If
90075** the index is unique, then the last integer will be 1.
90076**
90077** The list of integers in the stat column can optionally be followed
90078** by the keyword "unordered".  The "unordered" keyword, if it is present,
90079** must be separated from the last integer by a single space.  If the
90080** "unordered" keyword is present, then the query planner assumes that
90081** the index is unordered and will not use the index for a range query.
90082**
90083** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
90084** column contains a single integer which is the (estimated) number of
90085** rows in the table identified by sqlite_stat1.tbl.
90086**
90087** Format of sqlite_stat2:
90088**
90089** The sqlite_stat2 is only created and is only used if SQLite is compiled
90090** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
90091** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
90092** about the distribution of keys within an index.  The index is identified by
90093** the "idx" column and the "tbl" column is the name of the table to which
90094** the index belongs.  There are usually 10 rows in the sqlite_stat2
90095** table for each index.
90096**
90097** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
90098** inclusive are samples of the left-most key value in the index taken at
90099** evenly spaced points along the index.  Let the number of samples be S
90100** (10 in the standard build) and let C be the number of rows in the index.
90101** Then the sampled rows are given by:
90102**
90103**     rownumber = (i*C*2 + C)/(S*2)
90104**
90105** For i between 0 and S-1.  Conceptually, the index space is divided into
90106** S uniform buckets and the samples are the middle row from each bucket.
90107**
90108** The format for sqlite_stat2 is recorded here for legacy reference.  This
90109** version of SQLite does not support sqlite_stat2.  It neither reads nor
90110** writes the sqlite_stat2 table.  This version of SQLite only supports
90111** sqlite_stat3.
90112**
90113** Format for sqlite_stat3:
90114**
90115** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
90116** sqlite_stat4 format will be described first.  Further information
90117** about sqlite_stat3 follows the sqlite_stat4 description.
90118**
90119** Format for sqlite_stat4:
90120**
90121** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
90122** to aid the query planner in choosing good indices based on the values
90123** that indexed columns are compared against in the WHERE clauses of
90124** queries.
90125**
90126** The sqlite_stat4 table contains multiple entries for each index.
90127** The idx column names the index and the tbl column is the table of the
90128** index.  If the idx and tbl columns are the same, then the sample is
90129** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
90130** binary encoding of a key from the index.  The nEq column is a
90131** list of integers.  The first integer is the approximate number
90132** of entries in the index whose left-most column exactly matches
90133** the left-most column of the sample.  The second integer in nEq
90134** is the approximate number of entries in the index where the
90135** first two columns match the first two columns of the sample.
90136** And so forth.  nLt is another list of integers that show the approximate
90137** number of entries that are strictly less than the sample.  The first
90138** integer in nLt contains the number of entries in the index where the
90139** left-most column is less than the left-most column of the sample.
90140** The K-th integer in the nLt entry is the number of index entries
90141** where the first K columns are less than the first K columns of the
90142** sample.  The nDLt column is like nLt except that it contains the
90143** number of distinct entries in the index that are less than the
90144** sample.
90145**
90146** There can be an arbitrary number of sqlite_stat4 entries per index.
90147** The ANALYZE command will typically generate sqlite_stat4 tables
90148** that contain between 10 and 40 samples which are distributed across
90149** the key space, though not uniformly, and which include samples with
90150** large nEq values.
90151**
90152** Format for sqlite_stat3 redux:
90153**
90154** The sqlite_stat3 table is like sqlite_stat4 except that it only
90155** looks at the left-most column of the index.  The sqlite_stat3.sample
90156** column contains the actual value of the left-most column instead
90157** of a blob encoding of the complete index key as is found in
90158** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
90159** all contain just a single integer which is the same as the first
90160** integer in the equivalent columns in sqlite_stat4.
90161*/
90162#ifndef SQLITE_OMIT_ANALYZE
90163/* #include "sqliteInt.h" */
90164
90165#if defined(SQLITE_ENABLE_STAT4)
90166# define IsStat4     1
90167# define IsStat3     0
90168#elif defined(SQLITE_ENABLE_STAT3)
90169# define IsStat4     0
90170# define IsStat3     1
90171#else
90172# define IsStat4     0
90173# define IsStat3     0
90174# undef SQLITE_STAT4_SAMPLES
90175# define SQLITE_STAT4_SAMPLES 1
90176#endif
90177#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
90178
90179/*
90180** This routine generates code that opens the sqlite_statN tables.
90181** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
90182** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
90183** appropriate compile-time options are provided.
90184**
90185** If the sqlite_statN tables do not previously exist, it is created.
90186**
90187** Argument zWhere may be a pointer to a buffer containing a table name,
90188** or it may be a NULL pointer. If it is not NULL, then all entries in
90189** the sqlite_statN tables associated with the named table are deleted.
90190** If zWhere==0, then code is generated to delete all stat table entries.
90191*/
90192static void openStatTable(
90193  Parse *pParse,          /* Parsing context */
90194  int iDb,                /* The database we are looking in */
90195  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
90196  const char *zWhere,     /* Delete entries for this table or index */
90197  const char *zWhereType  /* Either "tbl" or "idx" */
90198){
90199  static const struct {
90200    const char *zName;
90201    const char *zCols;
90202  } aTable[] = {
90203    { "sqlite_stat1", "tbl,idx,stat" },
90204#if defined(SQLITE_ENABLE_STAT4)
90205    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
90206    { "sqlite_stat3", 0 },
90207#elif defined(SQLITE_ENABLE_STAT3)
90208    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
90209    { "sqlite_stat4", 0 },
90210#else
90211    { "sqlite_stat3", 0 },
90212    { "sqlite_stat4", 0 },
90213#endif
90214  };
90215  int i;
90216  sqlite3 *db = pParse->db;
90217  Db *pDb;
90218  Vdbe *v = sqlite3GetVdbe(pParse);
90219  int aRoot[ArraySize(aTable)];
90220  u8 aCreateTbl[ArraySize(aTable)];
90221
90222  if( v==0 ) return;
90223  assert( sqlite3BtreeHoldsAllMutexes(db) );
90224  assert( sqlite3VdbeDb(v)==db );
90225  pDb = &db->aDb[iDb];
90226
90227  /* Create new statistic tables if they do not exist, or clear them
90228  ** if they do already exist.
90229  */
90230  for(i=0; i<ArraySize(aTable); i++){
90231    const char *zTab = aTable[i].zName;
90232    Table *pStat;
90233    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
90234      if( aTable[i].zCols ){
90235        /* The sqlite_statN table does not exist. Create it. Note that a
90236        ** side-effect of the CREATE TABLE statement is to leave the rootpage
90237        ** of the new table in register pParse->regRoot. This is important
90238        ** because the OpenWrite opcode below will be needing it. */
90239        sqlite3NestedParse(pParse,
90240            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
90241        );
90242        aRoot[i] = pParse->regRoot;
90243        aCreateTbl[i] = OPFLAG_P2ISREG;
90244      }
90245    }else{
90246      /* The table already exists. If zWhere is not NULL, delete all entries
90247      ** associated with the table zWhere. If zWhere is NULL, delete the
90248      ** entire contents of the table. */
90249      aRoot[i] = pStat->tnum;
90250      aCreateTbl[i] = 0;
90251      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
90252      if( zWhere ){
90253        sqlite3NestedParse(pParse,
90254           "DELETE FROM %Q.%s WHERE %s=%Q",
90255           pDb->zName, zTab, zWhereType, zWhere
90256        );
90257      }else{
90258        /* The sqlite_stat[134] table already exists.  Delete all rows. */
90259        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
90260      }
90261    }
90262  }
90263
90264  /* Open the sqlite_stat[134] tables for writing. */
90265  for(i=0; aTable[i].zCols; i++){
90266    assert( i<ArraySize(aTable) );
90267    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
90268    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
90269    VdbeComment((v, aTable[i].zName));
90270  }
90271}
90272
90273/*
90274** Recommended number of samples for sqlite_stat4
90275*/
90276#ifndef SQLITE_STAT4_SAMPLES
90277# define SQLITE_STAT4_SAMPLES 24
90278#endif
90279
90280/*
90281** Three SQL functions - stat_init(), stat_push(), and stat_get() -
90282** share an instance of the following structure to hold their state
90283** information.
90284*/
90285typedef struct Stat4Accum Stat4Accum;
90286typedef struct Stat4Sample Stat4Sample;
90287struct Stat4Sample {
90288  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
90289  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
90290#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90291  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
90292  union {
90293    i64 iRowid;                     /* Rowid in main table of the key */
90294    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
90295  } u;
90296  u32 nRowid;                     /* Sizeof aRowid[] */
90297  u8 isPSample;                   /* True if a periodic sample */
90298  int iCol;                       /* If !isPSample, the reason for inclusion */
90299  u32 iHash;                      /* Tiebreaker hash */
90300#endif
90301};
90302struct Stat4Accum {
90303  tRowcnt nRow;             /* Number of rows in the entire table */
90304  tRowcnt nPSample;         /* How often to do a periodic sample */
90305  int nCol;                 /* Number of columns in index + pk/rowid */
90306  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
90307  int mxSample;             /* Maximum number of samples to accumulate */
90308  Stat4Sample current;      /* Current row as a Stat4Sample */
90309  u32 iPrn;                 /* Pseudo-random number used for sampling */
90310  Stat4Sample *aBest;       /* Array of nCol best samples */
90311  int iMin;                 /* Index in a[] of entry with minimum score */
90312  int nSample;              /* Current number of samples */
90313  int iGet;                 /* Index of current sample accessed by stat_get() */
90314  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
90315  sqlite3 *db;              /* Database connection, for malloc() */
90316};
90317
90318/* Reclaim memory used by a Stat4Sample
90319*/
90320#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90321static void sampleClear(sqlite3 *db, Stat4Sample *p){
90322  assert( db!=0 );
90323  if( p->nRowid ){
90324    sqlite3DbFree(db, p->u.aRowid);
90325    p->nRowid = 0;
90326  }
90327}
90328#endif
90329
90330/* Initialize the BLOB value of a ROWID
90331*/
90332#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90333static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
90334  assert( db!=0 );
90335  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
90336  p->u.aRowid = sqlite3DbMallocRaw(db, n);
90337  if( p->u.aRowid ){
90338    p->nRowid = n;
90339    memcpy(p->u.aRowid, pData, n);
90340  }else{
90341    p->nRowid = 0;
90342  }
90343}
90344#endif
90345
90346/* Initialize the INTEGER value of a ROWID.
90347*/
90348#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90349static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
90350  assert( db!=0 );
90351  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
90352  p->nRowid = 0;
90353  p->u.iRowid = iRowid;
90354}
90355#endif
90356
90357
90358/*
90359** Copy the contents of object (*pFrom) into (*pTo).
90360*/
90361#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90362static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
90363  pTo->isPSample = pFrom->isPSample;
90364  pTo->iCol = pFrom->iCol;
90365  pTo->iHash = pFrom->iHash;
90366  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
90367  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
90368  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
90369  if( pFrom->nRowid ){
90370    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
90371  }else{
90372    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
90373  }
90374}
90375#endif
90376
90377/*
90378** Reclaim all memory of a Stat4Accum structure.
90379*/
90380static void stat4Destructor(void *pOld){
90381  Stat4Accum *p = (Stat4Accum*)pOld;
90382#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90383  int i;
90384  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
90385  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
90386  sampleClear(p->db, &p->current);
90387#endif
90388  sqlite3DbFree(p->db, p);
90389}
90390
90391/*
90392** Implementation of the stat_init(N,K,C) SQL function. The three parameters
90393** are:
90394**     N:    The number of columns in the index including the rowid/pk (note 1)
90395**     K:    The number of columns in the index excluding the rowid/pk.
90396**     C:    The number of rows in the index (note 2)
90397**
90398** Note 1:  In the special case of the covering index that implements a
90399** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
90400** total number of columns in the table.
90401**
90402** Note 2:  C is only used for STAT3 and STAT4.
90403**
90404** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
90405** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
90406** PRIMARY KEY of the table.  The covering index that implements the
90407** original WITHOUT ROWID table as N==K as a special case.
90408**
90409** This routine allocates the Stat4Accum object in heap memory. The return
90410** value is a pointer to the Stat4Accum object.  The datatype of the
90411** return value is BLOB, but it is really just a pointer to the Stat4Accum
90412** object.
90413*/
90414static void statInit(
90415  sqlite3_context *context,
90416  int argc,
90417  sqlite3_value **argv
90418){
90419  Stat4Accum *p;
90420  int nCol;                       /* Number of columns in index being sampled */
90421  int nKeyCol;                    /* Number of key columns */
90422  int nColUp;                     /* nCol rounded up for alignment */
90423  int n;                          /* Bytes of space to allocate */
90424  sqlite3 *db;                    /* Database connection */
90425#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90426  int mxSample = SQLITE_STAT4_SAMPLES;
90427#endif
90428
90429  /* Decode the three function arguments */
90430  UNUSED_PARAMETER(argc);
90431  nCol = sqlite3_value_int(argv[0]);
90432  assert( nCol>0 );
90433  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
90434  nKeyCol = sqlite3_value_int(argv[1]);
90435  assert( nKeyCol<=nCol );
90436  assert( nKeyCol>0 );
90437
90438  /* Allocate the space required for the Stat4Accum object */
90439  n = sizeof(*p)
90440    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
90441    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
90442#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90443    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
90444    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
90445    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
90446#endif
90447  ;
90448  db = sqlite3_context_db_handle(context);
90449  p = sqlite3DbMallocZero(db, n);
90450  if( p==0 ){
90451    sqlite3_result_error_nomem(context);
90452    return;
90453  }
90454
90455  p->db = db;
90456  p->nRow = 0;
90457  p->nCol = nCol;
90458  p->nKeyCol = nKeyCol;
90459  p->current.anDLt = (tRowcnt*)&p[1];
90460  p->current.anEq = &p->current.anDLt[nColUp];
90461
90462#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90463  {
90464    u8 *pSpace;                     /* Allocated space not yet assigned */
90465    int i;                          /* Used to iterate through p->aSample[] */
90466
90467    p->iGet = -1;
90468    p->mxSample = mxSample;
90469    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
90470    p->current.anLt = &p->current.anEq[nColUp];
90471    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
90472
90473    /* Set up the Stat4Accum.a[] and aBest[] arrays */
90474    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
90475    p->aBest = &p->a[mxSample];
90476    pSpace = (u8*)(&p->a[mxSample+nCol]);
90477    for(i=0; i<(mxSample+nCol); i++){
90478      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90479      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90480      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90481    }
90482    assert( (pSpace - (u8*)p)==n );
90483
90484    for(i=0; i<nCol; i++){
90485      p->aBest[i].iCol = i;
90486    }
90487  }
90488#endif
90489
90490  /* Return a pointer to the allocated object to the caller.  Note that
90491  ** only the pointer (the 2nd parameter) matters.  The size of the object
90492  ** (given by the 3rd parameter) is never used and can be any positive
90493  ** value. */
90494  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
90495}
90496static const FuncDef statInitFuncdef = {
90497  2+IsStat34,      /* nArg */
90498  SQLITE_UTF8,     /* funcFlags */
90499  0,               /* pUserData */
90500  0,               /* pNext */
90501  statInit,        /* xFunc */
90502  0,               /* xStep */
90503  0,               /* xFinalize */
90504  "stat_init",     /* zName */
90505  0,               /* pHash */
90506  0                /* pDestructor */
90507};
90508
90509#ifdef SQLITE_ENABLE_STAT4
90510/*
90511** pNew and pOld are both candidate non-periodic samples selected for
90512** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
90513** considering only any trailing columns and the sample hash value, this
90514** function returns true if sample pNew is to be preferred over pOld.
90515** In other words, if we assume that the cardinalities of the selected
90516** column for pNew and pOld are equal, is pNew to be preferred over pOld.
90517**
90518** This function assumes that for each argument sample, the contents of
90519** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
90520*/
90521static int sampleIsBetterPost(
90522  Stat4Accum *pAccum,
90523  Stat4Sample *pNew,
90524  Stat4Sample *pOld
90525){
90526  int nCol = pAccum->nCol;
90527  int i;
90528  assert( pNew->iCol==pOld->iCol );
90529  for(i=pNew->iCol+1; i<nCol; i++){
90530    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
90531    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
90532  }
90533  if( pNew->iHash>pOld->iHash ) return 1;
90534  return 0;
90535}
90536#endif
90537
90538#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90539/*
90540** Return true if pNew is to be preferred over pOld.
90541**
90542** This function assumes that for each argument sample, the contents of
90543** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
90544*/
90545static int sampleIsBetter(
90546  Stat4Accum *pAccum,
90547  Stat4Sample *pNew,
90548  Stat4Sample *pOld
90549){
90550  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
90551  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
90552
90553  assert( pOld->isPSample==0 && pNew->isPSample==0 );
90554  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
90555
90556  if( (nEqNew>nEqOld) ) return 1;
90557#ifdef SQLITE_ENABLE_STAT4
90558  if( nEqNew==nEqOld ){
90559    if( pNew->iCol<pOld->iCol ) return 1;
90560    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
90561  }
90562  return 0;
90563#else
90564  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
90565#endif
90566}
90567
90568/*
90569** Copy the contents of sample *pNew into the p->a[] array. If necessary,
90570** remove the least desirable sample from p->a[] to make room.
90571*/
90572static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
90573  Stat4Sample *pSample = 0;
90574  int i;
90575
90576  assert( IsStat4 || nEqZero==0 );
90577
90578#ifdef SQLITE_ENABLE_STAT4
90579  if( pNew->isPSample==0 ){
90580    Stat4Sample *pUpgrade = 0;
90581    assert( pNew->anEq[pNew->iCol]>0 );
90582
90583    /* This sample is being added because the prefix that ends in column
90584    ** iCol occurs many times in the table. However, if we have already
90585    ** added a sample that shares this prefix, there is no need to add
90586    ** this one. Instead, upgrade the priority of the highest priority
90587    ** existing sample that shares this prefix.  */
90588    for(i=p->nSample-1; i>=0; i--){
90589      Stat4Sample *pOld = &p->a[i];
90590      if( pOld->anEq[pNew->iCol]==0 ){
90591        if( pOld->isPSample ) return;
90592        assert( pOld->iCol>pNew->iCol );
90593        assert( sampleIsBetter(p, pNew, pOld) );
90594        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
90595          pUpgrade = pOld;
90596        }
90597      }
90598    }
90599    if( pUpgrade ){
90600      pUpgrade->iCol = pNew->iCol;
90601      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
90602      goto find_new_min;
90603    }
90604  }
90605#endif
90606
90607  /* If necessary, remove sample iMin to make room for the new sample. */
90608  if( p->nSample>=p->mxSample ){
90609    Stat4Sample *pMin = &p->a[p->iMin];
90610    tRowcnt *anEq = pMin->anEq;
90611    tRowcnt *anLt = pMin->anLt;
90612    tRowcnt *anDLt = pMin->anDLt;
90613    sampleClear(p->db, pMin);
90614    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
90615    pSample = &p->a[p->nSample-1];
90616    pSample->nRowid = 0;
90617    pSample->anEq = anEq;
90618    pSample->anDLt = anDLt;
90619    pSample->anLt = anLt;
90620    p->nSample = p->mxSample-1;
90621  }
90622
90623  /* The "rows less-than" for the rowid column must be greater than that
90624  ** for the last sample in the p->a[] array. Otherwise, the samples would
90625  ** be out of order. */
90626#ifdef SQLITE_ENABLE_STAT4
90627  assert( p->nSample==0
90628       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
90629#endif
90630
90631  /* Insert the new sample */
90632  pSample = &p->a[p->nSample];
90633  sampleCopy(p, pSample, pNew);
90634  p->nSample++;
90635
90636  /* Zero the first nEqZero entries in the anEq[] array. */
90637  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
90638
90639#ifdef SQLITE_ENABLE_STAT4
90640 find_new_min:
90641#endif
90642  if( p->nSample>=p->mxSample ){
90643    int iMin = -1;
90644    for(i=0; i<p->mxSample; i++){
90645      if( p->a[i].isPSample ) continue;
90646      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
90647        iMin = i;
90648      }
90649    }
90650    assert( iMin>=0 );
90651    p->iMin = iMin;
90652  }
90653}
90654#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
90655
90656/*
90657** Field iChng of the index being scanned has changed. So at this point
90658** p->current contains a sample that reflects the previous row of the
90659** index. The value of anEq[iChng] and subsequent anEq[] elements are
90660** correct at this point.
90661*/
90662static void samplePushPrevious(Stat4Accum *p, int iChng){
90663#ifdef SQLITE_ENABLE_STAT4
90664  int i;
90665
90666  /* Check if any samples from the aBest[] array should be pushed
90667  ** into IndexSample.a[] at this point.  */
90668  for(i=(p->nCol-2); i>=iChng; i--){
90669    Stat4Sample *pBest = &p->aBest[i];
90670    pBest->anEq[i] = p->current.anEq[i];
90671    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
90672      sampleInsert(p, pBest, i);
90673    }
90674  }
90675
90676  /* Update the anEq[] fields of any samples already collected. */
90677  for(i=p->nSample-1; i>=0; i--){
90678    int j;
90679    for(j=iChng; j<p->nCol; j++){
90680      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
90681    }
90682  }
90683#endif
90684
90685#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
90686  if( iChng==0 ){
90687    tRowcnt nLt = p->current.anLt[0];
90688    tRowcnt nEq = p->current.anEq[0];
90689
90690    /* Check if this is to be a periodic sample. If so, add it. */
90691    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
90692      p->current.isPSample = 1;
90693      sampleInsert(p, &p->current, 0);
90694      p->current.isPSample = 0;
90695    }else
90696
90697    /* Or if it is a non-periodic sample. Add it in this case too. */
90698    if( p->nSample<p->mxSample
90699     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
90700    ){
90701      sampleInsert(p, &p->current, 0);
90702    }
90703  }
90704#endif
90705
90706#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
90707  UNUSED_PARAMETER( p );
90708  UNUSED_PARAMETER( iChng );
90709#endif
90710}
90711
90712/*
90713** Implementation of the stat_push SQL function:  stat_push(P,C,R)
90714** Arguments:
90715**
90716**    P     Pointer to the Stat4Accum object created by stat_init()
90717**    C     Index of left-most column to differ from previous row
90718**    R     Rowid for the current row.  Might be a key record for
90719**          WITHOUT ROWID tables.
90720**
90721** This SQL function always returns NULL.  It's purpose it to accumulate
90722** statistical data and/or samples in the Stat4Accum object about the
90723** index being analyzed.  The stat_get() SQL function will later be used to
90724** extract relevant information for constructing the sqlite_statN tables.
90725**
90726** The R parameter is only used for STAT3 and STAT4
90727*/
90728static void statPush(
90729  sqlite3_context *context,
90730  int argc,
90731  sqlite3_value **argv
90732){
90733  int i;
90734
90735  /* The three function arguments */
90736  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
90737  int iChng = sqlite3_value_int(argv[1]);
90738
90739  UNUSED_PARAMETER( argc );
90740  UNUSED_PARAMETER( context );
90741  assert( p->nCol>0 );
90742  assert( iChng<p->nCol );
90743
90744  if( p->nRow==0 ){
90745    /* This is the first call to this function. Do initialization. */
90746    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
90747  }else{
90748    /* Second and subsequent calls get processed here */
90749    samplePushPrevious(p, iChng);
90750
90751    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
90752    ** to the current row of the index. */
90753    for(i=0; i<iChng; i++){
90754      p->current.anEq[i]++;
90755    }
90756    for(i=iChng; i<p->nCol; i++){
90757      p->current.anDLt[i]++;
90758#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90759      p->current.anLt[i] += p->current.anEq[i];
90760#endif
90761      p->current.anEq[i] = 1;
90762    }
90763  }
90764  p->nRow++;
90765#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90766  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
90767    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
90768  }else{
90769    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
90770                                       sqlite3_value_blob(argv[2]));
90771  }
90772  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
90773#endif
90774
90775#ifdef SQLITE_ENABLE_STAT4
90776  {
90777    tRowcnt nLt = p->current.anLt[p->nCol-1];
90778
90779    /* Check if this is to be a periodic sample. If so, add it. */
90780    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
90781      p->current.isPSample = 1;
90782      p->current.iCol = 0;
90783      sampleInsert(p, &p->current, p->nCol-1);
90784      p->current.isPSample = 0;
90785    }
90786
90787    /* Update the aBest[] array. */
90788    for(i=0; i<(p->nCol-1); i++){
90789      p->current.iCol = i;
90790      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
90791        sampleCopy(p, &p->aBest[i], &p->current);
90792      }
90793    }
90794  }
90795#endif
90796}
90797static const FuncDef statPushFuncdef = {
90798  2+IsStat34,      /* nArg */
90799  SQLITE_UTF8,     /* funcFlags */
90800  0,               /* pUserData */
90801  0,               /* pNext */
90802  statPush,        /* xFunc */
90803  0,               /* xStep */
90804  0,               /* xFinalize */
90805  "stat_push",     /* zName */
90806  0,               /* pHash */
90807  0                /* pDestructor */
90808};
90809
90810#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
90811#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
90812#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
90813#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
90814#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
90815
90816/*
90817** Implementation of the stat_get(P,J) SQL function.  This routine is
90818** used to query statistical information that has been gathered into
90819** the Stat4Accum object by prior calls to stat_push().  The P parameter
90820** has type BLOB but it is really just a pointer to the Stat4Accum object.
90821** The content to returned is determined by the parameter J
90822** which is one of the STAT_GET_xxxx values defined above.
90823**
90824** If neither STAT3 nor STAT4 are enabled, then J is always
90825** STAT_GET_STAT1 and is hence omitted and this routine becomes
90826** a one-parameter function, stat_get(P), that always returns the
90827** stat1 table entry information.
90828*/
90829static void statGet(
90830  sqlite3_context *context,
90831  int argc,
90832  sqlite3_value **argv
90833){
90834  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
90835#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90836  /* STAT3 and STAT4 have a parameter on this routine. */
90837  int eCall = sqlite3_value_int(argv[1]);
90838  assert( argc==2 );
90839  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
90840       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
90841       || eCall==STAT_GET_NDLT
90842  );
90843  if( eCall==STAT_GET_STAT1 )
90844#else
90845  assert( argc==1 );
90846#endif
90847  {
90848    /* Return the value to store in the "stat" column of the sqlite_stat1
90849    ** table for this index.
90850    **
90851    ** The value is a string composed of a list of integers describing
90852    ** the index. The first integer in the list is the total number of
90853    ** entries in the index. There is one additional integer in the list
90854    ** for each indexed column. This additional integer is an estimate of
90855    ** the number of rows matched by a stabbing query on the index using
90856    ** a key with the corresponding number of fields. In other words,
90857    ** if the index is on columns (a,b) and the sqlite_stat1 value is
90858    ** "100 10 2", then SQLite estimates that:
90859    **
90860    **   * the index contains 100 rows,
90861    **   * "WHERE a=?" matches 10 rows, and
90862    **   * "WHERE a=? AND b=?" matches 2 rows.
90863    **
90864    ** If D is the count of distinct values and K is the total number of
90865    ** rows, then each estimate is computed as:
90866    **
90867    **        I = (K+D-1)/D
90868    */
90869    char *z;
90870    int i;
90871
90872    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
90873    if( zRet==0 ){
90874      sqlite3_result_error_nomem(context);
90875      return;
90876    }
90877
90878    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
90879    z = zRet + sqlite3Strlen30(zRet);
90880    for(i=0; i<p->nKeyCol; i++){
90881      u64 nDistinct = p->current.anDLt[i] + 1;
90882      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
90883      sqlite3_snprintf(24, z, " %llu", iVal);
90884      z += sqlite3Strlen30(z);
90885      assert( p->current.anEq[i] );
90886    }
90887    assert( z[0]=='\0' && z>zRet );
90888
90889    sqlite3_result_text(context, zRet, -1, sqlite3_free);
90890  }
90891#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90892  else if( eCall==STAT_GET_ROWID ){
90893    if( p->iGet<0 ){
90894      samplePushPrevious(p, 0);
90895      p->iGet = 0;
90896    }
90897    if( p->iGet<p->nSample ){
90898      Stat4Sample *pS = p->a + p->iGet;
90899      if( pS->nRowid==0 ){
90900        sqlite3_result_int64(context, pS->u.iRowid);
90901      }else{
90902        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
90903                            SQLITE_TRANSIENT);
90904      }
90905    }
90906  }else{
90907    tRowcnt *aCnt = 0;
90908
90909    assert( p->iGet<p->nSample );
90910    switch( eCall ){
90911      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
90912      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
90913      default: {
90914        aCnt = p->a[p->iGet].anDLt;
90915        p->iGet++;
90916        break;
90917      }
90918    }
90919
90920    if( IsStat3 ){
90921      sqlite3_result_int64(context, (i64)aCnt[0]);
90922    }else{
90923      char *zRet = sqlite3MallocZero(p->nCol * 25);
90924      if( zRet==0 ){
90925        sqlite3_result_error_nomem(context);
90926      }else{
90927        int i;
90928        char *z = zRet;
90929        for(i=0; i<p->nCol; i++){
90930          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
90931          z += sqlite3Strlen30(z);
90932        }
90933        assert( z[0]=='\0' && z>zRet );
90934        z[-1] = '\0';
90935        sqlite3_result_text(context, zRet, -1, sqlite3_free);
90936      }
90937    }
90938  }
90939#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
90940#ifndef SQLITE_DEBUG
90941  UNUSED_PARAMETER( argc );
90942#endif
90943}
90944static const FuncDef statGetFuncdef = {
90945  1+IsStat34,      /* nArg */
90946  SQLITE_UTF8,     /* funcFlags */
90947  0,               /* pUserData */
90948  0,               /* pNext */
90949  statGet,         /* xFunc */
90950  0,               /* xStep */
90951  0,               /* xFinalize */
90952  "stat_get",      /* zName */
90953  0,               /* pHash */
90954  0                /* pDestructor */
90955};
90956
90957static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
90958  assert( regOut!=regStat4 && regOut!=regStat4+1 );
90959#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90960  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
90961#elif SQLITE_DEBUG
90962  assert( iParam==STAT_GET_STAT1 );
90963#else
90964  UNUSED_PARAMETER( iParam );
90965#endif
90966  sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4, regOut);
90967  sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
90968  sqlite3VdbeChangeP5(v, 1 + IsStat34);
90969}
90970
90971/*
90972** Generate code to do an analysis of all indices associated with
90973** a single table.
90974*/
90975static void analyzeOneTable(
90976  Parse *pParse,   /* Parser context */
90977  Table *pTab,     /* Table whose indices are to be analyzed */
90978  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
90979  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
90980  int iMem,        /* Available memory locations begin here */
90981  int iTab         /* Next available cursor */
90982){
90983  sqlite3 *db = pParse->db;    /* Database handle */
90984  Index *pIdx;                 /* An index to being analyzed */
90985  int iIdxCur;                 /* Cursor open on index being analyzed */
90986  int iTabCur;                 /* Table cursor */
90987  Vdbe *v;                     /* The virtual machine being built up */
90988  int i;                       /* Loop counter */
90989  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
90990  int iDb;                     /* Index of database containing pTab */
90991  u8 needTableCnt = 1;         /* True to count the table */
90992  int regNewRowid = iMem++;    /* Rowid for the inserted record */
90993  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
90994  int regChng = iMem++;        /* Index of changed index field */
90995#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90996  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
90997#endif
90998  int regTemp = iMem++;        /* Temporary use register */
90999  int regTabname = iMem++;     /* Register containing table name */
91000  int regIdxname = iMem++;     /* Register containing index name */
91001  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
91002  int regPrev = iMem;          /* MUST BE LAST (see below) */
91003
91004  pParse->nMem = MAX(pParse->nMem, iMem);
91005  v = sqlite3GetVdbe(pParse);
91006  if( v==0 || NEVER(pTab==0) ){
91007    return;
91008  }
91009  if( pTab->tnum==0 ){
91010    /* Do not gather statistics on views or virtual tables */
91011    return;
91012  }
91013  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
91014    /* Do not gather statistics on system tables */
91015    return;
91016  }
91017  assert( sqlite3BtreeHoldsAllMutexes(db) );
91018  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91019  assert( iDb>=0 );
91020  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91021#ifndef SQLITE_OMIT_AUTHORIZATION
91022  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
91023      db->aDb[iDb].zName ) ){
91024    return;
91025  }
91026#endif
91027
91028  /* Establish a read-lock on the table at the shared-cache level.
91029  ** Open a read-only cursor on the table. Also allocate a cursor number
91030  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
91031  ** this time though.  */
91032  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91033  iTabCur = iTab++;
91034  iIdxCur = iTab++;
91035  pParse->nTab = MAX(pParse->nTab, iTab);
91036  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
91037  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
91038
91039  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91040    int nCol;                     /* Number of columns in pIdx. "N" */
91041    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
91042    int addrNextRow;              /* Address of "next_row:" */
91043    const char *zIdxName;         /* Name of the index */
91044    int nColTest;                 /* Number of columns to test for changes */
91045
91046    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
91047    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
91048    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
91049      nCol = pIdx->nKeyCol;
91050      zIdxName = pTab->zName;
91051      nColTest = nCol - 1;
91052    }else{
91053      nCol = pIdx->nColumn;
91054      zIdxName = pIdx->zName;
91055      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
91056    }
91057
91058    /* Populate the register containing the index name. */
91059    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
91060    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
91061
91062    /*
91063    ** Pseudo-code for loop that calls stat_push():
91064    **
91065    **   Rewind csr
91066    **   if eof(csr) goto end_of_scan;
91067    **   regChng = 0
91068    **   goto chng_addr_0;
91069    **
91070    **  next_row:
91071    **   regChng = 0
91072    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
91073    **   regChng = 1
91074    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
91075    **   ...
91076    **   regChng = N
91077    **   goto chng_addr_N
91078    **
91079    **  chng_addr_0:
91080    **   regPrev(0) = idx(0)
91081    **  chng_addr_1:
91082    **   regPrev(1) = idx(1)
91083    **  ...
91084    **
91085    **  endDistinctTest:
91086    **   regRowid = idx(rowid)
91087    **   stat_push(P, regChng, regRowid)
91088    **   Next csr
91089    **   if !eof(csr) goto next_row;
91090    **
91091    **  end_of_scan:
91092    */
91093
91094    /* Make sure there are enough memory cells allocated to accommodate
91095    ** the regPrev array and a trailing rowid (the rowid slot is required
91096    ** when building a record to insert into the sample column of
91097    ** the sqlite_stat4 table.  */
91098    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
91099
91100    /* Open a read-only cursor on the index being analyzed. */
91101    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
91102    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
91103    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91104    VdbeComment((v, "%s", pIdx->zName));
91105
91106    /* Invoke the stat_init() function. The arguments are:
91107    **
91108    **    (1) the number of columns in the index including the rowid
91109    **        (or for a WITHOUT ROWID table, the number of PK columns),
91110    **    (2) the number of columns in the key without the rowid/pk
91111    **    (3) the number of rows in the index,
91112    **
91113    **
91114    ** The third argument is only used for STAT3 and STAT4
91115    */
91116#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91117    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
91118#endif
91119    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
91120    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
91121    sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4+1, regStat4);
91122    sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
91123    sqlite3VdbeChangeP5(v, 2+IsStat34);
91124
91125    /* Implementation of the following:
91126    **
91127    **   Rewind csr
91128    **   if eof(csr) goto end_of_scan;
91129    **   regChng = 0
91130    **   goto next_push_0;
91131    **
91132    */
91133    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
91134    VdbeCoverage(v);
91135    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
91136    addrNextRow = sqlite3VdbeCurrentAddr(v);
91137
91138    if( nColTest>0 ){
91139      int endDistinctTest = sqlite3VdbeMakeLabel(v);
91140      int *aGotoChng;               /* Array of jump instruction addresses */
91141      aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
91142      if( aGotoChng==0 ) continue;
91143
91144      /*
91145      **  next_row:
91146      **   regChng = 0
91147      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
91148      **   regChng = 1
91149      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
91150      **   ...
91151      **   regChng = N
91152      **   goto endDistinctTest
91153      */
91154      sqlite3VdbeAddOp0(v, OP_Goto);
91155      addrNextRow = sqlite3VdbeCurrentAddr(v);
91156      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
91157        /* For a single-column UNIQUE index, once we have found a non-NULL
91158        ** row, we know that all the rest will be distinct, so skip
91159        ** subsequent distinctness tests. */
91160        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
91161        VdbeCoverage(v);
91162      }
91163      for(i=0; i<nColTest; i++){
91164        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
91165        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
91166        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
91167        aGotoChng[i] =
91168        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
91169        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
91170        VdbeCoverage(v);
91171      }
91172      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
91173      sqlite3VdbeGoto(v, endDistinctTest);
91174
91175
91176      /*
91177      **  chng_addr_0:
91178      **   regPrev(0) = idx(0)
91179      **  chng_addr_1:
91180      **   regPrev(1) = idx(1)
91181      **  ...
91182      */
91183      sqlite3VdbeJumpHere(v, addrNextRow-1);
91184      for(i=0; i<nColTest; i++){
91185        sqlite3VdbeJumpHere(v, aGotoChng[i]);
91186        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
91187      }
91188      sqlite3VdbeResolveLabel(v, endDistinctTest);
91189      sqlite3DbFree(db, aGotoChng);
91190    }
91191
91192    /*
91193    **  chng_addr_N:
91194    **   regRowid = idx(rowid)            // STAT34 only
91195    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
91196    **   Next csr
91197    **   if !eof(csr) goto next_row;
91198    */
91199#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91200    assert( regRowid==(regStat4+2) );
91201    if( HasRowid(pTab) ){
91202      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
91203    }else{
91204      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
91205      int j, k, regKey;
91206      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
91207      for(j=0; j<pPk->nKeyCol; j++){
91208        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
91209        assert( k>=0 && k<pTab->nCol );
91210        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
91211        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
91212      }
91213      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
91214      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
91215    }
91216#endif
91217    assert( regChng==(regStat4+1) );
91218    sqlite3VdbeAddOp3(v, OP_Function0, 1, regStat4, regTemp);
91219    sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
91220    sqlite3VdbeChangeP5(v, 2+IsStat34);
91221    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
91222
91223    /* Add the entry to the stat1 table. */
91224    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
91225    assert( "BBB"[0]==SQLITE_AFF_TEXT );
91226    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
91227    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
91228    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
91229    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91230
91231    /* Add the entries to the stat3 or stat4 table. */
91232#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91233    {
91234      int regEq = regStat1;
91235      int regLt = regStat1+1;
91236      int regDLt = regStat1+2;
91237      int regSample = regStat1+3;
91238      int regCol = regStat1+4;
91239      int regSampleRowid = regCol + nCol;
91240      int addrNext;
91241      int addrIsNull;
91242      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
91243
91244      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
91245
91246      addrNext = sqlite3VdbeCurrentAddr(v);
91247      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
91248      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
91249      VdbeCoverage(v);
91250      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
91251      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
91252      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
91253      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
91254      /* We know that the regSampleRowid row exists because it was read by
91255      ** the previous loop.  Thus the not-found jump of seekOp will never
91256      ** be taken */
91257      VdbeCoverageNeverTaken(v);
91258#ifdef SQLITE_ENABLE_STAT3
91259      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
91260#else
91261      for(i=0; i<nCol; i++){
91262        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
91263      }
91264      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
91265#endif
91266      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
91267      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
91268      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
91269      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
91270      sqlite3VdbeJumpHere(v, addrIsNull);
91271    }
91272#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91273
91274    /* End of analysis */
91275    sqlite3VdbeJumpHere(v, addrRewind);
91276  }
91277
91278
91279  /* Create a single sqlite_stat1 entry containing NULL as the index
91280  ** name and the row count as the content.
91281  */
91282  if( pOnlyIdx==0 && needTableCnt ){
91283    VdbeComment((v, "%s", pTab->zName));
91284    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
91285    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
91286    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
91287    assert( "BBB"[0]==SQLITE_AFF_TEXT );
91288    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
91289    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
91290    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
91291    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91292    sqlite3VdbeJumpHere(v, jZeroRows);
91293  }
91294}
91295
91296
91297/*
91298** Generate code that will cause the most recent index analysis to
91299** be loaded into internal hash tables where is can be used.
91300*/
91301static void loadAnalysis(Parse *pParse, int iDb){
91302  Vdbe *v = sqlite3GetVdbe(pParse);
91303  if( v ){
91304    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
91305  }
91306}
91307
91308/*
91309** Generate code that will do an analysis of an entire database
91310*/
91311static void analyzeDatabase(Parse *pParse, int iDb){
91312  sqlite3 *db = pParse->db;
91313  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
91314  HashElem *k;
91315  int iStatCur;
91316  int iMem;
91317  int iTab;
91318
91319  sqlite3BeginWriteOperation(pParse, 0, iDb);
91320  iStatCur = pParse->nTab;
91321  pParse->nTab += 3;
91322  openStatTable(pParse, iDb, iStatCur, 0, 0);
91323  iMem = pParse->nMem+1;
91324  iTab = pParse->nTab;
91325  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91326  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
91327    Table *pTab = (Table*)sqliteHashData(k);
91328    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
91329  }
91330  loadAnalysis(pParse, iDb);
91331}
91332
91333/*
91334** Generate code that will do an analysis of a single table in
91335** a database.  If pOnlyIdx is not NULL then it is a single index
91336** in pTab that should be analyzed.
91337*/
91338static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
91339  int iDb;
91340  int iStatCur;
91341
91342  assert( pTab!=0 );
91343  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
91344  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91345  sqlite3BeginWriteOperation(pParse, 0, iDb);
91346  iStatCur = pParse->nTab;
91347  pParse->nTab += 3;
91348  if( pOnlyIdx ){
91349    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
91350  }else{
91351    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
91352  }
91353  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
91354  loadAnalysis(pParse, iDb);
91355}
91356
91357/*
91358** Generate code for the ANALYZE command.  The parser calls this routine
91359** when it recognizes an ANALYZE command.
91360**
91361**        ANALYZE                            -- 1
91362**        ANALYZE  <database>                -- 2
91363**        ANALYZE  ?<database>.?<tablename>  -- 3
91364**
91365** Form 1 causes all indices in all attached databases to be analyzed.
91366** Form 2 analyzes all indices the single database named.
91367** Form 3 analyzes all indices associated with the named table.
91368*/
91369SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
91370  sqlite3 *db = pParse->db;
91371  int iDb;
91372  int i;
91373  char *z, *zDb;
91374  Table *pTab;
91375  Index *pIdx;
91376  Token *pTableName;
91377  Vdbe *v;
91378
91379  /* Read the database schema. If an error occurs, leave an error message
91380  ** and code in pParse and return NULL. */
91381  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
91382  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91383    return;
91384  }
91385
91386  assert( pName2!=0 || pName1==0 );
91387  if( pName1==0 ){
91388    /* Form 1:  Analyze everything */
91389    for(i=0; i<db->nDb; i++){
91390      if( i==1 ) continue;  /* Do not analyze the TEMP database */
91391      analyzeDatabase(pParse, i);
91392    }
91393  }else if( pName2->n==0 ){
91394    /* Form 2:  Analyze the database or table named */
91395    iDb = sqlite3FindDb(db, pName1);
91396    if( iDb>=0 ){
91397      analyzeDatabase(pParse, iDb);
91398    }else{
91399      z = sqlite3NameFromToken(db, pName1);
91400      if( z ){
91401        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
91402          analyzeTable(pParse, pIdx->pTable, pIdx);
91403        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
91404          analyzeTable(pParse, pTab, 0);
91405        }
91406        sqlite3DbFree(db, z);
91407      }
91408    }
91409  }else{
91410    /* Form 3: Analyze the fully qualified table name */
91411    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
91412    if( iDb>=0 ){
91413      zDb = db->aDb[iDb].zName;
91414      z = sqlite3NameFromToken(db, pTableName);
91415      if( z ){
91416        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
91417          analyzeTable(pParse, pIdx->pTable, pIdx);
91418        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
91419          analyzeTable(pParse, pTab, 0);
91420        }
91421        sqlite3DbFree(db, z);
91422      }
91423    }
91424  }
91425  v = sqlite3GetVdbe(pParse);
91426  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
91427}
91428
91429/*
91430** Used to pass information from the analyzer reader through to the
91431** callback routine.
91432*/
91433typedef struct analysisInfo analysisInfo;
91434struct analysisInfo {
91435  sqlite3 *db;
91436  const char *zDatabase;
91437};
91438
91439/*
91440** The first argument points to a nul-terminated string containing a
91441** list of space separated integers. Read the first nOut of these into
91442** the array aOut[].
91443*/
91444static void decodeIntArray(
91445  char *zIntArray,       /* String containing int array to decode */
91446  int nOut,              /* Number of slots in aOut[] */
91447  tRowcnt *aOut,         /* Store integers here */
91448  LogEst *aLog,          /* Or, if aOut==0, here */
91449  Index *pIndex          /* Handle extra flags for this index, if not NULL */
91450){
91451  char *z = zIntArray;
91452  int c;
91453  int i;
91454  tRowcnt v;
91455
91456#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91457  if( z==0 ) z = "";
91458#else
91459  assert( z!=0 );
91460#endif
91461  for(i=0; *z && i<nOut; i++){
91462    v = 0;
91463    while( (c=z[0])>='0' && c<='9' ){
91464      v = v*10 + c - '0';
91465      z++;
91466    }
91467#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91468    if( aOut ) aOut[i] = v;
91469    if( aLog ) aLog[i] = sqlite3LogEst(v);
91470#else
91471    assert( aOut==0 );
91472    UNUSED_PARAMETER(aOut);
91473    assert( aLog!=0 );
91474    aLog[i] = sqlite3LogEst(v);
91475#endif
91476    if( *z==' ' ) z++;
91477  }
91478#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
91479  assert( pIndex!=0 ); {
91480#else
91481  if( pIndex ){
91482#endif
91483    pIndex->bUnordered = 0;
91484    pIndex->noSkipScan = 0;
91485    while( z[0] ){
91486      if( sqlite3_strglob("unordered*", z)==0 ){
91487        pIndex->bUnordered = 1;
91488      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
91489        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
91490      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
91491        pIndex->noSkipScan = 1;
91492      }
91493#ifdef SQLITE_ENABLE_COSTMULT
91494      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
91495        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
91496      }
91497#endif
91498      while( z[0]!=0 && z[0]!=' ' ) z++;
91499      while( z[0]==' ' ) z++;
91500    }
91501  }
91502}
91503
91504/*
91505** This callback is invoked once for each index when reading the
91506** sqlite_stat1 table.
91507**
91508**     argv[0] = name of the table
91509**     argv[1] = name of the index (might be NULL)
91510**     argv[2] = results of analysis - on integer for each column
91511**
91512** Entries for which argv[1]==NULL simply record the number of rows in
91513** the table.
91514*/
91515static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
91516  analysisInfo *pInfo = (analysisInfo*)pData;
91517  Index *pIndex;
91518  Table *pTable;
91519  const char *z;
91520
91521  assert( argc==3 );
91522  UNUSED_PARAMETER2(NotUsed, argc);
91523
91524  if( argv==0 || argv[0]==0 || argv[2]==0 ){
91525    return 0;
91526  }
91527  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
91528  if( pTable==0 ){
91529    return 0;
91530  }
91531  if( argv[1]==0 ){
91532    pIndex = 0;
91533  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
91534    pIndex = sqlite3PrimaryKeyIndex(pTable);
91535  }else{
91536    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
91537  }
91538  z = argv[2];
91539
91540  if( pIndex ){
91541    tRowcnt *aiRowEst = 0;
91542    int nCol = pIndex->nKeyCol+1;
91543#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91544    /* Index.aiRowEst may already be set here if there are duplicate
91545    ** sqlite_stat1 entries for this index. In that case just clobber
91546    ** the old data with the new instead of allocating a new array.  */
91547    if( pIndex->aiRowEst==0 ){
91548      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
91549      if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
91550    }
91551    aiRowEst = pIndex->aiRowEst;
91552#endif
91553    pIndex->bUnordered = 0;
91554    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
91555    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
91556  }else{
91557    Index fakeIdx;
91558    fakeIdx.szIdxRow = pTable->szTabRow;
91559#ifdef SQLITE_ENABLE_COSTMULT
91560    fakeIdx.pTable = pTable;
91561#endif
91562    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
91563    pTable->szTabRow = fakeIdx.szIdxRow;
91564  }
91565
91566  return 0;
91567}
91568
91569/*
91570** If the Index.aSample variable is not NULL, delete the aSample[] array
91571** and its contents.
91572*/
91573SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
91574#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91575  if( pIdx->aSample ){
91576    int j;
91577    for(j=0; j<pIdx->nSample; j++){
91578      IndexSample *p = &pIdx->aSample[j];
91579      sqlite3DbFree(db, p->p);
91580    }
91581    sqlite3DbFree(db, pIdx->aSample);
91582  }
91583  if( db && db->pnBytesFreed==0 ){
91584    pIdx->nSample = 0;
91585    pIdx->aSample = 0;
91586  }
91587#else
91588  UNUSED_PARAMETER(db);
91589  UNUSED_PARAMETER(pIdx);
91590#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91591}
91592
91593#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91594/*
91595** Populate the pIdx->aAvgEq[] array based on the samples currently
91596** stored in pIdx->aSample[].
91597*/
91598static void initAvgEq(Index *pIdx){
91599  if( pIdx ){
91600    IndexSample *aSample = pIdx->aSample;
91601    IndexSample *pFinal = &aSample[pIdx->nSample-1];
91602    int iCol;
91603    int nCol = 1;
91604    if( pIdx->nSampleCol>1 ){
91605      /* If this is stat4 data, then calculate aAvgEq[] values for all
91606      ** sample columns except the last. The last is always set to 1, as
91607      ** once the trailing PK fields are considered all index keys are
91608      ** unique.  */
91609      nCol = pIdx->nSampleCol-1;
91610      pIdx->aAvgEq[nCol] = 1;
91611    }
91612    for(iCol=0; iCol<nCol; iCol++){
91613      int nSample = pIdx->nSample;
91614      int i;                    /* Used to iterate through samples */
91615      tRowcnt sumEq = 0;        /* Sum of the nEq values */
91616      tRowcnt avgEq = 0;
91617      tRowcnt nRow;             /* Number of rows in index */
91618      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
91619      i64 nDist100;             /* Number of distinct values in index */
91620
91621      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
91622        nRow = pFinal->anLt[iCol];
91623        nDist100 = (i64)100 * pFinal->anDLt[iCol];
91624        nSample--;
91625      }else{
91626        nRow = pIdx->aiRowEst[0];
91627        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
91628      }
91629      pIdx->nRowEst0 = nRow;
91630
91631      /* Set nSum to the number of distinct (iCol+1) field prefixes that
91632      ** occur in the stat4 table for this index. Set sumEq to the sum of
91633      ** the nEq values for column iCol for the same set (adding the value
91634      ** only once where there exist duplicate prefixes).  */
91635      for(i=0; i<nSample; i++){
91636        if( i==(pIdx->nSample-1)
91637         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
91638        ){
91639          sumEq += aSample[i].anEq[iCol];
91640          nSum100 += 100;
91641        }
91642      }
91643
91644      if( nDist100>nSum100 ){
91645        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
91646      }
91647      if( avgEq==0 ) avgEq = 1;
91648      pIdx->aAvgEq[iCol] = avgEq;
91649    }
91650  }
91651}
91652
91653/*
91654** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
91655** is supplied instead, find the PRIMARY KEY index for that table.
91656*/
91657static Index *findIndexOrPrimaryKey(
91658  sqlite3 *db,
91659  const char *zName,
91660  const char *zDb
91661){
91662  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
91663  if( pIdx==0 ){
91664    Table *pTab = sqlite3FindTable(db, zName, zDb);
91665    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
91666  }
91667  return pIdx;
91668}
91669
91670/*
91671** Load the content from either the sqlite_stat4 or sqlite_stat3 table
91672** into the relevant Index.aSample[] arrays.
91673**
91674** Arguments zSql1 and zSql2 must point to SQL statements that return
91675** data equivalent to the following (statements are different for stat3,
91676** see the caller of this function for details):
91677**
91678**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
91679**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
91680**
91681** where %Q is replaced with the database name before the SQL is executed.
91682*/
91683static int loadStatTbl(
91684  sqlite3 *db,                  /* Database handle */
91685  int bStat3,                   /* Assume single column records only */
91686  const char *zSql1,            /* SQL statement 1 (see above) */
91687  const char *zSql2,            /* SQL statement 2 (see above) */
91688  const char *zDb               /* Database name (e.g. "main") */
91689){
91690  int rc;                       /* Result codes from subroutines */
91691  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
91692  char *zSql;                   /* Text of the SQL statement */
91693  Index *pPrevIdx = 0;          /* Previous index in the loop */
91694  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
91695
91696  assert( db->lookaside.bEnabled==0 );
91697  zSql = sqlite3MPrintf(db, zSql1, zDb);
91698  if( !zSql ){
91699    return SQLITE_NOMEM;
91700  }
91701  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
91702  sqlite3DbFree(db, zSql);
91703  if( rc ) return rc;
91704
91705  while( sqlite3_step(pStmt)==SQLITE_ROW ){
91706    int nIdxCol = 1;              /* Number of columns in stat4 records */
91707
91708    char *zIndex;   /* Index name */
91709    Index *pIdx;    /* Pointer to the index object */
91710    int nSample;    /* Number of samples */
91711    int nByte;      /* Bytes of space required */
91712    int i;          /* Bytes of space required */
91713    tRowcnt *pSpace;
91714
91715    zIndex = (char *)sqlite3_column_text(pStmt, 0);
91716    if( zIndex==0 ) continue;
91717    nSample = sqlite3_column_int(pStmt, 1);
91718    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
91719    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
91720    /* Index.nSample is non-zero at this point if data has already been
91721    ** loaded from the stat4 table. In this case ignore stat3 data.  */
91722    if( pIdx==0 || pIdx->nSample ) continue;
91723    if( bStat3==0 ){
91724      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
91725      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
91726        nIdxCol = pIdx->nKeyCol;
91727      }else{
91728        nIdxCol = pIdx->nColumn;
91729      }
91730    }
91731    pIdx->nSampleCol = nIdxCol;
91732    nByte = sizeof(IndexSample) * nSample;
91733    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
91734    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
91735
91736    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
91737    if( pIdx->aSample==0 ){
91738      sqlite3_finalize(pStmt);
91739      return SQLITE_NOMEM;
91740    }
91741    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
91742    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
91743    for(i=0; i<nSample; i++){
91744      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
91745      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
91746      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
91747    }
91748    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
91749  }
91750  rc = sqlite3_finalize(pStmt);
91751  if( rc ) return rc;
91752
91753  zSql = sqlite3MPrintf(db, zSql2, zDb);
91754  if( !zSql ){
91755    return SQLITE_NOMEM;
91756  }
91757  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
91758  sqlite3DbFree(db, zSql);
91759  if( rc ) return rc;
91760
91761  while( sqlite3_step(pStmt)==SQLITE_ROW ){
91762    char *zIndex;                 /* Index name */
91763    Index *pIdx;                  /* Pointer to the index object */
91764    int nCol = 1;                 /* Number of columns in index */
91765
91766    zIndex = (char *)sqlite3_column_text(pStmt, 0);
91767    if( zIndex==0 ) continue;
91768    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
91769    if( pIdx==0 ) continue;
91770    /* This next condition is true if data has already been loaded from
91771    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
91772    nCol = pIdx->nSampleCol;
91773    if( bStat3 && nCol>1 ) continue;
91774    if( pIdx!=pPrevIdx ){
91775      initAvgEq(pPrevIdx);
91776      pPrevIdx = pIdx;
91777    }
91778    pSample = &pIdx->aSample[pIdx->nSample];
91779    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
91780    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
91781    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
91782
91783    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
91784    ** This is in case the sample record is corrupted. In that case, the
91785    ** sqlite3VdbeRecordCompare() may read up to two varints past the
91786    ** end of the allocated buffer before it realizes it is dealing with
91787    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
91788    ** a buffer overread.  */
91789    pSample->n = sqlite3_column_bytes(pStmt, 4);
91790    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
91791    if( pSample->p==0 ){
91792      sqlite3_finalize(pStmt);
91793      return SQLITE_NOMEM;
91794    }
91795    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
91796    pIdx->nSample++;
91797  }
91798  rc = sqlite3_finalize(pStmt);
91799  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
91800  return rc;
91801}
91802
91803/*
91804** Load content from the sqlite_stat4 and sqlite_stat3 tables into
91805** the Index.aSample[] arrays of all indices.
91806*/
91807static int loadStat4(sqlite3 *db, const char *zDb){
91808  int rc = SQLITE_OK;             /* Result codes from subroutines */
91809
91810  assert( db->lookaside.bEnabled==0 );
91811  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
91812    rc = loadStatTbl(db, 0,
91813      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
91814      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
91815      zDb
91816    );
91817  }
91818
91819  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
91820    rc = loadStatTbl(db, 1,
91821      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
91822      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
91823      zDb
91824    );
91825  }
91826
91827  return rc;
91828}
91829#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91830
91831/*
91832** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
91833** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
91834** arrays. The contents of sqlite_stat3/4 are used to populate the
91835** Index.aSample[] arrays.
91836**
91837** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
91838** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
91839** during compilation and the sqlite_stat3/4 table is present, no data is
91840** read from it.
91841**
91842** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
91843** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
91844** returned. However, in this case, data is read from the sqlite_stat1
91845** table (if it is present) before returning.
91846**
91847** If an OOM error occurs, this function always sets db->mallocFailed.
91848** This means if the caller does not care about other errors, the return
91849** code may be ignored.
91850*/
91851SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
91852  analysisInfo sInfo;
91853  HashElem *i;
91854  char *zSql;
91855  int rc;
91856
91857  assert( iDb>=0 && iDb<db->nDb );
91858  assert( db->aDb[iDb].pBt!=0 );
91859
91860  /* Clear any prior statistics */
91861  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91862  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
91863    Index *pIdx = sqliteHashData(i);
91864    sqlite3DefaultRowEst(pIdx);
91865#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91866    sqlite3DeleteIndexSamples(db, pIdx);
91867    pIdx->aSample = 0;
91868#endif
91869  }
91870
91871  /* Check to make sure the sqlite_stat1 table exists */
91872  sInfo.db = db;
91873  sInfo.zDatabase = db->aDb[iDb].zName;
91874  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
91875    return SQLITE_ERROR;
91876  }
91877
91878  /* Load new statistics out of the sqlite_stat1 table */
91879  zSql = sqlite3MPrintf(db,
91880      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
91881  if( zSql==0 ){
91882    rc = SQLITE_NOMEM;
91883  }else{
91884    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
91885    sqlite3DbFree(db, zSql);
91886  }
91887
91888
91889  /* Load the statistics from the sqlite_stat4 table. */
91890#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91891  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
91892    int lookasideEnabled = db->lookaside.bEnabled;
91893    db->lookaside.bEnabled = 0;
91894    rc = loadStat4(db, sInfo.zDatabase);
91895    db->lookaside.bEnabled = lookasideEnabled;
91896  }
91897  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
91898    Index *pIdx = sqliteHashData(i);
91899    sqlite3_free(pIdx->aiRowEst);
91900    pIdx->aiRowEst = 0;
91901  }
91902#endif
91903
91904  if( rc==SQLITE_NOMEM ){
91905    db->mallocFailed = 1;
91906  }
91907  return rc;
91908}
91909
91910
91911#endif /* SQLITE_OMIT_ANALYZE */
91912
91913/************** End of analyze.c *********************************************/
91914/************** Begin file attach.c ******************************************/
91915/*
91916** 2003 April 6
91917**
91918** The author disclaims copyright to this source code.  In place of
91919** a legal notice, here is a blessing:
91920**
91921**    May you do good and not evil.
91922**    May you find forgiveness for yourself and forgive others.
91923**    May you share freely, never taking more than you give.
91924**
91925*************************************************************************
91926** This file contains code used to implement the ATTACH and DETACH commands.
91927*/
91928/* #include "sqliteInt.h" */
91929
91930#ifndef SQLITE_OMIT_ATTACH
91931/*
91932** Resolve an expression that was part of an ATTACH or DETACH statement. This
91933** is slightly different from resolving a normal SQL expression, because simple
91934** identifiers are treated as strings, not possible column names or aliases.
91935**
91936** i.e. if the parser sees:
91937**
91938**     ATTACH DATABASE abc AS def
91939**
91940** it treats the two expressions as literal strings 'abc' and 'def' instead of
91941** looking for columns of the same name.
91942**
91943** This only applies to the root node of pExpr, so the statement:
91944**
91945**     ATTACH DATABASE abc||def AS 'db2'
91946**
91947** will fail because neither abc or def can be resolved.
91948*/
91949static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
91950{
91951  int rc = SQLITE_OK;
91952  if( pExpr ){
91953    if( pExpr->op!=TK_ID ){
91954      rc = sqlite3ResolveExprNames(pName, pExpr);
91955    }else{
91956      pExpr->op = TK_STRING;
91957    }
91958  }
91959  return rc;
91960}
91961
91962/*
91963** An SQL user-function registered to do the work of an ATTACH statement. The
91964** three arguments to the function come directly from an attach statement:
91965**
91966**     ATTACH DATABASE x AS y KEY z
91967**
91968**     SELECT sqlite_attach(x, y, z)
91969**
91970** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
91971** third argument.
91972*/
91973static void attachFunc(
91974  sqlite3_context *context,
91975  int NotUsed,
91976  sqlite3_value **argv
91977){
91978  int i;
91979  int rc = 0;
91980  sqlite3 *db = sqlite3_context_db_handle(context);
91981  const char *zName;
91982  const char *zFile;
91983  char *zPath = 0;
91984  char *zErr = 0;
91985  unsigned int flags;
91986  Db *aNew;
91987  char *zErrDyn = 0;
91988  sqlite3_vfs *pVfs;
91989
91990  UNUSED_PARAMETER(NotUsed);
91991
91992  zFile = (const char *)sqlite3_value_text(argv[0]);
91993  zName = (const char *)sqlite3_value_text(argv[1]);
91994  if( zFile==0 ) zFile = "";
91995  if( zName==0 ) zName = "";
91996
91997  /* Check for the following errors:
91998  **
91999  **     * Too many attached databases,
92000  **     * Transaction currently open
92001  **     * Specified database name already being used.
92002  */
92003  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
92004    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
92005      db->aLimit[SQLITE_LIMIT_ATTACHED]
92006    );
92007    goto attach_error;
92008  }
92009  if( !db->autoCommit ){
92010    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
92011    goto attach_error;
92012  }
92013  for(i=0; i<db->nDb; i++){
92014    char *z = db->aDb[i].zName;
92015    assert( z && zName );
92016    if( sqlite3StrICmp(z, zName)==0 ){
92017      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
92018      goto attach_error;
92019    }
92020  }
92021
92022  /* Allocate the new entry in the db->aDb[] array and initialize the schema
92023  ** hash tables.
92024  */
92025  if( db->aDb==db->aDbStatic ){
92026    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
92027    if( aNew==0 ) return;
92028    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
92029  }else{
92030    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
92031    if( aNew==0 ) return;
92032  }
92033  db->aDb = aNew;
92034  aNew = &db->aDb[db->nDb];
92035  memset(aNew, 0, sizeof(*aNew));
92036
92037  /* Open the database file. If the btree is successfully opened, use
92038  ** it to obtain the database schema. At this point the schema may
92039  ** or may not be initialized.
92040  */
92041  flags = db->openFlags;
92042  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
92043  if( rc!=SQLITE_OK ){
92044    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
92045    sqlite3_result_error(context, zErr, -1);
92046    sqlite3_free(zErr);
92047    return;
92048  }
92049  assert( pVfs );
92050  flags |= SQLITE_OPEN_MAIN_DB;
92051  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
92052  sqlite3_free( zPath );
92053  db->nDb++;
92054  if( rc==SQLITE_CONSTRAINT ){
92055    rc = SQLITE_ERROR;
92056    zErrDyn = sqlite3MPrintf(db, "database is already attached");
92057  }else if( rc==SQLITE_OK ){
92058    Pager *pPager;
92059    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
92060    if( !aNew->pSchema ){
92061      rc = SQLITE_NOMEM;
92062    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
92063      zErrDyn = sqlite3MPrintf(db,
92064        "attached databases must use the same text encoding as main database");
92065      rc = SQLITE_ERROR;
92066    }
92067    sqlite3BtreeEnter(aNew->pBt);
92068    pPager = sqlite3BtreePager(aNew->pBt);
92069    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
92070    sqlite3BtreeSecureDelete(aNew->pBt,
92071                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
92072#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92073    sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
92074#endif
92075    sqlite3BtreeLeave(aNew->pBt);
92076  }
92077  aNew->safety_level = 3;
92078  aNew->zName = sqlite3DbStrDup(db, zName);
92079  if( rc==SQLITE_OK && aNew->zName==0 ){
92080    rc = SQLITE_NOMEM;
92081  }
92082
92083
92084#ifdef SQLITE_HAS_CODEC
92085  if( rc==SQLITE_OK ){
92086    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
92087    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
92088    int nKey;
92089    char *zKey;
92090    int t = sqlite3_value_type(argv[2]);
92091    switch( t ){
92092      case SQLITE_INTEGER:
92093      case SQLITE_FLOAT:
92094        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
92095        rc = SQLITE_ERROR;
92096        break;
92097
92098      case SQLITE_TEXT:
92099      case SQLITE_BLOB:
92100        nKey = sqlite3_value_bytes(argv[2]);
92101        zKey = (char *)sqlite3_value_blob(argv[2]);
92102        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
92103        break;
92104
92105      case SQLITE_NULL:
92106        /* No key specified.  Use the key from the main database */
92107        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
92108        if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
92109          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
92110        }
92111        break;
92112    }
92113  }
92114#endif
92115
92116  /* If the file was opened successfully, read the schema for the new database.
92117  ** If this fails, or if opening the file failed, then close the file and
92118  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
92119  ** we found it.
92120  */
92121  if( rc==SQLITE_OK ){
92122    sqlite3BtreeEnterAll(db);
92123    rc = sqlite3Init(db, &zErrDyn);
92124    sqlite3BtreeLeaveAll(db);
92125  }
92126#ifdef SQLITE_USER_AUTHENTICATION
92127  if( rc==SQLITE_OK ){
92128    u8 newAuth = 0;
92129    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
92130    if( newAuth<db->auth.authLevel ){
92131      rc = SQLITE_AUTH_USER;
92132    }
92133  }
92134#endif
92135  if( rc ){
92136    int iDb = db->nDb - 1;
92137    assert( iDb>=2 );
92138    if( db->aDb[iDb].pBt ){
92139      sqlite3BtreeClose(db->aDb[iDb].pBt);
92140      db->aDb[iDb].pBt = 0;
92141      db->aDb[iDb].pSchema = 0;
92142    }
92143    sqlite3ResetAllSchemasOfConnection(db);
92144    db->nDb = iDb;
92145    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
92146      db->mallocFailed = 1;
92147      sqlite3DbFree(db, zErrDyn);
92148      zErrDyn = sqlite3MPrintf(db, "out of memory");
92149    }else if( zErrDyn==0 ){
92150      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
92151    }
92152    goto attach_error;
92153  }
92154
92155  return;
92156
92157attach_error:
92158  /* Return an error if we get here */
92159  if( zErrDyn ){
92160    sqlite3_result_error(context, zErrDyn, -1);
92161    sqlite3DbFree(db, zErrDyn);
92162  }
92163  if( rc ) sqlite3_result_error_code(context, rc);
92164}
92165
92166/*
92167** An SQL user-function registered to do the work of an DETACH statement. The
92168** three arguments to the function come directly from a detach statement:
92169**
92170**     DETACH DATABASE x
92171**
92172**     SELECT sqlite_detach(x)
92173*/
92174static void detachFunc(
92175  sqlite3_context *context,
92176  int NotUsed,
92177  sqlite3_value **argv
92178){
92179  const char *zName = (const char *)sqlite3_value_text(argv[0]);
92180  sqlite3 *db = sqlite3_context_db_handle(context);
92181  int i;
92182  Db *pDb = 0;
92183  char zErr[128];
92184
92185  UNUSED_PARAMETER(NotUsed);
92186
92187  if( zName==0 ) zName = "";
92188  for(i=0; i<db->nDb; i++){
92189    pDb = &db->aDb[i];
92190    if( pDb->pBt==0 ) continue;
92191    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
92192  }
92193
92194  if( i>=db->nDb ){
92195    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
92196    goto detach_error;
92197  }
92198  if( i<2 ){
92199    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
92200    goto detach_error;
92201  }
92202  if( !db->autoCommit ){
92203    sqlite3_snprintf(sizeof(zErr), zErr,
92204                     "cannot DETACH database within transaction");
92205    goto detach_error;
92206  }
92207  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
92208    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
92209    goto detach_error;
92210  }
92211
92212  sqlite3BtreeClose(pDb->pBt);
92213  pDb->pBt = 0;
92214  pDb->pSchema = 0;
92215  sqlite3CollapseDatabaseArray(db);
92216  return;
92217
92218detach_error:
92219  sqlite3_result_error(context, zErr, -1);
92220}
92221
92222/*
92223** This procedure generates VDBE code for a single invocation of either the
92224** sqlite_detach() or sqlite_attach() SQL user functions.
92225*/
92226static void codeAttach(
92227  Parse *pParse,       /* The parser context */
92228  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
92229  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
92230  Expr *pAuthArg,      /* Expression to pass to authorization callback */
92231  Expr *pFilename,     /* Name of database file */
92232  Expr *pDbname,       /* Name of the database to use internally */
92233  Expr *pKey           /* Database key for encryption extension */
92234){
92235  int rc;
92236  NameContext sName;
92237  Vdbe *v;
92238  sqlite3* db = pParse->db;
92239  int regArgs;
92240
92241  memset(&sName, 0, sizeof(NameContext));
92242  sName.pParse = pParse;
92243
92244  if(
92245      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
92246      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
92247      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
92248  ){
92249    goto attach_end;
92250  }
92251
92252#ifndef SQLITE_OMIT_AUTHORIZATION
92253  if( pAuthArg ){
92254    char *zAuthArg;
92255    if( pAuthArg->op==TK_STRING ){
92256      zAuthArg = pAuthArg->u.zToken;
92257    }else{
92258      zAuthArg = 0;
92259    }
92260    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
92261    if(rc!=SQLITE_OK ){
92262      goto attach_end;
92263    }
92264  }
92265#endif /* SQLITE_OMIT_AUTHORIZATION */
92266
92267
92268  v = sqlite3GetVdbe(pParse);
92269  regArgs = sqlite3GetTempRange(pParse, 4);
92270  sqlite3ExprCode(pParse, pFilename, regArgs);
92271  sqlite3ExprCode(pParse, pDbname, regArgs+1);
92272  sqlite3ExprCode(pParse, pKey, regArgs+2);
92273
92274  assert( v || db->mallocFailed );
92275  if( v ){
92276    sqlite3VdbeAddOp3(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3);
92277    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
92278    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
92279    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
92280
92281    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
92282    ** statement only). For DETACH, set it to false (expire all existing
92283    ** statements).
92284    */
92285    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
92286  }
92287
92288attach_end:
92289  sqlite3ExprDelete(db, pFilename);
92290  sqlite3ExprDelete(db, pDbname);
92291  sqlite3ExprDelete(db, pKey);
92292}
92293
92294/*
92295** Called by the parser to compile a DETACH statement.
92296**
92297**     DETACH pDbname
92298*/
92299SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
92300  static const FuncDef detach_func = {
92301    1,                /* nArg */
92302    SQLITE_UTF8,      /* funcFlags */
92303    0,                /* pUserData */
92304    0,                /* pNext */
92305    detachFunc,       /* xFunc */
92306    0,                /* xStep */
92307    0,                /* xFinalize */
92308    "sqlite_detach",  /* zName */
92309    0,                /* pHash */
92310    0                 /* pDestructor */
92311  };
92312  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
92313}
92314
92315/*
92316** Called by the parser to compile an ATTACH statement.
92317**
92318**     ATTACH p AS pDbname KEY pKey
92319*/
92320SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
92321  static const FuncDef attach_func = {
92322    3,                /* nArg */
92323    SQLITE_UTF8,      /* funcFlags */
92324    0,                /* pUserData */
92325    0,                /* pNext */
92326    attachFunc,       /* xFunc */
92327    0,                /* xStep */
92328    0,                /* xFinalize */
92329    "sqlite_attach",  /* zName */
92330    0,                /* pHash */
92331    0                 /* pDestructor */
92332  };
92333  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
92334}
92335#endif /* SQLITE_OMIT_ATTACH */
92336
92337/*
92338** Initialize a DbFixer structure.  This routine must be called prior
92339** to passing the structure to one of the sqliteFixAAAA() routines below.
92340*/
92341SQLITE_PRIVATE void sqlite3FixInit(
92342  DbFixer *pFix,      /* The fixer to be initialized */
92343  Parse *pParse,      /* Error messages will be written here */
92344  int iDb,            /* This is the database that must be used */
92345  const char *zType,  /* "view", "trigger", or "index" */
92346  const Token *pName  /* Name of the view, trigger, or index */
92347){
92348  sqlite3 *db;
92349
92350  db = pParse->db;
92351  assert( db->nDb>iDb );
92352  pFix->pParse = pParse;
92353  pFix->zDb = db->aDb[iDb].zName;
92354  pFix->pSchema = db->aDb[iDb].pSchema;
92355  pFix->zType = zType;
92356  pFix->pName = pName;
92357  pFix->bVarOnly = (iDb==1);
92358}
92359
92360/*
92361** The following set of routines walk through the parse tree and assign
92362** a specific database to all table references where the database name
92363** was left unspecified in the original SQL statement.  The pFix structure
92364** must have been initialized by a prior call to sqlite3FixInit().
92365**
92366** These routines are used to make sure that an index, trigger, or
92367** view in one database does not refer to objects in a different database.
92368** (Exception: indices, triggers, and views in the TEMP database are
92369** allowed to refer to anything.)  If a reference is explicitly made
92370** to an object in a different database, an error message is added to
92371** pParse->zErrMsg and these routines return non-zero.  If everything
92372** checks out, these routines return 0.
92373*/
92374SQLITE_PRIVATE int sqlite3FixSrcList(
92375  DbFixer *pFix,       /* Context of the fixation */
92376  SrcList *pList       /* The Source list to check and modify */
92377){
92378  int i;
92379  const char *zDb;
92380  struct SrcList_item *pItem;
92381
92382  if( NEVER(pList==0) ) return 0;
92383  zDb = pFix->zDb;
92384  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
92385    if( pFix->bVarOnly==0 ){
92386      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
92387        sqlite3ErrorMsg(pFix->pParse,
92388            "%s %T cannot reference objects in database %s",
92389            pFix->zType, pFix->pName, pItem->zDatabase);
92390        return 1;
92391      }
92392      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
92393      pItem->zDatabase = 0;
92394      pItem->pSchema = pFix->pSchema;
92395    }
92396#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
92397    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
92398    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
92399#endif
92400  }
92401  return 0;
92402}
92403#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
92404SQLITE_PRIVATE int sqlite3FixSelect(
92405  DbFixer *pFix,       /* Context of the fixation */
92406  Select *pSelect      /* The SELECT statement to be fixed to one database */
92407){
92408  while( pSelect ){
92409    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
92410      return 1;
92411    }
92412    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
92413      return 1;
92414    }
92415    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
92416      return 1;
92417    }
92418    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
92419      return 1;
92420    }
92421    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
92422      return 1;
92423    }
92424    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
92425      return 1;
92426    }
92427    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
92428      return 1;
92429    }
92430    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
92431      return 1;
92432    }
92433    pSelect = pSelect->pPrior;
92434  }
92435  return 0;
92436}
92437SQLITE_PRIVATE int sqlite3FixExpr(
92438  DbFixer *pFix,     /* Context of the fixation */
92439  Expr *pExpr        /* The expression to be fixed to one database */
92440){
92441  while( pExpr ){
92442    if( pExpr->op==TK_VARIABLE ){
92443      if( pFix->pParse->db->init.busy ){
92444        pExpr->op = TK_NULL;
92445      }else{
92446        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
92447        return 1;
92448      }
92449    }
92450    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
92451    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92452      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
92453    }else{
92454      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
92455    }
92456    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
92457      return 1;
92458    }
92459    pExpr = pExpr->pLeft;
92460  }
92461  return 0;
92462}
92463SQLITE_PRIVATE int sqlite3FixExprList(
92464  DbFixer *pFix,     /* Context of the fixation */
92465  ExprList *pList    /* The expression to be fixed to one database */
92466){
92467  int i;
92468  struct ExprList_item *pItem;
92469  if( pList==0 ) return 0;
92470  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
92471    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
92472      return 1;
92473    }
92474  }
92475  return 0;
92476}
92477#endif
92478
92479#ifndef SQLITE_OMIT_TRIGGER
92480SQLITE_PRIVATE int sqlite3FixTriggerStep(
92481  DbFixer *pFix,     /* Context of the fixation */
92482  TriggerStep *pStep /* The trigger step be fixed to one database */
92483){
92484  while( pStep ){
92485    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
92486      return 1;
92487    }
92488    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
92489      return 1;
92490    }
92491    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
92492      return 1;
92493    }
92494    pStep = pStep->pNext;
92495  }
92496  return 0;
92497}
92498#endif
92499
92500/************** End of attach.c **********************************************/
92501/************** Begin file auth.c ********************************************/
92502/*
92503** 2003 January 11
92504**
92505** The author disclaims copyright to this source code.  In place of
92506** a legal notice, here is a blessing:
92507**
92508**    May you do good and not evil.
92509**    May you find forgiveness for yourself and forgive others.
92510**    May you share freely, never taking more than you give.
92511**
92512*************************************************************************
92513** This file contains code used to implement the sqlite3_set_authorizer()
92514** API.  This facility is an optional feature of the library.  Embedded
92515** systems that do not need this facility may omit it by recompiling
92516** the library with -DSQLITE_OMIT_AUTHORIZATION=1
92517*/
92518/* #include "sqliteInt.h" */
92519
92520/*
92521** All of the code in this file may be omitted by defining a single
92522** macro.
92523*/
92524#ifndef SQLITE_OMIT_AUTHORIZATION
92525
92526/*
92527** Set or clear the access authorization function.
92528**
92529** The access authorization function is be called during the compilation
92530** phase to verify that the user has read and/or write access permission on
92531** various fields of the database.  The first argument to the auth function
92532** is a copy of the 3rd argument to this routine.  The second argument
92533** to the auth function is one of these constants:
92534**
92535**       SQLITE_CREATE_INDEX
92536**       SQLITE_CREATE_TABLE
92537**       SQLITE_CREATE_TEMP_INDEX
92538**       SQLITE_CREATE_TEMP_TABLE
92539**       SQLITE_CREATE_TEMP_TRIGGER
92540**       SQLITE_CREATE_TEMP_VIEW
92541**       SQLITE_CREATE_TRIGGER
92542**       SQLITE_CREATE_VIEW
92543**       SQLITE_DELETE
92544**       SQLITE_DROP_INDEX
92545**       SQLITE_DROP_TABLE
92546**       SQLITE_DROP_TEMP_INDEX
92547**       SQLITE_DROP_TEMP_TABLE
92548**       SQLITE_DROP_TEMP_TRIGGER
92549**       SQLITE_DROP_TEMP_VIEW
92550**       SQLITE_DROP_TRIGGER
92551**       SQLITE_DROP_VIEW
92552**       SQLITE_INSERT
92553**       SQLITE_PRAGMA
92554**       SQLITE_READ
92555**       SQLITE_SELECT
92556**       SQLITE_TRANSACTION
92557**       SQLITE_UPDATE
92558**
92559** The third and fourth arguments to the auth function are the name of
92560** the table and the column that are being accessed.  The auth function
92561** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
92562** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
92563** means that the SQL statement will never-run - the sqlite3_exec() call
92564** will return with an error.  SQLITE_IGNORE means that the SQL statement
92565** should run but attempts to read the specified column will return NULL
92566** and attempts to write the column will be ignored.
92567**
92568** Setting the auth function to NULL disables this hook.  The default
92569** setting of the auth function is NULL.
92570*/
92571SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
92572  sqlite3 *db,
92573  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
92574  void *pArg
92575){
92576#ifdef SQLITE_ENABLE_API_ARMOR
92577  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92578#endif
92579  sqlite3_mutex_enter(db->mutex);
92580  db->xAuth = (sqlite3_xauth)xAuth;
92581  db->pAuthArg = pArg;
92582  sqlite3ExpirePreparedStatements(db);
92583  sqlite3_mutex_leave(db->mutex);
92584  return SQLITE_OK;
92585}
92586
92587/*
92588** Write an error message into pParse->zErrMsg that explains that the
92589** user-supplied authorization function returned an illegal value.
92590*/
92591static void sqliteAuthBadReturnCode(Parse *pParse){
92592  sqlite3ErrorMsg(pParse, "authorizer malfunction");
92593  pParse->rc = SQLITE_ERROR;
92594}
92595
92596/*
92597** Invoke the authorization callback for permission to read column zCol from
92598** table zTab in database zDb. This function assumes that an authorization
92599** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
92600**
92601** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
92602** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
92603** is treated as SQLITE_DENY. In this case an error is left in pParse.
92604*/
92605SQLITE_PRIVATE int sqlite3AuthReadCol(
92606  Parse *pParse,                  /* The parser context */
92607  const char *zTab,               /* Table name */
92608  const char *zCol,               /* Column name */
92609  int iDb                         /* Index of containing database. */
92610){
92611  sqlite3 *db = pParse->db;       /* Database handle */
92612  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
92613  int rc;                         /* Auth callback return code */
92614
92615  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
92616#ifdef SQLITE_USER_AUTHENTICATION
92617                 ,db->auth.zAuthUser
92618#endif
92619                );
92620  if( rc==SQLITE_DENY ){
92621    if( db->nDb>2 || iDb!=0 ){
92622      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
92623    }else{
92624      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
92625    }
92626    pParse->rc = SQLITE_AUTH;
92627  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
92628    sqliteAuthBadReturnCode(pParse);
92629  }
92630  return rc;
92631}
92632
92633/*
92634** The pExpr should be a TK_COLUMN expression.  The table referred to
92635** is in pTabList or else it is the NEW or OLD table of a trigger.
92636** Check to see if it is OK to read this particular column.
92637**
92638** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
92639** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
92640** then generate an error.
92641*/
92642SQLITE_PRIVATE void sqlite3AuthRead(
92643  Parse *pParse,        /* The parser context */
92644  Expr *pExpr,          /* The expression to check authorization on */
92645  Schema *pSchema,      /* The schema of the expression */
92646  SrcList *pTabList     /* All table that pExpr might refer to */
92647){
92648  sqlite3 *db = pParse->db;
92649  Table *pTab = 0;      /* The table being read */
92650  const char *zCol;     /* Name of the column of the table */
92651  int iSrc;             /* Index in pTabList->a[] of table being read */
92652  int iDb;              /* The index of the database the expression refers to */
92653  int iCol;             /* Index of column in table */
92654
92655  if( db->xAuth==0 ) return;
92656  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
92657  if( iDb<0 ){
92658    /* An attempt to read a column out of a subquery or other
92659    ** temporary table. */
92660    return;
92661  }
92662
92663  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
92664  if( pExpr->op==TK_TRIGGER ){
92665    pTab = pParse->pTriggerTab;
92666  }else{
92667    assert( pTabList );
92668    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
92669      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
92670        pTab = pTabList->a[iSrc].pTab;
92671        break;
92672      }
92673    }
92674  }
92675  iCol = pExpr->iColumn;
92676  if( NEVER(pTab==0) ) return;
92677
92678  if( iCol>=0 ){
92679    assert( iCol<pTab->nCol );
92680    zCol = pTab->aCol[iCol].zName;
92681  }else if( pTab->iPKey>=0 ){
92682    assert( pTab->iPKey<pTab->nCol );
92683    zCol = pTab->aCol[pTab->iPKey].zName;
92684  }else{
92685    zCol = "ROWID";
92686  }
92687  assert( iDb>=0 && iDb<db->nDb );
92688  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
92689    pExpr->op = TK_NULL;
92690  }
92691}
92692
92693/*
92694** Do an authorization check using the code and arguments given.  Return
92695** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
92696** is returned, then the error count and error message in pParse are
92697** modified appropriately.
92698*/
92699SQLITE_PRIVATE int sqlite3AuthCheck(
92700  Parse *pParse,
92701  int code,
92702  const char *zArg1,
92703  const char *zArg2,
92704  const char *zArg3
92705){
92706  sqlite3 *db = pParse->db;
92707  int rc;
92708
92709  /* Don't do any authorization checks if the database is initialising
92710  ** or if the parser is being invoked from within sqlite3_declare_vtab.
92711  */
92712  if( db->init.busy || IN_DECLARE_VTAB ){
92713    return SQLITE_OK;
92714  }
92715
92716  if( db->xAuth==0 ){
92717    return SQLITE_OK;
92718  }
92719  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
92720#ifdef SQLITE_USER_AUTHENTICATION
92721                 ,db->auth.zAuthUser
92722#endif
92723                );
92724  if( rc==SQLITE_DENY ){
92725    sqlite3ErrorMsg(pParse, "not authorized");
92726    pParse->rc = SQLITE_AUTH;
92727  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
92728    rc = SQLITE_DENY;
92729    sqliteAuthBadReturnCode(pParse);
92730  }
92731  return rc;
92732}
92733
92734/*
92735** Push an authorization context.  After this routine is called, the
92736** zArg3 argument to authorization callbacks will be zContext until
92737** popped.  Or if pParse==0, this routine is a no-op.
92738*/
92739SQLITE_PRIVATE void sqlite3AuthContextPush(
92740  Parse *pParse,
92741  AuthContext *pContext,
92742  const char *zContext
92743){
92744  assert( pParse );
92745  pContext->pParse = pParse;
92746  pContext->zAuthContext = pParse->zAuthContext;
92747  pParse->zAuthContext = zContext;
92748}
92749
92750/*
92751** Pop an authorization context that was previously pushed
92752** by sqlite3AuthContextPush
92753*/
92754SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
92755  if( pContext->pParse ){
92756    pContext->pParse->zAuthContext = pContext->zAuthContext;
92757    pContext->pParse = 0;
92758  }
92759}
92760
92761#endif /* SQLITE_OMIT_AUTHORIZATION */
92762
92763/************** End of auth.c ************************************************/
92764/************** Begin file build.c *******************************************/
92765/*
92766** 2001 September 15
92767**
92768** The author disclaims copyright to this source code.  In place of
92769** a legal notice, here is a blessing:
92770**
92771**    May you do good and not evil.
92772**    May you find forgiveness for yourself and forgive others.
92773**    May you share freely, never taking more than you give.
92774**
92775*************************************************************************
92776** This file contains C code routines that are called by the SQLite parser
92777** when syntax rules are reduced.  The routines in this file handle the
92778** following kinds of SQL syntax:
92779**
92780**     CREATE TABLE
92781**     DROP TABLE
92782**     CREATE INDEX
92783**     DROP INDEX
92784**     creating ID lists
92785**     BEGIN TRANSACTION
92786**     COMMIT
92787**     ROLLBACK
92788*/
92789/* #include "sqliteInt.h" */
92790
92791/*
92792** This routine is called when a new SQL statement is beginning to
92793** be parsed.  Initialize the pParse structure as needed.
92794*/
92795SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
92796  pParse->explain = (u8)explainFlag;
92797  pParse->nVar = 0;
92798}
92799
92800#ifndef SQLITE_OMIT_SHARED_CACHE
92801/*
92802** The TableLock structure is only used by the sqlite3TableLock() and
92803** codeTableLocks() functions.
92804*/
92805struct TableLock {
92806  int iDb;             /* The database containing the table to be locked */
92807  int iTab;            /* The root page of the table to be locked */
92808  u8 isWriteLock;      /* True for write lock.  False for a read lock */
92809  const char *zName;   /* Name of the table */
92810};
92811
92812/*
92813** Record the fact that we want to lock a table at run-time.
92814**
92815** The table to be locked has root page iTab and is found in database iDb.
92816** A read or a write lock can be taken depending on isWritelock.
92817**
92818** This routine just records the fact that the lock is desired.  The
92819** code to make the lock occur is generated by a later call to
92820** codeTableLocks() which occurs during sqlite3FinishCoding().
92821*/
92822SQLITE_PRIVATE void sqlite3TableLock(
92823  Parse *pParse,     /* Parsing context */
92824  int iDb,           /* Index of the database containing the table to lock */
92825  int iTab,          /* Root page number of the table to be locked */
92826  u8 isWriteLock,    /* True for a write lock */
92827  const char *zName  /* Name of the table to be locked */
92828){
92829  Parse *pToplevel = sqlite3ParseToplevel(pParse);
92830  int i;
92831  int nBytes;
92832  TableLock *p;
92833  assert( iDb>=0 );
92834
92835  for(i=0; i<pToplevel->nTableLock; i++){
92836    p = &pToplevel->aTableLock[i];
92837    if( p->iDb==iDb && p->iTab==iTab ){
92838      p->isWriteLock = (p->isWriteLock || isWriteLock);
92839      return;
92840    }
92841  }
92842
92843  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
92844  pToplevel->aTableLock =
92845      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
92846  if( pToplevel->aTableLock ){
92847    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
92848    p->iDb = iDb;
92849    p->iTab = iTab;
92850    p->isWriteLock = isWriteLock;
92851    p->zName = zName;
92852  }else{
92853    pToplevel->nTableLock = 0;
92854    pToplevel->db->mallocFailed = 1;
92855  }
92856}
92857
92858/*
92859** Code an OP_TableLock instruction for each table locked by the
92860** statement (configured by calls to sqlite3TableLock()).
92861*/
92862static void codeTableLocks(Parse *pParse){
92863  int i;
92864  Vdbe *pVdbe;
92865
92866  pVdbe = sqlite3GetVdbe(pParse);
92867  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
92868
92869  for(i=0; i<pParse->nTableLock; i++){
92870    TableLock *p = &pParse->aTableLock[i];
92871    int p1 = p->iDb;
92872    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
92873                      p->zName, P4_STATIC);
92874  }
92875}
92876#else
92877  #define codeTableLocks(x)
92878#endif
92879
92880/*
92881** Return TRUE if the given yDbMask object is empty - if it contains no
92882** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
92883** macros when SQLITE_MAX_ATTACHED is greater than 30.
92884*/
92885#if SQLITE_MAX_ATTACHED>30
92886SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
92887  int i;
92888  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
92889  return 1;
92890}
92891#endif
92892
92893/*
92894** This routine is called after a single SQL statement has been
92895** parsed and a VDBE program to execute that statement has been
92896** prepared.  This routine puts the finishing touches on the
92897** VDBE program and resets the pParse structure for the next
92898** parse.
92899**
92900** Note that if an error occurred, it might be the case that
92901** no VDBE code was generated.
92902*/
92903SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
92904  sqlite3 *db;
92905  Vdbe *v;
92906
92907  assert( pParse->pToplevel==0 );
92908  db = pParse->db;
92909  if( pParse->nested ) return;
92910  if( db->mallocFailed || pParse->nErr ){
92911    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
92912    return;
92913  }
92914
92915  /* Begin by generating some termination code at the end of the
92916  ** vdbe program
92917  */
92918  v = sqlite3GetVdbe(pParse);
92919  assert( !pParse->isMultiWrite
92920       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
92921  if( v ){
92922    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
92923    sqlite3VdbeAddOp0(v, OP_Halt);
92924
92925#if SQLITE_USER_AUTHENTICATION
92926    if( pParse->nTableLock>0 && db->init.busy==0 ){
92927      sqlite3UserAuthInit(db);
92928      if( db->auth.authLevel<UAUTH_User ){
92929        pParse->rc = SQLITE_AUTH_USER;
92930        sqlite3ErrorMsg(pParse, "user not authenticated");
92931        return;
92932      }
92933    }
92934#endif
92935
92936    /* The cookie mask contains one bit for each database file open.
92937    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
92938    ** set for each database that is used.  Generate code to start a
92939    ** transaction on each used database and to verify the schema cookie
92940    ** on each used database.
92941    */
92942    if( db->mallocFailed==0
92943     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
92944    ){
92945      int iDb, i;
92946      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
92947      sqlite3VdbeJumpHere(v, 0);
92948      for(iDb=0; iDb<db->nDb; iDb++){
92949        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
92950        sqlite3VdbeUsesBtree(v, iDb);
92951        sqlite3VdbeAddOp4Int(v,
92952          OP_Transaction,                    /* Opcode */
92953          iDb,                               /* P1 */
92954          DbMaskTest(pParse->writeMask,iDb), /* P2 */
92955          pParse->cookieValue[iDb],          /* P3 */
92956          db->aDb[iDb].pSchema->iGeneration  /* P4 */
92957        );
92958        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
92959        VdbeComment((v,
92960              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
92961      }
92962#ifndef SQLITE_OMIT_VIRTUALTABLE
92963      for(i=0; i<pParse->nVtabLock; i++){
92964        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
92965        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
92966      }
92967      pParse->nVtabLock = 0;
92968#endif
92969
92970      /* Once all the cookies have been verified and transactions opened,
92971      ** obtain the required table-locks. This is a no-op unless the
92972      ** shared-cache feature is enabled.
92973      */
92974      codeTableLocks(pParse);
92975
92976      /* Initialize any AUTOINCREMENT data structures required.
92977      */
92978      sqlite3AutoincrementBegin(pParse);
92979
92980      /* Code constant expressions that where factored out of inner loops */
92981      if( pParse->pConstExpr ){
92982        ExprList *pEL = pParse->pConstExpr;
92983        pParse->okConstFactor = 0;
92984        for(i=0; i<pEL->nExpr; i++){
92985          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
92986        }
92987      }
92988
92989      /* Finally, jump back to the beginning of the executable code. */
92990      sqlite3VdbeGoto(v, 1);
92991    }
92992  }
92993
92994
92995  /* Get the VDBE program ready for execution
92996  */
92997  if( v && pParse->nErr==0 && !db->mallocFailed ){
92998    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
92999    /* A minimum of one cursor is required if autoincrement is used
93000    *  See ticket [a696379c1f08866] */
93001    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
93002    sqlite3VdbeMakeReady(v, pParse);
93003    pParse->rc = SQLITE_DONE;
93004    pParse->colNamesSet = 0;
93005  }else{
93006    pParse->rc = SQLITE_ERROR;
93007  }
93008  pParse->nTab = 0;
93009  pParse->nMem = 0;
93010  pParse->nSet = 0;
93011  pParse->nVar = 0;
93012  DbMaskZero(pParse->cookieMask);
93013}
93014
93015/*
93016** Run the parser and code generator recursively in order to generate
93017** code for the SQL statement given onto the end of the pParse context
93018** currently under construction.  When the parser is run recursively
93019** this way, the final OP_Halt is not appended and other initialization
93020** and finalization steps are omitted because those are handling by the
93021** outermost parser.
93022**
93023** Not everything is nestable.  This facility is designed to permit
93024** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
93025** care if you decide to try to use this routine for some other purposes.
93026*/
93027SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
93028  va_list ap;
93029  char *zSql;
93030  char *zErrMsg = 0;
93031  sqlite3 *db = pParse->db;
93032# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
93033  char saveBuf[SAVE_SZ];
93034
93035  if( pParse->nErr ) return;
93036  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
93037  va_start(ap, zFormat);
93038  zSql = sqlite3VMPrintf(db, zFormat, ap);
93039  va_end(ap);
93040  if( zSql==0 ){
93041    return;   /* A malloc must have failed */
93042  }
93043  pParse->nested++;
93044  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
93045  memset(&pParse->nVar, 0, SAVE_SZ);
93046  sqlite3RunParser(pParse, zSql, &zErrMsg);
93047  sqlite3DbFree(db, zErrMsg);
93048  sqlite3DbFree(db, zSql);
93049  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
93050  pParse->nested--;
93051}
93052
93053#if SQLITE_USER_AUTHENTICATION
93054/*
93055** Return TRUE if zTable is the name of the system table that stores the
93056** list of users and their access credentials.
93057*/
93058SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
93059  return sqlite3_stricmp(zTable, "sqlite_user")==0;
93060}
93061#endif
93062
93063/*
93064** Locate the in-memory structure that describes a particular database
93065** table given the name of that table and (optionally) the name of the
93066** database containing the table.  Return NULL if not found.
93067**
93068** If zDatabase is 0, all databases are searched for the table and the
93069** first matching table is returned.  (No checking for duplicate table
93070** names is done.)  The search order is TEMP first, then MAIN, then any
93071** auxiliary databases added using the ATTACH command.
93072**
93073** See also sqlite3LocateTable().
93074*/
93075SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
93076  Table *p = 0;
93077  int i;
93078
93079  /* All mutexes are required for schema access.  Make sure we hold them. */
93080  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
93081#if SQLITE_USER_AUTHENTICATION
93082  /* Only the admin user is allowed to know that the sqlite_user table
93083  ** exists */
93084  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
93085    return 0;
93086  }
93087#endif
93088  for(i=OMIT_TEMPDB; i<db->nDb; i++){
93089    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
93090    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
93091    assert( sqlite3SchemaMutexHeld(db, j, 0) );
93092    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
93093    if( p ) break;
93094  }
93095  return p;
93096}
93097
93098/*
93099** Locate the in-memory structure that describes a particular database
93100** table given the name of that table and (optionally) the name of the
93101** database containing the table.  Return NULL if not found.  Also leave an
93102** error message in pParse->zErrMsg.
93103**
93104** The difference between this routine and sqlite3FindTable() is that this
93105** routine leaves an error message in pParse->zErrMsg where
93106** sqlite3FindTable() does not.
93107*/
93108SQLITE_PRIVATE Table *sqlite3LocateTable(
93109  Parse *pParse,         /* context in which to report errors */
93110  int isView,            /* True if looking for a VIEW rather than a TABLE */
93111  const char *zName,     /* Name of the table we are looking for */
93112  const char *zDbase     /* Name of the database.  Might be NULL */
93113){
93114  Table *p;
93115
93116  /* Read the database schema. If an error occurs, leave an error message
93117  ** and code in pParse and return NULL. */
93118  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93119    return 0;
93120  }
93121
93122  p = sqlite3FindTable(pParse->db, zName, zDbase);
93123  if( p==0 ){
93124    const char *zMsg = isView ? "no such view" : "no such table";
93125#ifndef SQLITE_OMIT_VIRTUALTABLE
93126    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
93127      /* If zName is the not the name of a table in the schema created using
93128      ** CREATE, then check to see if it is the name of an virtual table that
93129      ** can be an eponymous virtual table. */
93130      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
93131      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
93132        return pMod->pEpoTab;
93133      }
93134    }
93135#endif
93136    if( zDbase ){
93137      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
93138    }else{
93139      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
93140    }
93141    pParse->checkSchema = 1;
93142  }
93143#if SQLITE_USER_AUTHENTICATION
93144  else if( pParse->db->auth.authLevel<UAUTH_User ){
93145    sqlite3ErrorMsg(pParse, "user not authenticated");
93146    p = 0;
93147  }
93148#endif
93149  return p;
93150}
93151
93152/*
93153** Locate the table identified by *p.
93154**
93155** This is a wrapper around sqlite3LocateTable(). The difference between
93156** sqlite3LocateTable() and this function is that this function restricts
93157** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
93158** non-NULL if it is part of a view or trigger program definition. See
93159** sqlite3FixSrcList() for details.
93160*/
93161SQLITE_PRIVATE Table *sqlite3LocateTableItem(
93162  Parse *pParse,
93163  int isView,
93164  struct SrcList_item *p
93165){
93166  const char *zDb;
93167  assert( p->pSchema==0 || p->zDatabase==0 );
93168  if( p->pSchema ){
93169    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
93170    zDb = pParse->db->aDb[iDb].zName;
93171  }else{
93172    zDb = p->zDatabase;
93173  }
93174  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
93175}
93176
93177/*
93178** Locate the in-memory structure that describes
93179** a particular index given the name of that index
93180** and the name of the database that contains the index.
93181** Return NULL if not found.
93182**
93183** If zDatabase is 0, all databases are searched for the
93184** table and the first matching index is returned.  (No checking
93185** for duplicate index names is done.)  The search order is
93186** TEMP first, then MAIN, then any auxiliary databases added
93187** using the ATTACH command.
93188*/
93189SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
93190  Index *p = 0;
93191  int i;
93192  /* All mutexes are required for schema access.  Make sure we hold them. */
93193  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
93194  for(i=OMIT_TEMPDB; i<db->nDb; i++){
93195    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
93196    Schema *pSchema = db->aDb[j].pSchema;
93197    assert( pSchema );
93198    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
93199    assert( sqlite3SchemaMutexHeld(db, j, 0) );
93200    p = sqlite3HashFind(&pSchema->idxHash, zName);
93201    if( p ) break;
93202  }
93203  return p;
93204}
93205
93206/*
93207** Reclaim the memory used by an index
93208*/
93209static void freeIndex(sqlite3 *db, Index *p){
93210#ifndef SQLITE_OMIT_ANALYZE
93211  sqlite3DeleteIndexSamples(db, p);
93212#endif
93213  sqlite3ExprDelete(db, p->pPartIdxWhere);
93214  sqlite3ExprListDelete(db, p->aColExpr);
93215  sqlite3DbFree(db, p->zColAff);
93216  if( p->isResized ) sqlite3DbFree(db, p->azColl);
93217#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
93218  sqlite3_free(p->aiRowEst);
93219#endif
93220  sqlite3DbFree(db, p);
93221}
93222
93223/*
93224** For the index called zIdxName which is found in the database iDb,
93225** unlike that index from its Table then remove the index from
93226** the index hash table and free all memory structures associated
93227** with the index.
93228*/
93229SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
93230  Index *pIndex;
93231  Hash *pHash;
93232
93233  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93234  pHash = &db->aDb[iDb].pSchema->idxHash;
93235  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
93236  if( ALWAYS(pIndex) ){
93237    if( pIndex->pTable->pIndex==pIndex ){
93238      pIndex->pTable->pIndex = pIndex->pNext;
93239    }else{
93240      Index *p;
93241      /* Justification of ALWAYS();  The index must be on the list of
93242      ** indices. */
93243      p = pIndex->pTable->pIndex;
93244      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
93245      if( ALWAYS(p && p->pNext==pIndex) ){
93246        p->pNext = pIndex->pNext;
93247      }
93248    }
93249    freeIndex(db, pIndex);
93250  }
93251  db->flags |= SQLITE_InternChanges;
93252}
93253
93254/*
93255** Look through the list of open database files in db->aDb[] and if
93256** any have been closed, remove them from the list.  Reallocate the
93257** db->aDb[] structure to a smaller size, if possible.
93258**
93259** Entry 0 (the "main" database) and entry 1 (the "temp" database)
93260** are never candidates for being collapsed.
93261*/
93262SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
93263  int i, j;
93264  for(i=j=2; i<db->nDb; i++){
93265    struct Db *pDb = &db->aDb[i];
93266    if( pDb->pBt==0 ){
93267      sqlite3DbFree(db, pDb->zName);
93268      pDb->zName = 0;
93269      continue;
93270    }
93271    if( j<i ){
93272      db->aDb[j] = db->aDb[i];
93273    }
93274    j++;
93275  }
93276  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
93277  db->nDb = j;
93278  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
93279    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
93280    sqlite3DbFree(db, db->aDb);
93281    db->aDb = db->aDbStatic;
93282  }
93283}
93284
93285/*
93286** Reset the schema for the database at index iDb.  Also reset the
93287** TEMP schema.
93288*/
93289SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
93290  Db *pDb;
93291  assert( iDb<db->nDb );
93292
93293  /* Case 1:  Reset the single schema identified by iDb */
93294  pDb = &db->aDb[iDb];
93295  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93296  assert( pDb->pSchema!=0 );
93297  sqlite3SchemaClear(pDb->pSchema);
93298
93299  /* If any database other than TEMP is reset, then also reset TEMP
93300  ** since TEMP might be holding triggers that reference tables in the
93301  ** other database.
93302  */
93303  if( iDb!=1 ){
93304    pDb = &db->aDb[1];
93305    assert( pDb->pSchema!=0 );
93306    sqlite3SchemaClear(pDb->pSchema);
93307  }
93308  return;
93309}
93310
93311/*
93312** Erase all schema information from all attached databases (including
93313** "main" and "temp") for a single database connection.
93314*/
93315SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
93316  int i;
93317  sqlite3BtreeEnterAll(db);
93318  for(i=0; i<db->nDb; i++){
93319    Db *pDb = &db->aDb[i];
93320    if( pDb->pSchema ){
93321      sqlite3SchemaClear(pDb->pSchema);
93322    }
93323  }
93324  db->flags &= ~SQLITE_InternChanges;
93325  sqlite3VtabUnlockList(db);
93326  sqlite3BtreeLeaveAll(db);
93327  sqlite3CollapseDatabaseArray(db);
93328}
93329
93330/*
93331** This routine is called when a commit occurs.
93332*/
93333SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
93334  db->flags &= ~SQLITE_InternChanges;
93335}
93336
93337/*
93338** Delete memory allocated for the column names of a table or view (the
93339** Table.aCol[] array).
93340*/
93341SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
93342  int i;
93343  Column *pCol;
93344  assert( pTable!=0 );
93345  if( (pCol = pTable->aCol)!=0 ){
93346    for(i=0; i<pTable->nCol; i++, pCol++){
93347      sqlite3DbFree(db, pCol->zName);
93348      sqlite3ExprDelete(db, pCol->pDflt);
93349      sqlite3DbFree(db, pCol->zDflt);
93350      sqlite3DbFree(db, pCol->zType);
93351      sqlite3DbFree(db, pCol->zColl);
93352    }
93353    sqlite3DbFree(db, pTable->aCol);
93354  }
93355}
93356
93357/*
93358** Remove the memory data structures associated with the given
93359** Table.  No changes are made to disk by this routine.
93360**
93361** This routine just deletes the data structure.  It does not unlink
93362** the table data structure from the hash table.  But it does destroy
93363** memory structures of the indices and foreign keys associated with
93364** the table.
93365**
93366** The db parameter is optional.  It is needed if the Table object
93367** contains lookaside memory.  (Table objects in the schema do not use
93368** lookaside memory, but some ephemeral Table objects do.)  Or the
93369** db parameter can be used with db->pnBytesFreed to measure the memory
93370** used by the Table object.
93371*/
93372SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
93373  Index *pIndex, *pNext;
93374  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
93375
93376  assert( !pTable || pTable->nRef>0 );
93377
93378  /* Do not delete the table until the reference count reaches zero. */
93379  if( !pTable ) return;
93380  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
93381
93382  /* Record the number of outstanding lookaside allocations in schema Tables
93383  ** prior to doing any free() operations.  Since schema Tables do not use
93384  ** lookaside, this number should not change. */
93385  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
93386                         db->lookaside.nOut : 0 );
93387
93388  /* Delete all indices associated with this table. */
93389  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
93390    pNext = pIndex->pNext;
93391    assert( pIndex->pSchema==pTable->pSchema );
93392    if( !db || db->pnBytesFreed==0 ){
93393      char *zName = pIndex->zName;
93394      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
93395         &pIndex->pSchema->idxHash, zName, 0
93396      );
93397      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
93398      assert( pOld==pIndex || pOld==0 );
93399    }
93400    freeIndex(db, pIndex);
93401  }
93402
93403  /* Delete any foreign keys attached to this table. */
93404  sqlite3FkDelete(db, pTable);
93405
93406  /* Delete the Table structure itself.
93407  */
93408  sqlite3DeleteColumnNames(db, pTable);
93409  sqlite3DbFree(db, pTable->zName);
93410  sqlite3DbFree(db, pTable->zColAff);
93411  sqlite3SelectDelete(db, pTable->pSelect);
93412  sqlite3ExprListDelete(db, pTable->pCheck);
93413#ifndef SQLITE_OMIT_VIRTUALTABLE
93414  sqlite3VtabClear(db, pTable);
93415#endif
93416  sqlite3DbFree(db, pTable);
93417
93418  /* Verify that no lookaside memory was used by schema tables */
93419  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
93420}
93421
93422/*
93423** Unlink the given table from the hash tables and the delete the
93424** table structure with all its indices and foreign keys.
93425*/
93426SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
93427  Table *p;
93428  Db *pDb;
93429
93430  assert( db!=0 );
93431  assert( iDb>=0 && iDb<db->nDb );
93432  assert( zTabName );
93433  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93434  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
93435  pDb = &db->aDb[iDb];
93436  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
93437  sqlite3DeleteTable(db, p);
93438  db->flags |= SQLITE_InternChanges;
93439}
93440
93441/*
93442** Given a token, return a string that consists of the text of that
93443** token.  Space to hold the returned string
93444** is obtained from sqliteMalloc() and must be freed by the calling
93445** function.
93446**
93447** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
93448** surround the body of the token are removed.
93449**
93450** Tokens are often just pointers into the original SQL text and so
93451** are not \000 terminated and are not persistent.  The returned string
93452** is \000 terminated and is persistent.
93453*/
93454SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
93455  char *zName;
93456  if( pName ){
93457    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
93458    sqlite3Dequote(zName);
93459  }else{
93460    zName = 0;
93461  }
93462  return zName;
93463}
93464
93465/*
93466** Open the sqlite_master table stored in database number iDb for
93467** writing. The table is opened using cursor 0.
93468*/
93469SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
93470  Vdbe *v = sqlite3GetVdbe(p);
93471  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
93472  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
93473  if( p->nTab==0 ){
93474    p->nTab = 1;
93475  }
93476}
93477
93478/*
93479** Parameter zName points to a nul-terminated buffer containing the name
93480** of a database ("main", "temp" or the name of an attached db). This
93481** function returns the index of the named database in db->aDb[], or
93482** -1 if the named db cannot be found.
93483*/
93484SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
93485  int i = -1;         /* Database number */
93486  if( zName ){
93487    Db *pDb;
93488    int n = sqlite3Strlen30(zName);
93489    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
93490      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
93491          0==sqlite3StrICmp(pDb->zName, zName) ){
93492        break;
93493      }
93494    }
93495  }
93496  return i;
93497}
93498
93499/*
93500** The token *pName contains the name of a database (either "main" or
93501** "temp" or the name of an attached db). This routine returns the
93502** index of the named database in db->aDb[], or -1 if the named db
93503** does not exist.
93504*/
93505SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
93506  int i;                               /* Database number */
93507  char *zName;                         /* Name we are searching for */
93508  zName = sqlite3NameFromToken(db, pName);
93509  i = sqlite3FindDbName(db, zName);
93510  sqlite3DbFree(db, zName);
93511  return i;
93512}
93513
93514/* The table or view or trigger name is passed to this routine via tokens
93515** pName1 and pName2. If the table name was fully qualified, for example:
93516**
93517** CREATE TABLE xxx.yyy (...);
93518**
93519** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
93520** the table name is not fully qualified, i.e.:
93521**
93522** CREATE TABLE yyy(...);
93523**
93524** Then pName1 is set to "yyy" and pName2 is "".
93525**
93526** This routine sets the *ppUnqual pointer to point at the token (pName1 or
93527** pName2) that stores the unqualified table name.  The index of the
93528** database "xxx" is returned.
93529*/
93530SQLITE_PRIVATE int sqlite3TwoPartName(
93531  Parse *pParse,      /* Parsing and code generating context */
93532  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
93533  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
93534  Token **pUnqual     /* Write the unqualified object name here */
93535){
93536  int iDb;                    /* Database holding the object */
93537  sqlite3 *db = pParse->db;
93538
93539  if( ALWAYS(pName2!=0) && pName2->n>0 ){
93540    if( db->init.busy ) {
93541      sqlite3ErrorMsg(pParse, "corrupt database");
93542      return -1;
93543    }
93544    *pUnqual = pName2;
93545    iDb = sqlite3FindDb(db, pName1);
93546    if( iDb<0 ){
93547      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
93548      return -1;
93549    }
93550  }else{
93551    assert( db->init.iDb==0 || db->init.busy );
93552    iDb = db->init.iDb;
93553    *pUnqual = pName1;
93554  }
93555  return iDb;
93556}
93557
93558/*
93559** This routine is used to check if the UTF-8 string zName is a legal
93560** unqualified name for a new schema object (table, index, view or
93561** trigger). All names are legal except those that begin with the string
93562** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
93563** is reserved for internal use.
93564*/
93565SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
93566  if( !pParse->db->init.busy && pParse->nested==0
93567          && (pParse->db->flags & SQLITE_WriteSchema)==0
93568          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
93569    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
93570    return SQLITE_ERROR;
93571  }
93572  return SQLITE_OK;
93573}
93574
93575/*
93576** Return the PRIMARY KEY index of a table
93577*/
93578SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
93579  Index *p;
93580  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
93581  return p;
93582}
93583
93584/*
93585** Return the column of index pIdx that corresponds to table
93586** column iCol.  Return -1 if not found.
93587*/
93588SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
93589  int i;
93590  for(i=0; i<pIdx->nColumn; i++){
93591    if( iCol==pIdx->aiColumn[i] ) return i;
93592  }
93593  return -1;
93594}
93595
93596/*
93597** Begin constructing a new table representation in memory.  This is
93598** the first of several action routines that get called in response
93599** to a CREATE TABLE statement.  In particular, this routine is called
93600** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
93601** flag is true if the table should be stored in the auxiliary database
93602** file instead of in the main database file.  This is normally the case
93603** when the "TEMP" or "TEMPORARY" keyword occurs in between
93604** CREATE and TABLE.
93605**
93606** The new table record is initialized and put in pParse->pNewTable.
93607** As more of the CREATE TABLE statement is parsed, additional action
93608** routines will be called to add more information to this record.
93609** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
93610** is called to complete the construction of the new table record.
93611*/
93612SQLITE_PRIVATE void sqlite3StartTable(
93613  Parse *pParse,   /* Parser context */
93614  Token *pName1,   /* First part of the name of the table or view */
93615  Token *pName2,   /* Second part of the name of the table or view */
93616  int isTemp,      /* True if this is a TEMP table */
93617  int isView,      /* True if this is a VIEW */
93618  int isVirtual,   /* True if this is a VIRTUAL table */
93619  int noErr        /* Do nothing if table already exists */
93620){
93621  Table *pTable;
93622  char *zName = 0; /* The name of the new table */
93623  sqlite3 *db = pParse->db;
93624  Vdbe *v;
93625  int iDb;         /* Database number to create the table in */
93626  Token *pName;    /* Unqualified name of the table to create */
93627
93628  /* The table or view name to create is passed to this routine via tokens
93629  ** pName1 and pName2. If the table name was fully qualified, for example:
93630  **
93631  ** CREATE TABLE xxx.yyy (...);
93632  **
93633  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
93634  ** the table name is not fully qualified, i.e.:
93635  **
93636  ** CREATE TABLE yyy(...);
93637  **
93638  ** Then pName1 is set to "yyy" and pName2 is "".
93639  **
93640  ** The call below sets the pName pointer to point at the token (pName1 or
93641  ** pName2) that stores the unqualified table name. The variable iDb is
93642  ** set to the index of the database that the table or view is to be
93643  ** created in.
93644  */
93645  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
93646  if( iDb<0 ) return;
93647  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
93648    /* If creating a temp table, the name may not be qualified. Unless
93649    ** the database name is "temp" anyway.  */
93650    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
93651    return;
93652  }
93653  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
93654
93655  pParse->sNameToken = *pName;
93656  zName = sqlite3NameFromToken(db, pName);
93657  if( zName==0 ) return;
93658  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
93659    goto begin_table_error;
93660  }
93661  if( db->init.iDb==1 ) isTemp = 1;
93662#ifndef SQLITE_OMIT_AUTHORIZATION
93663  assert( (isTemp & 1)==isTemp );
93664  {
93665    int code;
93666    char *zDb = db->aDb[iDb].zName;
93667    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
93668      goto begin_table_error;
93669    }
93670    if( isView ){
93671      if( !OMIT_TEMPDB && isTemp ){
93672        code = SQLITE_CREATE_TEMP_VIEW;
93673      }else{
93674        code = SQLITE_CREATE_VIEW;
93675      }
93676    }else{
93677      if( !OMIT_TEMPDB && isTemp ){
93678        code = SQLITE_CREATE_TEMP_TABLE;
93679      }else{
93680        code = SQLITE_CREATE_TABLE;
93681      }
93682    }
93683    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
93684      goto begin_table_error;
93685    }
93686  }
93687#endif
93688
93689  /* Make sure the new table name does not collide with an existing
93690  ** index or table name in the same database.  Issue an error message if
93691  ** it does. The exception is if the statement being parsed was passed
93692  ** to an sqlite3_declare_vtab() call. In that case only the column names
93693  ** and types will be used, so there is no need to test for namespace
93694  ** collisions.
93695  */
93696  if( !IN_DECLARE_VTAB ){
93697    char *zDb = db->aDb[iDb].zName;
93698    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93699      goto begin_table_error;
93700    }
93701    pTable = sqlite3FindTable(db, zName, zDb);
93702    if( pTable ){
93703      if( !noErr ){
93704        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
93705      }else{
93706        assert( !db->init.busy || CORRUPT_DB );
93707        sqlite3CodeVerifySchema(pParse, iDb);
93708      }
93709      goto begin_table_error;
93710    }
93711    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
93712      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
93713      goto begin_table_error;
93714    }
93715  }
93716
93717  pTable = sqlite3DbMallocZero(db, sizeof(Table));
93718  if( pTable==0 ){
93719    db->mallocFailed = 1;
93720    pParse->rc = SQLITE_NOMEM;
93721    pParse->nErr++;
93722    goto begin_table_error;
93723  }
93724  pTable->zName = zName;
93725  pTable->iPKey = -1;
93726  pTable->pSchema = db->aDb[iDb].pSchema;
93727  pTable->nRef = 1;
93728  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
93729  assert( pParse->pNewTable==0 );
93730  pParse->pNewTable = pTable;
93731
93732  /* If this is the magic sqlite_sequence table used by autoincrement,
93733  ** then record a pointer to this table in the main database structure
93734  ** so that INSERT can find the table easily.
93735  */
93736#ifndef SQLITE_OMIT_AUTOINCREMENT
93737  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
93738    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93739    pTable->pSchema->pSeqTab = pTable;
93740  }
93741#endif
93742
93743  /* Begin generating the code that will insert the table record into
93744  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
93745  ** and allocate the record number for the table entry now.  Before any
93746  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
93747  ** indices to be created and the table record must come before the
93748  ** indices.  Hence, the record number for the table must be allocated
93749  ** now.
93750  */
93751  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
93752    int addr1;
93753    int fileFormat;
93754    int reg1, reg2, reg3;
93755    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
93756    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
93757    sqlite3BeginWriteOperation(pParse, 1, iDb);
93758
93759#ifndef SQLITE_OMIT_VIRTUALTABLE
93760    if( isVirtual ){
93761      sqlite3VdbeAddOp0(v, OP_VBegin);
93762    }
93763#endif
93764
93765    /* If the file format and encoding in the database have not been set,
93766    ** set them now.
93767    */
93768    reg1 = pParse->regRowid = ++pParse->nMem;
93769    reg2 = pParse->regRoot = ++pParse->nMem;
93770    reg3 = ++pParse->nMem;
93771    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
93772    sqlite3VdbeUsesBtree(v, iDb);
93773    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
93774    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
93775                  1 : SQLITE_MAX_FILE_FORMAT;
93776    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
93777    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
93778    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
93779    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
93780    sqlite3VdbeJumpHere(v, addr1);
93781
93782    /* This just creates a place-holder record in the sqlite_master table.
93783    ** The record created does not contain anything yet.  It will be replaced
93784    ** by the real entry in code generated at sqlite3EndTable().
93785    **
93786    ** The rowid for the new entry is left in register pParse->regRowid.
93787    ** The root page number of the new table is left in reg pParse->regRoot.
93788    ** The rowid and root page number values are needed by the code that
93789    ** sqlite3EndTable will generate.
93790    */
93791#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
93792    if( isView || isVirtual ){
93793      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
93794    }else
93795#endif
93796    {
93797      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
93798    }
93799    sqlite3OpenMasterTable(pParse, iDb);
93800    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
93801    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
93802    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
93803    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93804    sqlite3VdbeAddOp0(v, OP_Close);
93805  }
93806
93807  /* Normal (non-error) return. */
93808  return;
93809
93810  /* If an error occurs, we jump here */
93811begin_table_error:
93812  sqlite3DbFree(db, zName);
93813  return;
93814}
93815
93816/*
93817** This macro is used to compare two strings in a case-insensitive manner.
93818** It is slightly faster than calling sqlite3StrICmp() directly, but
93819** produces larger code.
93820**
93821** WARNING: This macro is not compatible with the strcmp() family. It
93822** returns true if the two strings are equal, otherwise false.
93823*/
93824#define STRICMP(x, y) (\
93825sqlite3UpperToLower[*(unsigned char *)(x)]==   \
93826sqlite3UpperToLower[*(unsigned char *)(y)]     \
93827&& sqlite3StrICmp((x)+1,(y)+1)==0 )
93828
93829/*
93830** Add a new column to the table currently being constructed.
93831**
93832** The parser calls this routine once for each column declaration
93833** in a CREATE TABLE statement.  sqlite3StartTable() gets called
93834** first to get things going.  Then this routine is called for each
93835** column.
93836*/
93837SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
93838  Table *p;
93839  int i;
93840  char *z;
93841  Column *pCol;
93842  sqlite3 *db = pParse->db;
93843  if( (p = pParse->pNewTable)==0 ) return;
93844#if SQLITE_MAX_COLUMN
93845  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93846    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
93847    return;
93848  }
93849#endif
93850  z = sqlite3NameFromToken(db, pName);
93851  if( z==0 ) return;
93852  for(i=0; i<p->nCol; i++){
93853    if( STRICMP(z, p->aCol[i].zName) ){
93854      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
93855      sqlite3DbFree(db, z);
93856      return;
93857    }
93858  }
93859  if( (p->nCol & 0x7)==0 ){
93860    Column *aNew;
93861    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
93862    if( aNew==0 ){
93863      sqlite3DbFree(db, z);
93864      return;
93865    }
93866    p->aCol = aNew;
93867  }
93868  pCol = &p->aCol[p->nCol];
93869  memset(pCol, 0, sizeof(p->aCol[0]));
93870  pCol->zName = z;
93871
93872  /* If there is no type specified, columns have the default affinity
93873  ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
93874  ** be called next to set pCol->affinity correctly.
93875  */
93876  pCol->affinity = SQLITE_AFF_BLOB;
93877  pCol->szEst = 1;
93878  p->nCol++;
93879}
93880
93881/*
93882** This routine is called by the parser while in the middle of
93883** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
93884** been seen on a column.  This routine sets the notNull flag on
93885** the column currently under construction.
93886*/
93887SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
93888  Table *p;
93889  p = pParse->pNewTable;
93890  if( p==0 || NEVER(p->nCol<1) ) return;
93891  p->aCol[p->nCol-1].notNull = (u8)onError;
93892}
93893
93894/*
93895** Scan the column type name zType (length nType) and return the
93896** associated affinity type.
93897**
93898** This routine does a case-independent search of zType for the
93899** substrings in the following table. If one of the substrings is
93900** found, the corresponding affinity is returned. If zType contains
93901** more than one of the substrings, entries toward the top of
93902** the table take priority. For example, if zType is 'BLOBINT',
93903** SQLITE_AFF_INTEGER is returned.
93904**
93905** Substring     | Affinity
93906** --------------------------------
93907** 'INT'         | SQLITE_AFF_INTEGER
93908** 'CHAR'        | SQLITE_AFF_TEXT
93909** 'CLOB'        | SQLITE_AFF_TEXT
93910** 'TEXT'        | SQLITE_AFF_TEXT
93911** 'BLOB'        | SQLITE_AFF_BLOB
93912** 'REAL'        | SQLITE_AFF_REAL
93913** 'FLOA'        | SQLITE_AFF_REAL
93914** 'DOUB'        | SQLITE_AFF_REAL
93915**
93916** If none of the substrings in the above table are found,
93917** SQLITE_AFF_NUMERIC is returned.
93918*/
93919SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
93920  u32 h = 0;
93921  char aff = SQLITE_AFF_NUMERIC;
93922  const char *zChar = 0;
93923
93924  if( zIn==0 ) return aff;
93925  while( zIn[0] ){
93926    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
93927    zIn++;
93928    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
93929      aff = SQLITE_AFF_TEXT;
93930      zChar = zIn;
93931    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
93932      aff = SQLITE_AFF_TEXT;
93933    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
93934      aff = SQLITE_AFF_TEXT;
93935    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
93936        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
93937      aff = SQLITE_AFF_BLOB;
93938      if( zIn[0]=='(' ) zChar = zIn;
93939#ifndef SQLITE_OMIT_FLOATING_POINT
93940    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
93941        && aff==SQLITE_AFF_NUMERIC ){
93942      aff = SQLITE_AFF_REAL;
93943    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
93944        && aff==SQLITE_AFF_NUMERIC ){
93945      aff = SQLITE_AFF_REAL;
93946    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
93947        && aff==SQLITE_AFF_NUMERIC ){
93948      aff = SQLITE_AFF_REAL;
93949#endif
93950    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
93951      aff = SQLITE_AFF_INTEGER;
93952      break;
93953    }
93954  }
93955
93956  /* If pszEst is not NULL, store an estimate of the field size.  The
93957  ** estimate is scaled so that the size of an integer is 1.  */
93958  if( pszEst ){
93959    *pszEst = 1;   /* default size is approx 4 bytes */
93960    if( aff<SQLITE_AFF_NUMERIC ){
93961      if( zChar ){
93962        while( zChar[0] ){
93963          if( sqlite3Isdigit(zChar[0]) ){
93964            int v = 0;
93965            sqlite3GetInt32(zChar, &v);
93966            v = v/4 + 1;
93967            if( v>255 ) v = 255;
93968            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
93969            break;
93970          }
93971          zChar++;
93972        }
93973      }else{
93974        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
93975      }
93976    }
93977  }
93978  return aff;
93979}
93980
93981/*
93982** This routine is called by the parser while in the middle of
93983** parsing a CREATE TABLE statement.  The pFirst token is the first
93984** token in the sequence of tokens that describe the type of the
93985** column currently under construction.   pLast is the last token
93986** in the sequence.  Use this information to construct a string
93987** that contains the typename of the column and store that string
93988** in zType.
93989*/
93990SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
93991  Table *p;
93992  Column *pCol;
93993
93994  p = pParse->pNewTable;
93995  if( p==0 || NEVER(p->nCol<1) ) return;
93996  pCol = &p->aCol[p->nCol-1];
93997  assert( pCol->zType==0 || CORRUPT_DB );
93998  sqlite3DbFree(pParse->db, pCol->zType);
93999  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
94000  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
94001}
94002
94003/*
94004** The expression is the default value for the most recently added column
94005** of the table currently under construction.
94006**
94007** Default value expressions must be constant.  Raise an exception if this
94008** is not the case.
94009**
94010** This routine is called by the parser while in the middle of
94011** parsing a CREATE TABLE statement.
94012*/
94013SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
94014  Table *p;
94015  Column *pCol;
94016  sqlite3 *db = pParse->db;
94017  p = pParse->pNewTable;
94018  if( p!=0 ){
94019    pCol = &(p->aCol[p->nCol-1]);
94020    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
94021      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
94022          pCol->zName);
94023    }else{
94024      /* A copy of pExpr is used instead of the original, as pExpr contains
94025      ** tokens that point to volatile memory. The 'span' of the expression
94026      ** is required by pragma table_info.
94027      */
94028      sqlite3ExprDelete(db, pCol->pDflt);
94029      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
94030      sqlite3DbFree(db, pCol->zDflt);
94031      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
94032                                     (int)(pSpan->zEnd - pSpan->zStart));
94033    }
94034  }
94035  sqlite3ExprDelete(db, pSpan->pExpr);
94036}
94037
94038/*
94039** Backwards Compatibility Hack:
94040**
94041** Historical versions of SQLite accepted strings as column names in
94042** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
94043**
94044**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
94045**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
94046**
94047** This is goofy.  But to preserve backwards compatibility we continue to
94048** accept it.  This routine does the necessary conversion.  It converts
94049** the expression given in its argument from a TK_STRING into a TK_ID
94050** if the expression is just a TK_STRING with an optional COLLATE clause.
94051** If the epxression is anything other than TK_STRING, the expression is
94052** unchanged.
94053*/
94054static void sqlite3StringToId(Expr *p){
94055  if( p->op==TK_STRING ){
94056    p->op = TK_ID;
94057  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
94058    p->pLeft->op = TK_ID;
94059  }
94060}
94061
94062/*
94063** Designate the PRIMARY KEY for the table.  pList is a list of names
94064** of columns that form the primary key.  If pList is NULL, then the
94065** most recently added column of the table is the primary key.
94066**
94067** A table can have at most one primary key.  If the table already has
94068** a primary key (and this is the second primary key) then create an
94069** error.
94070**
94071** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
94072** then we will try to use that column as the rowid.  Set the Table.iPKey
94073** field of the table under construction to be the index of the
94074** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
94075** no INTEGER PRIMARY KEY.
94076**
94077** If the key is not an INTEGER PRIMARY KEY, then create a unique
94078** index for the key.  No index is created for INTEGER PRIMARY KEYs.
94079*/
94080SQLITE_PRIVATE void sqlite3AddPrimaryKey(
94081  Parse *pParse,    /* Parsing context */
94082  ExprList *pList,  /* List of field names to be indexed */
94083  int onError,      /* What to do with a uniqueness conflict */
94084  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
94085  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
94086){
94087  Table *pTab = pParse->pNewTable;
94088  char *zType = 0;
94089  int iCol = -1, i;
94090  int nTerm;
94091  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
94092  if( pTab->tabFlags & TF_HasPrimaryKey ){
94093    sqlite3ErrorMsg(pParse,
94094      "table \"%s\" has more than one primary key", pTab->zName);
94095    goto primary_key_exit;
94096  }
94097  pTab->tabFlags |= TF_HasPrimaryKey;
94098  if( pList==0 ){
94099    iCol = pTab->nCol - 1;
94100    pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
94101    zType = pTab->aCol[iCol].zType;
94102    nTerm = 1;
94103  }else{
94104    nTerm = pList->nExpr;
94105    for(i=0; i<nTerm; i++){
94106      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
94107      assert( pCExpr!=0 );
94108      sqlite3StringToId(pCExpr);
94109      if( pCExpr->op==TK_ID ){
94110        const char *zCName = pCExpr->u.zToken;
94111        for(iCol=0; iCol<pTab->nCol; iCol++){
94112          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
94113            pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
94114            zType = pTab->aCol[iCol].zType;
94115            break;
94116          }
94117        }
94118      }
94119    }
94120  }
94121  if( nTerm==1
94122   && zType && sqlite3StrICmp(zType, "INTEGER")==0
94123   && sortOrder!=SQLITE_SO_DESC
94124  ){
94125    pTab->iPKey = iCol;
94126    pTab->keyConf = (u8)onError;
94127    assert( autoInc==0 || autoInc==1 );
94128    pTab->tabFlags |= autoInc*TF_Autoincrement;
94129    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
94130  }else if( autoInc ){
94131#ifndef SQLITE_OMIT_AUTOINCREMENT
94132    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
94133       "INTEGER PRIMARY KEY");
94134#endif
94135  }else{
94136    Index *p;
94137    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
94138                           0, sortOrder, 0);
94139    if( p ){
94140      p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
94141    }
94142    pList = 0;
94143  }
94144
94145primary_key_exit:
94146  sqlite3ExprListDelete(pParse->db, pList);
94147  return;
94148}
94149
94150/*
94151** Add a new CHECK constraint to the table currently under construction.
94152*/
94153SQLITE_PRIVATE void sqlite3AddCheckConstraint(
94154  Parse *pParse,    /* Parsing context */
94155  Expr *pCheckExpr  /* The check expression */
94156){
94157#ifndef SQLITE_OMIT_CHECK
94158  Table *pTab = pParse->pNewTable;
94159  sqlite3 *db = pParse->db;
94160  if( pTab && !IN_DECLARE_VTAB
94161   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
94162  ){
94163    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
94164    if( pParse->constraintName.n ){
94165      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
94166    }
94167  }else
94168#endif
94169  {
94170    sqlite3ExprDelete(pParse->db, pCheckExpr);
94171  }
94172}
94173
94174/*
94175** Set the collation function of the most recently parsed table column
94176** to the CollSeq given.
94177*/
94178SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
94179  Table *p;
94180  int i;
94181  char *zColl;              /* Dequoted name of collation sequence */
94182  sqlite3 *db;
94183
94184  if( (p = pParse->pNewTable)==0 ) return;
94185  i = p->nCol-1;
94186  db = pParse->db;
94187  zColl = sqlite3NameFromToken(db, pToken);
94188  if( !zColl ) return;
94189
94190  if( sqlite3LocateCollSeq(pParse, zColl) ){
94191    Index *pIdx;
94192    sqlite3DbFree(db, p->aCol[i].zColl);
94193    p->aCol[i].zColl = zColl;
94194
94195    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
94196    ** then an index may have been created on this column before the
94197    ** collation type was added. Correct this if it is the case.
94198    */
94199    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
94200      assert( pIdx->nKeyCol==1 );
94201      if( pIdx->aiColumn[0]==i ){
94202        pIdx->azColl[0] = p->aCol[i].zColl;
94203      }
94204    }
94205  }else{
94206    sqlite3DbFree(db, zColl);
94207  }
94208}
94209
94210/*
94211** This function returns the collation sequence for database native text
94212** encoding identified by the string zName, length nName.
94213**
94214** If the requested collation sequence is not available, or not available
94215** in the database native encoding, the collation factory is invoked to
94216** request it. If the collation factory does not supply such a sequence,
94217** and the sequence is available in another text encoding, then that is
94218** returned instead.
94219**
94220** If no versions of the requested collations sequence are available, or
94221** another error occurs, NULL is returned and an error message written into
94222** pParse.
94223**
94224** This routine is a wrapper around sqlite3FindCollSeq().  This routine
94225** invokes the collation factory if the named collation cannot be found
94226** and generates an error message.
94227**
94228** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
94229*/
94230SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
94231  sqlite3 *db = pParse->db;
94232  u8 enc = ENC(db);
94233  u8 initbusy = db->init.busy;
94234  CollSeq *pColl;
94235
94236  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
94237  if( !initbusy && (!pColl || !pColl->xCmp) ){
94238    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
94239  }
94240
94241  return pColl;
94242}
94243
94244
94245/*
94246** Generate code that will increment the schema cookie.
94247**
94248** The schema cookie is used to determine when the schema for the
94249** database changes.  After each schema change, the cookie value
94250** changes.  When a process first reads the schema it records the
94251** cookie.  Thereafter, whenever it goes to access the database,
94252** it checks the cookie to make sure the schema has not changed
94253** since it was last read.
94254**
94255** This plan is not completely bullet-proof.  It is possible for
94256** the schema to change multiple times and for the cookie to be
94257** set back to prior value.  But schema changes are infrequent
94258** and the probability of hitting the same cookie value is only
94259** 1 chance in 2^32.  So we're safe enough.
94260*/
94261SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
94262  int r1 = sqlite3GetTempReg(pParse);
94263  sqlite3 *db = pParse->db;
94264  Vdbe *v = pParse->pVdbe;
94265  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94266  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
94267  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
94268  sqlite3ReleaseTempReg(pParse, r1);
94269}
94270
94271/*
94272** Measure the number of characters needed to output the given
94273** identifier.  The number returned includes any quotes used
94274** but does not include the null terminator.
94275**
94276** The estimate is conservative.  It might be larger that what is
94277** really needed.
94278*/
94279static int identLength(const char *z){
94280  int n;
94281  for(n=0; *z; n++, z++){
94282    if( *z=='"' ){ n++; }
94283  }
94284  return n + 2;
94285}
94286
94287/*
94288** The first parameter is a pointer to an output buffer. The second
94289** parameter is a pointer to an integer that contains the offset at
94290** which to write into the output buffer. This function copies the
94291** nul-terminated string pointed to by the third parameter, zSignedIdent,
94292** to the specified offset in the buffer and updates *pIdx to refer
94293** to the first byte after the last byte written before returning.
94294**
94295** If the string zSignedIdent consists entirely of alpha-numeric
94296** characters, does not begin with a digit and is not an SQL keyword,
94297** then it is copied to the output buffer exactly as it is. Otherwise,
94298** it is quoted using double-quotes.
94299*/
94300static void identPut(char *z, int *pIdx, char *zSignedIdent){
94301  unsigned char *zIdent = (unsigned char*)zSignedIdent;
94302  int i, j, needQuote;
94303  i = *pIdx;
94304
94305  for(j=0; zIdent[j]; j++){
94306    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
94307  }
94308  needQuote = sqlite3Isdigit(zIdent[0])
94309            || sqlite3KeywordCode(zIdent, j)!=TK_ID
94310            || zIdent[j]!=0
94311            || j==0;
94312
94313  if( needQuote ) z[i++] = '"';
94314  for(j=0; zIdent[j]; j++){
94315    z[i++] = zIdent[j];
94316    if( zIdent[j]=='"' ) z[i++] = '"';
94317  }
94318  if( needQuote ) z[i++] = '"';
94319  z[i] = 0;
94320  *pIdx = i;
94321}
94322
94323/*
94324** Generate a CREATE TABLE statement appropriate for the given
94325** table.  Memory to hold the text of the statement is obtained
94326** from sqliteMalloc() and must be freed by the calling function.
94327*/
94328static char *createTableStmt(sqlite3 *db, Table *p){
94329  int i, k, n;
94330  char *zStmt;
94331  char *zSep, *zSep2, *zEnd;
94332  Column *pCol;
94333  n = 0;
94334  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
94335    n += identLength(pCol->zName) + 5;
94336  }
94337  n += identLength(p->zName);
94338  if( n<50 ){
94339    zSep = "";
94340    zSep2 = ",";
94341    zEnd = ")";
94342  }else{
94343    zSep = "\n  ";
94344    zSep2 = ",\n  ";
94345    zEnd = "\n)";
94346  }
94347  n += 35 + 6*p->nCol;
94348  zStmt = sqlite3DbMallocRaw(0, n);
94349  if( zStmt==0 ){
94350    db->mallocFailed = 1;
94351    return 0;
94352  }
94353  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
94354  k = sqlite3Strlen30(zStmt);
94355  identPut(zStmt, &k, p->zName);
94356  zStmt[k++] = '(';
94357  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
94358    static const char * const azType[] = {
94359        /* SQLITE_AFF_BLOB    */ "",
94360        /* SQLITE_AFF_TEXT    */ " TEXT",
94361        /* SQLITE_AFF_NUMERIC */ " NUM",
94362        /* SQLITE_AFF_INTEGER */ " INT",
94363        /* SQLITE_AFF_REAL    */ " REAL"
94364    };
94365    int len;
94366    const char *zType;
94367
94368    sqlite3_snprintf(n-k, &zStmt[k], zSep);
94369    k += sqlite3Strlen30(&zStmt[k]);
94370    zSep = zSep2;
94371    identPut(zStmt, &k, pCol->zName);
94372    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
94373    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
94374    testcase( pCol->affinity==SQLITE_AFF_BLOB );
94375    testcase( pCol->affinity==SQLITE_AFF_TEXT );
94376    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
94377    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
94378    testcase( pCol->affinity==SQLITE_AFF_REAL );
94379
94380    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
94381    len = sqlite3Strlen30(zType);
94382    assert( pCol->affinity==SQLITE_AFF_BLOB
94383            || pCol->affinity==sqlite3AffinityType(zType, 0) );
94384    memcpy(&zStmt[k], zType, len);
94385    k += len;
94386    assert( k<=n );
94387  }
94388  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
94389  return zStmt;
94390}
94391
94392/*
94393** Resize an Index object to hold N columns total.  Return SQLITE_OK
94394** on success and SQLITE_NOMEM on an OOM error.
94395*/
94396static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
94397  char *zExtra;
94398  int nByte;
94399  if( pIdx->nColumn>=N ) return SQLITE_OK;
94400  assert( pIdx->isResized==0 );
94401  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
94402  zExtra = sqlite3DbMallocZero(db, nByte);
94403  if( zExtra==0 ) return SQLITE_NOMEM;
94404  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
94405  pIdx->azColl = (char**)zExtra;
94406  zExtra += sizeof(char*)*N;
94407  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
94408  pIdx->aiColumn = (i16*)zExtra;
94409  zExtra += sizeof(i16)*N;
94410  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
94411  pIdx->aSortOrder = (u8*)zExtra;
94412  pIdx->nColumn = N;
94413  pIdx->isResized = 1;
94414  return SQLITE_OK;
94415}
94416
94417/*
94418** Estimate the total row width for a table.
94419*/
94420static void estimateTableWidth(Table *pTab){
94421  unsigned wTable = 0;
94422  const Column *pTabCol;
94423  int i;
94424  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
94425    wTable += pTabCol->szEst;
94426  }
94427  if( pTab->iPKey<0 ) wTable++;
94428  pTab->szTabRow = sqlite3LogEst(wTable*4);
94429}
94430
94431/*
94432** Estimate the average size of a row for an index.
94433*/
94434static void estimateIndexWidth(Index *pIdx){
94435  unsigned wIndex = 0;
94436  int i;
94437  const Column *aCol = pIdx->pTable->aCol;
94438  for(i=0; i<pIdx->nColumn; i++){
94439    i16 x = pIdx->aiColumn[i];
94440    assert( x<pIdx->pTable->nCol );
94441    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
94442  }
94443  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
94444}
94445
94446/* Return true if value x is found any of the first nCol entries of aiCol[]
94447*/
94448static int hasColumn(const i16 *aiCol, int nCol, int x){
94449  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
94450  return 0;
94451}
94452
94453/*
94454** This routine runs at the end of parsing a CREATE TABLE statement that
94455** has a WITHOUT ROWID clause.  The job of this routine is to convert both
94456** internal schema data structures and the generated VDBE code so that they
94457** are appropriate for a WITHOUT ROWID table instead of a rowid table.
94458** Changes include:
94459**
94460**     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
94461**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
94462**          data storage is a covering index btree.
94463**     (2)  Bypass the creation of the sqlite_master table entry
94464**          for the PRIMARY KEY as the primary key index is now
94465**          identified by the sqlite_master table entry of the table itself.
94466**     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
94467**          schema to the rootpage from the main table.
94468**     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
94469**     (5)  Add all table columns to the PRIMARY KEY Index object
94470**          so that the PRIMARY KEY is a covering index.  The surplus
94471**          columns are part of KeyInfo.nXField and are not used for
94472**          sorting or lookup or uniqueness checks.
94473**     (6)  Replace the rowid tail on all automatically generated UNIQUE
94474**          indices with the PRIMARY KEY columns.
94475*/
94476static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
94477  Index *pIdx;
94478  Index *pPk;
94479  int nPk;
94480  int i, j;
94481  sqlite3 *db = pParse->db;
94482  Vdbe *v = pParse->pVdbe;
94483
94484  /* Convert the OP_CreateTable opcode that would normally create the
94485  ** root-page for the table into an OP_CreateIndex opcode.  The index
94486  ** created will become the PRIMARY KEY index.
94487  */
94488  if( pParse->addrCrTab ){
94489    assert( v );
94490    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
94491  }
94492
94493  /* Locate the PRIMARY KEY index.  Or, if this table was originally
94494  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
94495  */
94496  if( pTab->iPKey>=0 ){
94497    ExprList *pList;
94498    Token ipkToken;
94499    ipkToken.z = pTab->aCol[pTab->iPKey].zName;
94500    ipkToken.n = sqlite3Strlen30(ipkToken.z);
94501    pList = sqlite3ExprListAppend(pParse, 0,
94502                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
94503    if( pList==0 ) return;
94504    pList->a[0].sortOrder = pParse->iPkSortOrder;
94505    assert( pParse->pNewTable==pTab );
94506    pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
94507    if( pPk==0 ) return;
94508    pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
94509    pTab->iPKey = -1;
94510  }else{
94511    pPk = sqlite3PrimaryKeyIndex(pTab);
94512
94513    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
94514    ** table entry. This is only required if currently generating VDBE
94515    ** code for a CREATE TABLE (not when parsing one as part of reading
94516    ** a database schema).  */
94517    if( v ){
94518      assert( db->init.busy==0 );
94519      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
94520    }
94521
94522    /*
94523    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
94524    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
94525    ** code assumes the PRIMARY KEY contains no repeated columns.
94526    */
94527    for(i=j=1; i<pPk->nKeyCol; i++){
94528      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
94529        pPk->nColumn--;
94530      }else{
94531        pPk->aiColumn[j++] = pPk->aiColumn[i];
94532      }
94533    }
94534    pPk->nKeyCol = j;
94535  }
94536  pPk->isCovering = 1;
94537  assert( pPk!=0 );
94538  nPk = pPk->nKeyCol;
94539
94540  /* Make sure every column of the PRIMARY KEY is NOT NULL.  (Except,
94541  ** do not enforce this for imposter tables.) */
94542  if( !db->init.imposterTable ){
94543    for(i=0; i<nPk; i++){
94544      pTab->aCol[pPk->aiColumn[i]].notNull = 1;
94545    }
94546    pPk->uniqNotNull = 1;
94547  }
94548
94549  /* The root page of the PRIMARY KEY is the table root page */
94550  pPk->tnum = pTab->tnum;
94551
94552  /* Update the in-memory representation of all UNIQUE indices by converting
94553  ** the final rowid column into one or more columns of the PRIMARY KEY.
94554  */
94555  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94556    int n;
94557    if( IsPrimaryKeyIndex(pIdx) ) continue;
94558    for(i=n=0; i<nPk; i++){
94559      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
94560    }
94561    if( n==0 ){
94562      /* This index is a superset of the primary key */
94563      pIdx->nColumn = pIdx->nKeyCol;
94564      continue;
94565    }
94566    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
94567    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
94568      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
94569        pIdx->aiColumn[j] = pPk->aiColumn[i];
94570        pIdx->azColl[j] = pPk->azColl[i];
94571        j++;
94572      }
94573    }
94574    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
94575    assert( pIdx->nColumn>=j );
94576  }
94577
94578  /* Add all table columns to the PRIMARY KEY index
94579  */
94580  if( nPk<pTab->nCol ){
94581    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
94582    for(i=0, j=nPk; i<pTab->nCol; i++){
94583      if( !hasColumn(pPk->aiColumn, j, i) ){
94584        assert( j<pPk->nColumn );
94585        pPk->aiColumn[j] = i;
94586        pPk->azColl[j] = "BINARY";
94587        j++;
94588      }
94589    }
94590    assert( pPk->nColumn==j );
94591    assert( pTab->nCol==j );
94592  }else{
94593    pPk->nColumn = pTab->nCol;
94594  }
94595}
94596
94597/*
94598** This routine is called to report the final ")" that terminates
94599** a CREATE TABLE statement.
94600**
94601** The table structure that other action routines have been building
94602** is added to the internal hash tables, assuming no errors have
94603** occurred.
94604**
94605** An entry for the table is made in the master table on disk, unless
94606** this is a temporary table or db->init.busy==1.  When db->init.busy==1
94607** it means we are reading the sqlite_master table because we just
94608** connected to the database or because the sqlite_master table has
94609** recently changed, so the entry for this table already exists in
94610** the sqlite_master table.  We do not want to create it again.
94611**
94612** If the pSelect argument is not NULL, it means that this routine
94613** was called to create a table generated from a
94614** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
94615** the new table will match the result set of the SELECT.
94616*/
94617SQLITE_PRIVATE void sqlite3EndTable(
94618  Parse *pParse,          /* Parse context */
94619  Token *pCons,           /* The ',' token after the last column defn. */
94620  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
94621  u8 tabOpts,             /* Extra table options. Usually 0. */
94622  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
94623){
94624  Table *p;                 /* The new table */
94625  sqlite3 *db = pParse->db; /* The database connection */
94626  int iDb;                  /* Database in which the table lives */
94627  Index *pIdx;              /* An implied index of the table */
94628
94629  if( pEnd==0 && pSelect==0 ){
94630    return;
94631  }
94632  assert( !db->mallocFailed );
94633  p = pParse->pNewTable;
94634  if( p==0 ) return;
94635
94636  assert( !db->init.busy || !pSelect );
94637
94638  /* If the db->init.busy is 1 it means we are reading the SQL off the
94639  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
94640  ** So do not write to the disk again.  Extract the root page number
94641  ** for the table from the db->init.newTnum field.  (The page number
94642  ** should have been put there by the sqliteOpenCb routine.)
94643  */
94644  if( db->init.busy ){
94645    p->tnum = db->init.newTnum;
94646  }
94647
94648  /* Special processing for WITHOUT ROWID Tables */
94649  if( tabOpts & TF_WithoutRowid ){
94650    if( (p->tabFlags & TF_Autoincrement) ){
94651      sqlite3ErrorMsg(pParse,
94652          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
94653      return;
94654    }
94655    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
94656      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
94657    }else{
94658      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
94659      convertToWithoutRowidTable(pParse, p);
94660    }
94661  }
94662
94663  iDb = sqlite3SchemaToIndex(db, p->pSchema);
94664
94665#ifndef SQLITE_OMIT_CHECK
94666  /* Resolve names in all CHECK constraint expressions.
94667  */
94668  if( p->pCheck ){
94669    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
94670  }
94671#endif /* !defined(SQLITE_OMIT_CHECK) */
94672
94673  /* Estimate the average row size for the table and for all implied indices */
94674  estimateTableWidth(p);
94675  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
94676    estimateIndexWidth(pIdx);
94677  }
94678
94679  /* If not initializing, then create a record for the new table
94680  ** in the SQLITE_MASTER table of the database.
94681  **
94682  ** If this is a TEMPORARY table, write the entry into the auxiliary
94683  ** file instead of into the main database file.
94684  */
94685  if( !db->init.busy ){
94686    int n;
94687    Vdbe *v;
94688    char *zType;    /* "view" or "table" */
94689    char *zType2;   /* "VIEW" or "TABLE" */
94690    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
94691
94692    v = sqlite3GetVdbe(pParse);
94693    if( NEVER(v==0) ) return;
94694
94695    sqlite3VdbeAddOp1(v, OP_Close, 0);
94696
94697    /*
94698    ** Initialize zType for the new view or table.
94699    */
94700    if( p->pSelect==0 ){
94701      /* A regular table */
94702      zType = "table";
94703      zType2 = "TABLE";
94704#ifndef SQLITE_OMIT_VIEW
94705    }else{
94706      /* A view */
94707      zType = "view";
94708      zType2 = "VIEW";
94709#endif
94710    }
94711
94712    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
94713    ** statement to populate the new table. The root-page number for the
94714    ** new table is in register pParse->regRoot.
94715    **
94716    ** Once the SELECT has been coded by sqlite3Select(), it is in a
94717    ** suitable state to query for the column names and types to be used
94718    ** by the new table.
94719    **
94720    ** A shared-cache write-lock is not required to write to the new table,
94721    ** as a schema-lock must have already been obtained to create it. Since
94722    ** a schema-lock excludes all other database users, the write-lock would
94723    ** be redundant.
94724    */
94725    if( pSelect ){
94726      SelectDest dest;    /* Where the SELECT should store results */
94727      int regYield;       /* Register holding co-routine entry-point */
94728      int addrTop;        /* Top of the co-routine */
94729      int regRec;         /* A record to be insert into the new table */
94730      int regRowid;       /* Rowid of the next row to insert */
94731      int addrInsLoop;    /* Top of the loop for inserting rows */
94732      Table *pSelTab;     /* A table that describes the SELECT results */
94733
94734      regYield = ++pParse->nMem;
94735      regRec = ++pParse->nMem;
94736      regRowid = ++pParse->nMem;
94737      assert(pParse->nTab==1);
94738      sqlite3MayAbort(pParse);
94739      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
94740      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
94741      pParse->nTab = 2;
94742      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
94743      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
94744      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
94745      sqlite3Select(pParse, pSelect, &dest);
94746      sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
94747      sqlite3VdbeJumpHere(v, addrTop - 1);
94748      if( pParse->nErr ) return;
94749      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
94750      if( pSelTab==0 ) return;
94751      assert( p->aCol==0 );
94752      p->nCol = pSelTab->nCol;
94753      p->aCol = pSelTab->aCol;
94754      pSelTab->nCol = 0;
94755      pSelTab->aCol = 0;
94756      sqlite3DeleteTable(db, pSelTab);
94757      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
94758      VdbeCoverage(v);
94759      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
94760      sqlite3TableAffinity(v, p, 0);
94761      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
94762      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
94763      sqlite3VdbeGoto(v, addrInsLoop);
94764      sqlite3VdbeJumpHere(v, addrInsLoop);
94765      sqlite3VdbeAddOp1(v, OP_Close, 1);
94766    }
94767
94768    /* Compute the complete text of the CREATE statement */
94769    if( pSelect ){
94770      zStmt = createTableStmt(db, p);
94771    }else{
94772      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
94773      n = (int)(pEnd2->z - pParse->sNameToken.z);
94774      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
94775      zStmt = sqlite3MPrintf(db,
94776          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
94777      );
94778    }
94779
94780    /* A slot for the record has already been allocated in the
94781    ** SQLITE_MASTER table.  We just need to update that slot with all
94782    ** the information we've collected.
94783    */
94784    sqlite3NestedParse(pParse,
94785      "UPDATE %Q.%s "
94786         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
94787       "WHERE rowid=#%d",
94788      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
94789      zType,
94790      p->zName,
94791      p->zName,
94792      pParse->regRoot,
94793      zStmt,
94794      pParse->regRowid
94795    );
94796    sqlite3DbFree(db, zStmt);
94797    sqlite3ChangeCookie(pParse, iDb);
94798
94799#ifndef SQLITE_OMIT_AUTOINCREMENT
94800    /* Check to see if we need to create an sqlite_sequence table for
94801    ** keeping track of autoincrement keys.
94802    */
94803    if( p->tabFlags & TF_Autoincrement ){
94804      Db *pDb = &db->aDb[iDb];
94805      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94806      if( pDb->pSchema->pSeqTab==0 ){
94807        sqlite3NestedParse(pParse,
94808          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
94809          pDb->zName
94810        );
94811      }
94812    }
94813#endif
94814
94815    /* Reparse everything to update our internal data structures */
94816    sqlite3VdbeAddParseSchemaOp(v, iDb,
94817           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
94818  }
94819
94820
94821  /* Add the table to the in-memory representation of the database.
94822  */
94823  if( db->init.busy ){
94824    Table *pOld;
94825    Schema *pSchema = p->pSchema;
94826    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94827    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
94828    if( pOld ){
94829      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
94830      db->mallocFailed = 1;
94831      return;
94832    }
94833    pParse->pNewTable = 0;
94834    db->flags |= SQLITE_InternChanges;
94835
94836#ifndef SQLITE_OMIT_ALTERTABLE
94837    if( !p->pSelect ){
94838      const char *zName = (const char *)pParse->sNameToken.z;
94839      int nName;
94840      assert( !pSelect && pCons && pEnd );
94841      if( pCons->z==0 ){
94842        pCons = pEnd;
94843      }
94844      nName = (int)((const char *)pCons->z - zName);
94845      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
94846    }
94847#endif
94848  }
94849}
94850
94851#ifndef SQLITE_OMIT_VIEW
94852/*
94853** The parser calls this routine in order to create a new VIEW
94854*/
94855SQLITE_PRIVATE void sqlite3CreateView(
94856  Parse *pParse,     /* The parsing context */
94857  Token *pBegin,     /* The CREATE token that begins the statement */
94858  Token *pName1,     /* The token that holds the name of the view */
94859  Token *pName2,     /* The token that holds the name of the view */
94860  ExprList *pCNames, /* Optional list of view column names */
94861  Select *pSelect,   /* A SELECT statement that will become the new view */
94862  int isTemp,        /* TRUE for a TEMPORARY view */
94863  int noErr          /* Suppress error messages if VIEW already exists */
94864){
94865  Table *p;
94866  int n;
94867  const char *z;
94868  Token sEnd;
94869  DbFixer sFix;
94870  Token *pName = 0;
94871  int iDb;
94872  sqlite3 *db = pParse->db;
94873
94874  if( pParse->nVar>0 ){
94875    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
94876    goto create_view_fail;
94877  }
94878  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
94879  p = pParse->pNewTable;
94880  if( p==0 || pParse->nErr ) goto create_view_fail;
94881  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94882  iDb = sqlite3SchemaToIndex(db, p->pSchema);
94883  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
94884  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
94885
94886  /* Make a copy of the entire SELECT statement that defines the view.
94887  ** This will force all the Expr.token.z values to be dynamically
94888  ** allocated rather than point to the input string - which means that
94889  ** they will persist after the current sqlite3_exec() call returns.
94890  */
94891  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
94892  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
94893  if( db->mallocFailed ) goto create_view_fail;
94894
94895  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
94896  ** the end.
94897  */
94898  sEnd = pParse->sLastToken;
94899  assert( sEnd.z[0]!=0 );
94900  if( sEnd.z[0]!=';' ){
94901    sEnd.z += sEnd.n;
94902  }
94903  sEnd.n = 0;
94904  n = (int)(sEnd.z - pBegin->z);
94905  assert( n>0 );
94906  z = pBegin->z;
94907  while( sqlite3Isspace(z[n-1]) ){ n--; }
94908  sEnd.z = &z[n-1];
94909  sEnd.n = 1;
94910
94911  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
94912  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
94913
94914create_view_fail:
94915  sqlite3SelectDelete(db, pSelect);
94916  sqlite3ExprListDelete(db, pCNames);
94917  return;
94918}
94919#endif /* SQLITE_OMIT_VIEW */
94920
94921#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
94922/*
94923** The Table structure pTable is really a VIEW.  Fill in the names of
94924** the columns of the view in the pTable structure.  Return the number
94925** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
94926*/
94927SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
94928  Table *pSelTab;   /* A fake table from which we get the result set */
94929  Select *pSel;     /* Copy of the SELECT that implements the view */
94930  int nErr = 0;     /* Number of errors encountered */
94931  int n;            /* Temporarily holds the number of cursors assigned */
94932  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
94933  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
94934  u8 bEnabledLA;             /* Saved db->lookaside.bEnabled state */
94935
94936  assert( pTable );
94937
94938#ifndef SQLITE_OMIT_VIRTUALTABLE
94939  if( sqlite3VtabCallConnect(pParse, pTable) ){
94940    return SQLITE_ERROR;
94941  }
94942  if( IsVirtual(pTable) ) return 0;
94943#endif
94944
94945#ifndef SQLITE_OMIT_VIEW
94946  /* A positive nCol means the columns names for this view are
94947  ** already known.
94948  */
94949  if( pTable->nCol>0 ) return 0;
94950
94951  /* A negative nCol is a special marker meaning that we are currently
94952  ** trying to compute the column names.  If we enter this routine with
94953  ** a negative nCol, it means two or more views form a loop, like this:
94954  **
94955  **     CREATE VIEW one AS SELECT * FROM two;
94956  **     CREATE VIEW two AS SELECT * FROM one;
94957  **
94958  ** Actually, the error above is now caught prior to reaching this point.
94959  ** But the following test is still important as it does come up
94960  ** in the following:
94961  **
94962  **     CREATE TABLE main.ex1(a);
94963  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
94964  **     SELECT * FROM temp.ex1;
94965  */
94966  if( pTable->nCol<0 ){
94967    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
94968    return 1;
94969  }
94970  assert( pTable->nCol>=0 );
94971
94972  /* If we get this far, it means we need to compute the table names.
94973  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
94974  ** "*" elements in the results set of the view and will assign cursors
94975  ** to the elements of the FROM clause.  But we do not want these changes
94976  ** to be permanent.  So the computation is done on a copy of the SELECT
94977  ** statement that defines the view.
94978  */
94979  assert( pTable->pSelect );
94980  bEnabledLA = db->lookaside.bEnabled;
94981  if( pTable->pCheck ){
94982    db->lookaside.bEnabled = 0;
94983    sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
94984                               &pTable->nCol, &pTable->aCol);
94985  }else{
94986    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
94987    if( pSel ){
94988      n = pParse->nTab;
94989      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
94990      pTable->nCol = -1;
94991      db->lookaside.bEnabled = 0;
94992#ifndef SQLITE_OMIT_AUTHORIZATION
94993      xAuth = db->xAuth;
94994      db->xAuth = 0;
94995      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
94996      db->xAuth = xAuth;
94997#else
94998      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
94999#endif
95000      pParse->nTab = n;
95001      if( pSelTab ){
95002        assert( pTable->aCol==0 );
95003        pTable->nCol = pSelTab->nCol;
95004        pTable->aCol = pSelTab->aCol;
95005        pSelTab->nCol = 0;
95006        pSelTab->aCol = 0;
95007        sqlite3DeleteTable(db, pSelTab);
95008        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
95009      }else{
95010        pTable->nCol = 0;
95011        nErr++;
95012      }
95013      sqlite3SelectDelete(db, pSel);
95014    } else {
95015      nErr++;
95016    }
95017  }
95018  db->lookaside.bEnabled = bEnabledLA;
95019  pTable->pSchema->schemaFlags |= DB_UnresetViews;
95020#endif /* SQLITE_OMIT_VIEW */
95021  return nErr;
95022}
95023#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
95024
95025#ifndef SQLITE_OMIT_VIEW
95026/*
95027** Clear the column names from every VIEW in database idx.
95028*/
95029static void sqliteViewResetAll(sqlite3 *db, int idx){
95030  HashElem *i;
95031  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
95032  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
95033  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
95034    Table *pTab = sqliteHashData(i);
95035    if( pTab->pSelect ){
95036      sqlite3DeleteColumnNames(db, pTab);
95037      pTab->aCol = 0;
95038      pTab->nCol = 0;
95039    }
95040  }
95041  DbClearProperty(db, idx, DB_UnresetViews);
95042}
95043#else
95044# define sqliteViewResetAll(A,B)
95045#endif /* SQLITE_OMIT_VIEW */
95046
95047/*
95048** This function is called by the VDBE to adjust the internal schema
95049** used by SQLite when the btree layer moves a table root page. The
95050** root-page of a table or index in database iDb has changed from iFrom
95051** to iTo.
95052**
95053** Ticket #1728:  The symbol table might still contain information
95054** on tables and/or indices that are the process of being deleted.
95055** If you are unlucky, one of those deleted indices or tables might
95056** have the same rootpage number as the real table or index that is
95057** being moved.  So we cannot stop searching after the first match
95058** because the first match might be for one of the deleted indices
95059** or tables and not the table/index that is actually being moved.
95060** We must continue looping until all tables and indices with
95061** rootpage==iFrom have been converted to have a rootpage of iTo
95062** in order to be certain that we got the right one.
95063*/
95064#ifndef SQLITE_OMIT_AUTOVACUUM
95065SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
95066  HashElem *pElem;
95067  Hash *pHash;
95068  Db *pDb;
95069
95070  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95071  pDb = &db->aDb[iDb];
95072  pHash = &pDb->pSchema->tblHash;
95073  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
95074    Table *pTab = sqliteHashData(pElem);
95075    if( pTab->tnum==iFrom ){
95076      pTab->tnum = iTo;
95077    }
95078  }
95079  pHash = &pDb->pSchema->idxHash;
95080  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
95081    Index *pIdx = sqliteHashData(pElem);
95082    if( pIdx->tnum==iFrom ){
95083      pIdx->tnum = iTo;
95084    }
95085  }
95086}
95087#endif
95088
95089/*
95090** Write code to erase the table with root-page iTable from database iDb.
95091** Also write code to modify the sqlite_master table and internal schema
95092** if a root-page of another table is moved by the btree-layer whilst
95093** erasing iTable (this can happen with an auto-vacuum database).
95094*/
95095static void destroyRootPage(Parse *pParse, int iTable, int iDb){
95096  Vdbe *v = sqlite3GetVdbe(pParse);
95097  int r1 = sqlite3GetTempReg(pParse);
95098  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
95099  sqlite3MayAbort(pParse);
95100#ifndef SQLITE_OMIT_AUTOVACUUM
95101  /* OP_Destroy stores an in integer r1. If this integer
95102  ** is non-zero, then it is the root page number of a table moved to
95103  ** location iTable. The following code modifies the sqlite_master table to
95104  ** reflect this.
95105  **
95106  ** The "#NNN" in the SQL is a special constant that means whatever value
95107  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
95108  ** token for additional information.
95109  */
95110  sqlite3NestedParse(pParse,
95111     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
95112     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
95113#endif
95114  sqlite3ReleaseTempReg(pParse, r1);
95115}
95116
95117/*
95118** Write VDBE code to erase table pTab and all associated indices on disk.
95119** Code to update the sqlite_master tables and internal schema definitions
95120** in case a root-page belonging to another table is moved by the btree layer
95121** is also added (this can happen with an auto-vacuum database).
95122*/
95123static void destroyTable(Parse *pParse, Table *pTab){
95124#ifdef SQLITE_OMIT_AUTOVACUUM
95125  Index *pIdx;
95126  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95127  destroyRootPage(pParse, pTab->tnum, iDb);
95128  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95129    destroyRootPage(pParse, pIdx->tnum, iDb);
95130  }
95131#else
95132  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
95133  ** is not defined), then it is important to call OP_Destroy on the
95134  ** table and index root-pages in order, starting with the numerically
95135  ** largest root-page number. This guarantees that none of the root-pages
95136  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
95137  ** following were coded:
95138  **
95139  ** OP_Destroy 4 0
95140  ** ...
95141  ** OP_Destroy 5 0
95142  **
95143  ** and root page 5 happened to be the largest root-page number in the
95144  ** database, then root page 5 would be moved to page 4 by the
95145  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
95146  ** a free-list page.
95147  */
95148  int iTab = pTab->tnum;
95149  int iDestroyed = 0;
95150
95151  while( 1 ){
95152    Index *pIdx;
95153    int iLargest = 0;
95154
95155    if( iDestroyed==0 || iTab<iDestroyed ){
95156      iLargest = iTab;
95157    }
95158    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95159      int iIdx = pIdx->tnum;
95160      assert( pIdx->pSchema==pTab->pSchema );
95161      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
95162        iLargest = iIdx;
95163      }
95164    }
95165    if( iLargest==0 ){
95166      return;
95167    }else{
95168      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95169      assert( iDb>=0 && iDb<pParse->db->nDb );
95170      destroyRootPage(pParse, iLargest, iDb);
95171      iDestroyed = iLargest;
95172    }
95173  }
95174#endif
95175}
95176
95177/*
95178** Remove entries from the sqlite_statN tables (for N in (1,2,3))
95179** after a DROP INDEX or DROP TABLE command.
95180*/
95181static void sqlite3ClearStatTables(
95182  Parse *pParse,         /* The parsing context */
95183  int iDb,               /* The database number */
95184  const char *zType,     /* "idx" or "tbl" */
95185  const char *zName      /* Name of index or table */
95186){
95187  int i;
95188  const char *zDbName = pParse->db->aDb[iDb].zName;
95189  for(i=1; i<=4; i++){
95190    char zTab[24];
95191    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
95192    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
95193      sqlite3NestedParse(pParse,
95194        "DELETE FROM %Q.%s WHERE %s=%Q",
95195        zDbName, zTab, zType, zName
95196      );
95197    }
95198  }
95199}
95200
95201/*
95202** Generate code to drop a table.
95203*/
95204SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
95205  Vdbe *v;
95206  sqlite3 *db = pParse->db;
95207  Trigger *pTrigger;
95208  Db *pDb = &db->aDb[iDb];
95209
95210  v = sqlite3GetVdbe(pParse);
95211  assert( v!=0 );
95212  sqlite3BeginWriteOperation(pParse, 1, iDb);
95213
95214#ifndef SQLITE_OMIT_VIRTUALTABLE
95215  if( IsVirtual(pTab) ){
95216    sqlite3VdbeAddOp0(v, OP_VBegin);
95217  }
95218#endif
95219
95220  /* Drop all triggers associated with the table being dropped. Code
95221  ** is generated to remove entries from sqlite_master and/or
95222  ** sqlite_temp_master if required.
95223  */
95224  pTrigger = sqlite3TriggerList(pParse, pTab);
95225  while( pTrigger ){
95226    assert( pTrigger->pSchema==pTab->pSchema ||
95227        pTrigger->pSchema==db->aDb[1].pSchema );
95228    sqlite3DropTriggerPtr(pParse, pTrigger);
95229    pTrigger = pTrigger->pNext;
95230  }
95231
95232#ifndef SQLITE_OMIT_AUTOINCREMENT
95233  /* Remove any entries of the sqlite_sequence table associated with
95234  ** the table being dropped. This is done before the table is dropped
95235  ** at the btree level, in case the sqlite_sequence table needs to
95236  ** move as a result of the drop (can happen in auto-vacuum mode).
95237  */
95238  if( pTab->tabFlags & TF_Autoincrement ){
95239    sqlite3NestedParse(pParse,
95240      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
95241      pDb->zName, pTab->zName
95242    );
95243  }
95244#endif
95245
95246  /* Drop all SQLITE_MASTER table and index entries that refer to the
95247  ** table. The program name loops through the master table and deletes
95248  ** every row that refers to a table of the same name as the one being
95249  ** dropped. Triggers are handled separately because a trigger can be
95250  ** created in the temp database that refers to a table in another
95251  ** database.
95252  */
95253  sqlite3NestedParse(pParse,
95254      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
95255      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
95256  if( !isView && !IsVirtual(pTab) ){
95257    destroyTable(pParse, pTab);
95258  }
95259
95260  /* Remove the table entry from SQLite's internal schema and modify
95261  ** the schema cookie.
95262  */
95263  if( IsVirtual(pTab) ){
95264    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
95265  }
95266  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
95267  sqlite3ChangeCookie(pParse, iDb);
95268  sqliteViewResetAll(db, iDb);
95269}
95270
95271/*
95272** This routine is called to do the work of a DROP TABLE statement.
95273** pName is the name of the table to be dropped.
95274*/
95275SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
95276  Table *pTab;
95277  Vdbe *v;
95278  sqlite3 *db = pParse->db;
95279  int iDb;
95280
95281  if( db->mallocFailed ){
95282    goto exit_drop_table;
95283  }
95284  assert( pParse->nErr==0 );
95285  assert( pName->nSrc==1 );
95286  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
95287  if( noErr ) db->suppressErr++;
95288  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
95289  if( noErr ) db->suppressErr--;
95290
95291  if( pTab==0 ){
95292    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
95293    goto exit_drop_table;
95294  }
95295  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95296  assert( iDb>=0 && iDb<db->nDb );
95297
95298  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
95299  ** it is initialized.
95300  */
95301  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
95302    goto exit_drop_table;
95303  }
95304#ifndef SQLITE_OMIT_AUTHORIZATION
95305  {
95306    int code;
95307    const char *zTab = SCHEMA_TABLE(iDb);
95308    const char *zDb = db->aDb[iDb].zName;
95309    const char *zArg2 = 0;
95310    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
95311      goto exit_drop_table;
95312    }
95313    if( isView ){
95314      if( !OMIT_TEMPDB && iDb==1 ){
95315        code = SQLITE_DROP_TEMP_VIEW;
95316      }else{
95317        code = SQLITE_DROP_VIEW;
95318      }
95319#ifndef SQLITE_OMIT_VIRTUALTABLE
95320    }else if( IsVirtual(pTab) ){
95321      code = SQLITE_DROP_VTABLE;
95322      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
95323#endif
95324    }else{
95325      if( !OMIT_TEMPDB && iDb==1 ){
95326        code = SQLITE_DROP_TEMP_TABLE;
95327      }else{
95328        code = SQLITE_DROP_TABLE;
95329      }
95330    }
95331    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
95332      goto exit_drop_table;
95333    }
95334    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
95335      goto exit_drop_table;
95336    }
95337  }
95338#endif
95339  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
95340    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
95341    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
95342    goto exit_drop_table;
95343  }
95344
95345#ifndef SQLITE_OMIT_VIEW
95346  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
95347  ** on a table.
95348  */
95349  if( isView && pTab->pSelect==0 ){
95350    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
95351    goto exit_drop_table;
95352  }
95353  if( !isView && pTab->pSelect ){
95354    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
95355    goto exit_drop_table;
95356  }
95357#endif
95358
95359  /* Generate code to remove the table from the master table
95360  ** on disk.
95361  */
95362  v = sqlite3GetVdbe(pParse);
95363  if( v ){
95364    sqlite3BeginWriteOperation(pParse, 1, iDb);
95365    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
95366    sqlite3FkDropTable(pParse, pName, pTab);
95367    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
95368  }
95369
95370exit_drop_table:
95371  sqlite3SrcListDelete(db, pName);
95372}
95373
95374/*
95375** This routine is called to create a new foreign key on the table
95376** currently under construction.  pFromCol determines which columns
95377** in the current table point to the foreign key.  If pFromCol==0 then
95378** connect the key to the last column inserted.  pTo is the name of
95379** the table referred to (a.k.a the "parent" table).  pToCol is a list
95380** of tables in the parent pTo table.  flags contains all
95381** information about the conflict resolution algorithms specified
95382** in the ON DELETE, ON UPDATE and ON INSERT clauses.
95383**
95384** An FKey structure is created and added to the table currently
95385** under construction in the pParse->pNewTable field.
95386**
95387** The foreign key is set for IMMEDIATE processing.  A subsequent call
95388** to sqlite3DeferForeignKey() might change this to DEFERRED.
95389*/
95390SQLITE_PRIVATE void sqlite3CreateForeignKey(
95391  Parse *pParse,       /* Parsing context */
95392  ExprList *pFromCol,  /* Columns in this table that point to other table */
95393  Token *pTo,          /* Name of the other table */
95394  ExprList *pToCol,    /* Columns in the other table */
95395  int flags            /* Conflict resolution algorithms. */
95396){
95397  sqlite3 *db = pParse->db;
95398#ifndef SQLITE_OMIT_FOREIGN_KEY
95399  FKey *pFKey = 0;
95400  FKey *pNextTo;
95401  Table *p = pParse->pNewTable;
95402  int nByte;
95403  int i;
95404  int nCol;
95405  char *z;
95406
95407  assert( pTo!=0 );
95408  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
95409  if( pFromCol==0 ){
95410    int iCol = p->nCol-1;
95411    if( NEVER(iCol<0) ) goto fk_end;
95412    if( pToCol && pToCol->nExpr!=1 ){
95413      sqlite3ErrorMsg(pParse, "foreign key on %s"
95414         " should reference only one column of table %T",
95415         p->aCol[iCol].zName, pTo);
95416      goto fk_end;
95417    }
95418    nCol = 1;
95419  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
95420    sqlite3ErrorMsg(pParse,
95421        "number of columns in foreign key does not match the number of "
95422        "columns in the referenced table");
95423    goto fk_end;
95424  }else{
95425    nCol = pFromCol->nExpr;
95426  }
95427  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
95428  if( pToCol ){
95429    for(i=0; i<pToCol->nExpr; i++){
95430      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
95431    }
95432  }
95433  pFKey = sqlite3DbMallocZero(db, nByte );
95434  if( pFKey==0 ){
95435    goto fk_end;
95436  }
95437  pFKey->pFrom = p;
95438  pFKey->pNextFrom = p->pFKey;
95439  z = (char*)&pFKey->aCol[nCol];
95440  pFKey->zTo = z;
95441  memcpy(z, pTo->z, pTo->n);
95442  z[pTo->n] = 0;
95443  sqlite3Dequote(z);
95444  z += pTo->n+1;
95445  pFKey->nCol = nCol;
95446  if( pFromCol==0 ){
95447    pFKey->aCol[0].iFrom = p->nCol-1;
95448  }else{
95449    for(i=0; i<nCol; i++){
95450      int j;
95451      for(j=0; j<p->nCol; j++){
95452        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
95453          pFKey->aCol[i].iFrom = j;
95454          break;
95455        }
95456      }
95457      if( j>=p->nCol ){
95458        sqlite3ErrorMsg(pParse,
95459          "unknown column \"%s\" in foreign key definition",
95460          pFromCol->a[i].zName);
95461        goto fk_end;
95462      }
95463    }
95464  }
95465  if( pToCol ){
95466    for(i=0; i<nCol; i++){
95467      int n = sqlite3Strlen30(pToCol->a[i].zName);
95468      pFKey->aCol[i].zCol = z;
95469      memcpy(z, pToCol->a[i].zName, n);
95470      z[n] = 0;
95471      z += n+1;
95472    }
95473  }
95474  pFKey->isDeferred = 0;
95475  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
95476  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
95477
95478  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
95479  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
95480      pFKey->zTo, (void *)pFKey
95481  );
95482  if( pNextTo==pFKey ){
95483    db->mallocFailed = 1;
95484    goto fk_end;
95485  }
95486  if( pNextTo ){
95487    assert( pNextTo->pPrevTo==0 );
95488    pFKey->pNextTo = pNextTo;
95489    pNextTo->pPrevTo = pFKey;
95490  }
95491
95492  /* Link the foreign key to the table as the last step.
95493  */
95494  p->pFKey = pFKey;
95495  pFKey = 0;
95496
95497fk_end:
95498  sqlite3DbFree(db, pFKey);
95499#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
95500  sqlite3ExprListDelete(db, pFromCol);
95501  sqlite3ExprListDelete(db, pToCol);
95502}
95503
95504/*
95505** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
95506** clause is seen as part of a foreign key definition.  The isDeferred
95507** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
95508** The behavior of the most recently created foreign key is adjusted
95509** accordingly.
95510*/
95511SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
95512#ifndef SQLITE_OMIT_FOREIGN_KEY
95513  Table *pTab;
95514  FKey *pFKey;
95515  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
95516  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
95517  pFKey->isDeferred = (u8)isDeferred;
95518#endif
95519}
95520
95521/*
95522** Generate code that will erase and refill index *pIdx.  This is
95523** used to initialize a newly created index or to recompute the
95524** content of an index in response to a REINDEX command.
95525**
95526** if memRootPage is not negative, it means that the index is newly
95527** created.  The register specified by memRootPage contains the
95528** root page number of the index.  If memRootPage is negative, then
95529** the index already exists and must be cleared before being refilled and
95530** the root page number of the index is taken from pIndex->tnum.
95531*/
95532static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
95533  Table *pTab = pIndex->pTable;  /* The table that is indexed */
95534  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
95535  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
95536  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
95537  int addr1;                     /* Address of top of loop */
95538  int addr2;                     /* Address to jump to for next iteration */
95539  int tnum;                      /* Root page of index */
95540  int iPartIdxLabel;             /* Jump to this label to skip a row */
95541  Vdbe *v;                       /* Generate code into this virtual machine */
95542  KeyInfo *pKey;                 /* KeyInfo for index */
95543  int regRecord;                 /* Register holding assembled index record */
95544  sqlite3 *db = pParse->db;      /* The database connection */
95545  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
95546
95547#ifndef SQLITE_OMIT_AUTHORIZATION
95548  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
95549      db->aDb[iDb].zName ) ){
95550    return;
95551  }
95552#endif
95553
95554  /* Require a write-lock on the table to perform this operation */
95555  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
95556
95557  v = sqlite3GetVdbe(pParse);
95558  if( v==0 ) return;
95559  if( memRootPage>=0 ){
95560    tnum = memRootPage;
95561  }else{
95562    tnum = pIndex->tnum;
95563  }
95564  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
95565
95566  /* Open the sorter cursor if we are to use one. */
95567  iSorter = pParse->nTab++;
95568  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
95569                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
95570
95571  /* Open the table. Loop through all rows of the table, inserting index
95572  ** records into the sorter. */
95573  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
95574  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
95575  regRecord = sqlite3GetTempReg(pParse);
95576
95577  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
95578  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
95579  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
95580  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
95581  sqlite3VdbeJumpHere(v, addr1);
95582  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
95583  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
95584                    (char *)pKey, P4_KEYINFO);
95585  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
95586
95587  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
95588  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
95589  if( IsUniqueIndex(pIndex) && pKey!=0 ){
95590    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
95591    sqlite3VdbeGoto(v, j2);
95592    addr2 = sqlite3VdbeCurrentAddr(v);
95593    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
95594                         pIndex->nKeyCol); VdbeCoverage(v);
95595    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
95596  }else{
95597    addr2 = sqlite3VdbeCurrentAddr(v);
95598  }
95599  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
95600  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
95601  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
95602  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
95603  sqlite3ReleaseTempReg(pParse, regRecord);
95604  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
95605  sqlite3VdbeJumpHere(v, addr1);
95606
95607  sqlite3VdbeAddOp1(v, OP_Close, iTab);
95608  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
95609  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
95610}
95611
95612/*
95613** Allocate heap space to hold an Index object with nCol columns.
95614**
95615** Increase the allocation size to provide an extra nExtra bytes
95616** of 8-byte aligned space after the Index object and return a
95617** pointer to this extra space in *ppExtra.
95618*/
95619SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
95620  sqlite3 *db,         /* Database connection */
95621  i16 nCol,            /* Total number of columns in the index */
95622  int nExtra,          /* Number of bytes of extra space to alloc */
95623  char **ppExtra       /* Pointer to the "extra" space */
95624){
95625  Index *p;            /* Allocated index object */
95626  int nByte;           /* Bytes of space for Index object + arrays */
95627
95628  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
95629          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
95630          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
95631                 sizeof(i16)*nCol +            /* Index.aiColumn   */
95632                 sizeof(u8)*nCol);             /* Index.aSortOrder */
95633  p = sqlite3DbMallocZero(db, nByte + nExtra);
95634  if( p ){
95635    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
95636    p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
95637    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
95638    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
95639    p->aSortOrder = (u8*)pExtra;
95640    p->nColumn = nCol;
95641    p->nKeyCol = nCol - 1;
95642    *ppExtra = ((char*)p) + nByte;
95643  }
95644  return p;
95645}
95646
95647/*
95648** Create a new index for an SQL table.  pName1.pName2 is the name of the index
95649** and pTblList is the name of the table that is to be indexed.  Both will
95650** be NULL for a primary key or an index that is created to satisfy a
95651** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
95652** as the table to be indexed.  pParse->pNewTable is a table that is
95653** currently being constructed by a CREATE TABLE statement.
95654**
95655** pList is a list of columns to be indexed.  pList will be NULL if this
95656** is a primary key or unique-constraint on the most recent column added
95657** to the table currently under construction.
95658**
95659** If the index is created successfully, return a pointer to the new Index
95660** structure. This is used by sqlite3AddPrimaryKey() to mark the index
95661** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
95662*/
95663SQLITE_PRIVATE Index *sqlite3CreateIndex(
95664  Parse *pParse,     /* All information about this parse */
95665  Token *pName1,     /* First part of index name. May be NULL */
95666  Token *pName2,     /* Second part of index name. May be NULL */
95667  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
95668  ExprList *pList,   /* A list of columns to be indexed */
95669  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
95670  Token *pStart,     /* The CREATE token that begins this statement */
95671  Expr *pPIWhere,    /* WHERE clause for partial indices */
95672  int sortOrder,     /* Sort order of primary key when pList==NULL */
95673  int ifNotExist     /* Omit error if index already exists */
95674){
95675  Index *pRet = 0;     /* Pointer to return */
95676  Table *pTab = 0;     /* Table to be indexed */
95677  Index *pIndex = 0;   /* The index to be created */
95678  char *zName = 0;     /* Name of the index */
95679  int nName;           /* Number of characters in zName */
95680  int i, j;
95681  DbFixer sFix;        /* For assigning database names to pTable */
95682  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
95683  sqlite3 *db = pParse->db;
95684  Db *pDb;             /* The specific table containing the indexed database */
95685  int iDb;             /* Index of the database that is being written */
95686  Token *pName = 0;    /* Unqualified name of the index to create */
95687  struct ExprList_item *pListItem; /* For looping over pList */
95688  int nExtra = 0;                  /* Space allocated for zExtra[] */
95689  int nExtraCol;                   /* Number of extra columns needed */
95690  char *zExtra = 0;                /* Extra space after the Index object */
95691  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
95692
95693  if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
95694    goto exit_create_index;
95695  }
95696  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95697    goto exit_create_index;
95698  }
95699
95700  /*
95701  ** Find the table that is to be indexed.  Return early if not found.
95702  */
95703  if( pTblName!=0 ){
95704
95705    /* Use the two-part index name to determine the database
95706    ** to search for the table. 'Fix' the table name to this db
95707    ** before looking up the table.
95708    */
95709    assert( pName1 && pName2 );
95710    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
95711    if( iDb<0 ) goto exit_create_index;
95712    assert( pName && pName->z );
95713
95714#ifndef SQLITE_OMIT_TEMPDB
95715    /* If the index name was unqualified, check if the table
95716    ** is a temp table. If so, set the database to 1. Do not do this
95717    ** if initialising a database schema.
95718    */
95719    if( !db->init.busy ){
95720      pTab = sqlite3SrcListLookup(pParse, pTblName);
95721      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
95722        iDb = 1;
95723      }
95724    }
95725#endif
95726
95727    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
95728    if( sqlite3FixSrcList(&sFix, pTblName) ){
95729      /* Because the parser constructs pTblName from a single identifier,
95730      ** sqlite3FixSrcList can never fail. */
95731      assert(0);
95732    }
95733    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
95734    assert( db->mallocFailed==0 || pTab==0 );
95735    if( pTab==0 ) goto exit_create_index;
95736    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
95737      sqlite3ErrorMsg(pParse,
95738           "cannot create a TEMP index on non-TEMP table \"%s\"",
95739           pTab->zName);
95740      goto exit_create_index;
95741    }
95742    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
95743  }else{
95744    assert( pName==0 );
95745    assert( pStart==0 );
95746    pTab = pParse->pNewTable;
95747    if( !pTab ) goto exit_create_index;
95748    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95749  }
95750  pDb = &db->aDb[iDb];
95751
95752  assert( pTab!=0 );
95753  assert( pParse->nErr==0 );
95754  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
95755       && db->init.busy==0
95756#if SQLITE_USER_AUTHENTICATION
95757       && sqlite3UserAuthTable(pTab->zName)==0
95758#endif
95759       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
95760    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
95761    goto exit_create_index;
95762  }
95763#ifndef SQLITE_OMIT_VIEW
95764  if( pTab->pSelect ){
95765    sqlite3ErrorMsg(pParse, "views may not be indexed");
95766    goto exit_create_index;
95767  }
95768#endif
95769#ifndef SQLITE_OMIT_VIRTUALTABLE
95770  if( IsVirtual(pTab) ){
95771    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
95772    goto exit_create_index;
95773  }
95774#endif
95775
95776  /*
95777  ** Find the name of the index.  Make sure there is not already another
95778  ** index or table with the same name.
95779  **
95780  ** Exception:  If we are reading the names of permanent indices from the
95781  ** sqlite_master table (because some other process changed the schema) and
95782  ** one of the index names collides with the name of a temporary table or
95783  ** index, then we will continue to process this index.
95784  **
95785  ** If pName==0 it means that we are
95786  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
95787  ** own name.
95788  */
95789  if( pName ){
95790    zName = sqlite3NameFromToken(db, pName);
95791    if( zName==0 ) goto exit_create_index;
95792    assert( pName->z!=0 );
95793    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
95794      goto exit_create_index;
95795    }
95796    if( !db->init.busy ){
95797      if( sqlite3FindTable(db, zName, 0)!=0 ){
95798        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
95799        goto exit_create_index;
95800      }
95801    }
95802    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
95803      if( !ifNotExist ){
95804        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
95805      }else{
95806        assert( !db->init.busy );
95807        sqlite3CodeVerifySchema(pParse, iDb);
95808      }
95809      goto exit_create_index;
95810    }
95811  }else{
95812    int n;
95813    Index *pLoop;
95814    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
95815    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
95816    if( zName==0 ){
95817      goto exit_create_index;
95818    }
95819  }
95820
95821  /* Check for authorization to create an index.
95822  */
95823#ifndef SQLITE_OMIT_AUTHORIZATION
95824  {
95825    const char *zDb = pDb->zName;
95826    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
95827      goto exit_create_index;
95828    }
95829    i = SQLITE_CREATE_INDEX;
95830    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
95831    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
95832      goto exit_create_index;
95833    }
95834  }
95835#endif
95836
95837  /* If pList==0, it means this routine was called to make a primary
95838  ** key out of the last column added to the table under construction.
95839  ** So create a fake list to simulate this.
95840  */
95841  if( pList==0 ){
95842    Token prevCol;
95843    prevCol.z = pTab->aCol[pTab->nCol-1].zName;
95844    prevCol.n = sqlite3Strlen30(prevCol.z);
95845    pList = sqlite3ExprListAppend(pParse, 0,
95846              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
95847    if( pList==0 ) goto exit_create_index;
95848    assert( pList->nExpr==1 );
95849    sqlite3ExprListSetSortOrder(pList, sortOrder);
95850  }else{
95851    sqlite3ExprListCheckLength(pParse, pList, "index");
95852  }
95853
95854  /* Figure out how many bytes of space are required to store explicitly
95855  ** specified collation sequence names.
95856  */
95857  for(i=0; i<pList->nExpr; i++){
95858    Expr *pExpr = pList->a[i].pExpr;
95859    assert( pExpr!=0 );
95860    if( pExpr->op==TK_COLLATE ){
95861      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
95862    }
95863  }
95864
95865  /*
95866  ** Allocate the index structure.
95867  */
95868  nName = sqlite3Strlen30(zName);
95869  nExtraCol = pPk ? pPk->nKeyCol : 1;
95870  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
95871                                      nName + nExtra + 1, &zExtra);
95872  if( db->mallocFailed ){
95873    goto exit_create_index;
95874  }
95875  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
95876  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
95877  pIndex->zName = zExtra;
95878  zExtra += nName + 1;
95879  memcpy(pIndex->zName, zName, nName+1);
95880  pIndex->pTable = pTab;
95881  pIndex->onError = (u8)onError;
95882  pIndex->uniqNotNull = onError!=OE_None;
95883  pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
95884  pIndex->pSchema = db->aDb[iDb].pSchema;
95885  pIndex->nKeyCol = pList->nExpr;
95886  if( pPIWhere ){
95887    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
95888    pIndex->pPartIdxWhere = pPIWhere;
95889    pPIWhere = 0;
95890  }
95891  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95892
95893  /* Check to see if we should honor DESC requests on index columns
95894  */
95895  if( pDb->pSchema->file_format>=4 ){
95896    sortOrderMask = -1;   /* Honor DESC */
95897  }else{
95898    sortOrderMask = 0;    /* Ignore DESC */
95899  }
95900
95901  /* Analyze the list of expressions that form the terms of the index and
95902  ** report any errors.  In the common case where the expression is exactly
95903  ** a table column, store that column in aiColumn[].  For general expressions,
95904  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
95905  **
95906  ** TODO: Issue a warning if two or more columns of the index are identical.
95907  ** TODO: Issue a warning if the table primary key is used as part of the
95908  ** index key.
95909  */
95910  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
95911    Expr *pCExpr;                  /* The i-th index expression */
95912    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
95913    char *zColl;                   /* Collation sequence name */
95914
95915    sqlite3StringToId(pListItem->pExpr);
95916    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
95917    if( pParse->nErr ) goto exit_create_index;
95918    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
95919    if( pCExpr->op!=TK_COLUMN ){
95920      if( pTab==pParse->pNewTable ){
95921        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
95922                                "UNIQUE constraints");
95923        goto exit_create_index;
95924      }
95925      if( pIndex->aColExpr==0 ){
95926        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
95927        pIndex->aColExpr = pCopy;
95928        if( !db->mallocFailed ){
95929          assert( pCopy!=0 );
95930          pListItem = &pCopy->a[i];
95931        }
95932      }
95933      j = XN_EXPR;
95934      pIndex->aiColumn[i] = XN_EXPR;
95935      pIndex->uniqNotNull = 0;
95936    }else{
95937      j = pCExpr->iColumn;
95938      assert( j<=0x7fff );
95939      if( j<0 ){
95940        j = pTab->iPKey;
95941      }else if( pTab->aCol[j].notNull==0 ){
95942        pIndex->uniqNotNull = 0;
95943      }
95944      pIndex->aiColumn[i] = (i16)j;
95945    }
95946    zColl = 0;
95947    if( pListItem->pExpr->op==TK_COLLATE ){
95948      int nColl;
95949      zColl = pListItem->pExpr->u.zToken;
95950      nColl = sqlite3Strlen30(zColl) + 1;
95951      assert( nExtra>=nColl );
95952      memcpy(zExtra, zColl, nColl);
95953      zColl = zExtra;
95954      zExtra += nColl;
95955      nExtra -= nColl;
95956    }else if( j>=0 ){
95957      zColl = pTab->aCol[j].zColl;
95958    }
95959    if( !zColl ) zColl = "BINARY";
95960    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
95961      goto exit_create_index;
95962    }
95963    pIndex->azColl[i] = zColl;
95964    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
95965    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
95966  }
95967
95968  /* Append the table key to the end of the index.  For WITHOUT ROWID
95969  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
95970  ** normal tables (when pPk==0) this will be the rowid.
95971  */
95972  if( pPk ){
95973    for(j=0; j<pPk->nKeyCol; j++){
95974      int x = pPk->aiColumn[j];
95975      assert( x>=0 );
95976      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
95977        pIndex->nColumn--;
95978      }else{
95979        pIndex->aiColumn[i] = x;
95980        pIndex->azColl[i] = pPk->azColl[j];
95981        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
95982        i++;
95983      }
95984    }
95985    assert( i==pIndex->nColumn );
95986  }else{
95987    pIndex->aiColumn[i] = XN_ROWID;
95988    pIndex->azColl[i] = "BINARY";
95989  }
95990  sqlite3DefaultRowEst(pIndex);
95991  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
95992
95993  if( pTab==pParse->pNewTable ){
95994    /* This routine has been called to create an automatic index as a
95995    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
95996    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
95997    ** i.e. one of:
95998    **
95999    ** CREATE TABLE t(x PRIMARY KEY, y);
96000    ** CREATE TABLE t(x, y, UNIQUE(x, y));
96001    **
96002    ** Either way, check to see if the table already has such an index. If
96003    ** so, don't bother creating this one. This only applies to
96004    ** automatically created indices. Users can do as they wish with
96005    ** explicit indices.
96006    **
96007    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
96008    ** (and thus suppressing the second one) even if they have different
96009    ** sort orders.
96010    **
96011    ** If there are different collating sequences or if the columns of
96012    ** the constraint occur in different orders, then the constraints are
96013    ** considered distinct and both result in separate indices.
96014    */
96015    Index *pIdx;
96016    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96017      int k;
96018      assert( IsUniqueIndex(pIdx) );
96019      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
96020      assert( IsUniqueIndex(pIndex) );
96021
96022      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
96023      for(k=0; k<pIdx->nKeyCol; k++){
96024        const char *z1;
96025        const char *z2;
96026        assert( pIdx->aiColumn[k]>=0 );
96027        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
96028        z1 = pIdx->azColl[k];
96029        z2 = pIndex->azColl[k];
96030        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
96031      }
96032      if( k==pIdx->nKeyCol ){
96033        if( pIdx->onError!=pIndex->onError ){
96034          /* This constraint creates the same index as a previous
96035          ** constraint specified somewhere in the CREATE TABLE statement.
96036          ** However the ON CONFLICT clauses are different. If both this
96037          ** constraint and the previous equivalent constraint have explicit
96038          ** ON CONFLICT clauses this is an error. Otherwise, use the
96039          ** explicitly specified behavior for the index.
96040          */
96041          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
96042            sqlite3ErrorMsg(pParse,
96043                "conflicting ON CONFLICT clauses specified", 0);
96044          }
96045          if( pIdx->onError==OE_Default ){
96046            pIdx->onError = pIndex->onError;
96047          }
96048        }
96049        pRet = pIdx;
96050        goto exit_create_index;
96051      }
96052    }
96053  }
96054
96055  /* Link the new Index structure to its table and to the other
96056  ** in-memory database structures.
96057  */
96058  assert( pParse->nErr==0 );
96059  if( db->init.busy ){
96060    Index *p;
96061    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
96062    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
96063                          pIndex->zName, pIndex);
96064    if( p ){
96065      assert( p==pIndex );  /* Malloc must have failed */
96066      db->mallocFailed = 1;
96067      goto exit_create_index;
96068    }
96069    db->flags |= SQLITE_InternChanges;
96070    if( pTblName!=0 ){
96071      pIndex->tnum = db->init.newTnum;
96072    }
96073  }
96074
96075  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
96076  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
96077  ** emit code to allocate the index rootpage on disk and make an entry for
96078  ** the index in the sqlite_master table and populate the index with
96079  ** content.  But, do not do this if we are simply reading the sqlite_master
96080  ** table to parse the schema, or if this index is the PRIMARY KEY index
96081  ** of a WITHOUT ROWID table.
96082  **
96083  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
96084  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
96085  ** has just been created, it contains no data and the index initialization
96086  ** step can be skipped.
96087  */
96088  else if( HasRowid(pTab) || pTblName!=0 ){
96089    Vdbe *v;
96090    char *zStmt;
96091    int iMem = ++pParse->nMem;
96092
96093    v = sqlite3GetVdbe(pParse);
96094    if( v==0 ) goto exit_create_index;
96095
96096    sqlite3BeginWriteOperation(pParse, 1, iDb);
96097
96098    /* Create the rootpage for the index using CreateIndex. But before
96099    ** doing so, code a Noop instruction and store its address in
96100    ** Index.tnum. This is required in case this index is actually a
96101    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
96102    ** that case the convertToWithoutRowidTable() routine will replace
96103    ** the Noop with a Goto to jump over the VDBE code generated below. */
96104    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
96105    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
96106
96107    /* Gather the complete text of the CREATE INDEX statement into
96108    ** the zStmt variable
96109    */
96110    if( pStart ){
96111      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
96112      if( pName->z[n-1]==';' ) n--;
96113      /* A named index with an explicit CREATE INDEX statement */
96114      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
96115        onError==OE_None ? "" : " UNIQUE", n, pName->z);
96116    }else{
96117      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
96118      /* zStmt = sqlite3MPrintf(""); */
96119      zStmt = 0;
96120    }
96121
96122    /* Add an entry in sqlite_master for this index
96123    */
96124    sqlite3NestedParse(pParse,
96125        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
96126        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
96127        pIndex->zName,
96128        pTab->zName,
96129        iMem,
96130        zStmt
96131    );
96132    sqlite3DbFree(db, zStmt);
96133
96134    /* Fill the index with data and reparse the schema. Code an OP_Expire
96135    ** to invalidate all pre-compiled statements.
96136    */
96137    if( pTblName ){
96138      sqlite3RefillIndex(pParse, pIndex, iMem);
96139      sqlite3ChangeCookie(pParse, iDb);
96140      sqlite3VdbeAddParseSchemaOp(v, iDb,
96141         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
96142      sqlite3VdbeAddOp1(v, OP_Expire, 0);
96143    }
96144
96145    sqlite3VdbeJumpHere(v, pIndex->tnum);
96146  }
96147
96148  /* When adding an index to the list of indices for a table, make
96149  ** sure all indices labeled OE_Replace come after all those labeled
96150  ** OE_Ignore.  This is necessary for the correct constraint check
96151  ** processing (in sqlite3GenerateConstraintChecks()) as part of
96152  ** UPDATE and INSERT statements.
96153  */
96154  if( db->init.busy || pTblName==0 ){
96155    if( onError!=OE_Replace || pTab->pIndex==0
96156         || pTab->pIndex->onError==OE_Replace){
96157      pIndex->pNext = pTab->pIndex;
96158      pTab->pIndex = pIndex;
96159    }else{
96160      Index *pOther = pTab->pIndex;
96161      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
96162        pOther = pOther->pNext;
96163      }
96164      pIndex->pNext = pOther->pNext;
96165      pOther->pNext = pIndex;
96166    }
96167    pRet = pIndex;
96168    pIndex = 0;
96169  }
96170
96171  /* Clean up before exiting */
96172exit_create_index:
96173  if( pIndex ) freeIndex(db, pIndex);
96174  sqlite3ExprDelete(db, pPIWhere);
96175  sqlite3ExprListDelete(db, pList);
96176  sqlite3SrcListDelete(db, pTblName);
96177  sqlite3DbFree(db, zName);
96178  return pRet;
96179}
96180
96181/*
96182** Fill the Index.aiRowEst[] array with default information - information
96183** to be used when we have not run the ANALYZE command.
96184**
96185** aiRowEst[0] is supposed to contain the number of elements in the index.
96186** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
96187** number of rows in the table that match any particular value of the
96188** first column of the index.  aiRowEst[2] is an estimate of the number
96189** of rows that match any particular combination of the first 2 columns
96190** of the index.  And so forth.  It must always be the case that
96191*
96192**           aiRowEst[N]<=aiRowEst[N-1]
96193**           aiRowEst[N]>=1
96194**
96195** Apart from that, we have little to go on besides intuition as to
96196** how aiRowEst[] should be initialized.  The numbers generated here
96197** are based on typical values found in actual indices.
96198*/
96199SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
96200  /*                10,  9,  8,  7,  6 */
96201  LogEst aVal[] = { 33, 32, 30, 28, 26 };
96202  LogEst *a = pIdx->aiRowLogEst;
96203  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
96204  int i;
96205
96206  /* Set the first entry (number of rows in the index) to the estimated
96207  ** number of rows in the table. Or 10, if the estimated number of rows
96208  ** in the table is less than that.  */
96209  a[0] = pIdx->pTable->nRowLogEst;
96210  if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
96211
96212  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
96213  ** 6 and each subsequent value (if any) is 5.  */
96214  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
96215  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
96216    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
96217  }
96218
96219  assert( 0==sqlite3LogEst(1) );
96220  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
96221}
96222
96223/*
96224** This routine will drop an existing named index.  This routine
96225** implements the DROP INDEX statement.
96226*/
96227SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
96228  Index *pIndex;
96229  Vdbe *v;
96230  sqlite3 *db = pParse->db;
96231  int iDb;
96232
96233  assert( pParse->nErr==0 );   /* Never called with prior errors */
96234  if( db->mallocFailed ){
96235    goto exit_drop_index;
96236  }
96237  assert( pName->nSrc==1 );
96238  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96239    goto exit_drop_index;
96240  }
96241  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
96242  if( pIndex==0 ){
96243    if( !ifExists ){
96244      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
96245    }else{
96246      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
96247    }
96248    pParse->checkSchema = 1;
96249    goto exit_drop_index;
96250  }
96251  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
96252    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
96253      "or PRIMARY KEY constraint cannot be dropped", 0);
96254    goto exit_drop_index;
96255  }
96256  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
96257#ifndef SQLITE_OMIT_AUTHORIZATION
96258  {
96259    int code = SQLITE_DROP_INDEX;
96260    Table *pTab = pIndex->pTable;
96261    const char *zDb = db->aDb[iDb].zName;
96262    const char *zTab = SCHEMA_TABLE(iDb);
96263    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
96264      goto exit_drop_index;
96265    }
96266    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
96267    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
96268      goto exit_drop_index;
96269    }
96270  }
96271#endif
96272
96273  /* Generate code to remove the index and from the master table */
96274  v = sqlite3GetVdbe(pParse);
96275  if( v ){
96276    sqlite3BeginWriteOperation(pParse, 1, iDb);
96277    sqlite3NestedParse(pParse,
96278       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
96279       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
96280    );
96281    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
96282    sqlite3ChangeCookie(pParse, iDb);
96283    destroyRootPage(pParse, pIndex->tnum, iDb);
96284    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
96285  }
96286
96287exit_drop_index:
96288  sqlite3SrcListDelete(db, pName);
96289}
96290
96291/*
96292** pArray is a pointer to an array of objects. Each object in the
96293** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
96294** to extend the array so that there is space for a new object at the end.
96295**
96296** When this function is called, *pnEntry contains the current size of
96297** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
96298** in total).
96299**
96300** If the realloc() is successful (i.e. if no OOM condition occurs), the
96301** space allocated for the new object is zeroed, *pnEntry updated to
96302** reflect the new size of the array and a pointer to the new allocation
96303** returned. *pIdx is set to the index of the new array entry in this case.
96304**
96305** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
96306** unchanged and a copy of pArray returned.
96307*/
96308SQLITE_PRIVATE void *sqlite3ArrayAllocate(
96309  sqlite3 *db,      /* Connection to notify of malloc failures */
96310  void *pArray,     /* Array of objects.  Might be reallocated */
96311  int szEntry,      /* Size of each object in the array */
96312  int *pnEntry,     /* Number of objects currently in use */
96313  int *pIdx         /* Write the index of a new slot here */
96314){
96315  char *z;
96316  int n = *pnEntry;
96317  if( (n & (n-1))==0 ){
96318    int sz = (n==0) ? 1 : 2*n;
96319    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
96320    if( pNew==0 ){
96321      *pIdx = -1;
96322      return pArray;
96323    }
96324    pArray = pNew;
96325  }
96326  z = (char*)pArray;
96327  memset(&z[n * szEntry], 0, szEntry);
96328  *pIdx = n;
96329  ++*pnEntry;
96330  return pArray;
96331}
96332
96333/*
96334** Append a new element to the given IdList.  Create a new IdList if
96335** need be.
96336**
96337** A new IdList is returned, or NULL if malloc() fails.
96338*/
96339SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
96340  int i;
96341  if( pList==0 ){
96342    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
96343    if( pList==0 ) return 0;
96344  }
96345  pList->a = sqlite3ArrayAllocate(
96346      db,
96347      pList->a,
96348      sizeof(pList->a[0]),
96349      &pList->nId,
96350      &i
96351  );
96352  if( i<0 ){
96353    sqlite3IdListDelete(db, pList);
96354    return 0;
96355  }
96356  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
96357  return pList;
96358}
96359
96360/*
96361** Delete an IdList.
96362*/
96363SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
96364  int i;
96365  if( pList==0 ) return;
96366  for(i=0; i<pList->nId; i++){
96367    sqlite3DbFree(db, pList->a[i].zName);
96368  }
96369  sqlite3DbFree(db, pList->a);
96370  sqlite3DbFree(db, pList);
96371}
96372
96373/*
96374** Return the index in pList of the identifier named zId.  Return -1
96375** if not found.
96376*/
96377SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
96378  int i;
96379  if( pList==0 ) return -1;
96380  for(i=0; i<pList->nId; i++){
96381    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
96382  }
96383  return -1;
96384}
96385
96386/*
96387** Expand the space allocated for the given SrcList object by
96388** creating nExtra new slots beginning at iStart.  iStart is zero based.
96389** New slots are zeroed.
96390**
96391** For example, suppose a SrcList initially contains two entries: A,B.
96392** To append 3 new entries onto the end, do this:
96393**
96394**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
96395**
96396** After the call above it would contain:  A, B, nil, nil, nil.
96397** If the iStart argument had been 1 instead of 2, then the result
96398** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
96399** the iStart value would be 0.  The result then would
96400** be: nil, nil, nil, A, B.
96401**
96402** If a memory allocation fails the SrcList is unchanged.  The
96403** db->mallocFailed flag will be set to true.
96404*/
96405SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
96406  sqlite3 *db,       /* Database connection to notify of OOM errors */
96407  SrcList *pSrc,     /* The SrcList to be enlarged */
96408  int nExtra,        /* Number of new slots to add to pSrc->a[] */
96409  int iStart         /* Index in pSrc->a[] of first new slot */
96410){
96411  int i;
96412
96413  /* Sanity checking on calling parameters */
96414  assert( iStart>=0 );
96415  assert( nExtra>=1 );
96416  assert( pSrc!=0 );
96417  assert( iStart<=pSrc->nSrc );
96418
96419  /* Allocate additional space if needed */
96420  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
96421    SrcList *pNew;
96422    int nAlloc = pSrc->nSrc+nExtra;
96423    int nGot;
96424    pNew = sqlite3DbRealloc(db, pSrc,
96425               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
96426    if( pNew==0 ){
96427      assert( db->mallocFailed );
96428      return pSrc;
96429    }
96430    pSrc = pNew;
96431    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
96432    pSrc->nAlloc = nGot;
96433  }
96434
96435  /* Move existing slots that come after the newly inserted slots
96436  ** out of the way */
96437  for(i=pSrc->nSrc-1; i>=iStart; i--){
96438    pSrc->a[i+nExtra] = pSrc->a[i];
96439  }
96440  pSrc->nSrc += nExtra;
96441
96442  /* Zero the newly allocated slots */
96443  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
96444  for(i=iStart; i<iStart+nExtra; i++){
96445    pSrc->a[i].iCursor = -1;
96446  }
96447
96448  /* Return a pointer to the enlarged SrcList */
96449  return pSrc;
96450}
96451
96452
96453/*
96454** Append a new table name to the given SrcList.  Create a new SrcList if
96455** need be.  A new entry is created in the SrcList even if pTable is NULL.
96456**
96457** A SrcList is returned, or NULL if there is an OOM error.  The returned
96458** SrcList might be the same as the SrcList that was input or it might be
96459** a new one.  If an OOM error does occurs, then the prior value of pList
96460** that is input to this routine is automatically freed.
96461**
96462** If pDatabase is not null, it means that the table has an optional
96463** database name prefix.  Like this:  "database.table".  The pDatabase
96464** points to the table name and the pTable points to the database name.
96465** The SrcList.a[].zName field is filled with the table name which might
96466** come from pTable (if pDatabase is NULL) or from pDatabase.
96467** SrcList.a[].zDatabase is filled with the database name from pTable,
96468** or with NULL if no database is specified.
96469**
96470** In other words, if call like this:
96471**
96472**         sqlite3SrcListAppend(D,A,B,0);
96473**
96474** Then B is a table name and the database name is unspecified.  If called
96475** like this:
96476**
96477**         sqlite3SrcListAppend(D,A,B,C);
96478**
96479** Then C is the table name and B is the database name.  If C is defined
96480** then so is B.  In other words, we never have a case where:
96481**
96482**         sqlite3SrcListAppend(D,A,0,C);
96483**
96484** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
96485** before being added to the SrcList.
96486*/
96487SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
96488  sqlite3 *db,        /* Connection to notify of malloc failures */
96489  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
96490  Token *pTable,      /* Table to append */
96491  Token *pDatabase    /* Database of the table */
96492){
96493  struct SrcList_item *pItem;
96494  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
96495  if( pList==0 ){
96496    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
96497    if( pList==0 ) return 0;
96498    pList->nAlloc = 1;
96499  }
96500  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
96501  if( db->mallocFailed ){
96502    sqlite3SrcListDelete(db, pList);
96503    return 0;
96504  }
96505  pItem = &pList->a[pList->nSrc-1];
96506  if( pDatabase && pDatabase->z==0 ){
96507    pDatabase = 0;
96508  }
96509  if( pDatabase ){
96510    Token *pTemp = pDatabase;
96511    pDatabase = pTable;
96512    pTable = pTemp;
96513  }
96514  pItem->zName = sqlite3NameFromToken(db, pTable);
96515  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
96516  return pList;
96517}
96518
96519/*
96520** Assign VdbeCursor index numbers to all tables in a SrcList
96521*/
96522SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
96523  int i;
96524  struct SrcList_item *pItem;
96525  assert(pList || pParse->db->mallocFailed );
96526  if( pList ){
96527    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
96528      if( pItem->iCursor>=0 ) break;
96529      pItem->iCursor = pParse->nTab++;
96530      if( pItem->pSelect ){
96531        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
96532      }
96533    }
96534  }
96535}
96536
96537/*
96538** Delete an entire SrcList including all its substructure.
96539*/
96540SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
96541  int i;
96542  struct SrcList_item *pItem;
96543  if( pList==0 ) return;
96544  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
96545    sqlite3DbFree(db, pItem->zDatabase);
96546    sqlite3DbFree(db, pItem->zName);
96547    sqlite3DbFree(db, pItem->zAlias);
96548    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
96549    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
96550    sqlite3DeleteTable(db, pItem->pTab);
96551    sqlite3SelectDelete(db, pItem->pSelect);
96552    sqlite3ExprDelete(db, pItem->pOn);
96553    sqlite3IdListDelete(db, pItem->pUsing);
96554  }
96555  sqlite3DbFree(db, pList);
96556}
96557
96558/*
96559** This routine is called by the parser to add a new term to the
96560** end of a growing FROM clause.  The "p" parameter is the part of
96561** the FROM clause that has already been constructed.  "p" is NULL
96562** if this is the first term of the FROM clause.  pTable and pDatabase
96563** are the name of the table and database named in the FROM clause term.
96564** pDatabase is NULL if the database name qualifier is missing - the
96565** usual case.  If the term has an alias, then pAlias points to the
96566** alias token.  If the term is a subquery, then pSubquery is the
96567** SELECT statement that the subquery encodes.  The pTable and
96568** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
96569** parameters are the content of the ON and USING clauses.
96570**
96571** Return a new SrcList which encodes is the FROM with the new
96572** term added.
96573*/
96574SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
96575  Parse *pParse,          /* Parsing context */
96576  SrcList *p,             /* The left part of the FROM clause already seen */
96577  Token *pTable,          /* Name of the table to add to the FROM clause */
96578  Token *pDatabase,       /* Name of the database containing pTable */
96579  Token *pAlias,          /* The right-hand side of the AS subexpression */
96580  Select *pSubquery,      /* A subquery used in place of a table name */
96581  Expr *pOn,              /* The ON clause of a join */
96582  IdList *pUsing          /* The USING clause of a join */
96583){
96584  struct SrcList_item *pItem;
96585  sqlite3 *db = pParse->db;
96586  if( !p && (pOn || pUsing) ){
96587    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
96588      (pOn ? "ON" : "USING")
96589    );
96590    goto append_from_error;
96591  }
96592  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
96593  if( p==0 || NEVER(p->nSrc==0) ){
96594    goto append_from_error;
96595  }
96596  pItem = &p->a[p->nSrc-1];
96597  assert( pAlias!=0 );
96598  if( pAlias->n ){
96599    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
96600  }
96601  pItem->pSelect = pSubquery;
96602  pItem->pOn = pOn;
96603  pItem->pUsing = pUsing;
96604  return p;
96605
96606 append_from_error:
96607  assert( p==0 );
96608  sqlite3ExprDelete(db, pOn);
96609  sqlite3IdListDelete(db, pUsing);
96610  sqlite3SelectDelete(db, pSubquery);
96611  return 0;
96612}
96613
96614/*
96615** Add an INDEXED BY or NOT INDEXED clause to the most recently added
96616** element of the source-list passed as the second argument.
96617*/
96618SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
96619  assert( pIndexedBy!=0 );
96620  if( p && ALWAYS(p->nSrc>0) ){
96621    struct SrcList_item *pItem = &p->a[p->nSrc-1];
96622    assert( pItem->fg.notIndexed==0 );
96623    assert( pItem->fg.isIndexedBy==0 );
96624    assert( pItem->fg.isTabFunc==0 );
96625    if( pIndexedBy->n==1 && !pIndexedBy->z ){
96626      /* A "NOT INDEXED" clause was supplied. See parse.y
96627      ** construct "indexed_opt" for details. */
96628      pItem->fg.notIndexed = 1;
96629    }else{
96630      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
96631      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
96632    }
96633  }
96634}
96635
96636/*
96637** Add the list of function arguments to the SrcList entry for a
96638** table-valued-function.
96639*/
96640SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
96641  if( p && pList ){
96642    struct SrcList_item *pItem = &p->a[p->nSrc-1];
96643    assert( pItem->fg.notIndexed==0 );
96644    assert( pItem->fg.isIndexedBy==0 );
96645    assert( pItem->fg.isTabFunc==0 );
96646    pItem->u1.pFuncArg = pList;
96647    pItem->fg.isTabFunc = 1;
96648  }else{
96649    sqlite3ExprListDelete(pParse->db, pList);
96650  }
96651}
96652
96653/*
96654** When building up a FROM clause in the parser, the join operator
96655** is initially attached to the left operand.  But the code generator
96656** expects the join operator to be on the right operand.  This routine
96657** Shifts all join operators from left to right for an entire FROM
96658** clause.
96659**
96660** Example: Suppose the join is like this:
96661**
96662**           A natural cross join B
96663**
96664** The operator is "natural cross join".  The A and B operands are stored
96665** in p->a[0] and p->a[1], respectively.  The parser initially stores the
96666** operator with A.  This routine shifts that operator over to B.
96667*/
96668SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
96669  if( p ){
96670    int i;
96671    for(i=p->nSrc-1; i>0; i--){
96672      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
96673    }
96674    p->a[0].fg.jointype = 0;
96675  }
96676}
96677
96678/*
96679** Begin a transaction
96680*/
96681SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
96682  sqlite3 *db;
96683  Vdbe *v;
96684  int i;
96685
96686  assert( pParse!=0 );
96687  db = pParse->db;
96688  assert( db!=0 );
96689/*  if( db->aDb[0].pBt==0 ) return; */
96690  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
96691    return;
96692  }
96693  v = sqlite3GetVdbe(pParse);
96694  if( !v ) return;
96695  if( type!=TK_DEFERRED ){
96696    for(i=0; i<db->nDb; i++){
96697      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
96698      sqlite3VdbeUsesBtree(v, i);
96699    }
96700  }
96701  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
96702}
96703
96704/*
96705** Commit a transaction
96706*/
96707SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
96708  Vdbe *v;
96709
96710  assert( pParse!=0 );
96711  assert( pParse->db!=0 );
96712  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
96713    return;
96714  }
96715  v = sqlite3GetVdbe(pParse);
96716  if( v ){
96717    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
96718  }
96719}
96720
96721/*
96722** Rollback a transaction
96723*/
96724SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
96725  Vdbe *v;
96726
96727  assert( pParse!=0 );
96728  assert( pParse->db!=0 );
96729  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
96730    return;
96731  }
96732  v = sqlite3GetVdbe(pParse);
96733  if( v ){
96734    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
96735  }
96736}
96737
96738/*
96739** This function is called by the parser when it parses a command to create,
96740** release or rollback an SQL savepoint.
96741*/
96742SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
96743  char *zName = sqlite3NameFromToken(pParse->db, pName);
96744  if( zName ){
96745    Vdbe *v = sqlite3GetVdbe(pParse);
96746#ifndef SQLITE_OMIT_AUTHORIZATION
96747    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
96748    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
96749#endif
96750    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
96751      sqlite3DbFree(pParse->db, zName);
96752      return;
96753    }
96754    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
96755  }
96756}
96757
96758/*
96759** Make sure the TEMP database is open and available for use.  Return
96760** the number of errors.  Leave any error messages in the pParse structure.
96761*/
96762SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
96763  sqlite3 *db = pParse->db;
96764  if( db->aDb[1].pBt==0 && !pParse->explain ){
96765    int rc;
96766    Btree *pBt;
96767    static const int flags =
96768          SQLITE_OPEN_READWRITE |
96769          SQLITE_OPEN_CREATE |
96770          SQLITE_OPEN_EXCLUSIVE |
96771          SQLITE_OPEN_DELETEONCLOSE |
96772          SQLITE_OPEN_TEMP_DB;
96773
96774    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
96775    if( rc!=SQLITE_OK ){
96776      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
96777        "file for storing temporary tables");
96778      pParse->rc = rc;
96779      return 1;
96780    }
96781    db->aDb[1].pBt = pBt;
96782    assert( db->aDb[1].pSchema );
96783    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
96784      db->mallocFailed = 1;
96785      return 1;
96786    }
96787  }
96788  return 0;
96789}
96790
96791/*
96792** Record the fact that the schema cookie will need to be verified
96793** for database iDb.  The code to actually verify the schema cookie
96794** will occur at the end of the top-level VDBE and will be generated
96795** later, by sqlite3FinishCoding().
96796*/
96797SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
96798  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96799  sqlite3 *db = pToplevel->db;
96800
96801  assert( iDb>=0 && iDb<db->nDb );
96802  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
96803  assert( iDb<SQLITE_MAX_ATTACHED+2 );
96804  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96805  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
96806    DbMaskSet(pToplevel->cookieMask, iDb);
96807    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
96808    if( !OMIT_TEMPDB && iDb==1 ){
96809      sqlite3OpenTempDatabase(pToplevel);
96810    }
96811  }
96812}
96813
96814/*
96815** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
96816** attached database. Otherwise, invoke it for the database named zDb only.
96817*/
96818SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
96819  sqlite3 *db = pParse->db;
96820  int i;
96821  for(i=0; i<db->nDb; i++){
96822    Db *pDb = &db->aDb[i];
96823    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
96824      sqlite3CodeVerifySchema(pParse, i);
96825    }
96826  }
96827}
96828
96829/*
96830** Generate VDBE code that prepares for doing an operation that
96831** might change the database.
96832**
96833** This routine starts a new transaction if we are not already within
96834** a transaction.  If we are already within a transaction, then a checkpoint
96835** is set if the setStatement parameter is true.  A checkpoint should
96836** be set for operations that might fail (due to a constraint) part of
96837** the way through and which will need to undo some writes without having to
96838** rollback the whole transaction.  For operations where all constraints
96839** can be checked before any changes are made to the database, it is never
96840** necessary to undo a write and the checkpoint should not be set.
96841*/
96842SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
96843  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96844  sqlite3CodeVerifySchema(pParse, iDb);
96845  DbMaskSet(pToplevel->writeMask, iDb);
96846  pToplevel->isMultiWrite |= setStatement;
96847}
96848
96849/*
96850** Indicate that the statement currently under construction might write
96851** more than one entry (example: deleting one row then inserting another,
96852** inserting multiple rows in a table, or inserting a row and index entries.)
96853** If an abort occurs after some of these writes have completed, then it will
96854** be necessary to undo the completed writes.
96855*/
96856SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
96857  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96858  pToplevel->isMultiWrite = 1;
96859}
96860
96861/*
96862** The code generator calls this routine if is discovers that it is
96863** possible to abort a statement prior to completion.  In order to
96864** perform this abort without corrupting the database, we need to make
96865** sure that the statement is protected by a statement transaction.
96866**
96867** Technically, we only need to set the mayAbort flag if the
96868** isMultiWrite flag was previously set.  There is a time dependency
96869** such that the abort must occur after the multiwrite.  This makes
96870** some statements involving the REPLACE conflict resolution algorithm
96871** go a little faster.  But taking advantage of this time dependency
96872** makes it more difficult to prove that the code is correct (in
96873** particular, it prevents us from writing an effective
96874** implementation of sqlite3AssertMayAbort()) and so we have chosen
96875** to take the safe route and skip the optimization.
96876*/
96877SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
96878  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96879  pToplevel->mayAbort = 1;
96880}
96881
96882/*
96883** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
96884** error. The onError parameter determines which (if any) of the statement
96885** and/or current transaction is rolled back.
96886*/
96887SQLITE_PRIVATE void sqlite3HaltConstraint(
96888  Parse *pParse,    /* Parsing context */
96889  int errCode,      /* extended error code */
96890  int onError,      /* Constraint type */
96891  char *p4,         /* Error message */
96892  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
96893  u8 p5Errmsg       /* P5_ErrMsg type */
96894){
96895  Vdbe *v = sqlite3GetVdbe(pParse);
96896  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
96897  if( onError==OE_Abort ){
96898    sqlite3MayAbort(pParse);
96899  }
96900  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
96901  if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
96902}
96903
96904/*
96905** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
96906*/
96907SQLITE_PRIVATE void sqlite3UniqueConstraint(
96908  Parse *pParse,    /* Parsing context */
96909  int onError,      /* Constraint type */
96910  Index *pIdx       /* The index that triggers the constraint */
96911){
96912  char *zErr;
96913  int j;
96914  StrAccum errMsg;
96915  Table *pTab = pIdx->pTable;
96916
96917  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
96918  if( pIdx->aColExpr ){
96919    sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
96920  }else{
96921    for(j=0; j<pIdx->nKeyCol; j++){
96922      char *zCol;
96923      assert( pIdx->aiColumn[j]>=0 );
96924      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
96925      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
96926      sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
96927    }
96928  }
96929  zErr = sqlite3StrAccumFinish(&errMsg);
96930  sqlite3HaltConstraint(pParse,
96931    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
96932                            : SQLITE_CONSTRAINT_UNIQUE,
96933    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
96934}
96935
96936
96937/*
96938** Code an OP_Halt due to non-unique rowid.
96939*/
96940SQLITE_PRIVATE void sqlite3RowidConstraint(
96941  Parse *pParse,    /* Parsing context */
96942  int onError,      /* Conflict resolution algorithm */
96943  Table *pTab       /* The table with the non-unique rowid */
96944){
96945  char *zMsg;
96946  int rc;
96947  if( pTab->iPKey>=0 ){
96948    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
96949                          pTab->aCol[pTab->iPKey].zName);
96950    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
96951  }else{
96952    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
96953    rc = SQLITE_CONSTRAINT_ROWID;
96954  }
96955  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
96956                        P5_ConstraintUnique);
96957}
96958
96959/*
96960** Check to see if pIndex uses the collating sequence pColl.  Return
96961** true if it does and false if it does not.
96962*/
96963#ifndef SQLITE_OMIT_REINDEX
96964static int collationMatch(const char *zColl, Index *pIndex){
96965  int i;
96966  assert( zColl!=0 );
96967  for(i=0; i<pIndex->nColumn; i++){
96968    const char *z = pIndex->azColl[i];
96969    assert( z!=0 || pIndex->aiColumn[i]<0 );
96970    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
96971      return 1;
96972    }
96973  }
96974  return 0;
96975}
96976#endif
96977
96978/*
96979** Recompute all indices of pTab that use the collating sequence pColl.
96980** If pColl==0 then recompute all indices of pTab.
96981*/
96982#ifndef SQLITE_OMIT_REINDEX
96983static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
96984  Index *pIndex;              /* An index associated with pTab */
96985
96986  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
96987    if( zColl==0 || collationMatch(zColl, pIndex) ){
96988      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96989      sqlite3BeginWriteOperation(pParse, 0, iDb);
96990      sqlite3RefillIndex(pParse, pIndex, -1);
96991    }
96992  }
96993}
96994#endif
96995
96996/*
96997** Recompute all indices of all tables in all databases where the
96998** indices use the collating sequence pColl.  If pColl==0 then recompute
96999** all indices everywhere.
97000*/
97001#ifndef SQLITE_OMIT_REINDEX
97002static void reindexDatabases(Parse *pParse, char const *zColl){
97003  Db *pDb;                    /* A single database */
97004  int iDb;                    /* The database index number */
97005  sqlite3 *db = pParse->db;   /* The database connection */
97006  HashElem *k;                /* For looping over tables in pDb */
97007  Table *pTab;                /* A table in the database */
97008
97009  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
97010  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
97011    assert( pDb!=0 );
97012    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
97013      pTab = (Table*)sqliteHashData(k);
97014      reindexTable(pParse, pTab, zColl);
97015    }
97016  }
97017}
97018#endif
97019
97020/*
97021** Generate code for the REINDEX command.
97022**
97023**        REINDEX                            -- 1
97024**        REINDEX  <collation>               -- 2
97025**        REINDEX  ?<database>.?<tablename>  -- 3
97026**        REINDEX  ?<database>.?<indexname>  -- 4
97027**
97028** Form 1 causes all indices in all attached databases to be rebuilt.
97029** Form 2 rebuilds all indices in all databases that use the named
97030** collating function.  Forms 3 and 4 rebuild the named index or all
97031** indices associated with the named table.
97032*/
97033#ifndef SQLITE_OMIT_REINDEX
97034SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
97035  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
97036  char *z;                    /* Name of a table or index */
97037  const char *zDb;            /* Name of the database */
97038  Table *pTab;                /* A table in the database */
97039  Index *pIndex;              /* An index associated with pTab */
97040  int iDb;                    /* The database index number */
97041  sqlite3 *db = pParse->db;   /* The database connection */
97042  Token *pObjName;            /* Name of the table or index to be reindexed */
97043
97044  /* Read the database schema. If an error occurs, leave an error message
97045  ** and code in pParse and return NULL. */
97046  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97047    return;
97048  }
97049
97050  if( pName1==0 ){
97051    reindexDatabases(pParse, 0);
97052    return;
97053  }else if( NEVER(pName2==0) || pName2->z==0 ){
97054    char *zColl;
97055    assert( pName1->z );
97056    zColl = sqlite3NameFromToken(pParse->db, pName1);
97057    if( !zColl ) return;
97058    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
97059    if( pColl ){
97060      reindexDatabases(pParse, zColl);
97061      sqlite3DbFree(db, zColl);
97062      return;
97063    }
97064    sqlite3DbFree(db, zColl);
97065  }
97066  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
97067  if( iDb<0 ) return;
97068  z = sqlite3NameFromToken(db, pObjName);
97069  if( z==0 ) return;
97070  zDb = db->aDb[iDb].zName;
97071  pTab = sqlite3FindTable(db, z, zDb);
97072  if( pTab ){
97073    reindexTable(pParse, pTab, 0);
97074    sqlite3DbFree(db, z);
97075    return;
97076  }
97077  pIndex = sqlite3FindIndex(db, z, zDb);
97078  sqlite3DbFree(db, z);
97079  if( pIndex ){
97080    sqlite3BeginWriteOperation(pParse, 0, iDb);
97081    sqlite3RefillIndex(pParse, pIndex, -1);
97082    return;
97083  }
97084  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
97085}
97086#endif
97087
97088/*
97089** Return a KeyInfo structure that is appropriate for the given Index.
97090**
97091** The KeyInfo structure for an index is cached in the Index object.
97092** So there might be multiple references to the returned pointer.  The
97093** caller should not try to modify the KeyInfo object.
97094**
97095** The caller should invoke sqlite3KeyInfoUnref() on the returned object
97096** when it has finished using it.
97097*/
97098SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
97099  int i;
97100  int nCol = pIdx->nColumn;
97101  int nKey = pIdx->nKeyCol;
97102  KeyInfo *pKey;
97103  if( pParse->nErr ) return 0;
97104  if( pIdx->uniqNotNull ){
97105    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
97106  }else{
97107    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
97108  }
97109  if( pKey ){
97110    assert( sqlite3KeyInfoIsWriteable(pKey) );
97111    for(i=0; i<nCol; i++){
97112      char *zColl = pIdx->azColl[i];
97113      assert( zColl!=0 );
97114      pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
97115                        sqlite3LocateCollSeq(pParse, zColl);
97116      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
97117    }
97118    if( pParse->nErr ){
97119      sqlite3KeyInfoUnref(pKey);
97120      pKey = 0;
97121    }
97122  }
97123  return pKey;
97124}
97125
97126#ifndef SQLITE_OMIT_CTE
97127/*
97128** This routine is invoked once per CTE by the parser while parsing a
97129** WITH clause.
97130*/
97131SQLITE_PRIVATE With *sqlite3WithAdd(
97132  Parse *pParse,          /* Parsing context */
97133  With *pWith,            /* Existing WITH clause, or NULL */
97134  Token *pName,           /* Name of the common-table */
97135  ExprList *pArglist,     /* Optional column name list for the table */
97136  Select *pQuery          /* Query used to initialize the table */
97137){
97138  sqlite3 *db = pParse->db;
97139  With *pNew;
97140  char *zName;
97141
97142  /* Check that the CTE name is unique within this WITH clause. If
97143  ** not, store an error in the Parse structure. */
97144  zName = sqlite3NameFromToken(pParse->db, pName);
97145  if( zName && pWith ){
97146    int i;
97147    for(i=0; i<pWith->nCte; i++){
97148      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
97149        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
97150      }
97151    }
97152  }
97153
97154  if( pWith ){
97155    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
97156    pNew = sqlite3DbRealloc(db, pWith, nByte);
97157  }else{
97158    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
97159  }
97160  assert( zName!=0 || pNew==0 );
97161  assert( db->mallocFailed==0 || pNew==0 );
97162
97163  if( pNew==0 ){
97164    sqlite3ExprListDelete(db, pArglist);
97165    sqlite3SelectDelete(db, pQuery);
97166    sqlite3DbFree(db, zName);
97167    pNew = pWith;
97168  }else{
97169    pNew->a[pNew->nCte].pSelect = pQuery;
97170    pNew->a[pNew->nCte].pCols = pArglist;
97171    pNew->a[pNew->nCte].zName = zName;
97172    pNew->a[pNew->nCte].zCteErr = 0;
97173    pNew->nCte++;
97174  }
97175
97176  return pNew;
97177}
97178
97179/*
97180** Free the contents of the With object passed as the second argument.
97181*/
97182SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
97183  if( pWith ){
97184    int i;
97185    for(i=0; i<pWith->nCte; i++){
97186      struct Cte *pCte = &pWith->a[i];
97187      sqlite3ExprListDelete(db, pCte->pCols);
97188      sqlite3SelectDelete(db, pCte->pSelect);
97189      sqlite3DbFree(db, pCte->zName);
97190    }
97191    sqlite3DbFree(db, pWith);
97192  }
97193}
97194#endif /* !defined(SQLITE_OMIT_CTE) */
97195
97196/************** End of build.c ***********************************************/
97197/************** Begin file callback.c ****************************************/
97198/*
97199** 2005 May 23
97200**
97201** The author disclaims copyright to this source code.  In place of
97202** a legal notice, here is a blessing:
97203**
97204**    May you do good and not evil.
97205**    May you find forgiveness for yourself and forgive others.
97206**    May you share freely, never taking more than you give.
97207**
97208*************************************************************************
97209**
97210** This file contains functions used to access the internal hash tables
97211** of user defined functions and collation sequences.
97212*/
97213
97214/* #include "sqliteInt.h" */
97215
97216/*
97217** Invoke the 'collation needed' callback to request a collation sequence
97218** in the encoding enc of name zName, length nName.
97219*/
97220static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
97221  assert( !db->xCollNeeded || !db->xCollNeeded16 );
97222  if( db->xCollNeeded ){
97223    char *zExternal = sqlite3DbStrDup(db, zName);
97224    if( !zExternal ) return;
97225    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
97226    sqlite3DbFree(db, zExternal);
97227  }
97228#ifndef SQLITE_OMIT_UTF16
97229  if( db->xCollNeeded16 ){
97230    char const *zExternal;
97231    sqlite3_value *pTmp = sqlite3ValueNew(db);
97232    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
97233    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
97234    if( zExternal ){
97235      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
97236    }
97237    sqlite3ValueFree(pTmp);
97238  }
97239#endif
97240}
97241
97242/*
97243** This routine is called if the collation factory fails to deliver a
97244** collation function in the best encoding but there may be other versions
97245** of this collation function (for other text encodings) available. Use one
97246** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
97247** possible.
97248*/
97249static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
97250  CollSeq *pColl2;
97251  char *z = pColl->zName;
97252  int i;
97253  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
97254  for(i=0; i<3; i++){
97255    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
97256    if( pColl2->xCmp!=0 ){
97257      memcpy(pColl, pColl2, sizeof(CollSeq));
97258      pColl->xDel = 0;         /* Do not copy the destructor */
97259      return SQLITE_OK;
97260    }
97261  }
97262  return SQLITE_ERROR;
97263}
97264
97265/*
97266** This function is responsible for invoking the collation factory callback
97267** or substituting a collation sequence of a different encoding when the
97268** requested collation sequence is not available in the desired encoding.
97269**
97270** If it is not NULL, then pColl must point to the database native encoding
97271** collation sequence with name zName, length nName.
97272**
97273** The return value is either the collation sequence to be used in database
97274** db for collation type name zName, length nName, or NULL, if no collation
97275** sequence can be found.  If no collation is found, leave an error message.
97276**
97277** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
97278*/
97279SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
97280  Parse *pParse,        /* Parsing context */
97281  u8 enc,               /* The desired encoding for the collating sequence */
97282  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
97283  const char *zName     /* Collating sequence name */
97284){
97285  CollSeq *p;
97286  sqlite3 *db = pParse->db;
97287
97288  p = pColl;
97289  if( !p ){
97290    p = sqlite3FindCollSeq(db, enc, zName, 0);
97291  }
97292  if( !p || !p->xCmp ){
97293    /* No collation sequence of this type for this encoding is registered.
97294    ** Call the collation factory to see if it can supply us with one.
97295    */
97296    callCollNeeded(db, enc, zName);
97297    p = sqlite3FindCollSeq(db, enc, zName, 0);
97298  }
97299  if( p && !p->xCmp && synthCollSeq(db, p) ){
97300    p = 0;
97301  }
97302  assert( !p || p->xCmp );
97303  if( p==0 ){
97304    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
97305  }
97306  return p;
97307}
97308
97309/*
97310** This routine is called on a collation sequence before it is used to
97311** check that it is defined. An undefined collation sequence exists when
97312** a database is loaded that contains references to collation sequences
97313** that have not been defined by sqlite3_create_collation() etc.
97314**
97315** If required, this routine calls the 'collation needed' callback to
97316** request a definition of the collating sequence. If this doesn't work,
97317** an equivalent collating sequence that uses a text encoding different
97318** from the main database is substituted, if one is available.
97319*/
97320SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
97321  if( pColl ){
97322    const char *zName = pColl->zName;
97323    sqlite3 *db = pParse->db;
97324    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
97325    if( !p ){
97326      return SQLITE_ERROR;
97327    }
97328    assert( p==pColl );
97329  }
97330  return SQLITE_OK;
97331}
97332
97333
97334
97335/*
97336** Locate and return an entry from the db.aCollSeq hash table. If the entry
97337** specified by zName and nName is not found and parameter 'create' is
97338** true, then create a new entry. Otherwise return NULL.
97339**
97340** Each pointer stored in the sqlite3.aCollSeq hash table contains an
97341** array of three CollSeq structures. The first is the collation sequence
97342** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
97343**
97344** Stored immediately after the three collation sequences is a copy of
97345** the collation sequence name. A pointer to this string is stored in
97346** each collation sequence structure.
97347*/
97348static CollSeq *findCollSeqEntry(
97349  sqlite3 *db,          /* Database connection */
97350  const char *zName,    /* Name of the collating sequence */
97351  int create            /* Create a new entry if true */
97352){
97353  CollSeq *pColl;
97354  pColl = sqlite3HashFind(&db->aCollSeq, zName);
97355
97356  if( 0==pColl && create ){
97357    int nName = sqlite3Strlen30(zName);
97358    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
97359    if( pColl ){
97360      CollSeq *pDel = 0;
97361      pColl[0].zName = (char*)&pColl[3];
97362      pColl[0].enc = SQLITE_UTF8;
97363      pColl[1].zName = (char*)&pColl[3];
97364      pColl[1].enc = SQLITE_UTF16LE;
97365      pColl[2].zName = (char*)&pColl[3];
97366      pColl[2].enc = SQLITE_UTF16BE;
97367      memcpy(pColl[0].zName, zName, nName);
97368      pColl[0].zName[nName] = 0;
97369      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
97370
97371      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
97372      ** return the pColl pointer to be deleted (because it wasn't added
97373      ** to the hash table).
97374      */
97375      assert( pDel==0 || pDel==pColl );
97376      if( pDel!=0 ){
97377        db->mallocFailed = 1;
97378        sqlite3DbFree(db, pDel);
97379        pColl = 0;
97380      }
97381    }
97382  }
97383  return pColl;
97384}
97385
97386/*
97387** Parameter zName points to a UTF-8 encoded string nName bytes long.
97388** Return the CollSeq* pointer for the collation sequence named zName
97389** for the encoding 'enc' from the database 'db'.
97390**
97391** If the entry specified is not found and 'create' is true, then create a
97392** new entry.  Otherwise return NULL.
97393**
97394** A separate function sqlite3LocateCollSeq() is a wrapper around
97395** this routine.  sqlite3LocateCollSeq() invokes the collation factory
97396** if necessary and generates an error message if the collating sequence
97397** cannot be found.
97398**
97399** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
97400*/
97401SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
97402  sqlite3 *db,
97403  u8 enc,
97404  const char *zName,
97405  int create
97406){
97407  CollSeq *pColl;
97408  if( zName ){
97409    pColl = findCollSeqEntry(db, zName, create);
97410  }else{
97411    pColl = db->pDfltColl;
97412  }
97413  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
97414  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
97415  if( pColl ) pColl += enc-1;
97416  return pColl;
97417}
97418
97419/* During the search for the best function definition, this procedure
97420** is called to test how well the function passed as the first argument
97421** matches the request for a function with nArg arguments in a system
97422** that uses encoding enc. The value returned indicates how well the
97423** request is matched. A higher value indicates a better match.
97424**
97425** If nArg is -1 that means to only return a match (non-zero) if p->nArg
97426** is also -1.  In other words, we are searching for a function that
97427** takes a variable number of arguments.
97428**
97429** If nArg is -2 that means that we are searching for any function
97430** regardless of the number of arguments it uses, so return a positive
97431** match score for any
97432**
97433** The returned value is always between 0 and 6, as follows:
97434**
97435** 0: Not a match.
97436** 1: UTF8/16 conversion required and function takes any number of arguments.
97437** 2: UTF16 byte order change required and function takes any number of args.
97438** 3: encoding matches and function takes any number of arguments
97439** 4: UTF8/16 conversion required - argument count matches exactly
97440** 5: UTF16 byte order conversion required - argument count matches exactly
97441** 6: Perfect match:  encoding and argument count match exactly.
97442**
97443** If nArg==(-2) then any function with a non-null xStep or xFunc is
97444** a perfect match and any function with both xStep and xFunc NULL is
97445** a non-match.
97446*/
97447#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
97448static int matchQuality(
97449  FuncDef *p,     /* The function we are evaluating for match quality */
97450  int nArg,       /* Desired number of arguments.  (-1)==any */
97451  u8 enc          /* Desired text encoding */
97452){
97453  int match;
97454
97455  /* nArg of -2 is a special case */
97456  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
97457
97458  /* Wrong number of arguments means "no match" */
97459  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
97460
97461  /* Give a better score to a function with a specific number of arguments
97462  ** than to function that accepts any number of arguments. */
97463  if( p->nArg==nArg ){
97464    match = 4;
97465  }else{
97466    match = 1;
97467  }
97468
97469  /* Bonus points if the text encoding matches */
97470  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
97471    match += 2;  /* Exact encoding match */
97472  }else if( (enc & p->funcFlags & 2)!=0 ){
97473    match += 1;  /* Both are UTF16, but with different byte orders */
97474  }
97475
97476  return match;
97477}
97478
97479/*
97480** Search a FuncDefHash for a function with the given name.  Return
97481** a pointer to the matching FuncDef if found, or 0 if there is no match.
97482*/
97483static FuncDef *functionSearch(
97484  FuncDefHash *pHash,  /* Hash table to search */
97485  int h,               /* Hash of the name */
97486  const char *zFunc,   /* Name of function */
97487  int nFunc            /* Number of bytes in zFunc */
97488){
97489  FuncDef *p;
97490  for(p=pHash->a[h]; p; p=p->pHash){
97491    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
97492      return p;
97493    }
97494  }
97495  return 0;
97496}
97497
97498/*
97499** Insert a new FuncDef into a FuncDefHash hash table.
97500*/
97501SQLITE_PRIVATE void sqlite3FuncDefInsert(
97502  FuncDefHash *pHash,  /* The hash table into which to insert */
97503  FuncDef *pDef        /* The function definition to insert */
97504){
97505  FuncDef *pOther;
97506  int nName = sqlite3Strlen30(pDef->zName);
97507  u8 c1 = (u8)pDef->zName[0];
97508  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
97509  pOther = functionSearch(pHash, h, pDef->zName, nName);
97510  if( pOther ){
97511    assert( pOther!=pDef && pOther->pNext!=pDef );
97512    pDef->pNext = pOther->pNext;
97513    pOther->pNext = pDef;
97514  }else{
97515    pDef->pNext = 0;
97516    pDef->pHash = pHash->a[h];
97517    pHash->a[h] = pDef;
97518  }
97519}
97520
97521
97522
97523/*
97524** Locate a user function given a name, a number of arguments and a flag
97525** indicating whether the function prefers UTF-16 over UTF-8.  Return a
97526** pointer to the FuncDef structure that defines that function, or return
97527** NULL if the function does not exist.
97528**
97529** If the createFlag argument is true, then a new (blank) FuncDef
97530** structure is created and liked into the "db" structure if a
97531** no matching function previously existed.
97532**
97533** If nArg is -2, then the first valid function found is returned.  A
97534** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
97535** case is used to see if zName is a valid function name for some number
97536** of arguments.  If nArg is -2, then createFlag must be 0.
97537**
97538** If createFlag is false, then a function with the required name and
97539** number of arguments may be returned even if the eTextRep flag does not
97540** match that requested.
97541*/
97542SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
97543  sqlite3 *db,       /* An open database */
97544  const char *zName, /* Name of the function.  Not null-terminated */
97545  int nName,         /* Number of characters in the name */
97546  int nArg,          /* Number of arguments.  -1 means any number */
97547  u8 enc,            /* Preferred text encoding */
97548  u8 createFlag      /* Create new entry if true and does not otherwise exist */
97549){
97550  FuncDef *p;         /* Iterator variable */
97551  FuncDef *pBest = 0; /* Best match found so far */
97552  int bestScore = 0;  /* Score of best match */
97553  int h;              /* Hash value */
97554
97555  assert( nArg>=(-2) );
97556  assert( nArg>=(-1) || createFlag==0 );
97557  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
97558
97559  /* First search for a match amongst the application-defined functions.
97560  */
97561  p = functionSearch(&db->aFunc, h, zName, nName);
97562  while( p ){
97563    int score = matchQuality(p, nArg, enc);
97564    if( score>bestScore ){
97565      pBest = p;
97566      bestScore = score;
97567    }
97568    p = p->pNext;
97569  }
97570
97571  /* If no match is found, search the built-in functions.
97572  **
97573  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
97574  ** functions even if a prior app-defined function was found.  And give
97575  ** priority to built-in functions.
97576  **
97577  ** Except, if createFlag is true, that means that we are trying to
97578  ** install a new function.  Whatever FuncDef structure is returned it will
97579  ** have fields overwritten with new information appropriate for the
97580  ** new function.  But the FuncDefs for built-in functions are read-only.
97581  ** So we must not search for built-ins when creating a new function.
97582  */
97583  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
97584    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
97585    bestScore = 0;
97586    p = functionSearch(pHash, h, zName, nName);
97587    while( p ){
97588      int score = matchQuality(p, nArg, enc);
97589      if( score>bestScore ){
97590        pBest = p;
97591        bestScore = score;
97592      }
97593      p = p->pNext;
97594    }
97595  }
97596
97597  /* If the createFlag parameter is true and the search did not reveal an
97598  ** exact match for the name, number of arguments and encoding, then add a
97599  ** new entry to the hash table and return it.
97600  */
97601  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
97602      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
97603    pBest->zName = (char *)&pBest[1];
97604    pBest->nArg = (u16)nArg;
97605    pBest->funcFlags = enc;
97606    memcpy(pBest->zName, zName, nName);
97607    pBest->zName[nName] = 0;
97608    sqlite3FuncDefInsert(&db->aFunc, pBest);
97609  }
97610
97611  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
97612    return pBest;
97613  }
97614  return 0;
97615}
97616
97617/*
97618** Free all resources held by the schema structure. The void* argument points
97619** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
97620** pointer itself, it just cleans up subsidiary resources (i.e. the contents
97621** of the schema hash tables).
97622**
97623** The Schema.cache_size variable is not cleared.
97624*/
97625SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
97626  Hash temp1;
97627  Hash temp2;
97628  HashElem *pElem;
97629  Schema *pSchema = (Schema *)p;
97630
97631  temp1 = pSchema->tblHash;
97632  temp2 = pSchema->trigHash;
97633  sqlite3HashInit(&pSchema->trigHash);
97634  sqlite3HashClear(&pSchema->idxHash);
97635  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
97636    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
97637  }
97638  sqlite3HashClear(&temp2);
97639  sqlite3HashInit(&pSchema->tblHash);
97640  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
97641    Table *pTab = sqliteHashData(pElem);
97642    sqlite3DeleteTable(0, pTab);
97643  }
97644  sqlite3HashClear(&temp1);
97645  sqlite3HashClear(&pSchema->fkeyHash);
97646  pSchema->pSeqTab = 0;
97647  if( pSchema->schemaFlags & DB_SchemaLoaded ){
97648    pSchema->iGeneration++;
97649    pSchema->schemaFlags &= ~DB_SchemaLoaded;
97650  }
97651}
97652
97653/*
97654** Find and return the schema associated with a BTree.  Create
97655** a new one if necessary.
97656*/
97657SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
97658  Schema * p;
97659  if( pBt ){
97660    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
97661  }else{
97662    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
97663  }
97664  if( !p ){
97665    db->mallocFailed = 1;
97666  }else if ( 0==p->file_format ){
97667    sqlite3HashInit(&p->tblHash);
97668    sqlite3HashInit(&p->idxHash);
97669    sqlite3HashInit(&p->trigHash);
97670    sqlite3HashInit(&p->fkeyHash);
97671    p->enc = SQLITE_UTF8;
97672  }
97673  return p;
97674}
97675
97676/************** End of callback.c ********************************************/
97677/************** Begin file delete.c ******************************************/
97678/*
97679** 2001 September 15
97680**
97681** The author disclaims copyright to this source code.  In place of
97682** a legal notice, here is a blessing:
97683**
97684**    May you do good and not evil.
97685**    May you find forgiveness for yourself and forgive others.
97686**    May you share freely, never taking more than you give.
97687**
97688*************************************************************************
97689** This file contains C code routines that are called by the parser
97690** in order to generate code for DELETE FROM statements.
97691*/
97692/* #include "sqliteInt.h" */
97693
97694/*
97695** While a SrcList can in general represent multiple tables and subqueries
97696** (as in the FROM clause of a SELECT statement) in this case it contains
97697** the name of a single table, as one might find in an INSERT, DELETE,
97698** or UPDATE statement.  Look up that table in the symbol table and
97699** return a pointer.  Set an error message and return NULL if the table
97700** name is not found or if any other error occurs.
97701**
97702** The following fields are initialized appropriate in pSrc:
97703**
97704**    pSrc->a[0].pTab       Pointer to the Table object
97705**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
97706**
97707*/
97708SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
97709  struct SrcList_item *pItem = pSrc->a;
97710  Table *pTab;
97711  assert( pItem && pSrc->nSrc==1 );
97712  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
97713  sqlite3DeleteTable(pParse->db, pItem->pTab);
97714  pItem->pTab = pTab;
97715  if( pTab ){
97716    pTab->nRef++;
97717  }
97718  if( sqlite3IndexedByLookup(pParse, pItem) ){
97719    pTab = 0;
97720  }
97721  return pTab;
97722}
97723
97724/*
97725** Check to make sure the given table is writable.  If it is not
97726** writable, generate an error message and return 1.  If it is
97727** writable return 0;
97728*/
97729SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
97730  /* A table is not writable under the following circumstances:
97731  **
97732  **   1) It is a virtual table and no implementation of the xUpdate method
97733  **      has been provided, or
97734  **   2) It is a system table (i.e. sqlite_master), this call is not
97735  **      part of a nested parse and writable_schema pragma has not
97736  **      been specified.
97737  **
97738  ** In either case leave an error message in pParse and return non-zero.
97739  */
97740  if( ( IsVirtual(pTab)
97741     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
97742   || ( (pTab->tabFlags & TF_Readonly)!=0
97743     && (pParse->db->flags & SQLITE_WriteSchema)==0
97744     && pParse->nested==0 )
97745  ){
97746    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
97747    return 1;
97748  }
97749
97750#ifndef SQLITE_OMIT_VIEW
97751  if( !viewOk && pTab->pSelect ){
97752    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
97753    return 1;
97754  }
97755#endif
97756  return 0;
97757}
97758
97759
97760#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
97761/*
97762** Evaluate a view and store its result in an ephemeral table.  The
97763** pWhere argument is an optional WHERE clause that restricts the
97764** set of rows in the view that are to be added to the ephemeral table.
97765*/
97766SQLITE_PRIVATE void sqlite3MaterializeView(
97767  Parse *pParse,       /* Parsing context */
97768  Table *pView,        /* View definition */
97769  Expr *pWhere,        /* Optional WHERE clause to be added */
97770  int iCur             /* Cursor number for ephemeral table */
97771){
97772  SelectDest dest;
97773  Select *pSel;
97774  SrcList *pFrom;
97775  sqlite3 *db = pParse->db;
97776  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
97777  pWhere = sqlite3ExprDup(db, pWhere, 0);
97778  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
97779  if( pFrom ){
97780    assert( pFrom->nSrc==1 );
97781    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
97782    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
97783    assert( pFrom->a[0].pOn==0 );
97784    assert( pFrom->a[0].pUsing==0 );
97785  }
97786  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
97787  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
97788  sqlite3Select(pParse, pSel, &dest);
97789  sqlite3SelectDelete(db, pSel);
97790}
97791#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
97792
97793#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
97794/*
97795** Generate an expression tree to implement the WHERE, ORDER BY,
97796** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
97797**
97798**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
97799**                            \__________________________/
97800**                               pLimitWhere (pInClause)
97801*/
97802SQLITE_PRIVATE Expr *sqlite3LimitWhere(
97803  Parse *pParse,               /* The parser context */
97804  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
97805  Expr *pWhere,                /* The WHERE clause.  May be null */
97806  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
97807  Expr *pLimit,                /* The LIMIT clause.  May be null */
97808  Expr *pOffset,               /* The OFFSET clause.  May be null */
97809  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
97810){
97811  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
97812  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
97813  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
97814  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
97815  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
97816  Select *pSelect = NULL;      /* Complete SELECT tree */
97817
97818  /* Check that there isn't an ORDER BY without a LIMIT clause.
97819  */
97820  if( pOrderBy && (pLimit == 0) ) {
97821    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
97822    goto limit_where_cleanup_2;
97823  }
97824
97825  /* We only need to generate a select expression if there
97826  ** is a limit/offset term to enforce.
97827  */
97828  if( pLimit == 0 ) {
97829    /* if pLimit is null, pOffset will always be null as well. */
97830    assert( pOffset == 0 );
97831    return pWhere;
97832  }
97833
97834  /* Generate a select expression tree to enforce the limit/offset
97835  ** term for the DELETE or UPDATE statement.  For example:
97836  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
97837  ** becomes:
97838  **   DELETE FROM table_a WHERE rowid IN (
97839  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
97840  **   );
97841  */
97842
97843  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
97844  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
97845  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
97846  if( pEList == 0 ) goto limit_where_cleanup_2;
97847
97848  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
97849  ** and the SELECT subtree. */
97850  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
97851  if( pSelectSrc == 0 ) {
97852    sqlite3ExprListDelete(pParse->db, pEList);
97853    goto limit_where_cleanup_2;
97854  }
97855
97856  /* generate the SELECT expression tree. */
97857  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
97858                             pOrderBy,0,pLimit,pOffset);
97859  if( pSelect == 0 ) return 0;
97860
97861  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
97862  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
97863  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
97864  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
97865  if( pInClause == 0 ) goto limit_where_cleanup_1;
97866
97867  pInClause->x.pSelect = pSelect;
97868  pInClause->flags |= EP_xIsSelect;
97869  sqlite3ExprSetHeightAndFlags(pParse, pInClause);
97870  return pInClause;
97871
97872  /* something went wrong. clean up anything allocated. */
97873limit_where_cleanup_1:
97874  sqlite3SelectDelete(pParse->db, pSelect);
97875  return 0;
97876
97877limit_where_cleanup_2:
97878  sqlite3ExprDelete(pParse->db, pWhere);
97879  sqlite3ExprListDelete(pParse->db, pOrderBy);
97880  sqlite3ExprDelete(pParse->db, pLimit);
97881  sqlite3ExprDelete(pParse->db, pOffset);
97882  return 0;
97883}
97884#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
97885       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
97886
97887/*
97888** Generate code for a DELETE FROM statement.
97889**
97890**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
97891**                 \________/       \________________/
97892**                  pTabList              pWhere
97893*/
97894SQLITE_PRIVATE void sqlite3DeleteFrom(
97895  Parse *pParse,         /* The parser context */
97896  SrcList *pTabList,     /* The table from which we should delete things */
97897  Expr *pWhere           /* The WHERE clause.  May be null */
97898){
97899  Vdbe *v;               /* The virtual database engine */
97900  Table *pTab;           /* The table from which records will be deleted */
97901  const char *zDb;       /* Name of database holding pTab */
97902  int i;                 /* Loop counter */
97903  WhereInfo *pWInfo;     /* Information about the WHERE clause */
97904  Index *pIdx;           /* For looping over indices of the table */
97905  int iTabCur;           /* Cursor number for the table */
97906  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
97907  int iIdxCur = 0;       /* Cursor number of the first index */
97908  int nIdx;              /* Number of indices */
97909  sqlite3 *db;           /* Main database structure */
97910  AuthContext sContext;  /* Authorization context */
97911  NameContext sNC;       /* Name context to resolve expressions in */
97912  int iDb;               /* Database number */
97913  int memCnt = -1;       /* Memory cell used for change counting */
97914  int rcauth;            /* Value returned by authorization callback */
97915  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
97916  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
97917  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
97918  Index *pPk;            /* The PRIMARY KEY index on the table */
97919  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
97920  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
97921  int iKey;              /* Memory cell holding key of row to be deleted */
97922  i16 nKey;              /* Number of memory cells in the row key */
97923  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
97924  int iRowSet = 0;       /* Register for rowset of rows to delete */
97925  int addrBypass = 0;    /* Address of jump over the delete logic */
97926  int addrLoop = 0;      /* Top of the delete loop */
97927  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
97928
97929#ifndef SQLITE_OMIT_TRIGGER
97930  int isView;                  /* True if attempting to delete from a view */
97931  Trigger *pTrigger;           /* List of table triggers, if required */
97932  int bComplex;                /* True if there are either triggers or FKs */
97933#endif
97934
97935  memset(&sContext, 0, sizeof(sContext));
97936  db = pParse->db;
97937  if( pParse->nErr || db->mallocFailed ){
97938    goto delete_from_cleanup;
97939  }
97940  assert( pTabList->nSrc==1 );
97941
97942  /* Locate the table which we want to delete.  This table has to be
97943  ** put in an SrcList structure because some of the subroutines we
97944  ** will be calling are designed to work with multiple tables and expect
97945  ** an SrcList* parameter instead of just a Table* parameter.
97946  */
97947  pTab = sqlite3SrcListLookup(pParse, pTabList);
97948  if( pTab==0 )  goto delete_from_cleanup;
97949
97950  /* Figure out if we have any triggers and if the table being
97951  ** deleted from is a view
97952  */
97953#ifndef SQLITE_OMIT_TRIGGER
97954  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
97955  isView = pTab->pSelect!=0;
97956  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
97957#else
97958# define pTrigger 0
97959# define isView 0
97960# define bComplex 0
97961#endif
97962#ifdef SQLITE_OMIT_VIEW
97963# undef isView
97964# define isView 0
97965#endif
97966
97967  /* If pTab is really a view, make sure it has been initialized.
97968  */
97969  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97970    goto delete_from_cleanup;
97971  }
97972
97973  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
97974    goto delete_from_cleanup;
97975  }
97976  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97977  assert( iDb<db->nDb );
97978  zDb = db->aDb[iDb].zName;
97979  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
97980  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
97981  if( rcauth==SQLITE_DENY ){
97982    goto delete_from_cleanup;
97983  }
97984  assert(!isView || pTrigger);
97985
97986  /* Assign cursor numbers to the table and all its indices.
97987  */
97988  assert( pTabList->nSrc==1 );
97989  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
97990  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
97991    pParse->nTab++;
97992  }
97993
97994  /* Start the view context
97995  */
97996  if( isView ){
97997    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
97998  }
97999
98000  /* Begin generating code.
98001  */
98002  v = sqlite3GetVdbe(pParse);
98003  if( v==0 ){
98004    goto delete_from_cleanup;
98005  }
98006  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98007  sqlite3BeginWriteOperation(pParse, 1, iDb);
98008
98009  /* If we are trying to delete from a view, realize that view into
98010  ** an ephemeral table.
98011  */
98012#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
98013  if( isView ){
98014    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
98015    iDataCur = iIdxCur = iTabCur;
98016  }
98017#endif
98018
98019  /* Resolve the column names in the WHERE clause.
98020  */
98021  memset(&sNC, 0, sizeof(sNC));
98022  sNC.pParse = pParse;
98023  sNC.pSrcList = pTabList;
98024  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
98025    goto delete_from_cleanup;
98026  }
98027
98028  /* Initialize the counter of the number of rows deleted, if
98029  ** we are counting rows.
98030  */
98031  if( db->flags & SQLITE_CountRows ){
98032    memCnt = ++pParse->nMem;
98033    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
98034  }
98035
98036#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
98037  /* Special case: A DELETE without a WHERE clause deletes everything.
98038  ** It is easier just to erase the whole table. Prior to version 3.6.5,
98039  ** this optimization caused the row change count (the value returned by
98040  ** API function sqlite3_count_changes) to be set incorrectly.  */
98041  if( rcauth==SQLITE_OK
98042   && pWhere==0
98043   && !bComplex
98044   && !IsVirtual(pTab)
98045  ){
98046    assert( !isView );
98047    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
98048    if( HasRowid(pTab) ){
98049      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
98050                        pTab->zName, P4_STATIC);
98051    }
98052    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98053      assert( pIdx->pSchema==pTab->pSchema );
98054      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
98055    }
98056  }else
98057#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
98058  {
98059    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
98060    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
98061    if( HasRowid(pTab) ){
98062      /* For a rowid table, initialize the RowSet to an empty set */
98063      pPk = 0;
98064      nPk = 1;
98065      iRowSet = ++pParse->nMem;
98066      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
98067    }else{
98068      /* For a WITHOUT ROWID table, create an ephemeral table used to
98069      ** hold all primary keys for rows to be deleted. */
98070      pPk = sqlite3PrimaryKeyIndex(pTab);
98071      assert( pPk!=0 );
98072      nPk = pPk->nKeyCol;
98073      iPk = pParse->nMem+1;
98074      pParse->nMem += nPk;
98075      iEphCur = pParse->nTab++;
98076      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
98077      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
98078    }
98079
98080    /* Construct a query to find the rowid or primary key for every row
98081    ** to be deleted, based on the WHERE clause. Set variable eOnePass
98082    ** to indicate the strategy used to implement this delete:
98083    **
98084    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
98085    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
98086    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
98087    */
98088    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
98089    if( pWInfo==0 ) goto delete_from_cleanup;
98090    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
98091    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
98092    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
98093
98094    /* Keep track of the number of rows to be deleted */
98095    if( db->flags & SQLITE_CountRows ){
98096      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
98097    }
98098
98099    /* Extract the rowid or primary key for the current row */
98100    if( pPk ){
98101      for(i=0; i<nPk; i++){
98102        assert( pPk->aiColumn[i]>=0 );
98103        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
98104                                        pPk->aiColumn[i], iPk+i);
98105      }
98106      iKey = iPk;
98107    }else{
98108      iKey = pParse->nMem + 1;
98109      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
98110      if( iKey>pParse->nMem ) pParse->nMem = iKey;
98111    }
98112
98113    if( eOnePass!=ONEPASS_OFF ){
98114      /* For ONEPASS, no need to store the rowid/primary-key. There is only
98115      ** one, so just keep it in its register(s) and fall through to the
98116      ** delete code.  */
98117      nKey = nPk; /* OP_Found will use an unpacked key */
98118      aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
98119      if( aToOpen==0 ){
98120        sqlite3WhereEnd(pWInfo);
98121        goto delete_from_cleanup;
98122      }
98123      memset(aToOpen, 1, nIdx+1);
98124      aToOpen[nIdx+1] = 0;
98125      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
98126      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
98127      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
98128    }else{
98129      if( pPk ){
98130        /* Add the PK key for this row to the temporary table */
98131        iKey = ++pParse->nMem;
98132        nKey = 0;   /* Zero tells OP_Found to use a composite key */
98133        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
98134            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
98135        sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
98136      }else{
98137        /* Add the rowid of the row to be deleted to the RowSet */
98138        nKey = 1;  /* OP_Seek always uses a single rowid */
98139        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
98140      }
98141    }
98142
98143    /* If this DELETE cannot use the ONEPASS strategy, this is the
98144    ** end of the WHERE loop */
98145    if( eOnePass!=ONEPASS_OFF ){
98146      addrBypass = sqlite3VdbeMakeLabel(v);
98147    }else{
98148      sqlite3WhereEnd(pWInfo);
98149    }
98150
98151    /* Unless this is a view, open cursors for the table we are
98152    ** deleting from and all its indices. If this is a view, then the
98153    ** only effect this statement has is to fire the INSTEAD OF
98154    ** triggers.
98155    */
98156    if( !isView ){
98157      int iAddrOnce = 0;
98158      if( eOnePass==ONEPASS_MULTI ){
98159        iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
98160      }
98161      testcase( IsVirtual(pTab) );
98162      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
98163                                 &iDataCur, &iIdxCur);
98164      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
98165      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
98166      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
98167    }
98168
98169    /* Set up a loop over the rowids/primary-keys that were found in the
98170    ** where-clause loop above.
98171    */
98172    if( eOnePass!=ONEPASS_OFF ){
98173      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
98174      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
98175        assert( pPk!=0 || pTab->pSelect!=0 );
98176        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
98177        VdbeCoverage(v);
98178      }
98179    }else if( pPk ){
98180      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
98181      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
98182      assert( nKey==0 );  /* OP_Found will use a composite key */
98183    }else{
98184      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
98185      VdbeCoverage(v);
98186      assert( nKey==1 );
98187    }
98188
98189    /* Delete the row */
98190#ifndef SQLITE_OMIT_VIRTUALTABLE
98191    if( IsVirtual(pTab) ){
98192      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98193      sqlite3VtabMakeWritable(pParse, pTab);
98194      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
98195      sqlite3VdbeChangeP5(v, OE_Abort);
98196      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
98197      sqlite3MayAbort(pParse);
98198      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
98199        pParse->isMultiWrite = 0;
98200      }
98201    }else
98202#endif
98203    {
98204      int count = (pParse->nested==0);    /* True to count changes */
98205      int iIdxNoSeek = -1;
98206      if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
98207        iIdxNoSeek = aiCurOnePass[1];
98208      }
98209      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98210          iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
98211    }
98212
98213    /* End of the loop over all rowids/primary-keys. */
98214    if( eOnePass!=ONEPASS_OFF ){
98215      sqlite3VdbeResolveLabel(v, addrBypass);
98216      sqlite3WhereEnd(pWInfo);
98217    }else if( pPk ){
98218      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
98219      sqlite3VdbeJumpHere(v, addrLoop);
98220    }else{
98221      sqlite3VdbeGoto(v, addrLoop);
98222      sqlite3VdbeJumpHere(v, addrLoop);
98223    }
98224
98225    /* Close the cursors open on the table and its indexes. */
98226    if( !isView && !IsVirtual(pTab) ){
98227      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
98228      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
98229        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
98230      }
98231    }
98232  } /* End non-truncate path */
98233
98234  /* Update the sqlite_sequence table by storing the content of the
98235  ** maximum rowid counter values recorded while inserting into
98236  ** autoincrement tables.
98237  */
98238  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98239    sqlite3AutoincrementEnd(pParse);
98240  }
98241
98242  /* Return the number of rows that were deleted. If this routine is
98243  ** generating code because of a call to sqlite3NestedParse(), do not
98244  ** invoke the callback function.
98245  */
98246  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
98247    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
98248    sqlite3VdbeSetNumCols(v, 1);
98249    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
98250  }
98251
98252delete_from_cleanup:
98253  sqlite3AuthContextPop(&sContext);
98254  sqlite3SrcListDelete(db, pTabList);
98255  sqlite3ExprDelete(db, pWhere);
98256  sqlite3DbFree(db, aToOpen);
98257  return;
98258}
98259/* Make sure "isView" and other macros defined above are undefined. Otherwise
98260** they may interfere with compilation of other functions in this file
98261** (or in another file, if this file becomes part of the amalgamation).  */
98262#ifdef isView
98263 #undef isView
98264#endif
98265#ifdef pTrigger
98266 #undef pTrigger
98267#endif
98268
98269/*
98270** This routine generates VDBE code that causes a single row of a
98271** single table to be deleted.  Both the original table entry and
98272** all indices are removed.
98273**
98274** Preconditions:
98275**
98276**   1.  iDataCur is an open cursor on the btree that is the canonical data
98277**       store for the table.  (This will be either the table itself,
98278**       in the case of a rowid table, or the PRIMARY KEY index in the case
98279**       of a WITHOUT ROWID table.)
98280**
98281**   2.  Read/write cursors for all indices of pTab must be open as
98282**       cursor number iIdxCur+i for the i-th index.
98283**
98284**   3.  The primary key for the row to be deleted must be stored in a
98285**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
98286**       that a search record formed from OP_MakeRecord is contained in the
98287**       single memory location iPk.
98288**
98289** eMode:
98290**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
98291**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
98292**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
98293**   then this function must seek iDataCur to the entry identified by iPk
98294**   and nPk before reading from it.
98295**
98296**   If eMode is ONEPASS_MULTI, then this call is being made as part
98297**   of a ONEPASS delete that affects multiple rows. In this case, if
98298**   iIdxNoSeek is a valid cursor number (>=0), then its position should
98299**   be preserved following the delete operation. Or, if iIdxNoSeek is not
98300**   a valid cursor number, the position of iDataCur should be preserved
98301**   instead.
98302**
98303** iIdxNoSeek:
98304**   If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
98305**   index cursor (from within array of cursors starting at iIdxCur) that
98306**   already points to the index entry to be deleted.
98307*/
98308SQLITE_PRIVATE void sqlite3GenerateRowDelete(
98309  Parse *pParse,     /* Parsing context */
98310  Table *pTab,       /* Table containing the row to be deleted */
98311  Trigger *pTrigger, /* List of triggers to (potentially) fire */
98312  int iDataCur,      /* Cursor from which column data is extracted */
98313  int iIdxCur,       /* First index cursor */
98314  int iPk,           /* First memory cell containing the PRIMARY KEY */
98315  i16 nPk,           /* Number of PRIMARY KEY memory cells */
98316  u8 count,          /* If non-zero, increment the row change counter */
98317  u8 onconf,         /* Default ON CONFLICT policy for triggers */
98318  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
98319  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
98320){
98321  Vdbe *v = pParse->pVdbe;        /* Vdbe */
98322  int iOld = 0;                   /* First register in OLD.* array */
98323  int iLabel;                     /* Label resolved to end of generated code */
98324  u8 opSeek;                      /* Seek opcode */
98325
98326  /* Vdbe is guaranteed to have been allocated by this stage. */
98327  assert( v );
98328  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
98329                         iDataCur, iIdxCur, iPk, (int)nPk));
98330
98331  /* Seek cursor iCur to the row to delete. If this row no longer exists
98332  ** (this can happen if a trigger program has already deleted it), do
98333  ** not attempt to delete it or fire any DELETE triggers.  */
98334  iLabel = sqlite3VdbeMakeLabel(v);
98335  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
98336  if( eMode==ONEPASS_OFF ){
98337    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
98338    VdbeCoverageIf(v, opSeek==OP_NotExists);
98339    VdbeCoverageIf(v, opSeek==OP_NotFound);
98340  }
98341
98342  /* If there are any triggers to fire, allocate a range of registers to
98343  ** use for the old.* references in the triggers.  */
98344  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
98345    u32 mask;                     /* Mask of OLD.* columns in use */
98346    int iCol;                     /* Iterator used while populating OLD.* */
98347    int addrStart;                /* Start of BEFORE trigger programs */
98348
98349    /* TODO: Could use temporary registers here. Also could attempt to
98350    ** avoid copying the contents of the rowid register.  */
98351    mask = sqlite3TriggerColmask(
98352        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
98353    );
98354    mask |= sqlite3FkOldmask(pParse, pTab);
98355    iOld = pParse->nMem+1;
98356    pParse->nMem += (1 + pTab->nCol);
98357
98358    /* Populate the OLD.* pseudo-table register array. These values will be
98359    ** used by any BEFORE and AFTER triggers that exist.  */
98360    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
98361    for(iCol=0; iCol<pTab->nCol; iCol++){
98362      testcase( mask!=0xffffffff && iCol==31 );
98363      testcase( mask!=0xffffffff && iCol==32 );
98364      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
98365        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
98366      }
98367    }
98368
98369    /* Invoke BEFORE DELETE trigger programs. */
98370    addrStart = sqlite3VdbeCurrentAddr(v);
98371    sqlite3CodeRowTrigger(pParse, pTrigger,
98372        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
98373    );
98374
98375    /* If any BEFORE triggers were coded, then seek the cursor to the
98376    ** row to be deleted again. It may be that the BEFORE triggers moved
98377    ** the cursor or of already deleted the row that the cursor was
98378    ** pointing to.
98379    */
98380    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
98381      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
98382      VdbeCoverageIf(v, opSeek==OP_NotExists);
98383      VdbeCoverageIf(v, opSeek==OP_NotFound);
98384    }
98385
98386    /* Do FK processing. This call checks that any FK constraints that
98387    ** refer to this table (i.e. constraints attached to other tables)
98388    ** are not violated by deleting this row.  */
98389    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
98390  }
98391
98392  /* Delete the index and table entries. Skip this step if pTab is really
98393  ** a view (in which case the only effect of the DELETE statement is to
98394  ** fire the INSTEAD OF triggers).  */
98395  if( pTab->pSelect==0 ){
98396    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
98397    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
98398    if( count ){
98399      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
98400    }
98401    if( iIdxNoSeek>=0 ){
98402      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
98403    }
98404    sqlite3VdbeChangeP5(v, eMode==ONEPASS_MULTI);
98405  }
98406
98407  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
98408  ** handle rows (possibly in other tables) that refer via a foreign key
98409  ** to the row just deleted. */
98410  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
98411
98412  /* Invoke AFTER DELETE trigger programs. */
98413  sqlite3CodeRowTrigger(pParse, pTrigger,
98414      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
98415  );
98416
98417  /* Jump here if the row had already been deleted before any BEFORE
98418  ** trigger programs were invoked. Or if a trigger program throws a
98419  ** RAISE(IGNORE) exception.  */
98420  sqlite3VdbeResolveLabel(v, iLabel);
98421  VdbeModuleComment((v, "END: GenRowDel()"));
98422}
98423
98424/*
98425** This routine generates VDBE code that causes the deletion of all
98426** index entries associated with a single row of a single table, pTab
98427**
98428** Preconditions:
98429**
98430**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
98431**       btree for the table pTab.  (This will be either the table itself
98432**       for rowid tables or to the primary key index for WITHOUT ROWID
98433**       tables.)
98434**
98435**   2.  Read/write cursors for all indices of pTab must be open as
98436**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
98437**       index is the 0-th index.)
98438**
98439**   3.  The "iDataCur" cursor must be already be positioned on the row
98440**       that is to be deleted.
98441*/
98442SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
98443  Parse *pParse,     /* Parsing and code generating context */
98444  Table *pTab,       /* Table containing the row to be deleted */
98445  int iDataCur,      /* Cursor of table holding data. */
98446  int iIdxCur,       /* First index cursor */
98447  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
98448  int iIdxNoSeek     /* Do not delete from this cursor */
98449){
98450  int i;             /* Index loop counter */
98451  int r1 = -1;       /* Register holding an index key */
98452  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
98453  Index *pIdx;       /* Current index */
98454  Index *pPrior = 0; /* Prior index */
98455  Vdbe *v;           /* The prepared statement under construction */
98456  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
98457
98458  v = pParse->pVdbe;
98459  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
98460  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
98461    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
98462    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
98463    if( pIdx==pPk ) continue;
98464    if( iIdxCur+i==iIdxNoSeek ) continue;
98465    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
98466    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
98467        &iPartIdxLabel, pPrior, r1);
98468    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
98469        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
98470    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
98471    pPrior = pIdx;
98472  }
98473}
98474
98475/*
98476** Generate code that will assemble an index key and stores it in register
98477** regOut.  The key with be for index pIdx which is an index on pTab.
98478** iCur is the index of a cursor open on the pTab table and pointing to
98479** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
98480** iCur must be the cursor of the PRIMARY KEY index.
98481**
98482** Return a register number which is the first in a block of
98483** registers that holds the elements of the index key.  The
98484** block of registers has already been deallocated by the time
98485** this routine returns.
98486**
98487** If *piPartIdxLabel is not NULL, fill it in with a label and jump
98488** to that label if pIdx is a partial index that should be skipped.
98489** The label should be resolved using sqlite3ResolvePartIdxLabel().
98490** A partial index should be skipped if its WHERE clause evaluates
98491** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
98492** will be set to zero which is an empty label that is ignored by
98493** sqlite3ResolvePartIdxLabel().
98494**
98495** The pPrior and regPrior parameters are used to implement a cache to
98496** avoid unnecessary register loads.  If pPrior is not NULL, then it is
98497** a pointer to a different index for which an index key has just been
98498** computed into register regPrior.  If the current pIdx index is generating
98499** its key into the same sequence of registers and if pPrior and pIdx share
98500** a column in common, then the register corresponding to that column already
98501** holds the correct value and the loading of that register is skipped.
98502** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
98503** on a table with multiple indices, and especially with the ROWID or
98504** PRIMARY KEY columns of the index.
98505*/
98506SQLITE_PRIVATE int sqlite3GenerateIndexKey(
98507  Parse *pParse,       /* Parsing context */
98508  Index *pIdx,         /* The index for which to generate a key */
98509  int iDataCur,        /* Cursor number from which to take column data */
98510  int regOut,          /* Put the new key into this register if not 0 */
98511  int prefixOnly,      /* Compute only a unique prefix of the key */
98512  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
98513  Index *pPrior,       /* Previously generated index key */
98514  int regPrior         /* Register holding previous generated key */
98515){
98516  Vdbe *v = pParse->pVdbe;
98517  int j;
98518  int regBase;
98519  int nCol;
98520
98521  if( piPartIdxLabel ){
98522    if( pIdx->pPartIdxWhere ){
98523      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
98524      pParse->iSelfTab = iDataCur;
98525      sqlite3ExprCachePush(pParse);
98526      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
98527                            SQLITE_JUMPIFNULL);
98528    }else{
98529      *piPartIdxLabel = 0;
98530    }
98531  }
98532  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
98533  regBase = sqlite3GetTempRange(pParse, nCol);
98534  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
98535  for(j=0; j<nCol; j++){
98536    if( pPrior
98537     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
98538     && pPrior->aiColumn[j]!=XN_EXPR
98539    ){
98540      /* This column was already computed by the previous index */
98541      continue;
98542    }
98543    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
98544    /* If the column affinity is REAL but the number is an integer, then it
98545    ** might be stored in the table as an integer (using a compact
98546    ** representation) then converted to REAL by an OP_RealAffinity opcode.
98547    ** But we are getting ready to store this value back into an index, where
98548    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
98549    ** opcode if it is present */
98550    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
98551  }
98552  if( regOut ){
98553    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
98554  }
98555  sqlite3ReleaseTempRange(pParse, regBase, nCol);
98556  return regBase;
98557}
98558
98559/*
98560** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
98561** because it was a partial index, then this routine should be called to
98562** resolve that label.
98563*/
98564SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
98565  if( iLabel ){
98566    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
98567    sqlite3ExprCachePop(pParse);
98568  }
98569}
98570
98571/************** End of delete.c **********************************************/
98572/************** Begin file func.c ********************************************/
98573/*
98574** 2002 February 23
98575**
98576** The author disclaims copyright to this source code.  In place of
98577** a legal notice, here is a blessing:
98578**
98579**    May you do good and not evil.
98580**    May you find forgiveness for yourself and forgive others.
98581**    May you share freely, never taking more than you give.
98582**
98583*************************************************************************
98584** This file contains the C-language implementations for many of the SQL
98585** functions of SQLite.  (Some function, and in particular the date and
98586** time functions, are implemented separately.)
98587*/
98588/* #include "sqliteInt.h" */
98589/* #include <stdlib.h> */
98590/* #include <assert.h> */
98591/* #include "vdbeInt.h" */
98592
98593/*
98594** Return the collating function associated with a function.
98595*/
98596static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
98597  VdbeOp *pOp;
98598  assert( context->pVdbe!=0 );
98599  pOp = &context->pVdbe->aOp[context->iOp-1];
98600  assert( pOp->opcode==OP_CollSeq );
98601  assert( pOp->p4type==P4_COLLSEQ );
98602  return pOp->p4.pColl;
98603}
98604
98605/*
98606** Indicate that the accumulator load should be skipped on this
98607** iteration of the aggregate loop.
98608*/
98609static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
98610  context->skipFlag = 1;
98611}
98612
98613/*
98614** Implementation of the non-aggregate min() and max() functions
98615*/
98616static void minmaxFunc(
98617  sqlite3_context *context,
98618  int argc,
98619  sqlite3_value **argv
98620){
98621  int i;
98622  int mask;    /* 0 for min() or 0xffffffff for max() */
98623  int iBest;
98624  CollSeq *pColl;
98625
98626  assert( argc>1 );
98627  mask = sqlite3_user_data(context)==0 ? 0 : -1;
98628  pColl = sqlite3GetFuncCollSeq(context);
98629  assert( pColl );
98630  assert( mask==-1 || mask==0 );
98631  iBest = 0;
98632  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
98633  for(i=1; i<argc; i++){
98634    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
98635    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
98636      testcase( mask==0 );
98637      iBest = i;
98638    }
98639  }
98640  sqlite3_result_value(context, argv[iBest]);
98641}
98642
98643/*
98644** Return the type of the argument.
98645*/
98646static void typeofFunc(
98647  sqlite3_context *context,
98648  int NotUsed,
98649  sqlite3_value **argv
98650){
98651  const char *z = 0;
98652  UNUSED_PARAMETER(NotUsed);
98653  switch( sqlite3_value_type(argv[0]) ){
98654    case SQLITE_INTEGER: z = "integer"; break;
98655    case SQLITE_TEXT:    z = "text";    break;
98656    case SQLITE_FLOAT:   z = "real";    break;
98657    case SQLITE_BLOB:    z = "blob";    break;
98658    default:             z = "null";    break;
98659  }
98660  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
98661}
98662
98663
98664/*
98665** Implementation of the length() function
98666*/
98667static void lengthFunc(
98668  sqlite3_context *context,
98669  int argc,
98670  sqlite3_value **argv
98671){
98672  int len;
98673
98674  assert( argc==1 );
98675  UNUSED_PARAMETER(argc);
98676  switch( sqlite3_value_type(argv[0]) ){
98677    case SQLITE_BLOB:
98678    case SQLITE_INTEGER:
98679    case SQLITE_FLOAT: {
98680      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
98681      break;
98682    }
98683    case SQLITE_TEXT: {
98684      const unsigned char *z = sqlite3_value_text(argv[0]);
98685      if( z==0 ) return;
98686      len = 0;
98687      while( *z ){
98688        len++;
98689        SQLITE_SKIP_UTF8(z);
98690      }
98691      sqlite3_result_int(context, len);
98692      break;
98693    }
98694    default: {
98695      sqlite3_result_null(context);
98696      break;
98697    }
98698  }
98699}
98700
98701/*
98702** Implementation of the abs() function.
98703**
98704** IMP: R-23979-26855 The abs(X) function returns the absolute value of
98705** the numeric argument X.
98706*/
98707static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
98708  assert( argc==1 );
98709  UNUSED_PARAMETER(argc);
98710  switch( sqlite3_value_type(argv[0]) ){
98711    case SQLITE_INTEGER: {
98712      i64 iVal = sqlite3_value_int64(argv[0]);
98713      if( iVal<0 ){
98714        if( iVal==SMALLEST_INT64 ){
98715          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
98716          ** then abs(X) throws an integer overflow error since there is no
98717          ** equivalent positive 64-bit two complement value. */
98718          sqlite3_result_error(context, "integer overflow", -1);
98719          return;
98720        }
98721        iVal = -iVal;
98722      }
98723      sqlite3_result_int64(context, iVal);
98724      break;
98725    }
98726    case SQLITE_NULL: {
98727      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
98728      sqlite3_result_null(context);
98729      break;
98730    }
98731    default: {
98732      /* Because sqlite3_value_double() returns 0.0 if the argument is not
98733      ** something that can be converted into a number, we have:
98734      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
98735      ** that cannot be converted to a numeric value.
98736      */
98737      double rVal = sqlite3_value_double(argv[0]);
98738      if( rVal<0 ) rVal = -rVal;
98739      sqlite3_result_double(context, rVal);
98740      break;
98741    }
98742  }
98743}
98744
98745/*
98746** Implementation of the instr() function.
98747**
98748** instr(haystack,needle) finds the first occurrence of needle
98749** in haystack and returns the number of previous characters plus 1,
98750** or 0 if needle does not occur within haystack.
98751**
98752** If both haystack and needle are BLOBs, then the result is one more than
98753** the number of bytes in haystack prior to the first occurrence of needle,
98754** or 0 if needle never occurs in haystack.
98755*/
98756static void instrFunc(
98757  sqlite3_context *context,
98758  int argc,
98759  sqlite3_value **argv
98760){
98761  const unsigned char *zHaystack;
98762  const unsigned char *zNeedle;
98763  int nHaystack;
98764  int nNeedle;
98765  int typeHaystack, typeNeedle;
98766  int N = 1;
98767  int isText;
98768
98769  UNUSED_PARAMETER(argc);
98770  typeHaystack = sqlite3_value_type(argv[0]);
98771  typeNeedle = sqlite3_value_type(argv[1]);
98772  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
98773  nHaystack = sqlite3_value_bytes(argv[0]);
98774  nNeedle = sqlite3_value_bytes(argv[1]);
98775  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
98776    zHaystack = sqlite3_value_blob(argv[0]);
98777    zNeedle = sqlite3_value_blob(argv[1]);
98778    isText = 0;
98779  }else{
98780    zHaystack = sqlite3_value_text(argv[0]);
98781    zNeedle = sqlite3_value_text(argv[1]);
98782    isText = 1;
98783  }
98784  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
98785    N++;
98786    do{
98787      nHaystack--;
98788      zHaystack++;
98789    }while( isText && (zHaystack[0]&0xc0)==0x80 );
98790  }
98791  if( nNeedle>nHaystack ) N = 0;
98792  sqlite3_result_int(context, N);
98793}
98794
98795/*
98796** Implementation of the printf() function.
98797*/
98798static void printfFunc(
98799  sqlite3_context *context,
98800  int argc,
98801  sqlite3_value **argv
98802){
98803  PrintfArguments x;
98804  StrAccum str;
98805  const char *zFormat;
98806  int n;
98807  sqlite3 *db = sqlite3_context_db_handle(context);
98808
98809  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
98810    x.nArg = argc-1;
98811    x.nUsed = 0;
98812    x.apArg = argv+1;
98813    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
98814    sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
98815    n = str.nChar;
98816    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
98817                        SQLITE_DYNAMIC);
98818  }
98819}
98820
98821/*
98822** Implementation of the substr() function.
98823**
98824** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
98825** p1 is 1-indexed.  So substr(x,1,1) returns the first character
98826** of x.  If x is text, then we actually count UTF-8 characters.
98827** If x is a blob, then we count bytes.
98828**
98829** If p1 is negative, then we begin abs(p1) from the end of x[].
98830**
98831** If p2 is negative, return the p2 characters preceding p1.
98832*/
98833static void substrFunc(
98834  sqlite3_context *context,
98835  int argc,
98836  sqlite3_value **argv
98837){
98838  const unsigned char *z;
98839  const unsigned char *z2;
98840  int len;
98841  int p0type;
98842  i64 p1, p2;
98843  int negP2 = 0;
98844
98845  assert( argc==3 || argc==2 );
98846  if( sqlite3_value_type(argv[1])==SQLITE_NULL
98847   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
98848  ){
98849    return;
98850  }
98851  p0type = sqlite3_value_type(argv[0]);
98852  p1 = sqlite3_value_int(argv[1]);
98853  if( p0type==SQLITE_BLOB ){
98854    len = sqlite3_value_bytes(argv[0]);
98855    z = sqlite3_value_blob(argv[0]);
98856    if( z==0 ) return;
98857    assert( len==sqlite3_value_bytes(argv[0]) );
98858  }else{
98859    z = sqlite3_value_text(argv[0]);
98860    if( z==0 ) return;
98861    len = 0;
98862    if( p1<0 ){
98863      for(z2=z; *z2; len++){
98864        SQLITE_SKIP_UTF8(z2);
98865      }
98866    }
98867  }
98868#ifdef SQLITE_SUBSTR_COMPATIBILITY
98869  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
98870  ** as substr(X,1,N) - it returns the first N characters of X.  This
98871  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
98872  ** from 2009-02-02 for compatibility of applications that exploited the
98873  ** old buggy behavior. */
98874  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
98875#endif
98876  if( argc==3 ){
98877    p2 = sqlite3_value_int(argv[2]);
98878    if( p2<0 ){
98879      p2 = -p2;
98880      negP2 = 1;
98881    }
98882  }else{
98883    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
98884  }
98885  if( p1<0 ){
98886    p1 += len;
98887    if( p1<0 ){
98888      p2 += p1;
98889      if( p2<0 ) p2 = 0;
98890      p1 = 0;
98891    }
98892  }else if( p1>0 ){
98893    p1--;
98894  }else if( p2>0 ){
98895    p2--;
98896  }
98897  if( negP2 ){
98898    p1 -= p2;
98899    if( p1<0 ){
98900      p2 += p1;
98901      p1 = 0;
98902    }
98903  }
98904  assert( p1>=0 && p2>=0 );
98905  if( p0type!=SQLITE_BLOB ){
98906    while( *z && p1 ){
98907      SQLITE_SKIP_UTF8(z);
98908      p1--;
98909    }
98910    for(z2=z; *z2 && p2; p2--){
98911      SQLITE_SKIP_UTF8(z2);
98912    }
98913    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
98914                          SQLITE_UTF8);
98915  }else{
98916    if( p1+p2>len ){
98917      p2 = len-p1;
98918      if( p2<0 ) p2 = 0;
98919    }
98920    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
98921  }
98922}
98923
98924/*
98925** Implementation of the round() function
98926*/
98927#ifndef SQLITE_OMIT_FLOATING_POINT
98928static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
98929  int n = 0;
98930  double r;
98931  char *zBuf;
98932  assert( argc==1 || argc==2 );
98933  if( argc==2 ){
98934    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
98935    n = sqlite3_value_int(argv[1]);
98936    if( n>30 ) n = 30;
98937    if( n<0 ) n = 0;
98938  }
98939  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
98940  r = sqlite3_value_double(argv[0]);
98941  /* If Y==0 and X will fit in a 64-bit int,
98942  ** handle the rounding directly,
98943  ** otherwise use printf.
98944  */
98945  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
98946    r = (double)((sqlite_int64)(r+0.5));
98947  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
98948    r = -(double)((sqlite_int64)((-r)+0.5));
98949  }else{
98950    zBuf = sqlite3_mprintf("%.*f",n,r);
98951    if( zBuf==0 ){
98952      sqlite3_result_error_nomem(context);
98953      return;
98954    }
98955    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
98956    sqlite3_free(zBuf);
98957  }
98958  sqlite3_result_double(context, r);
98959}
98960#endif
98961
98962/*
98963** Allocate nByte bytes of space using sqlite3Malloc(). If the
98964** allocation fails, call sqlite3_result_error_nomem() to notify
98965** the database handle that malloc() has failed and return NULL.
98966** If nByte is larger than the maximum string or blob length, then
98967** raise an SQLITE_TOOBIG exception and return NULL.
98968*/
98969static void *contextMalloc(sqlite3_context *context, i64 nByte){
98970  char *z;
98971  sqlite3 *db = sqlite3_context_db_handle(context);
98972  assert( nByte>0 );
98973  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
98974  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
98975  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
98976    sqlite3_result_error_toobig(context);
98977    z = 0;
98978  }else{
98979    z = sqlite3Malloc(nByte);
98980    if( !z ){
98981      sqlite3_result_error_nomem(context);
98982    }
98983  }
98984  return z;
98985}
98986
98987/*
98988** Implementation of the upper() and lower() SQL functions.
98989*/
98990static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
98991  char *z1;
98992  const char *z2;
98993  int i, n;
98994  UNUSED_PARAMETER(argc);
98995  z2 = (char*)sqlite3_value_text(argv[0]);
98996  n = sqlite3_value_bytes(argv[0]);
98997  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
98998  assert( z2==(char*)sqlite3_value_text(argv[0]) );
98999  if( z2 ){
99000    z1 = contextMalloc(context, ((i64)n)+1);
99001    if( z1 ){
99002      for(i=0; i<n; i++){
99003        z1[i] = (char)sqlite3Toupper(z2[i]);
99004      }
99005      sqlite3_result_text(context, z1, n, sqlite3_free);
99006    }
99007  }
99008}
99009static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
99010  char *z1;
99011  const char *z2;
99012  int i, n;
99013  UNUSED_PARAMETER(argc);
99014  z2 = (char*)sqlite3_value_text(argv[0]);
99015  n = sqlite3_value_bytes(argv[0]);
99016  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
99017  assert( z2==(char*)sqlite3_value_text(argv[0]) );
99018  if( z2 ){
99019    z1 = contextMalloc(context, ((i64)n)+1);
99020    if( z1 ){
99021      for(i=0; i<n; i++){
99022        z1[i] = sqlite3Tolower(z2[i]);
99023      }
99024      sqlite3_result_text(context, z1, n, sqlite3_free);
99025    }
99026  }
99027}
99028
99029/*
99030** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
99031** as VDBE code so that unused argument values do not have to be computed.
99032** However, we still need some kind of function implementation for this
99033** routines in the function table.  The noopFunc macro provides this.
99034** noopFunc will never be called so it doesn't matter what the implementation
99035** is.  We might as well use the "version()" function as a substitute.
99036*/
99037#define noopFunc versionFunc   /* Substitute function - never called */
99038
99039/*
99040** Implementation of random().  Return a random integer.
99041*/
99042static void randomFunc(
99043  sqlite3_context *context,
99044  int NotUsed,
99045  sqlite3_value **NotUsed2
99046){
99047  sqlite_int64 r;
99048  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99049  sqlite3_randomness(sizeof(r), &r);
99050  if( r<0 ){
99051    /* We need to prevent a random number of 0x8000000000000000
99052    ** (or -9223372036854775808) since when you do abs() of that
99053    ** number of you get the same value back again.  To do this
99054    ** in a way that is testable, mask the sign bit off of negative
99055    ** values, resulting in a positive value.  Then take the
99056    ** 2s complement of that positive value.  The end result can
99057    ** therefore be no less than -9223372036854775807.
99058    */
99059    r = -(r & LARGEST_INT64);
99060  }
99061  sqlite3_result_int64(context, r);
99062}
99063
99064/*
99065** Implementation of randomblob(N).  Return a random blob
99066** that is N bytes long.
99067*/
99068static void randomBlob(
99069  sqlite3_context *context,
99070  int argc,
99071  sqlite3_value **argv
99072){
99073  int n;
99074  unsigned char *p;
99075  assert( argc==1 );
99076  UNUSED_PARAMETER(argc);
99077  n = sqlite3_value_int(argv[0]);
99078  if( n<1 ){
99079    n = 1;
99080  }
99081  p = contextMalloc(context, n);
99082  if( p ){
99083    sqlite3_randomness(n, p);
99084    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
99085  }
99086}
99087
99088/*
99089** Implementation of the last_insert_rowid() SQL function.  The return
99090** value is the same as the sqlite3_last_insert_rowid() API function.
99091*/
99092static void last_insert_rowid(
99093  sqlite3_context *context,
99094  int NotUsed,
99095  sqlite3_value **NotUsed2
99096){
99097  sqlite3 *db = sqlite3_context_db_handle(context);
99098  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99099  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
99100  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
99101  ** function. */
99102  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
99103}
99104
99105/*
99106** Implementation of the changes() SQL function.
99107**
99108** IMP: R-62073-11209 The changes() SQL function is a wrapper
99109** around the sqlite3_changes() C/C++ function and hence follows the same
99110** rules for counting changes.
99111*/
99112static void changes(
99113  sqlite3_context *context,
99114  int NotUsed,
99115  sqlite3_value **NotUsed2
99116){
99117  sqlite3 *db = sqlite3_context_db_handle(context);
99118  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99119  sqlite3_result_int(context, sqlite3_changes(db));
99120}
99121
99122/*
99123** Implementation of the total_changes() SQL function.  The return value is
99124** the same as the sqlite3_total_changes() API function.
99125*/
99126static void total_changes(
99127  sqlite3_context *context,
99128  int NotUsed,
99129  sqlite3_value **NotUsed2
99130){
99131  sqlite3 *db = sqlite3_context_db_handle(context);
99132  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99133  /* IMP: R-52756-41993 This function is a wrapper around the
99134  ** sqlite3_total_changes() C/C++ interface. */
99135  sqlite3_result_int(context, sqlite3_total_changes(db));
99136}
99137
99138/*
99139** A structure defining how to do GLOB-style comparisons.
99140*/
99141struct compareInfo {
99142  u8 matchAll;
99143  u8 matchOne;
99144  u8 matchSet;
99145  u8 noCase;
99146};
99147
99148/*
99149** For LIKE and GLOB matching on EBCDIC machines, assume that every
99150** character is exactly one byte in size.  Also, provde the Utf8Read()
99151** macro for fast reading of the next character in the common case where
99152** the next character is ASCII.
99153*/
99154#if defined(SQLITE_EBCDIC)
99155# define sqlite3Utf8Read(A)        (*((*A)++))
99156# define Utf8Read(A)               (*(A++))
99157#else
99158# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
99159#endif
99160
99161static const struct compareInfo globInfo = { '*', '?', '[', 0 };
99162/* The correct SQL-92 behavior is for the LIKE operator to ignore
99163** case.  Thus  'a' LIKE 'A' would be true. */
99164static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
99165/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
99166** is case sensitive causing 'a' LIKE 'A' to be false */
99167static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
99168
99169/*
99170** Compare two UTF-8 strings for equality where the first string can
99171** potentially be a "glob" or "like" expression.  Return true (1) if they
99172** are the same and false (0) if they are different.
99173**
99174** Globbing rules:
99175**
99176**      '*'       Matches any sequence of zero or more characters.
99177**
99178**      '?'       Matches exactly one character.
99179**
99180**     [...]      Matches one character from the enclosed list of
99181**                characters.
99182**
99183**     [^...]     Matches one character not in the enclosed list.
99184**
99185** With the [...] and [^...] matching, a ']' character can be included
99186** in the list by making it the first character after '[' or '^'.  A
99187** range of characters can be specified using '-'.  Example:
99188** "[a-z]" matches any single lower-case letter.  To match a '-', make
99189** it the last character in the list.
99190**
99191** Like matching rules:
99192**
99193**      '%'       Matches any sequence of zero or more characters
99194**
99195***     '_'       Matches any one character
99196**
99197**      Ec        Where E is the "esc" character and c is any other
99198**                character, including '%', '_', and esc, match exactly c.
99199**
99200** The comments within this routine usually assume glob matching.
99201**
99202** This routine is usually quick, but can be N**2 in the worst case.
99203*/
99204static int patternCompare(
99205  const u8 *zPattern,              /* The glob pattern */
99206  const u8 *zString,               /* The string to compare against the glob */
99207  const struct compareInfo *pInfo, /* Information about how to do the compare */
99208  u32 esc                          /* The escape character */
99209){
99210  u32 c, c2;                       /* Next pattern and input string chars */
99211  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
99212  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
99213  u32 matchOther;                  /* "[" or the escape character */
99214  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
99215  const u8 *zEscaped = 0;          /* One past the last escaped input char */
99216
99217  /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
99218  ** have the matchSet operator.  So we either have to look for one or
99219  ** the other, never both.  Hence the single variable matchOther is used
99220  ** to store the one we have to look for.
99221  */
99222  matchOther = esc ? esc : pInfo->matchSet;
99223
99224  while( (c = Utf8Read(zPattern))!=0 ){
99225    if( c==matchAll ){  /* Match "*" */
99226      /* Skip over multiple "*" characters in the pattern.  If there
99227      ** are also "?" characters, skip those as well, but consume a
99228      ** single character of the input string for each "?" skipped */
99229      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
99230        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
99231          return 0;
99232        }
99233      }
99234      if( c==0 ){
99235        return 1;   /* "*" at the end of the pattern matches */
99236      }else if( c==matchOther ){
99237        if( esc ){
99238          c = sqlite3Utf8Read(&zPattern);
99239          if( c==0 ) return 0;
99240        }else{
99241          /* "[...]" immediately follows the "*".  We have to do a slow
99242          ** recursive search in this case, but it is an unusual case. */
99243          assert( matchOther<0x80 );  /* '[' is a single-byte character */
99244          while( *zString
99245                 && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
99246            SQLITE_SKIP_UTF8(zString);
99247          }
99248          return *zString!=0;
99249        }
99250      }
99251
99252      /* At this point variable c contains the first character of the
99253      ** pattern string past the "*".  Search in the input string for the
99254      ** first matching character and recursively contine the match from
99255      ** that point.
99256      **
99257      ** For a case-insensitive search, set variable cx to be the same as
99258      ** c but in the other case and search the input string for either
99259      ** c or cx.
99260      */
99261      if( c<=0x80 ){
99262        u32 cx;
99263        if( noCase ){
99264          cx = sqlite3Toupper(c);
99265          c = sqlite3Tolower(c);
99266        }else{
99267          cx = c;
99268        }
99269        while( (c2 = *(zString++))!=0 ){
99270          if( c2!=c && c2!=cx ) continue;
99271          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
99272        }
99273      }else{
99274        while( (c2 = Utf8Read(zString))!=0 ){
99275          if( c2!=c ) continue;
99276          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
99277        }
99278      }
99279      return 0;
99280    }
99281    if( c==matchOther ){
99282      if( esc ){
99283        c = sqlite3Utf8Read(&zPattern);
99284        if( c==0 ) return 0;
99285        zEscaped = zPattern;
99286      }else{
99287        u32 prior_c = 0;
99288        int seen = 0;
99289        int invert = 0;
99290        c = sqlite3Utf8Read(&zString);
99291        if( c==0 ) return 0;
99292        c2 = sqlite3Utf8Read(&zPattern);
99293        if( c2=='^' ){
99294          invert = 1;
99295          c2 = sqlite3Utf8Read(&zPattern);
99296        }
99297        if( c2==']' ){
99298          if( c==']' ) seen = 1;
99299          c2 = sqlite3Utf8Read(&zPattern);
99300        }
99301        while( c2 && c2!=']' ){
99302          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
99303            c2 = sqlite3Utf8Read(&zPattern);
99304            if( c>=prior_c && c<=c2 ) seen = 1;
99305            prior_c = 0;
99306          }else{
99307            if( c==c2 ){
99308              seen = 1;
99309            }
99310            prior_c = c2;
99311          }
99312          c2 = sqlite3Utf8Read(&zPattern);
99313        }
99314        if( c2==0 || (seen ^ invert)==0 ){
99315          return 0;
99316        }
99317        continue;
99318      }
99319    }
99320    c2 = Utf8Read(zString);
99321    if( c==c2 ) continue;
99322    if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
99323      continue;
99324    }
99325    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
99326    return 0;
99327  }
99328  return *zString==0;
99329}
99330
99331/*
99332** The sqlite3_strglob() interface.
99333*/
99334SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
99335  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
99336}
99337
99338/*
99339** Count the number of times that the LIKE operator (or GLOB which is
99340** just a variation of LIKE) gets called.  This is used for testing
99341** only.
99342*/
99343#ifdef SQLITE_TEST
99344SQLITE_API int sqlite3_like_count = 0;
99345#endif
99346
99347
99348/*
99349** Implementation of the like() SQL function.  This function implements
99350** the build-in LIKE operator.  The first argument to the function is the
99351** pattern and the second argument is the string.  So, the SQL statements:
99352**
99353**       A LIKE B
99354**
99355** is implemented as like(B,A).
99356**
99357** This same function (with a different compareInfo structure) computes
99358** the GLOB operator.
99359*/
99360static void likeFunc(
99361  sqlite3_context *context,
99362  int argc,
99363  sqlite3_value **argv
99364){
99365  const unsigned char *zA, *zB;
99366  u32 escape = 0;
99367  int nPat;
99368  sqlite3 *db = sqlite3_context_db_handle(context);
99369
99370  zB = sqlite3_value_text(argv[0]);
99371  zA = sqlite3_value_text(argv[1]);
99372
99373  /* Limit the length of the LIKE or GLOB pattern to avoid problems
99374  ** of deep recursion and N*N behavior in patternCompare().
99375  */
99376  nPat = sqlite3_value_bytes(argv[0]);
99377  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
99378  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
99379  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
99380    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
99381    return;
99382  }
99383  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
99384
99385  if( argc==3 ){
99386    /* The escape character string must consist of a single UTF-8 character.
99387    ** Otherwise, return an error.
99388    */
99389    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
99390    if( zEsc==0 ) return;
99391    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
99392      sqlite3_result_error(context,
99393          "ESCAPE expression must be a single character", -1);
99394      return;
99395    }
99396    escape = sqlite3Utf8Read(&zEsc);
99397  }
99398  if( zA && zB ){
99399    struct compareInfo *pInfo = sqlite3_user_data(context);
99400#ifdef SQLITE_TEST
99401    sqlite3_like_count++;
99402#endif
99403
99404    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
99405  }
99406}
99407
99408/*
99409** Implementation of the NULLIF(x,y) function.  The result is the first
99410** argument if the arguments are different.  The result is NULL if the
99411** arguments are equal to each other.
99412*/
99413static void nullifFunc(
99414  sqlite3_context *context,
99415  int NotUsed,
99416  sqlite3_value **argv
99417){
99418  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
99419  UNUSED_PARAMETER(NotUsed);
99420  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
99421    sqlite3_result_value(context, argv[0]);
99422  }
99423}
99424
99425/*
99426** Implementation of the sqlite_version() function.  The result is the version
99427** of the SQLite library that is running.
99428*/
99429static void versionFunc(
99430  sqlite3_context *context,
99431  int NotUsed,
99432  sqlite3_value **NotUsed2
99433){
99434  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99435  /* IMP: R-48699-48617 This function is an SQL wrapper around the
99436  ** sqlite3_libversion() C-interface. */
99437  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
99438}
99439
99440/*
99441** Implementation of the sqlite_source_id() function. The result is a string
99442** that identifies the particular version of the source code used to build
99443** SQLite.
99444*/
99445static void sourceidFunc(
99446  sqlite3_context *context,
99447  int NotUsed,
99448  sqlite3_value **NotUsed2
99449){
99450  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99451  /* IMP: R-24470-31136 This function is an SQL wrapper around the
99452  ** sqlite3_sourceid() C interface. */
99453  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
99454}
99455
99456/*
99457** Implementation of the sqlite_log() function.  This is a wrapper around
99458** sqlite3_log().  The return value is NULL.  The function exists purely for
99459** its side-effects.
99460*/
99461static void errlogFunc(
99462  sqlite3_context *context,
99463  int argc,
99464  sqlite3_value **argv
99465){
99466  UNUSED_PARAMETER(argc);
99467  UNUSED_PARAMETER(context);
99468  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
99469}
99470
99471/*
99472** Implementation of the sqlite_compileoption_used() function.
99473** The result is an integer that identifies if the compiler option
99474** was used to build SQLite.
99475*/
99476#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
99477static void compileoptionusedFunc(
99478  sqlite3_context *context,
99479  int argc,
99480  sqlite3_value **argv
99481){
99482  const char *zOptName;
99483  assert( argc==1 );
99484  UNUSED_PARAMETER(argc);
99485  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
99486  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
99487  ** function.
99488  */
99489  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
99490    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
99491  }
99492}
99493#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
99494
99495/*
99496** Implementation of the sqlite_compileoption_get() function.
99497** The result is a string that identifies the compiler options
99498** used to build SQLite.
99499*/
99500#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
99501static void compileoptiongetFunc(
99502  sqlite3_context *context,
99503  int argc,
99504  sqlite3_value **argv
99505){
99506  int n;
99507  assert( argc==1 );
99508  UNUSED_PARAMETER(argc);
99509  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
99510  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
99511  */
99512  n = sqlite3_value_int(argv[0]);
99513  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
99514}
99515#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
99516
99517/* Array for converting from half-bytes (nybbles) into ASCII hex
99518** digits. */
99519static const char hexdigits[] = {
99520  '0', '1', '2', '3', '4', '5', '6', '7',
99521  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
99522};
99523
99524/*
99525** Implementation of the QUOTE() function.  This function takes a single
99526** argument.  If the argument is numeric, the return value is the same as
99527** the argument.  If the argument is NULL, the return value is the string
99528** "NULL".  Otherwise, the argument is enclosed in single quotes with
99529** single-quote escapes.
99530*/
99531static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
99532  assert( argc==1 );
99533  UNUSED_PARAMETER(argc);
99534  switch( sqlite3_value_type(argv[0]) ){
99535    case SQLITE_FLOAT: {
99536      double r1, r2;
99537      char zBuf[50];
99538      r1 = sqlite3_value_double(argv[0]);
99539      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
99540      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
99541      if( r1!=r2 ){
99542        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
99543      }
99544      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
99545      break;
99546    }
99547    case SQLITE_INTEGER: {
99548      sqlite3_result_value(context, argv[0]);
99549      break;
99550    }
99551    case SQLITE_BLOB: {
99552      char *zText = 0;
99553      char const *zBlob = sqlite3_value_blob(argv[0]);
99554      int nBlob = sqlite3_value_bytes(argv[0]);
99555      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
99556      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
99557      if( zText ){
99558        int i;
99559        for(i=0; i<nBlob; i++){
99560          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
99561          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
99562        }
99563        zText[(nBlob*2)+2] = '\'';
99564        zText[(nBlob*2)+3] = '\0';
99565        zText[0] = 'X';
99566        zText[1] = '\'';
99567        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
99568        sqlite3_free(zText);
99569      }
99570      break;
99571    }
99572    case SQLITE_TEXT: {
99573      int i,j;
99574      u64 n;
99575      const unsigned char *zArg = sqlite3_value_text(argv[0]);
99576      char *z;
99577
99578      if( zArg==0 ) return;
99579      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
99580      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
99581      if( z ){
99582        z[0] = '\'';
99583        for(i=0, j=1; zArg[i]; i++){
99584          z[j++] = zArg[i];
99585          if( zArg[i]=='\'' ){
99586            z[j++] = '\'';
99587          }
99588        }
99589        z[j++] = '\'';
99590        z[j] = 0;
99591        sqlite3_result_text(context, z, j, sqlite3_free);
99592      }
99593      break;
99594    }
99595    default: {
99596      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
99597      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
99598      break;
99599    }
99600  }
99601}
99602
99603/*
99604** The unicode() function.  Return the integer unicode code-point value
99605** for the first character of the input string.
99606*/
99607static void unicodeFunc(
99608  sqlite3_context *context,
99609  int argc,
99610  sqlite3_value **argv
99611){
99612  const unsigned char *z = sqlite3_value_text(argv[0]);
99613  (void)argc;
99614  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
99615}
99616
99617/*
99618** The char() function takes zero or more arguments, each of which is
99619** an integer.  It constructs a string where each character of the string
99620** is the unicode character for the corresponding integer argument.
99621*/
99622static void charFunc(
99623  sqlite3_context *context,
99624  int argc,
99625  sqlite3_value **argv
99626){
99627  unsigned char *z, *zOut;
99628  int i;
99629  zOut = z = sqlite3_malloc64( argc*4+1 );
99630  if( z==0 ){
99631    sqlite3_result_error_nomem(context);
99632    return;
99633  }
99634  for(i=0; i<argc; i++){
99635    sqlite3_int64 x;
99636    unsigned c;
99637    x = sqlite3_value_int64(argv[i]);
99638    if( x<0 || x>0x10ffff ) x = 0xfffd;
99639    c = (unsigned)(x & 0x1fffff);
99640    if( c<0x00080 ){
99641      *zOut++ = (u8)(c&0xFF);
99642    }else if( c<0x00800 ){
99643      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
99644      *zOut++ = 0x80 + (u8)(c & 0x3F);
99645    }else if( c<0x10000 ){
99646      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
99647      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
99648      *zOut++ = 0x80 + (u8)(c & 0x3F);
99649    }else{
99650      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
99651      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
99652      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
99653      *zOut++ = 0x80 + (u8)(c & 0x3F);
99654    }                                                    \
99655  }
99656  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
99657}
99658
99659/*
99660** The hex() function.  Interpret the argument as a blob.  Return
99661** a hexadecimal rendering as text.
99662*/
99663static void hexFunc(
99664  sqlite3_context *context,
99665  int argc,
99666  sqlite3_value **argv
99667){
99668  int i, n;
99669  const unsigned char *pBlob;
99670  char *zHex, *z;
99671  assert( argc==1 );
99672  UNUSED_PARAMETER(argc);
99673  pBlob = sqlite3_value_blob(argv[0]);
99674  n = sqlite3_value_bytes(argv[0]);
99675  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
99676  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
99677  if( zHex ){
99678    for(i=0; i<n; i++, pBlob++){
99679      unsigned char c = *pBlob;
99680      *(z++) = hexdigits[(c>>4)&0xf];
99681      *(z++) = hexdigits[c&0xf];
99682    }
99683    *z = 0;
99684    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
99685  }
99686}
99687
99688/*
99689** The zeroblob(N) function returns a zero-filled blob of size N bytes.
99690*/
99691static void zeroblobFunc(
99692  sqlite3_context *context,
99693  int argc,
99694  sqlite3_value **argv
99695){
99696  i64 n;
99697  int rc;
99698  assert( argc==1 );
99699  UNUSED_PARAMETER(argc);
99700  n = sqlite3_value_int64(argv[0]);
99701  if( n<0 ) n = 0;
99702  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
99703  if( rc ){
99704    sqlite3_result_error_code(context, rc);
99705  }
99706}
99707
99708/*
99709** The replace() function.  Three arguments are all strings: call
99710** them A, B, and C. The result is also a string which is derived
99711** from A by replacing every occurrence of B with C.  The match
99712** must be exact.  Collating sequences are not used.
99713*/
99714static void replaceFunc(
99715  sqlite3_context *context,
99716  int argc,
99717  sqlite3_value **argv
99718){
99719  const unsigned char *zStr;        /* The input string A */
99720  const unsigned char *zPattern;    /* The pattern string B */
99721  const unsigned char *zRep;        /* The replacement string C */
99722  unsigned char *zOut;              /* The output */
99723  int nStr;                /* Size of zStr */
99724  int nPattern;            /* Size of zPattern */
99725  int nRep;                /* Size of zRep */
99726  i64 nOut;                /* Maximum size of zOut */
99727  int loopLimit;           /* Last zStr[] that might match zPattern[] */
99728  int i, j;                /* Loop counters */
99729
99730  assert( argc==3 );
99731  UNUSED_PARAMETER(argc);
99732  zStr = sqlite3_value_text(argv[0]);
99733  if( zStr==0 ) return;
99734  nStr = sqlite3_value_bytes(argv[0]);
99735  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
99736  zPattern = sqlite3_value_text(argv[1]);
99737  if( zPattern==0 ){
99738    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
99739            || sqlite3_context_db_handle(context)->mallocFailed );
99740    return;
99741  }
99742  if( zPattern[0]==0 ){
99743    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
99744    sqlite3_result_value(context, argv[0]);
99745    return;
99746  }
99747  nPattern = sqlite3_value_bytes(argv[1]);
99748  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
99749  zRep = sqlite3_value_text(argv[2]);
99750  if( zRep==0 ) return;
99751  nRep = sqlite3_value_bytes(argv[2]);
99752  assert( zRep==sqlite3_value_text(argv[2]) );
99753  nOut = nStr + 1;
99754  assert( nOut<SQLITE_MAX_LENGTH );
99755  zOut = contextMalloc(context, (i64)nOut);
99756  if( zOut==0 ){
99757    return;
99758  }
99759  loopLimit = nStr - nPattern;
99760  for(i=j=0; i<=loopLimit; i++){
99761    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
99762      zOut[j++] = zStr[i];
99763    }else{
99764      u8 *zOld;
99765      sqlite3 *db = sqlite3_context_db_handle(context);
99766      nOut += nRep - nPattern;
99767      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
99768      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
99769      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
99770        sqlite3_result_error_toobig(context);
99771        sqlite3_free(zOut);
99772        return;
99773      }
99774      zOld = zOut;
99775      zOut = sqlite3_realloc64(zOut, (int)nOut);
99776      if( zOut==0 ){
99777        sqlite3_result_error_nomem(context);
99778        sqlite3_free(zOld);
99779        return;
99780      }
99781      memcpy(&zOut[j], zRep, nRep);
99782      j += nRep;
99783      i += nPattern-1;
99784    }
99785  }
99786  assert( j+nStr-i+1==nOut );
99787  memcpy(&zOut[j], &zStr[i], nStr-i);
99788  j += nStr - i;
99789  assert( j<=nOut );
99790  zOut[j] = 0;
99791  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
99792}
99793
99794/*
99795** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
99796** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
99797*/
99798static void trimFunc(
99799  sqlite3_context *context,
99800  int argc,
99801  sqlite3_value **argv
99802){
99803  const unsigned char *zIn;         /* Input string */
99804  const unsigned char *zCharSet;    /* Set of characters to trim */
99805  int nIn;                          /* Number of bytes in input */
99806  int flags;                        /* 1: trimleft  2: trimright  3: trim */
99807  int i;                            /* Loop counter */
99808  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
99809  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
99810  int nChar;                        /* Number of characters in zCharSet */
99811
99812  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
99813    return;
99814  }
99815  zIn = sqlite3_value_text(argv[0]);
99816  if( zIn==0 ) return;
99817  nIn = sqlite3_value_bytes(argv[0]);
99818  assert( zIn==sqlite3_value_text(argv[0]) );
99819  if( argc==1 ){
99820    static const unsigned char lenOne[] = { 1 };
99821    static unsigned char * const azOne[] = { (u8*)" " };
99822    nChar = 1;
99823    aLen = (u8*)lenOne;
99824    azChar = (unsigned char **)azOne;
99825    zCharSet = 0;
99826  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
99827    return;
99828  }else{
99829    const unsigned char *z;
99830    for(z=zCharSet, nChar=0; *z; nChar++){
99831      SQLITE_SKIP_UTF8(z);
99832    }
99833    if( nChar>0 ){
99834      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
99835      if( azChar==0 ){
99836        return;
99837      }
99838      aLen = (unsigned char*)&azChar[nChar];
99839      for(z=zCharSet, nChar=0; *z; nChar++){
99840        azChar[nChar] = (unsigned char *)z;
99841        SQLITE_SKIP_UTF8(z);
99842        aLen[nChar] = (u8)(z - azChar[nChar]);
99843      }
99844    }
99845  }
99846  if( nChar>0 ){
99847    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
99848    if( flags & 1 ){
99849      while( nIn>0 ){
99850        int len = 0;
99851        for(i=0; i<nChar; i++){
99852          len = aLen[i];
99853          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
99854        }
99855        if( i>=nChar ) break;
99856        zIn += len;
99857        nIn -= len;
99858      }
99859    }
99860    if( flags & 2 ){
99861      while( nIn>0 ){
99862        int len = 0;
99863        for(i=0; i<nChar; i++){
99864          len = aLen[i];
99865          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
99866        }
99867        if( i>=nChar ) break;
99868        nIn -= len;
99869      }
99870    }
99871    if( zCharSet ){
99872      sqlite3_free(azChar);
99873    }
99874  }
99875  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
99876}
99877
99878
99879/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
99880** is only available if the SQLITE_SOUNDEX compile-time option is used
99881** when SQLite is built.
99882*/
99883#ifdef SQLITE_SOUNDEX
99884/*
99885** Compute the soundex encoding of a word.
99886**
99887** IMP: R-59782-00072 The soundex(X) function returns a string that is the
99888** soundex encoding of the string X.
99889*/
99890static void soundexFunc(
99891  sqlite3_context *context,
99892  int argc,
99893  sqlite3_value **argv
99894){
99895  char zResult[8];
99896  const u8 *zIn;
99897  int i, j;
99898  static const unsigned char iCode[] = {
99899    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99900    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99901    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99902    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99903    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
99904    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
99905    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
99906    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
99907  };
99908  assert( argc==1 );
99909  zIn = (u8*)sqlite3_value_text(argv[0]);
99910  if( zIn==0 ) zIn = (u8*)"";
99911  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
99912  if( zIn[i] ){
99913    u8 prevcode = iCode[zIn[i]&0x7f];
99914    zResult[0] = sqlite3Toupper(zIn[i]);
99915    for(j=1; j<4 && zIn[i]; i++){
99916      int code = iCode[zIn[i]&0x7f];
99917      if( code>0 ){
99918        if( code!=prevcode ){
99919          prevcode = code;
99920          zResult[j++] = code + '0';
99921        }
99922      }else{
99923        prevcode = 0;
99924      }
99925    }
99926    while( j<4 ){
99927      zResult[j++] = '0';
99928    }
99929    zResult[j] = 0;
99930    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
99931  }else{
99932    /* IMP: R-64894-50321 The string "?000" is returned if the argument
99933    ** is NULL or contains no ASCII alphabetic characters. */
99934    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
99935  }
99936}
99937#endif /* SQLITE_SOUNDEX */
99938
99939#ifndef SQLITE_OMIT_LOAD_EXTENSION
99940/*
99941** A function that loads a shared-library extension then returns NULL.
99942*/
99943static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
99944  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
99945  const char *zProc;
99946  sqlite3 *db = sqlite3_context_db_handle(context);
99947  char *zErrMsg = 0;
99948
99949  if( argc==2 ){
99950    zProc = (const char *)sqlite3_value_text(argv[1]);
99951  }else{
99952    zProc = 0;
99953  }
99954  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
99955    sqlite3_result_error(context, zErrMsg, -1);
99956    sqlite3_free(zErrMsg);
99957  }
99958}
99959#endif
99960
99961
99962/*
99963** An instance of the following structure holds the context of a
99964** sum() or avg() aggregate computation.
99965*/
99966typedef struct SumCtx SumCtx;
99967struct SumCtx {
99968  double rSum;      /* Floating point sum */
99969  i64 iSum;         /* Integer sum */
99970  i64 cnt;          /* Number of elements summed */
99971  u8 overflow;      /* True if integer overflow seen */
99972  u8 approx;        /* True if non-integer value was input to the sum */
99973};
99974
99975/*
99976** Routines used to compute the sum, average, and total.
99977**
99978** The SUM() function follows the (broken) SQL standard which means
99979** that it returns NULL if it sums over no inputs.  TOTAL returns
99980** 0.0 in that case.  In addition, TOTAL always returns a float where
99981** SUM might return an integer if it never encounters a floating point
99982** value.  TOTAL never fails, but SUM might through an exception if
99983** it overflows an integer.
99984*/
99985static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
99986  SumCtx *p;
99987  int type;
99988  assert( argc==1 );
99989  UNUSED_PARAMETER(argc);
99990  p = sqlite3_aggregate_context(context, sizeof(*p));
99991  type = sqlite3_value_numeric_type(argv[0]);
99992  if( p && type!=SQLITE_NULL ){
99993    p->cnt++;
99994    if( type==SQLITE_INTEGER ){
99995      i64 v = sqlite3_value_int64(argv[0]);
99996      p->rSum += v;
99997      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
99998        p->overflow = 1;
99999      }
100000    }else{
100001      p->rSum += sqlite3_value_double(argv[0]);
100002      p->approx = 1;
100003    }
100004  }
100005}
100006static void sumFinalize(sqlite3_context *context){
100007  SumCtx *p;
100008  p = sqlite3_aggregate_context(context, 0);
100009  if( p && p->cnt>0 ){
100010    if( p->overflow ){
100011      sqlite3_result_error(context,"integer overflow",-1);
100012    }else if( p->approx ){
100013      sqlite3_result_double(context, p->rSum);
100014    }else{
100015      sqlite3_result_int64(context, p->iSum);
100016    }
100017  }
100018}
100019static void avgFinalize(sqlite3_context *context){
100020  SumCtx *p;
100021  p = sqlite3_aggregate_context(context, 0);
100022  if( p && p->cnt>0 ){
100023    sqlite3_result_double(context, p->rSum/(double)p->cnt);
100024  }
100025}
100026static void totalFinalize(sqlite3_context *context){
100027  SumCtx *p;
100028  p = sqlite3_aggregate_context(context, 0);
100029  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
100030  sqlite3_result_double(context, p ? p->rSum : (double)0);
100031}
100032
100033/*
100034** The following structure keeps track of state information for the
100035** count() aggregate function.
100036*/
100037typedef struct CountCtx CountCtx;
100038struct CountCtx {
100039  i64 n;
100040};
100041
100042/*
100043** Routines to implement the count() aggregate function.
100044*/
100045static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
100046  CountCtx *p;
100047  p = sqlite3_aggregate_context(context, sizeof(*p));
100048  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
100049    p->n++;
100050  }
100051
100052#ifndef SQLITE_OMIT_DEPRECATED
100053  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
100054  ** sure it still operates correctly, verify that its count agrees with our
100055  ** internal count when using count(*) and when the total count can be
100056  ** expressed as a 32-bit integer. */
100057  assert( argc==1 || p==0 || p->n>0x7fffffff
100058          || p->n==sqlite3_aggregate_count(context) );
100059#endif
100060}
100061static void countFinalize(sqlite3_context *context){
100062  CountCtx *p;
100063  p = sqlite3_aggregate_context(context, 0);
100064  sqlite3_result_int64(context, p ? p->n : 0);
100065}
100066
100067/*
100068** Routines to implement min() and max() aggregate functions.
100069*/
100070static void minmaxStep(
100071  sqlite3_context *context,
100072  int NotUsed,
100073  sqlite3_value **argv
100074){
100075  Mem *pArg  = (Mem *)argv[0];
100076  Mem *pBest;
100077  UNUSED_PARAMETER(NotUsed);
100078
100079  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
100080  if( !pBest ) return;
100081
100082  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
100083    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
100084  }else if( pBest->flags ){
100085    int max;
100086    int cmp;
100087    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
100088    /* This step function is used for both the min() and max() aggregates,
100089    ** the only difference between the two being that the sense of the
100090    ** comparison is inverted. For the max() aggregate, the
100091    ** sqlite3_user_data() function returns (void *)-1. For min() it
100092    ** returns (void *)db, where db is the sqlite3* database pointer.
100093    ** Therefore the next statement sets variable 'max' to 1 for the max()
100094    ** aggregate, or 0 for min().
100095    */
100096    max = sqlite3_user_data(context)!=0;
100097    cmp = sqlite3MemCompare(pBest, pArg, pColl);
100098    if( (max && cmp<0) || (!max && cmp>0) ){
100099      sqlite3VdbeMemCopy(pBest, pArg);
100100    }else{
100101      sqlite3SkipAccumulatorLoad(context);
100102    }
100103  }else{
100104    pBest->db = sqlite3_context_db_handle(context);
100105    sqlite3VdbeMemCopy(pBest, pArg);
100106  }
100107}
100108static void minMaxFinalize(sqlite3_context *context){
100109  sqlite3_value *pRes;
100110  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
100111  if( pRes ){
100112    if( pRes->flags ){
100113      sqlite3_result_value(context, pRes);
100114    }
100115    sqlite3VdbeMemRelease(pRes);
100116  }
100117}
100118
100119/*
100120** group_concat(EXPR, ?SEPARATOR?)
100121*/
100122static void groupConcatStep(
100123  sqlite3_context *context,
100124  int argc,
100125  sqlite3_value **argv
100126){
100127  const char *zVal;
100128  StrAccum *pAccum;
100129  const char *zSep;
100130  int nVal, nSep;
100131  assert( argc==1 || argc==2 );
100132  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
100133  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
100134
100135  if( pAccum ){
100136    sqlite3 *db = sqlite3_context_db_handle(context);
100137    int firstTerm = pAccum->mxAlloc==0;
100138    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
100139    if( !firstTerm ){
100140      if( argc==2 ){
100141        zSep = (char*)sqlite3_value_text(argv[1]);
100142        nSep = sqlite3_value_bytes(argv[1]);
100143      }else{
100144        zSep = ",";
100145        nSep = 1;
100146      }
100147      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
100148    }
100149    zVal = (char*)sqlite3_value_text(argv[0]);
100150    nVal = sqlite3_value_bytes(argv[0]);
100151    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
100152  }
100153}
100154static void groupConcatFinalize(sqlite3_context *context){
100155  StrAccum *pAccum;
100156  pAccum = sqlite3_aggregate_context(context, 0);
100157  if( pAccum ){
100158    if( pAccum->accError==STRACCUM_TOOBIG ){
100159      sqlite3_result_error_toobig(context);
100160    }else if( pAccum->accError==STRACCUM_NOMEM ){
100161      sqlite3_result_error_nomem(context);
100162    }else{
100163      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
100164                          sqlite3_free);
100165    }
100166  }
100167}
100168
100169/*
100170** This routine does per-connection function registration.  Most
100171** of the built-in functions above are part of the global function set.
100172** This routine only deals with those that are not global.
100173*/
100174SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
100175  int rc = sqlite3_overload_function(db, "MATCH", 2);
100176  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
100177  if( rc==SQLITE_NOMEM ){
100178    db->mallocFailed = 1;
100179  }
100180}
100181
100182/*
100183** Set the LIKEOPT flag on the 2-argument function with the given name.
100184*/
100185static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
100186  FuncDef *pDef;
100187  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
100188                             2, SQLITE_UTF8, 0);
100189  if( ALWAYS(pDef) ){
100190    pDef->funcFlags |= flagVal;
100191  }
100192}
100193
100194/*
100195** Register the built-in LIKE and GLOB functions.  The caseSensitive
100196** parameter determines whether or not the LIKE operator is case
100197** sensitive.  GLOB is always case sensitive.
100198*/
100199SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
100200  struct compareInfo *pInfo;
100201  if( caseSensitive ){
100202    pInfo = (struct compareInfo*)&likeInfoAlt;
100203  }else{
100204    pInfo = (struct compareInfo*)&likeInfoNorm;
100205  }
100206  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
100207  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
100208  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
100209      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
100210  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
100211  setLikeOptFlag(db, "like",
100212      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
100213}
100214
100215/*
100216** pExpr points to an expression which implements a function.  If
100217** it is appropriate to apply the LIKE optimization to that function
100218** then set aWc[0] through aWc[2] to the wildcard characters and
100219** return TRUE.  If the function is not a LIKE-style function then
100220** return FALSE.
100221**
100222** *pIsNocase is set to true if uppercase and lowercase are equivalent for
100223** the function (default for LIKE).  If the function makes the distinction
100224** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
100225** false.
100226*/
100227SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
100228  FuncDef *pDef;
100229  if( pExpr->op!=TK_FUNCTION
100230   || !pExpr->x.pList
100231   || pExpr->x.pList->nExpr!=2
100232  ){
100233    return 0;
100234  }
100235  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
100236  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
100237                             sqlite3Strlen30(pExpr->u.zToken),
100238                             2, SQLITE_UTF8, 0);
100239  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
100240    return 0;
100241  }
100242
100243  /* The memcpy() statement assumes that the wildcard characters are
100244  ** the first three statements in the compareInfo structure.  The
100245  ** asserts() that follow verify that assumption
100246  */
100247  memcpy(aWc, pDef->pUserData, 3);
100248  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
100249  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
100250  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
100251  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
100252  return 1;
100253}
100254
100255/*
100256** All of the FuncDef structures in the aBuiltinFunc[] array above
100257** to the global function hash table.  This occurs at start-time (as
100258** a consequence of calling sqlite3_initialize()).
100259**
100260** After this routine runs
100261*/
100262SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
100263  /*
100264  ** The following array holds FuncDef structures for all of the functions
100265  ** defined in this file.
100266  **
100267  ** The array cannot be constant since changes are made to the
100268  ** FuncDef.pHash elements at start-time.  The elements of this array
100269  ** are read-only after initialization is complete.
100270  */
100271  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
100272    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
100273    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
100274    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
100275    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
100276    FUNCTION(trim,               1, 3, 0, trimFunc         ),
100277    FUNCTION(trim,               2, 3, 0, trimFunc         ),
100278    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
100279    FUNCTION(min,                0, 0, 1, 0                ),
100280    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
100281                                          SQLITE_FUNC_MINMAX ),
100282    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
100283    FUNCTION(max,                0, 1, 1, 0                ),
100284    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
100285                                          SQLITE_FUNC_MINMAX ),
100286    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
100287    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
100288    FUNCTION(instr,              2, 0, 0, instrFunc        ),
100289    FUNCTION(substr,             2, 0, 0, substrFunc       ),
100290    FUNCTION(substr,             3, 0, 0, substrFunc       ),
100291    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
100292    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
100293    FUNCTION(char,              -1, 0, 0, charFunc         ),
100294    FUNCTION(abs,                1, 0, 0, absFunc          ),
100295#ifndef SQLITE_OMIT_FLOATING_POINT
100296    FUNCTION(round,              1, 0, 0, roundFunc        ),
100297    FUNCTION(round,              2, 0, 0, roundFunc        ),
100298#endif
100299    FUNCTION(upper,              1, 0, 0, upperFunc        ),
100300    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
100301    FUNCTION(coalesce,           1, 0, 0, 0                ),
100302    FUNCTION(coalesce,           0, 0, 0, 0                ),
100303    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
100304    FUNCTION(hex,                1, 0, 0, hexFunc          ),
100305    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
100306    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100307    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100308    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100309    VFUNCTION(random,            0, 0, 0, randomFunc       ),
100310    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
100311    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
100312    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
100313    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
100314    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
100315#if SQLITE_USER_AUTHENTICATION
100316    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
100317#endif
100318#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
100319    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
100320    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
100321#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
100322    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
100323    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
100324    VFUNCTION(changes,           0, 0, 0, changes          ),
100325    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
100326    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
100327    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
100328  #ifdef SQLITE_SOUNDEX
100329    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
100330  #endif
100331  #ifndef SQLITE_OMIT_LOAD_EXTENSION
100332    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
100333    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
100334  #endif
100335    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
100336    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
100337    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
100338    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
100339               SQLITE_FUNC_COUNT  ),
100340    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
100341    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
100342    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
100343
100344    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100345  #ifdef SQLITE_CASE_SENSITIVE_LIKE
100346    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100347    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100348  #else
100349    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
100350    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
100351  #endif
100352  };
100353
100354  int i;
100355  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
100356  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
100357
100358  for(i=0; i<ArraySize(aBuiltinFunc); i++){
100359    sqlite3FuncDefInsert(pHash, &aFunc[i]);
100360  }
100361  sqlite3RegisterDateTimeFunctions();
100362#ifndef SQLITE_OMIT_ALTERTABLE
100363  sqlite3AlterFunctions();
100364#endif
100365#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
100366  sqlite3AnalyzeFunctions();
100367#endif
100368}
100369
100370/************** End of func.c ************************************************/
100371/************** Begin file fkey.c ********************************************/
100372/*
100373**
100374** The author disclaims copyright to this source code.  In place of
100375** a legal notice, here is a blessing:
100376**
100377**    May you do good and not evil.
100378**    May you find forgiveness for yourself and forgive others.
100379**    May you share freely, never taking more than you give.
100380**
100381*************************************************************************
100382** This file contains code used by the compiler to add foreign key
100383** support to compiled SQL statements.
100384*/
100385/* #include "sqliteInt.h" */
100386
100387#ifndef SQLITE_OMIT_FOREIGN_KEY
100388#ifndef SQLITE_OMIT_TRIGGER
100389
100390/*
100391** Deferred and Immediate FKs
100392** --------------------------
100393**
100394** Foreign keys in SQLite come in two flavours: deferred and immediate.
100395** If an immediate foreign key constraint is violated,
100396** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
100397** statement transaction rolled back. If a
100398** deferred foreign key constraint is violated, no action is taken
100399** immediately. However if the application attempts to commit the
100400** transaction before fixing the constraint violation, the attempt fails.
100401**
100402** Deferred constraints are implemented using a simple counter associated
100403** with the database handle. The counter is set to zero each time a
100404** database transaction is opened. Each time a statement is executed
100405** that causes a foreign key violation, the counter is incremented. Each
100406** time a statement is executed that removes an existing violation from
100407** the database, the counter is decremented. When the transaction is
100408** committed, the commit fails if the current value of the counter is
100409** greater than zero. This scheme has two big drawbacks:
100410**
100411**   * When a commit fails due to a deferred foreign key constraint,
100412**     there is no way to tell which foreign constraint is not satisfied,
100413**     or which row it is not satisfied for.
100414**
100415**   * If the database contains foreign key violations when the
100416**     transaction is opened, this may cause the mechanism to malfunction.
100417**
100418** Despite these problems, this approach is adopted as it seems simpler
100419** than the alternatives.
100420**
100421** INSERT operations:
100422**
100423**   I.1) For each FK for which the table is the child table, search
100424**        the parent table for a match. If none is found increment the
100425**        constraint counter.
100426**
100427**   I.2) For each FK for which the table is the parent table,
100428**        search the child table for rows that correspond to the new
100429**        row in the parent table. Decrement the counter for each row
100430**        found (as the constraint is now satisfied).
100431**
100432** DELETE operations:
100433**
100434**   D.1) For each FK for which the table is the child table,
100435**        search the parent table for a row that corresponds to the
100436**        deleted row in the child table. If such a row is not found,
100437**        decrement the counter.
100438**
100439**   D.2) For each FK for which the table is the parent table, search
100440**        the child table for rows that correspond to the deleted row
100441**        in the parent table. For each found increment the counter.
100442**
100443** UPDATE operations:
100444**
100445**   An UPDATE command requires that all 4 steps above are taken, but only
100446**   for FK constraints for which the affected columns are actually
100447**   modified (values must be compared at runtime).
100448**
100449** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
100450** This simplifies the implementation a bit.
100451**
100452** For the purposes of immediate FK constraints, the OR REPLACE conflict
100453** resolution is considered to delete rows before the new row is inserted.
100454** If a delete caused by OR REPLACE violates an FK constraint, an exception
100455** is thrown, even if the FK constraint would be satisfied after the new
100456** row is inserted.
100457**
100458** Immediate constraints are usually handled similarly. The only difference
100459** is that the counter used is stored as part of each individual statement
100460** object (struct Vdbe). If, after the statement has run, its immediate
100461** constraint counter is greater than zero,
100462** it returns SQLITE_CONSTRAINT_FOREIGNKEY
100463** and the statement transaction is rolled back. An exception is an INSERT
100464** statement that inserts a single row only (no triggers). In this case,
100465** instead of using a counter, an exception is thrown immediately if the
100466** INSERT violates a foreign key constraint. This is necessary as such
100467** an INSERT does not open a statement transaction.
100468**
100469** TODO: How should dropping a table be handled? How should renaming a
100470** table be handled?
100471**
100472**
100473** Query API Notes
100474** ---------------
100475**
100476** Before coding an UPDATE or DELETE row operation, the code-generator
100477** for those two operations needs to know whether or not the operation
100478** requires any FK processing and, if so, which columns of the original
100479** row are required by the FK processing VDBE code (i.e. if FKs were
100480** implemented using triggers, which of the old.* columns would be
100481** accessed). No information is required by the code-generator before
100482** coding an INSERT operation. The functions used by the UPDATE/DELETE
100483** generation code to query for this information are:
100484**
100485**   sqlite3FkRequired() - Test to see if FK processing is required.
100486**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
100487**
100488**
100489** Externally accessible module functions
100490** --------------------------------------
100491**
100492**   sqlite3FkCheck()    - Check for foreign key violations.
100493**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
100494**   sqlite3FkDelete()   - Delete an FKey structure.
100495*/
100496
100497/*
100498** VDBE Calling Convention
100499** -----------------------
100500**
100501** Example:
100502**
100503**   For the following INSERT statement:
100504**
100505**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
100506**     INSERT INTO t1 VALUES(1, 2, 3.1);
100507**
100508**   Register (x):        2    (type integer)
100509**   Register (x+1):      1    (type integer)
100510**   Register (x+2):      NULL (type NULL)
100511**   Register (x+3):      3.1  (type real)
100512*/
100513
100514/*
100515** A foreign key constraint requires that the key columns in the parent
100516** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
100517** Given that pParent is the parent table for foreign key constraint pFKey,
100518** search the schema for a unique index on the parent key columns.
100519**
100520** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
100521** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
100522** is set to point to the unique index.
100523**
100524** If the parent key consists of a single column (the foreign key constraint
100525** is not a composite foreign key), output variable *paiCol is set to NULL.
100526** Otherwise, it is set to point to an allocated array of size N, where
100527** N is the number of columns in the parent key. The first element of the
100528** array is the index of the child table column that is mapped by the FK
100529** constraint to the parent table column stored in the left-most column
100530** of index *ppIdx. The second element of the array is the index of the
100531** child table column that corresponds to the second left-most column of
100532** *ppIdx, and so on.
100533**
100534** If the required index cannot be found, either because:
100535**
100536**   1) The named parent key columns do not exist, or
100537**
100538**   2) The named parent key columns do exist, but are not subject to a
100539**      UNIQUE or PRIMARY KEY constraint, or
100540**
100541**   3) No parent key columns were provided explicitly as part of the
100542**      foreign key definition, and the parent table does not have a
100543**      PRIMARY KEY, or
100544**
100545**   4) No parent key columns were provided explicitly as part of the
100546**      foreign key definition, and the PRIMARY KEY of the parent table
100547**      consists of a different number of columns to the child key in
100548**      the child table.
100549**
100550** then non-zero is returned, and a "foreign key mismatch" error loaded
100551** into pParse. If an OOM error occurs, non-zero is returned and the
100552** pParse->db->mallocFailed flag is set.
100553*/
100554SQLITE_PRIVATE int sqlite3FkLocateIndex(
100555  Parse *pParse,                  /* Parse context to store any error in */
100556  Table *pParent,                 /* Parent table of FK constraint pFKey */
100557  FKey *pFKey,                    /* Foreign key to find index for */
100558  Index **ppIdx,                  /* OUT: Unique index on parent table */
100559  int **paiCol                    /* OUT: Map of index columns in pFKey */
100560){
100561  Index *pIdx = 0;                    /* Value to return via *ppIdx */
100562  int *aiCol = 0;                     /* Value to return via *paiCol */
100563  int nCol = pFKey->nCol;             /* Number of columns in parent key */
100564  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
100565
100566  /* The caller is responsible for zeroing output parameters. */
100567  assert( ppIdx && *ppIdx==0 );
100568  assert( !paiCol || *paiCol==0 );
100569  assert( pParse );
100570
100571  /* If this is a non-composite (single column) foreign key, check if it
100572  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
100573  ** and *paiCol set to zero and return early.
100574  **
100575  ** Otherwise, for a composite foreign key (more than one column), allocate
100576  ** space for the aiCol array (returned via output parameter *paiCol).
100577  ** Non-composite foreign keys do not require the aiCol array.
100578  */
100579  if( nCol==1 ){
100580    /* The FK maps to the IPK if any of the following are true:
100581    **
100582    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
100583    **      mapped to the primary key of table pParent, or
100584    **   2) The FK is explicitly mapped to a column declared as INTEGER
100585    **      PRIMARY KEY.
100586    */
100587    if( pParent->iPKey>=0 ){
100588      if( !zKey ) return 0;
100589      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
100590    }
100591  }else if( paiCol ){
100592    assert( nCol>1 );
100593    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
100594    if( !aiCol ) return 1;
100595    *paiCol = aiCol;
100596  }
100597
100598  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
100599    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
100600      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
100601      ** of columns. If each indexed column corresponds to a foreign key
100602      ** column of pFKey, then this index is a winner.  */
100603
100604      if( zKey==0 ){
100605        /* If zKey is NULL, then this foreign key is implicitly mapped to
100606        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
100607        ** identified by the test.  */
100608        if( IsPrimaryKeyIndex(pIdx) ){
100609          if( aiCol ){
100610            int i;
100611            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
100612          }
100613          break;
100614        }
100615      }else{
100616        /* If zKey is non-NULL, then this foreign key was declared to
100617        ** map to an explicit list of columns in table pParent. Check if this
100618        ** index matches those columns. Also, check that the index uses
100619        ** the default collation sequences for each column. */
100620        int i, j;
100621        for(i=0; i<nCol; i++){
100622          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
100623          char *zDfltColl;                  /* Def. collation for column */
100624          char *zIdxCol;                    /* Name of indexed column */
100625
100626          if( iCol<0 ) break; /* No foreign keys against expression indexes */
100627
100628          /* If the index uses a collation sequence that is different from
100629          ** the default collation sequence for the column, this index is
100630          ** unusable. Bail out early in this case.  */
100631          zDfltColl = pParent->aCol[iCol].zColl;
100632          if( !zDfltColl ){
100633            zDfltColl = "BINARY";
100634          }
100635          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
100636
100637          zIdxCol = pParent->aCol[iCol].zName;
100638          for(j=0; j<nCol; j++){
100639            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
100640              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
100641              break;
100642            }
100643          }
100644          if( j==nCol ) break;
100645        }
100646        if( i==nCol ) break;      /* pIdx is usable */
100647      }
100648    }
100649  }
100650
100651  if( !pIdx ){
100652    if( !pParse->disableTriggers ){
100653      sqlite3ErrorMsg(pParse,
100654           "foreign key mismatch - \"%w\" referencing \"%w\"",
100655           pFKey->pFrom->zName, pFKey->zTo);
100656    }
100657    sqlite3DbFree(pParse->db, aiCol);
100658    return 1;
100659  }
100660
100661  *ppIdx = pIdx;
100662  return 0;
100663}
100664
100665/*
100666** This function is called when a row is inserted into or deleted from the
100667** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
100668** on the child table of pFKey, this function is invoked twice for each row
100669** affected - once to "delete" the old row, and then again to "insert" the
100670** new row.
100671**
100672** Each time it is called, this function generates VDBE code to locate the
100673** row in the parent table that corresponds to the row being inserted into
100674** or deleted from the child table. If the parent row can be found, no
100675** special action is taken. Otherwise, if the parent row can *not* be
100676** found in the parent table:
100677**
100678**   Operation | FK type   | Action taken
100679**   --------------------------------------------------------------------------
100680**   INSERT      immediate   Increment the "immediate constraint counter".
100681**
100682**   DELETE      immediate   Decrement the "immediate constraint counter".
100683**
100684**   INSERT      deferred    Increment the "deferred constraint counter".
100685**
100686**   DELETE      deferred    Decrement the "deferred constraint counter".
100687**
100688** These operations are identified in the comment at the top of this file
100689** (fkey.c) as "I.1" and "D.1".
100690*/
100691static void fkLookupParent(
100692  Parse *pParse,        /* Parse context */
100693  int iDb,              /* Index of database housing pTab */
100694  Table *pTab,          /* Parent table of FK pFKey */
100695  Index *pIdx,          /* Unique index on parent key columns in pTab */
100696  FKey *pFKey,          /* Foreign key constraint */
100697  int *aiCol,           /* Map from parent key columns to child table columns */
100698  int regData,          /* Address of array containing child table row */
100699  int nIncr,            /* Increment constraint counter by this */
100700  int isIgnore          /* If true, pretend pTab contains all NULL values */
100701){
100702  int i;                                    /* Iterator variable */
100703  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
100704  int iCur = pParse->nTab - 1;              /* Cursor number to use */
100705  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
100706
100707  /* If nIncr is less than zero, then check at runtime if there are any
100708  ** outstanding constraints to resolve. If there are not, there is no need
100709  ** to check if deleting this row resolves any outstanding violations.
100710  **
100711  ** Check if any of the key columns in the child table row are NULL. If
100712  ** any are, then the constraint is considered satisfied. No need to
100713  ** search for a matching row in the parent table.  */
100714  if( nIncr<0 ){
100715    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
100716    VdbeCoverage(v);
100717  }
100718  for(i=0; i<pFKey->nCol; i++){
100719    int iReg = aiCol[i] + regData + 1;
100720    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
100721  }
100722
100723  if( isIgnore==0 ){
100724    if( pIdx==0 ){
100725      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
100726      ** column of the parent table (table pTab).  */
100727      int iMustBeInt;               /* Address of MustBeInt instruction */
100728      int regTemp = sqlite3GetTempReg(pParse);
100729
100730      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
100731      ** apply the affinity of the parent key). If this fails, then there
100732      ** is no matching parent key. Before using MustBeInt, make a copy of
100733      ** the value. Otherwise, the value inserted into the child key column
100734      ** will have INTEGER affinity applied to it, which may not be correct.  */
100735      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
100736      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
100737      VdbeCoverage(v);
100738
100739      /* If the parent table is the same as the child table, and we are about
100740      ** to increment the constraint-counter (i.e. this is an INSERT operation),
100741      ** then check if the row being inserted matches itself. If so, do not
100742      ** increment the constraint-counter.  */
100743      if( pTab==pFKey->pFrom && nIncr==1 ){
100744        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
100745        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100746      }
100747
100748      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
100749      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
100750      sqlite3VdbeGoto(v, iOk);
100751      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
100752      sqlite3VdbeJumpHere(v, iMustBeInt);
100753      sqlite3ReleaseTempReg(pParse, regTemp);
100754    }else{
100755      int nCol = pFKey->nCol;
100756      int regTemp = sqlite3GetTempRange(pParse, nCol);
100757      int regRec = sqlite3GetTempReg(pParse);
100758
100759      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
100760      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
100761      for(i=0; i<nCol; i++){
100762        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
100763      }
100764
100765      /* If the parent table is the same as the child table, and we are about
100766      ** to increment the constraint-counter (i.e. this is an INSERT operation),
100767      ** then check if the row being inserted matches itself. If so, do not
100768      ** increment the constraint-counter.
100769      **
100770      ** If any of the parent-key values are NULL, then the row cannot match
100771      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
100772      ** of the parent-key values are NULL (at this point it is known that
100773      ** none of the child key values are).
100774      */
100775      if( pTab==pFKey->pFrom && nIncr==1 ){
100776        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
100777        for(i=0; i<nCol; i++){
100778          int iChild = aiCol[i]+1+regData;
100779          int iParent = pIdx->aiColumn[i]+1+regData;
100780          assert( pIdx->aiColumn[i]>=0 );
100781          assert( aiCol[i]!=pTab->iPKey );
100782          if( pIdx->aiColumn[i]==pTab->iPKey ){
100783            /* The parent key is a composite key that includes the IPK column */
100784            iParent = regData;
100785          }
100786          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
100787          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
100788        }
100789        sqlite3VdbeGoto(v, iOk);
100790      }
100791
100792      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
100793                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
100794      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
100795
100796      sqlite3ReleaseTempReg(pParse, regRec);
100797      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
100798    }
100799  }
100800
100801  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
100802   && !pParse->pToplevel
100803   && !pParse->isMultiWrite
100804  ){
100805    /* Special case: If this is an INSERT statement that will insert exactly
100806    ** one row into the table, raise a constraint immediately instead of
100807    ** incrementing a counter. This is necessary as the VM code is being
100808    ** generated for will not open a statement transaction.  */
100809    assert( nIncr==1 );
100810    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
100811        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
100812  }else{
100813    if( nIncr>0 && pFKey->isDeferred==0 ){
100814      sqlite3MayAbort(pParse);
100815    }
100816    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
100817  }
100818
100819  sqlite3VdbeResolveLabel(v, iOk);
100820  sqlite3VdbeAddOp1(v, OP_Close, iCur);
100821}
100822
100823
100824/*
100825** Return an Expr object that refers to a memory register corresponding
100826** to column iCol of table pTab.
100827**
100828** regBase is the first of an array of register that contains the data
100829** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
100830** column.  regBase+2 holds the second column, and so forth.
100831*/
100832static Expr *exprTableRegister(
100833  Parse *pParse,     /* Parsing and code generating context */
100834  Table *pTab,       /* The table whose content is at r[regBase]... */
100835  int regBase,       /* Contents of table pTab */
100836  i16 iCol           /* Which column of pTab is desired */
100837){
100838  Expr *pExpr;
100839  Column *pCol;
100840  const char *zColl;
100841  sqlite3 *db = pParse->db;
100842
100843  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
100844  if( pExpr ){
100845    if( iCol>=0 && iCol!=pTab->iPKey ){
100846      pCol = &pTab->aCol[iCol];
100847      pExpr->iTable = regBase + iCol + 1;
100848      pExpr->affinity = pCol->affinity;
100849      zColl = pCol->zColl;
100850      if( zColl==0 ) zColl = db->pDfltColl->zName;
100851      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
100852    }else{
100853      pExpr->iTable = regBase;
100854      pExpr->affinity = SQLITE_AFF_INTEGER;
100855    }
100856  }
100857  return pExpr;
100858}
100859
100860/*
100861** Return an Expr object that refers to column iCol of table pTab which
100862** has cursor iCur.
100863*/
100864static Expr *exprTableColumn(
100865  sqlite3 *db,      /* The database connection */
100866  Table *pTab,      /* The table whose column is desired */
100867  int iCursor,      /* The open cursor on the table */
100868  i16 iCol          /* The column that is wanted */
100869){
100870  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
100871  if( pExpr ){
100872    pExpr->pTab = pTab;
100873    pExpr->iTable = iCursor;
100874    pExpr->iColumn = iCol;
100875  }
100876  return pExpr;
100877}
100878
100879/*
100880** This function is called to generate code executed when a row is deleted
100881** from the parent table of foreign key constraint pFKey and, if pFKey is
100882** deferred, when a row is inserted into the same table. When generating
100883** code for an SQL UPDATE operation, this function may be called twice -
100884** once to "delete" the old row and once to "insert" the new row.
100885**
100886** Parameter nIncr is passed -1 when inserting a row (as this may decrease
100887** the number of FK violations in the db) or +1 when deleting one (as this
100888** may increase the number of FK constraint problems).
100889**
100890** The code generated by this function scans through the rows in the child
100891** table that correspond to the parent table row being deleted or inserted.
100892** For each child row found, one of the following actions is taken:
100893**
100894**   Operation | FK type   | Action taken
100895**   --------------------------------------------------------------------------
100896**   DELETE      immediate   Increment the "immediate constraint counter".
100897**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
100898**                           throw a "FOREIGN KEY constraint failed" exception.
100899**
100900**   INSERT      immediate   Decrement the "immediate constraint counter".
100901**
100902**   DELETE      deferred    Increment the "deferred constraint counter".
100903**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
100904**                           throw a "FOREIGN KEY constraint failed" exception.
100905**
100906**   INSERT      deferred    Decrement the "deferred constraint counter".
100907**
100908** These operations are identified in the comment at the top of this file
100909** (fkey.c) as "I.2" and "D.2".
100910*/
100911static void fkScanChildren(
100912  Parse *pParse,                  /* Parse context */
100913  SrcList *pSrc,                  /* The child table to be scanned */
100914  Table *pTab,                    /* The parent table */
100915  Index *pIdx,                    /* Index on parent covering the foreign key */
100916  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
100917  int *aiCol,                     /* Map from pIdx cols to child table cols */
100918  int regData,                    /* Parent row data starts here */
100919  int nIncr                       /* Amount to increment deferred counter by */
100920){
100921  sqlite3 *db = pParse->db;       /* Database handle */
100922  int i;                          /* Iterator variable */
100923  Expr *pWhere = 0;               /* WHERE clause to scan with */
100924  NameContext sNameContext;       /* Context used to resolve WHERE clause */
100925  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
100926  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
100927  Vdbe *v = sqlite3GetVdbe(pParse);
100928
100929  assert( pIdx==0 || pIdx->pTable==pTab );
100930  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
100931  assert( pIdx!=0 || pFKey->nCol==1 );
100932  assert( pIdx!=0 || HasRowid(pTab) );
100933
100934  if( nIncr<0 ){
100935    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
100936    VdbeCoverage(v);
100937  }
100938
100939  /* Create an Expr object representing an SQL expression like:
100940  **
100941  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
100942  **
100943  ** The collation sequence used for the comparison should be that of
100944  ** the parent key columns. The affinity of the parent key column should
100945  ** be applied to each child key value before the comparison takes place.
100946  */
100947  for(i=0; i<pFKey->nCol; i++){
100948    Expr *pLeft;                  /* Value from parent table row */
100949    Expr *pRight;                 /* Column ref to child table */
100950    Expr *pEq;                    /* Expression (pLeft = pRight) */
100951    i16 iCol;                     /* Index of column in child table */
100952    const char *zCol;             /* Name of column in child table */
100953
100954    iCol = pIdx ? pIdx->aiColumn[i] : -1;
100955    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
100956    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
100957    assert( iCol>=0 );
100958    zCol = pFKey->pFrom->aCol[iCol].zName;
100959    pRight = sqlite3Expr(db, TK_ID, zCol);
100960    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
100961    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
100962  }
100963
100964  /* If the child table is the same as the parent table, then add terms
100965  ** to the WHERE clause that prevent this entry from being scanned.
100966  ** The added WHERE clause terms are like this:
100967  **
100968  **     $current_rowid!=rowid
100969  **     NOT( $current_a==a AND $current_b==b AND ... )
100970  **
100971  ** The first form is used for rowid tables.  The second form is used
100972  ** for WITHOUT ROWID tables.  In the second form, the primary key is
100973  ** (a,b,...)
100974  */
100975  if( pTab==pFKey->pFrom && nIncr>0 ){
100976    Expr *pNe;                    /* Expression (pLeft != pRight) */
100977    Expr *pLeft;                  /* Value from parent table row */
100978    Expr *pRight;                 /* Column ref to child table */
100979    if( HasRowid(pTab) ){
100980      pLeft = exprTableRegister(pParse, pTab, regData, -1);
100981      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
100982      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
100983    }else{
100984      Expr *pEq, *pAll = 0;
100985      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
100986      assert( pIdx!=0 );
100987      for(i=0; i<pPk->nKeyCol; i++){
100988        i16 iCol = pIdx->aiColumn[i];
100989        assert( iCol>=0 );
100990        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
100991        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
100992        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
100993        pAll = sqlite3ExprAnd(db, pAll, pEq);
100994      }
100995      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
100996    }
100997    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
100998  }
100999
101000  /* Resolve the references in the WHERE clause. */
101001  memset(&sNameContext, 0, sizeof(NameContext));
101002  sNameContext.pSrcList = pSrc;
101003  sNameContext.pParse = pParse;
101004  sqlite3ResolveExprNames(&sNameContext, pWhere);
101005
101006  /* Create VDBE to loop through the entries in pSrc that match the WHERE
101007  ** clause. For each row found, increment either the deferred or immediate
101008  ** foreign key constraint counter. */
101009  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
101010  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
101011  if( pWInfo ){
101012    sqlite3WhereEnd(pWInfo);
101013  }
101014
101015  /* Clean up the WHERE clause constructed above. */
101016  sqlite3ExprDelete(db, pWhere);
101017  if( iFkIfZero ){
101018    sqlite3VdbeJumpHere(v, iFkIfZero);
101019  }
101020}
101021
101022/*
101023** This function returns a linked list of FKey objects (connected by
101024** FKey.pNextTo) holding all children of table pTab.  For example,
101025** given the following schema:
101026**
101027**   CREATE TABLE t1(a PRIMARY KEY);
101028**   CREATE TABLE t2(b REFERENCES t1(a);
101029**
101030** Calling this function with table "t1" as an argument returns a pointer
101031** to the FKey structure representing the foreign key constraint on table
101032** "t2". Calling this function with "t2" as the argument would return a
101033** NULL pointer (as there are no FK constraints for which t2 is the parent
101034** table).
101035*/
101036SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
101037  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
101038}
101039
101040/*
101041** The second argument is a Trigger structure allocated by the
101042** fkActionTrigger() routine. This function deletes the Trigger structure
101043** and all of its sub-components.
101044**
101045** The Trigger structure or any of its sub-components may be allocated from
101046** the lookaside buffer belonging to database handle dbMem.
101047*/
101048static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
101049  if( p ){
101050    TriggerStep *pStep = p->step_list;
101051    sqlite3ExprDelete(dbMem, pStep->pWhere);
101052    sqlite3ExprListDelete(dbMem, pStep->pExprList);
101053    sqlite3SelectDelete(dbMem, pStep->pSelect);
101054    sqlite3ExprDelete(dbMem, p->pWhen);
101055    sqlite3DbFree(dbMem, p);
101056  }
101057}
101058
101059/*
101060** This function is called to generate code that runs when table pTab is
101061** being dropped from the database. The SrcList passed as the second argument
101062** to this function contains a single entry guaranteed to resolve to
101063** table pTab.
101064**
101065** Normally, no code is required. However, if either
101066**
101067**   (a) The table is the parent table of a FK constraint, or
101068**   (b) The table is the child table of a deferred FK constraint and it is
101069**       determined at runtime that there are outstanding deferred FK
101070**       constraint violations in the database,
101071**
101072** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
101073** the table from the database. Triggers are disabled while running this
101074** DELETE, but foreign key actions are not.
101075*/
101076SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
101077  sqlite3 *db = pParse->db;
101078  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
101079    int iSkip = 0;
101080    Vdbe *v = sqlite3GetVdbe(pParse);
101081
101082    assert( v );                  /* VDBE has already been allocated */
101083    if( sqlite3FkReferences(pTab)==0 ){
101084      /* Search for a deferred foreign key constraint for which this table
101085      ** is the child table. If one cannot be found, return without
101086      ** generating any VDBE code. If one can be found, then jump over
101087      ** the entire DELETE if there are no outstanding deferred constraints
101088      ** when this statement is run.  */
101089      FKey *p;
101090      for(p=pTab->pFKey; p; p=p->pNextFrom){
101091        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
101092      }
101093      if( !p ) return;
101094      iSkip = sqlite3VdbeMakeLabel(v);
101095      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
101096    }
101097
101098    pParse->disableTriggers = 1;
101099    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
101100    pParse->disableTriggers = 0;
101101
101102    /* If the DELETE has generated immediate foreign key constraint
101103    ** violations, halt the VDBE and return an error at this point, before
101104    ** any modifications to the schema are made. This is because statement
101105    ** transactions are not able to rollback schema changes.
101106    **
101107    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
101108    ** the statement transaction will not be rolled back even if FK
101109    ** constraints are violated.
101110    */
101111    if( (db->flags & SQLITE_DeferFKs)==0 ){
101112      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
101113      VdbeCoverage(v);
101114      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
101115          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
101116    }
101117
101118    if( iSkip ){
101119      sqlite3VdbeResolveLabel(v, iSkip);
101120    }
101121  }
101122}
101123
101124
101125/*
101126** The second argument points to an FKey object representing a foreign key
101127** for which pTab is the child table. An UPDATE statement against pTab
101128** is currently being processed. For each column of the table that is
101129** actually updated, the corresponding element in the aChange[] array
101130** is zero or greater (if a column is unmodified the corresponding element
101131** is set to -1). If the rowid column is modified by the UPDATE statement
101132** the bChngRowid argument is non-zero.
101133**
101134** This function returns true if any of the columns that are part of the
101135** child key for FK constraint *p are modified.
101136*/
101137static int fkChildIsModified(
101138  Table *pTab,                    /* Table being updated */
101139  FKey *p,                        /* Foreign key for which pTab is the child */
101140  int *aChange,                   /* Array indicating modified columns */
101141  int bChngRowid                  /* True if rowid is modified by this update */
101142){
101143  int i;
101144  for(i=0; i<p->nCol; i++){
101145    int iChildKey = p->aCol[i].iFrom;
101146    if( aChange[iChildKey]>=0 ) return 1;
101147    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
101148  }
101149  return 0;
101150}
101151
101152/*
101153** The second argument points to an FKey object representing a foreign key
101154** for which pTab is the parent table. An UPDATE statement against pTab
101155** is currently being processed. For each column of the table that is
101156** actually updated, the corresponding element in the aChange[] array
101157** is zero or greater (if a column is unmodified the corresponding element
101158** is set to -1). If the rowid column is modified by the UPDATE statement
101159** the bChngRowid argument is non-zero.
101160**
101161** This function returns true if any of the columns that are part of the
101162** parent key for FK constraint *p are modified.
101163*/
101164static int fkParentIsModified(
101165  Table *pTab,
101166  FKey *p,
101167  int *aChange,
101168  int bChngRowid
101169){
101170  int i;
101171  for(i=0; i<p->nCol; i++){
101172    char *zKey = p->aCol[i].zCol;
101173    int iKey;
101174    for(iKey=0; iKey<pTab->nCol; iKey++){
101175      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
101176        Column *pCol = &pTab->aCol[iKey];
101177        if( zKey ){
101178          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
101179        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
101180          return 1;
101181        }
101182      }
101183    }
101184  }
101185  return 0;
101186}
101187
101188/*
101189** Return true if the parser passed as the first argument is being
101190** used to code a trigger that is really a "SET NULL" action belonging
101191** to trigger pFKey.
101192*/
101193static int isSetNullAction(Parse *pParse, FKey *pFKey){
101194  Parse *pTop = sqlite3ParseToplevel(pParse);
101195  if( pTop->pTriggerPrg ){
101196    Trigger *p = pTop->pTriggerPrg->pTrigger;
101197    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
101198     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
101199    ){
101200      return 1;
101201    }
101202  }
101203  return 0;
101204}
101205
101206/*
101207** This function is called when inserting, deleting or updating a row of
101208** table pTab to generate VDBE code to perform foreign key constraint
101209** processing for the operation.
101210**
101211** For a DELETE operation, parameter regOld is passed the index of the
101212** first register in an array of (pTab->nCol+1) registers containing the
101213** rowid of the row being deleted, followed by each of the column values
101214** of the row being deleted, from left to right. Parameter regNew is passed
101215** zero in this case.
101216**
101217** For an INSERT operation, regOld is passed zero and regNew is passed the
101218** first register of an array of (pTab->nCol+1) registers containing the new
101219** row data.
101220**
101221** For an UPDATE operation, this function is called twice. Once before
101222** the original record is deleted from the table using the calling convention
101223** described for DELETE. Then again after the original record is deleted
101224** but before the new record is inserted using the INSERT convention.
101225*/
101226SQLITE_PRIVATE void sqlite3FkCheck(
101227  Parse *pParse,                  /* Parse context */
101228  Table *pTab,                    /* Row is being deleted from this table */
101229  int regOld,                     /* Previous row data is stored here */
101230  int regNew,                     /* New row data is stored here */
101231  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
101232  int bChngRowid                  /* True if rowid is UPDATEd */
101233){
101234  sqlite3 *db = pParse->db;       /* Database handle */
101235  FKey *pFKey;                    /* Used to iterate through FKs */
101236  int iDb;                        /* Index of database containing pTab */
101237  const char *zDb;                /* Name of database containing pTab */
101238  int isIgnoreErrors = pParse->disableTriggers;
101239
101240  /* Exactly one of regOld and regNew should be non-zero. */
101241  assert( (regOld==0)!=(regNew==0) );
101242
101243  /* If foreign-keys are disabled, this function is a no-op. */
101244  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
101245
101246  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101247  zDb = db->aDb[iDb].zName;
101248
101249  /* Loop through all the foreign key constraints for which pTab is the
101250  ** child table (the table that the foreign key definition is part of).  */
101251  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
101252    Table *pTo;                   /* Parent table of foreign key pFKey */
101253    Index *pIdx = 0;              /* Index on key columns in pTo */
101254    int *aiFree = 0;
101255    int *aiCol;
101256    int iCol;
101257    int i;
101258    int bIgnore = 0;
101259
101260    if( aChange
101261     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
101262     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
101263    ){
101264      continue;
101265    }
101266
101267    /* Find the parent table of this foreign key. Also find a unique index
101268    ** on the parent key columns in the parent table. If either of these
101269    ** schema items cannot be located, set an error in pParse and return
101270    ** early.  */
101271    if( pParse->disableTriggers ){
101272      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
101273    }else{
101274      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
101275    }
101276    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
101277      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
101278      if( !isIgnoreErrors || db->mallocFailed ) return;
101279      if( pTo==0 ){
101280        /* If isIgnoreErrors is true, then a table is being dropped. In this
101281        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
101282        ** before actually dropping it in order to check FK constraints.
101283        ** If the parent table of an FK constraint on the current table is
101284        ** missing, behave as if it is empty. i.e. decrement the relevant
101285        ** FK counter for each row of the current table with non-NULL keys.
101286        */
101287        Vdbe *v = sqlite3GetVdbe(pParse);
101288        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
101289        for(i=0; i<pFKey->nCol; i++){
101290          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
101291          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
101292        }
101293        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
101294      }
101295      continue;
101296    }
101297    assert( pFKey->nCol==1 || (aiFree && pIdx) );
101298
101299    if( aiFree ){
101300      aiCol = aiFree;
101301    }else{
101302      iCol = pFKey->aCol[0].iFrom;
101303      aiCol = &iCol;
101304    }
101305    for(i=0; i<pFKey->nCol; i++){
101306      if( aiCol[i]==pTab->iPKey ){
101307        aiCol[i] = -1;
101308      }
101309      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
101310#ifndef SQLITE_OMIT_AUTHORIZATION
101311      /* Request permission to read the parent key columns. If the
101312      ** authorization callback returns SQLITE_IGNORE, behave as if any
101313      ** values read from the parent table are NULL. */
101314      if( db->xAuth ){
101315        int rcauth;
101316        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
101317        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
101318        bIgnore = (rcauth==SQLITE_IGNORE);
101319      }
101320#endif
101321    }
101322
101323    /* Take a shared-cache advisory read-lock on the parent table. Allocate
101324    ** a cursor to use to search the unique index on the parent key columns
101325    ** in the parent table.  */
101326    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
101327    pParse->nTab++;
101328
101329    if( regOld!=0 ){
101330      /* A row is being removed from the child table. Search for the parent.
101331      ** If the parent does not exist, removing the child row resolves an
101332      ** outstanding foreign key constraint violation. */
101333      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
101334    }
101335    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
101336      /* A row is being added to the child table. If a parent row cannot
101337      ** be found, adding the child row has violated the FK constraint.
101338      **
101339      ** If this operation is being performed as part of a trigger program
101340      ** that is actually a "SET NULL" action belonging to this very
101341      ** foreign key, then omit this scan altogether. As all child key
101342      ** values are guaranteed to be NULL, it is not possible for adding
101343      ** this row to cause an FK violation.  */
101344      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
101345    }
101346
101347    sqlite3DbFree(db, aiFree);
101348  }
101349
101350  /* Loop through all the foreign key constraints that refer to this table.
101351  ** (the "child" constraints) */
101352  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
101353    Index *pIdx = 0;              /* Foreign key index for pFKey */
101354    SrcList *pSrc;
101355    int *aiCol = 0;
101356
101357    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
101358      continue;
101359    }
101360
101361    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
101362     && !pParse->pToplevel && !pParse->isMultiWrite
101363    ){
101364      assert( regOld==0 && regNew!=0 );
101365      /* Inserting a single row into a parent table cannot cause (or fix)
101366      ** an immediate foreign key violation. So do nothing in this case.  */
101367      continue;
101368    }
101369
101370    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
101371      if( !isIgnoreErrors || db->mallocFailed ) return;
101372      continue;
101373    }
101374    assert( aiCol || pFKey->nCol==1 );
101375
101376    /* Create a SrcList structure containing the child table.  We need the
101377    ** child table as a SrcList for sqlite3WhereBegin() */
101378    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
101379    if( pSrc ){
101380      struct SrcList_item *pItem = pSrc->a;
101381      pItem->pTab = pFKey->pFrom;
101382      pItem->zName = pFKey->pFrom->zName;
101383      pItem->pTab->nRef++;
101384      pItem->iCursor = pParse->nTab++;
101385
101386      if( regNew!=0 ){
101387        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
101388      }
101389      if( regOld!=0 ){
101390        int eAction = pFKey->aAction[aChange!=0];
101391        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
101392        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
101393        ** action applies, then any foreign key violations caused by
101394        ** removing the parent key will be rectified by the action trigger.
101395        ** So do not set the "may-abort" flag in this case.
101396        **
101397        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
101398        ** may-abort flag will eventually be set on this statement anyway
101399        ** (when this function is called as part of processing the UPDATE
101400        ** within the action trigger).
101401        **
101402        ** Note 2: At first glance it may seem like SQLite could simply omit
101403        ** all OP_FkCounter related scans when either CASCADE or SET NULL
101404        ** applies. The trouble starts if the CASCADE or SET NULL action
101405        ** trigger causes other triggers or action rules attached to the
101406        ** child table to fire. In these cases the fk constraint counters
101407        ** might be set incorrectly if any OP_FkCounter related scans are
101408        ** omitted.  */
101409        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
101410          sqlite3MayAbort(pParse);
101411        }
101412      }
101413      pItem->zName = 0;
101414      sqlite3SrcListDelete(db, pSrc);
101415    }
101416    sqlite3DbFree(db, aiCol);
101417  }
101418}
101419
101420#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
101421
101422/*
101423** This function is called before generating code to update or delete a
101424** row contained in table pTab.
101425*/
101426SQLITE_PRIVATE u32 sqlite3FkOldmask(
101427  Parse *pParse,                  /* Parse context */
101428  Table *pTab                     /* Table being modified */
101429){
101430  u32 mask = 0;
101431  if( pParse->db->flags&SQLITE_ForeignKeys ){
101432    FKey *p;
101433    int i;
101434    for(p=pTab->pFKey; p; p=p->pNextFrom){
101435      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
101436    }
101437    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
101438      Index *pIdx = 0;
101439      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
101440      if( pIdx ){
101441        for(i=0; i<pIdx->nKeyCol; i++){
101442          assert( pIdx->aiColumn[i]>=0 );
101443          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
101444        }
101445      }
101446    }
101447  }
101448  return mask;
101449}
101450
101451
101452/*
101453** This function is called before generating code to update or delete a
101454** row contained in table pTab. If the operation is a DELETE, then
101455** parameter aChange is passed a NULL value. For an UPDATE, aChange points
101456** to an array of size N, where N is the number of columns in table pTab.
101457** If the i'th column is not modified by the UPDATE, then the corresponding
101458** entry in the aChange[] array is set to -1. If the column is modified,
101459** the value is 0 or greater. Parameter chngRowid is set to true if the
101460** UPDATE statement modifies the rowid fields of the table.
101461**
101462** If any foreign key processing will be required, this function returns
101463** true. If there is no foreign key related processing, this function
101464** returns false.
101465*/
101466SQLITE_PRIVATE int sqlite3FkRequired(
101467  Parse *pParse,                  /* Parse context */
101468  Table *pTab,                    /* Table being modified */
101469  int *aChange,                   /* Non-NULL for UPDATE operations */
101470  int chngRowid                   /* True for UPDATE that affects rowid */
101471){
101472  if( pParse->db->flags&SQLITE_ForeignKeys ){
101473    if( !aChange ){
101474      /* A DELETE operation. Foreign key processing is required if the
101475      ** table in question is either the child or parent table for any
101476      ** foreign key constraint.  */
101477      return (sqlite3FkReferences(pTab) || pTab->pFKey);
101478    }else{
101479      /* This is an UPDATE. Foreign key processing is only required if the
101480      ** operation modifies one or more child or parent key columns. */
101481      FKey *p;
101482
101483      /* Check if any child key columns are being modified. */
101484      for(p=pTab->pFKey; p; p=p->pNextFrom){
101485        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
101486      }
101487
101488      /* Check if any parent key columns are being modified. */
101489      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
101490        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
101491      }
101492    }
101493  }
101494  return 0;
101495}
101496
101497/*
101498** This function is called when an UPDATE or DELETE operation is being
101499** compiled on table pTab, which is the parent table of foreign-key pFKey.
101500** If the current operation is an UPDATE, then the pChanges parameter is
101501** passed a pointer to the list of columns being modified. If it is a
101502** DELETE, pChanges is passed a NULL pointer.
101503**
101504** It returns a pointer to a Trigger structure containing a trigger
101505** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
101506** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
101507** returned (these actions require no special handling by the triggers
101508** sub-system, code for them is created by fkScanChildren()).
101509**
101510** For example, if pFKey is the foreign key and pTab is table "p" in
101511** the following schema:
101512**
101513**   CREATE TABLE p(pk PRIMARY KEY);
101514**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
101515**
101516** then the returned trigger structure is equivalent to:
101517**
101518**   CREATE TRIGGER ... DELETE ON p BEGIN
101519**     DELETE FROM c WHERE ck = old.pk;
101520**   END;
101521**
101522** The returned pointer is cached as part of the foreign key object. It
101523** is eventually freed along with the rest of the foreign key object by
101524** sqlite3FkDelete().
101525*/
101526static Trigger *fkActionTrigger(
101527  Parse *pParse,                  /* Parse context */
101528  Table *pTab,                    /* Table being updated or deleted from */
101529  FKey *pFKey,                    /* Foreign key to get action for */
101530  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
101531){
101532  sqlite3 *db = pParse->db;       /* Database handle */
101533  int action;                     /* One of OE_None, OE_Cascade etc. */
101534  Trigger *pTrigger;              /* Trigger definition to return */
101535  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
101536
101537  action = pFKey->aAction[iAction];
101538  pTrigger = pFKey->apTrigger[iAction];
101539
101540  if( action!=OE_None && !pTrigger ){
101541    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
101542    char const *zFrom;            /* Name of child table */
101543    int nFrom;                    /* Length in bytes of zFrom */
101544    Index *pIdx = 0;              /* Parent key index for this FK */
101545    int *aiCol = 0;               /* child table cols -> parent key cols */
101546    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
101547    Expr *pWhere = 0;             /* WHERE clause of trigger step */
101548    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
101549    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
101550    int i;                        /* Iterator variable */
101551    Expr *pWhen = 0;              /* WHEN clause for the trigger */
101552
101553    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
101554    assert( aiCol || pFKey->nCol==1 );
101555
101556    for(i=0; i<pFKey->nCol; i++){
101557      Token tOld = { "old", 3 };  /* Literal "old" token */
101558      Token tNew = { "new", 3 };  /* Literal "new" token */
101559      Token tFromCol;             /* Name of column in child table */
101560      Token tToCol;               /* Name of column in parent table */
101561      int iFromCol;               /* Idx of column in child table */
101562      Expr *pEq;                  /* tFromCol = OLD.tToCol */
101563
101564      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
101565      assert( iFromCol>=0 );
101566      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
101567      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
101568      tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
101569      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
101570
101571      tToCol.n = sqlite3Strlen30(tToCol.z);
101572      tFromCol.n = sqlite3Strlen30(tFromCol.z);
101573
101574      /* Create the expression "OLD.zToCol = zFromCol". It is important
101575      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
101576      ** that the affinity and collation sequence associated with the
101577      ** parent table are used for the comparison. */
101578      pEq = sqlite3PExpr(pParse, TK_EQ,
101579          sqlite3PExpr(pParse, TK_DOT,
101580            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
101581            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
101582          , 0),
101583          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
101584      , 0);
101585      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
101586
101587      /* For ON UPDATE, construct the next term of the WHEN clause.
101588      ** The final WHEN clause will be like this:
101589      **
101590      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
101591      */
101592      if( pChanges ){
101593        pEq = sqlite3PExpr(pParse, TK_IS,
101594            sqlite3PExpr(pParse, TK_DOT,
101595              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
101596              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
101597              0),
101598            sqlite3PExpr(pParse, TK_DOT,
101599              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
101600              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
101601              0),
101602            0);
101603        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
101604      }
101605
101606      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
101607        Expr *pNew;
101608        if( action==OE_Cascade ){
101609          pNew = sqlite3PExpr(pParse, TK_DOT,
101610            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
101611            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
101612          , 0);
101613        }else if( action==OE_SetDflt ){
101614          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
101615          if( pDflt ){
101616            pNew = sqlite3ExprDup(db, pDflt, 0);
101617          }else{
101618            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
101619          }
101620        }else{
101621          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
101622        }
101623        pList = sqlite3ExprListAppend(pParse, pList, pNew);
101624        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
101625      }
101626    }
101627    sqlite3DbFree(db, aiCol);
101628
101629    zFrom = pFKey->pFrom->zName;
101630    nFrom = sqlite3Strlen30(zFrom);
101631
101632    if( action==OE_Restrict ){
101633      Token tFrom;
101634      Expr *pRaise;
101635
101636      tFrom.z = zFrom;
101637      tFrom.n = nFrom;
101638      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
101639      if( pRaise ){
101640        pRaise->affinity = OE_Abort;
101641      }
101642      pSelect = sqlite3SelectNew(pParse,
101643          sqlite3ExprListAppend(pParse, 0, pRaise),
101644          sqlite3SrcListAppend(db, 0, &tFrom, 0),
101645          pWhere,
101646          0, 0, 0, 0, 0, 0
101647      );
101648      pWhere = 0;
101649    }
101650
101651    /* Disable lookaside memory allocation */
101652    enableLookaside = db->lookaside.bEnabled;
101653    db->lookaside.bEnabled = 0;
101654
101655    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
101656        sizeof(Trigger) +         /* struct Trigger */
101657        sizeof(TriggerStep) +     /* Single step in trigger program */
101658        nFrom + 1                 /* Space for pStep->zTarget */
101659    );
101660    if( pTrigger ){
101661      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
101662      pStep->zTarget = (char *)&pStep[1];
101663      memcpy((char *)pStep->zTarget, zFrom, nFrom);
101664
101665      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101666      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
101667      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101668      if( pWhen ){
101669        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
101670        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101671      }
101672    }
101673
101674    /* Re-enable the lookaside buffer, if it was disabled earlier. */
101675    db->lookaside.bEnabled = enableLookaside;
101676
101677    sqlite3ExprDelete(db, pWhere);
101678    sqlite3ExprDelete(db, pWhen);
101679    sqlite3ExprListDelete(db, pList);
101680    sqlite3SelectDelete(db, pSelect);
101681    if( db->mallocFailed==1 ){
101682      fkTriggerDelete(db, pTrigger);
101683      return 0;
101684    }
101685    assert( pStep!=0 );
101686
101687    switch( action ){
101688      case OE_Restrict:
101689        pStep->op = TK_SELECT;
101690        break;
101691      case OE_Cascade:
101692        if( !pChanges ){
101693          pStep->op = TK_DELETE;
101694          break;
101695        }
101696      default:
101697        pStep->op = TK_UPDATE;
101698    }
101699    pStep->pTrig = pTrigger;
101700    pTrigger->pSchema = pTab->pSchema;
101701    pTrigger->pTabSchema = pTab->pSchema;
101702    pFKey->apTrigger[iAction] = pTrigger;
101703    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
101704  }
101705
101706  return pTrigger;
101707}
101708
101709/*
101710** This function is called when deleting or updating a row to implement
101711** any required CASCADE, SET NULL or SET DEFAULT actions.
101712*/
101713SQLITE_PRIVATE void sqlite3FkActions(
101714  Parse *pParse,                  /* Parse context */
101715  Table *pTab,                    /* Table being updated or deleted from */
101716  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
101717  int regOld,                     /* Address of array containing old row */
101718  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
101719  int bChngRowid                  /* True if rowid is UPDATEd */
101720){
101721  /* If foreign-key support is enabled, iterate through all FKs that
101722  ** refer to table pTab. If there is an action associated with the FK
101723  ** for this operation (either update or delete), invoke the associated
101724  ** trigger sub-program.  */
101725  if( pParse->db->flags&SQLITE_ForeignKeys ){
101726    FKey *pFKey;                  /* Iterator variable */
101727    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
101728      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
101729        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
101730        if( pAct ){
101731          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
101732        }
101733      }
101734    }
101735  }
101736}
101737
101738#endif /* ifndef SQLITE_OMIT_TRIGGER */
101739
101740/*
101741** Free all memory associated with foreign key definitions attached to
101742** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
101743** hash table.
101744*/
101745SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
101746  FKey *pFKey;                    /* Iterator variable */
101747  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
101748
101749  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
101750  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
101751
101752    /* Remove the FK from the fkeyHash hash table. */
101753    if( !db || db->pnBytesFreed==0 ){
101754      if( pFKey->pPrevTo ){
101755        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
101756      }else{
101757        void *p = (void *)pFKey->pNextTo;
101758        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
101759        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
101760      }
101761      if( pFKey->pNextTo ){
101762        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
101763      }
101764    }
101765
101766    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
101767    ** classified as either immediate or deferred.
101768    */
101769    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
101770
101771    /* Delete any triggers created to implement actions for this FK. */
101772#ifndef SQLITE_OMIT_TRIGGER
101773    fkTriggerDelete(db, pFKey->apTrigger[0]);
101774    fkTriggerDelete(db, pFKey->apTrigger[1]);
101775#endif
101776
101777    pNext = pFKey->pNextFrom;
101778    sqlite3DbFree(db, pFKey);
101779  }
101780}
101781#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
101782
101783/************** End of fkey.c ************************************************/
101784/************** Begin file insert.c ******************************************/
101785/*
101786** 2001 September 15
101787**
101788** The author disclaims copyright to this source code.  In place of
101789** a legal notice, here is a blessing:
101790**
101791**    May you do good and not evil.
101792**    May you find forgiveness for yourself and forgive others.
101793**    May you share freely, never taking more than you give.
101794**
101795*************************************************************************
101796** This file contains C code routines that are called by the parser
101797** to handle INSERT statements in SQLite.
101798*/
101799/* #include "sqliteInt.h" */
101800
101801/*
101802** Generate code that will
101803**
101804**   (1) acquire a lock for table pTab then
101805**   (2) open pTab as cursor iCur.
101806**
101807** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
101808** for that table that is actually opened.
101809*/
101810SQLITE_PRIVATE void sqlite3OpenTable(
101811  Parse *pParse,  /* Generate code into this VDBE */
101812  int iCur,       /* The cursor number of the table */
101813  int iDb,        /* The database index in sqlite3.aDb[] */
101814  Table *pTab,    /* The table to be opened */
101815  int opcode      /* OP_OpenRead or OP_OpenWrite */
101816){
101817  Vdbe *v;
101818  assert( !IsVirtual(pTab) );
101819  v = sqlite3GetVdbe(pParse);
101820  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
101821  sqlite3TableLock(pParse, iDb, pTab->tnum,
101822                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
101823  if( HasRowid(pTab) ){
101824    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
101825    VdbeComment((v, "%s", pTab->zName));
101826  }else{
101827    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
101828    assert( pPk!=0 );
101829    assert( pPk->tnum==pTab->tnum );
101830    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
101831    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
101832    VdbeComment((v, "%s", pTab->zName));
101833  }
101834}
101835
101836/*
101837** Return a pointer to the column affinity string associated with index
101838** pIdx. A column affinity string has one character for each column in
101839** the table, according to the affinity of the column:
101840**
101841**  Character      Column affinity
101842**  ------------------------------
101843**  'A'            BLOB
101844**  'B'            TEXT
101845**  'C'            NUMERIC
101846**  'D'            INTEGER
101847**  'F'            REAL
101848**
101849** An extra 'D' is appended to the end of the string to cover the
101850** rowid that appears as the last column in every index.
101851**
101852** Memory for the buffer containing the column index affinity string
101853** is managed along with the rest of the Index structure. It will be
101854** released when sqlite3DeleteIndex() is called.
101855*/
101856SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
101857  if( !pIdx->zColAff ){
101858    /* The first time a column affinity string for a particular index is
101859    ** required, it is allocated and populated here. It is then stored as
101860    ** a member of the Index structure for subsequent use.
101861    **
101862    ** The column affinity string will eventually be deleted by
101863    ** sqliteDeleteIndex() when the Index structure itself is cleaned
101864    ** up.
101865    */
101866    int n;
101867    Table *pTab = pIdx->pTable;
101868    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
101869    if( !pIdx->zColAff ){
101870      db->mallocFailed = 1;
101871      return 0;
101872    }
101873    for(n=0; n<pIdx->nColumn; n++){
101874      i16 x = pIdx->aiColumn[n];
101875      if( x>=0 ){
101876        pIdx->zColAff[n] = pTab->aCol[x].affinity;
101877      }else if( x==XN_ROWID ){
101878        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
101879      }else{
101880        char aff;
101881        assert( x==XN_EXPR );
101882        assert( pIdx->aColExpr!=0 );
101883        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
101884        if( aff==0 ) aff = SQLITE_AFF_BLOB;
101885        pIdx->zColAff[n] = aff;
101886      }
101887    }
101888    pIdx->zColAff[n] = 0;
101889  }
101890
101891  return pIdx->zColAff;
101892}
101893
101894/*
101895** Compute the affinity string for table pTab, if it has not already been
101896** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
101897**
101898** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
101899** if iReg>0 then code an OP_Affinity opcode that will set the affinities
101900** for register iReg and following.  Or if affinities exists and iReg==0,
101901** then just set the P4 operand of the previous opcode (which should  be
101902** an OP_MakeRecord) to the affinity string.
101903**
101904** A column affinity string has one character per column:
101905**
101906**  Character      Column affinity
101907**  ------------------------------
101908**  'A'            BLOB
101909**  'B'            TEXT
101910**  'C'            NUMERIC
101911**  'D'            INTEGER
101912**  'E'            REAL
101913*/
101914SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
101915  int i;
101916  char *zColAff = pTab->zColAff;
101917  if( zColAff==0 ){
101918    sqlite3 *db = sqlite3VdbeDb(v);
101919    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
101920    if( !zColAff ){
101921      db->mallocFailed = 1;
101922      return;
101923    }
101924
101925    for(i=0; i<pTab->nCol; i++){
101926      zColAff[i] = pTab->aCol[i].affinity;
101927    }
101928    do{
101929      zColAff[i--] = 0;
101930    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
101931    pTab->zColAff = zColAff;
101932  }
101933  i = sqlite3Strlen30(zColAff);
101934  if( i ){
101935    if( iReg ){
101936      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
101937    }else{
101938      sqlite3VdbeChangeP4(v, -1, zColAff, i);
101939    }
101940  }
101941}
101942
101943/*
101944** Return non-zero if the table pTab in database iDb or any of its indices
101945** have been opened at any point in the VDBE program. This is used to see if
101946** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
101947** run without using a temporary table for the results of the SELECT.
101948*/
101949static int readsTable(Parse *p, int iDb, Table *pTab){
101950  Vdbe *v = sqlite3GetVdbe(p);
101951  int i;
101952  int iEnd = sqlite3VdbeCurrentAddr(v);
101953#ifndef SQLITE_OMIT_VIRTUALTABLE
101954  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
101955#endif
101956
101957  for(i=1; i<iEnd; i++){
101958    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
101959    assert( pOp!=0 );
101960    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
101961      Index *pIndex;
101962      int tnum = pOp->p2;
101963      if( tnum==pTab->tnum ){
101964        return 1;
101965      }
101966      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
101967        if( tnum==pIndex->tnum ){
101968          return 1;
101969        }
101970      }
101971    }
101972#ifndef SQLITE_OMIT_VIRTUALTABLE
101973    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
101974      assert( pOp->p4.pVtab!=0 );
101975      assert( pOp->p4type==P4_VTAB );
101976      return 1;
101977    }
101978#endif
101979  }
101980  return 0;
101981}
101982
101983#ifndef SQLITE_OMIT_AUTOINCREMENT
101984/*
101985** Locate or create an AutoincInfo structure associated with table pTab
101986** which is in database iDb.  Return the register number for the register
101987** that holds the maximum rowid.
101988**
101989** There is at most one AutoincInfo structure per table even if the
101990** same table is autoincremented multiple times due to inserts within
101991** triggers.  A new AutoincInfo structure is created if this is the
101992** first use of table pTab.  On 2nd and subsequent uses, the original
101993** AutoincInfo structure is used.
101994**
101995** Three memory locations are allocated:
101996**
101997**   (1)  Register to hold the name of the pTab table.
101998**   (2)  Register to hold the maximum ROWID of pTab.
101999**   (3)  Register to hold the rowid in sqlite_sequence of pTab
102000**
102001** The 2nd register is the one that is returned.  That is all the
102002** insert routine needs to know about.
102003*/
102004static int autoIncBegin(
102005  Parse *pParse,      /* Parsing context */
102006  int iDb,            /* Index of the database holding pTab */
102007  Table *pTab         /* The table we are writing to */
102008){
102009  int memId = 0;      /* Register holding maximum rowid */
102010  if( pTab->tabFlags & TF_Autoincrement ){
102011    Parse *pToplevel = sqlite3ParseToplevel(pParse);
102012    AutoincInfo *pInfo;
102013
102014    pInfo = pToplevel->pAinc;
102015    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
102016    if( pInfo==0 ){
102017      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
102018      if( pInfo==0 ) return 0;
102019      pInfo->pNext = pToplevel->pAinc;
102020      pToplevel->pAinc = pInfo;
102021      pInfo->pTab = pTab;
102022      pInfo->iDb = iDb;
102023      pToplevel->nMem++;                  /* Register to hold name of table */
102024      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
102025      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
102026    }
102027    memId = pInfo->regCtr;
102028  }
102029  return memId;
102030}
102031
102032/*
102033** This routine generates code that will initialize all of the
102034** register used by the autoincrement tracker.
102035*/
102036SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
102037  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
102038  sqlite3 *db = pParse->db;  /* The database connection */
102039  Db *pDb;                   /* Database only autoinc table */
102040  int memId;                 /* Register holding max rowid */
102041  int addr;                  /* A VDBE address */
102042  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
102043
102044  /* This routine is never called during trigger-generation.  It is
102045  ** only called from the top-level */
102046  assert( pParse->pTriggerTab==0 );
102047  assert( sqlite3IsToplevel(pParse) );
102048
102049  assert( v );   /* We failed long ago if this is not so */
102050  for(p = pParse->pAinc; p; p = p->pNext){
102051    pDb = &db->aDb[p->iDb];
102052    memId = p->regCtr;
102053    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
102054    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
102055    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
102056    addr = sqlite3VdbeCurrentAddr(v);
102057    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
102058    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
102059    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
102060    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
102061    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
102062    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
102063    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
102064    sqlite3VdbeGoto(v, addr+9);
102065    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
102066    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
102067    sqlite3VdbeAddOp0(v, OP_Close);
102068  }
102069}
102070
102071/*
102072** Update the maximum rowid for an autoincrement calculation.
102073**
102074** This routine should be called when the top of the stack holds a
102075** new rowid that is about to be inserted.  If that new rowid is
102076** larger than the maximum rowid in the memId memory cell, then the
102077** memory cell is updated.  The stack is unchanged.
102078*/
102079static void autoIncStep(Parse *pParse, int memId, int regRowid){
102080  if( memId>0 ){
102081    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
102082  }
102083}
102084
102085/*
102086** This routine generates the code needed to write autoincrement
102087** maximum rowid values back into the sqlite_sequence register.
102088** Every statement that might do an INSERT into an autoincrement
102089** table (either directly or through triggers) needs to call this
102090** routine just before the "exit" code.
102091*/
102092SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
102093  AutoincInfo *p;
102094  Vdbe *v = pParse->pVdbe;
102095  sqlite3 *db = pParse->db;
102096
102097  assert( v );
102098  for(p = pParse->pAinc; p; p = p->pNext){
102099    Db *pDb = &db->aDb[p->iDb];
102100    int addr1;
102101    int iRec;
102102    int memId = p->regCtr;
102103
102104    iRec = sqlite3GetTempReg(pParse);
102105    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
102106    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
102107    addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
102108    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
102109    sqlite3VdbeJumpHere(v, addr1);
102110    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
102111    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
102112    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
102113    sqlite3VdbeAddOp0(v, OP_Close);
102114    sqlite3ReleaseTempReg(pParse, iRec);
102115  }
102116}
102117#else
102118/*
102119** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
102120** above are all no-ops
102121*/
102122# define autoIncBegin(A,B,C) (0)
102123# define autoIncStep(A,B,C)
102124#endif /* SQLITE_OMIT_AUTOINCREMENT */
102125
102126
102127/* Forward declaration */
102128static int xferOptimization(
102129  Parse *pParse,        /* Parser context */
102130  Table *pDest,         /* The table we are inserting into */
102131  Select *pSelect,      /* A SELECT statement to use as the data source */
102132  int onError,          /* How to handle constraint errors */
102133  int iDbDest           /* The database of pDest */
102134);
102135
102136/*
102137** This routine is called to handle SQL of the following forms:
102138**
102139**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
102140**    insert into TABLE (IDLIST) select
102141**    insert into TABLE (IDLIST) default values
102142**
102143** The IDLIST following the table name is always optional.  If omitted,
102144** then a list of all (non-hidden) columns for the table is substituted.
102145** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
102146** is omitted.
102147**
102148** For the pSelect parameter holds the values to be inserted for the
102149** first two forms shown above.  A VALUES clause is really just short-hand
102150** for a SELECT statement that omits the FROM clause and everything else
102151** that follows.  If the pSelect parameter is NULL, that means that the
102152** DEFAULT VALUES form of the INSERT statement is intended.
102153**
102154** The code generated follows one of four templates.  For a simple
102155** insert with data coming from a single-row VALUES clause, the code executes
102156** once straight down through.  Pseudo-code follows (we call this
102157** the "1st template"):
102158**
102159**         open write cursor to <table> and its indices
102160**         put VALUES clause expressions into registers
102161**         write the resulting record into <table>
102162**         cleanup
102163**
102164** The three remaining templates assume the statement is of the form
102165**
102166**   INSERT INTO <table> SELECT ...
102167**
102168** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
102169** in other words if the SELECT pulls all columns from a single table
102170** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
102171** if <table2> and <table1> are distinct tables but have identical
102172** schemas, including all the same indices, then a special optimization
102173** is invoked that copies raw records from <table2> over to <table1>.
102174** See the xferOptimization() function for the implementation of this
102175** template.  This is the 2nd template.
102176**
102177**         open a write cursor to <table>
102178**         open read cursor on <table2>
102179**         transfer all records in <table2> over to <table>
102180**         close cursors
102181**         foreach index on <table>
102182**           open a write cursor on the <table> index
102183**           open a read cursor on the corresponding <table2> index
102184**           transfer all records from the read to the write cursors
102185**           close cursors
102186**         end foreach
102187**
102188** The 3rd template is for when the second template does not apply
102189** and the SELECT clause does not read from <table> at any time.
102190** The generated code follows this template:
102191**
102192**         X <- A
102193**         goto B
102194**      A: setup for the SELECT
102195**         loop over the rows in the SELECT
102196**           load values into registers R..R+n
102197**           yield X
102198**         end loop
102199**         cleanup after the SELECT
102200**         end-coroutine X
102201**      B: open write cursor to <table> and its indices
102202**      C: yield X, at EOF goto D
102203**         insert the select result into <table> from R..R+n
102204**         goto C
102205**      D: cleanup
102206**
102207** The 4th template is used if the insert statement takes its
102208** values from a SELECT but the data is being inserted into a table
102209** that is also read as part of the SELECT.  In the third form,
102210** we have to use an intermediate table to store the results of
102211** the select.  The template is like this:
102212**
102213**         X <- A
102214**         goto B
102215**      A: setup for the SELECT
102216**         loop over the tables in the SELECT
102217**           load value into register R..R+n
102218**           yield X
102219**         end loop
102220**         cleanup after the SELECT
102221**         end co-routine R
102222**      B: open temp table
102223**      L: yield X, at EOF goto M
102224**         insert row from R..R+n into temp table
102225**         goto L
102226**      M: open write cursor to <table> and its indices
102227**         rewind temp table
102228**      C: loop over rows of intermediate table
102229**           transfer values form intermediate table into <table>
102230**         end loop
102231**      D: cleanup
102232*/
102233SQLITE_PRIVATE void sqlite3Insert(
102234  Parse *pParse,        /* Parser context */
102235  SrcList *pTabList,    /* Name of table into which we are inserting */
102236  Select *pSelect,      /* A SELECT statement to use as the data source */
102237  IdList *pColumn,      /* Column names corresponding to IDLIST. */
102238  int onError           /* How to handle constraint errors */
102239){
102240  sqlite3 *db;          /* The main database structure */
102241  Table *pTab;          /* The table to insert into.  aka TABLE */
102242  char *zTab;           /* Name of the table into which we are inserting */
102243  const char *zDb;      /* Name of the database holding this table */
102244  int i, j, idx;        /* Loop counters */
102245  Vdbe *v;              /* Generate code into this virtual machine */
102246  Index *pIdx;          /* For looping over indices of the table */
102247  int nColumn;          /* Number of columns in the data */
102248  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
102249  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
102250  int iIdxCur = 0;      /* First index cursor */
102251  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
102252  int endOfLoop;        /* Label for the end of the insertion loop */
102253  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
102254  int addrInsTop = 0;   /* Jump to label "D" */
102255  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
102256  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
102257  int iDb;              /* Index of database holding TABLE */
102258  Db *pDb;              /* The database containing table being inserted into */
102259  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
102260  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
102261  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
102262  u8 bIdListInOrder;    /* True if IDLIST is in table order */
102263  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
102264
102265  /* Register allocations */
102266  int regFromSelect = 0;/* Base register for data coming from SELECT */
102267  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
102268  int regRowCount = 0;  /* Memory cell used for the row counter */
102269  int regIns;           /* Block of regs holding rowid+data being inserted */
102270  int regRowid;         /* registers holding insert rowid */
102271  int regData;          /* register holding first column to insert */
102272  int *aRegIdx = 0;     /* One register allocated to each index */
102273
102274#ifndef SQLITE_OMIT_TRIGGER
102275  int isView;                 /* True if attempting to insert into a view */
102276  Trigger *pTrigger;          /* List of triggers on pTab, if required */
102277  int tmask;                  /* Mask of trigger times */
102278#endif
102279
102280  db = pParse->db;
102281  memset(&dest, 0, sizeof(dest));
102282  if( pParse->nErr || db->mallocFailed ){
102283    goto insert_cleanup;
102284  }
102285
102286  /* If the Select object is really just a simple VALUES() list with a
102287  ** single row (the common case) then keep that one row of values
102288  ** and discard the other (unused) parts of the pSelect object
102289  */
102290  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
102291    pList = pSelect->pEList;
102292    pSelect->pEList = 0;
102293    sqlite3SelectDelete(db, pSelect);
102294    pSelect = 0;
102295  }
102296
102297  /* Locate the table into which we will be inserting new information.
102298  */
102299  assert( pTabList->nSrc==1 );
102300  zTab = pTabList->a[0].zName;
102301  if( NEVER(zTab==0) ) goto insert_cleanup;
102302  pTab = sqlite3SrcListLookup(pParse, pTabList);
102303  if( pTab==0 ){
102304    goto insert_cleanup;
102305  }
102306  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102307  assert( iDb<db->nDb );
102308  pDb = &db->aDb[iDb];
102309  zDb = pDb->zName;
102310  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
102311    goto insert_cleanup;
102312  }
102313  withoutRowid = !HasRowid(pTab);
102314
102315  /* Figure out if we have any triggers and if the table being
102316  ** inserted into is a view
102317  */
102318#ifndef SQLITE_OMIT_TRIGGER
102319  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
102320  isView = pTab->pSelect!=0;
102321#else
102322# define pTrigger 0
102323# define tmask 0
102324# define isView 0
102325#endif
102326#ifdef SQLITE_OMIT_VIEW
102327# undef isView
102328# define isView 0
102329#endif
102330  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
102331
102332  /* If pTab is really a view, make sure it has been initialized.
102333  ** ViewGetColumnNames() is a no-op if pTab is not a view.
102334  */
102335  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102336    goto insert_cleanup;
102337  }
102338
102339  /* Cannot insert into a read-only table.
102340  */
102341  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102342    goto insert_cleanup;
102343  }
102344
102345  /* Allocate a VDBE
102346  */
102347  v = sqlite3GetVdbe(pParse);
102348  if( v==0 ) goto insert_cleanup;
102349  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102350  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
102351
102352#ifndef SQLITE_OMIT_XFER_OPT
102353  /* If the statement is of the form
102354  **
102355  **       INSERT INTO <table1> SELECT * FROM <table2>;
102356  **
102357  ** Then special optimizations can be applied that make the transfer
102358  ** very fast and which reduce fragmentation of indices.
102359  **
102360  ** This is the 2nd template.
102361  */
102362  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
102363    assert( !pTrigger );
102364    assert( pList==0 );
102365    goto insert_end;
102366  }
102367#endif /* SQLITE_OMIT_XFER_OPT */
102368
102369  /* If this is an AUTOINCREMENT table, look up the sequence number in the
102370  ** sqlite_sequence table and store it in memory cell regAutoinc.
102371  */
102372  regAutoinc = autoIncBegin(pParse, iDb, pTab);
102373
102374  /* Allocate registers for holding the rowid of the new row,
102375  ** the content of the new row, and the assembled row record.
102376  */
102377  regRowid = regIns = pParse->nMem+1;
102378  pParse->nMem += pTab->nCol + 1;
102379  if( IsVirtual(pTab) ){
102380    regRowid++;
102381    pParse->nMem++;
102382  }
102383  regData = regRowid+1;
102384
102385  /* If the INSERT statement included an IDLIST term, then make sure
102386  ** all elements of the IDLIST really are columns of the table and
102387  ** remember the column indices.
102388  **
102389  ** If the table has an INTEGER PRIMARY KEY column and that column
102390  ** is named in the IDLIST, then record in the ipkColumn variable
102391  ** the index into IDLIST of the primary key column.  ipkColumn is
102392  ** the index of the primary key as it appears in IDLIST, not as
102393  ** is appears in the original table.  (The index of the INTEGER
102394  ** PRIMARY KEY in the original table is pTab->iPKey.)
102395  */
102396  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
102397  if( pColumn ){
102398    for(i=0; i<pColumn->nId; i++){
102399      pColumn->a[i].idx = -1;
102400    }
102401    for(i=0; i<pColumn->nId; i++){
102402      for(j=0; j<pTab->nCol; j++){
102403        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
102404          pColumn->a[i].idx = j;
102405          if( i!=j ) bIdListInOrder = 0;
102406          if( j==pTab->iPKey ){
102407            ipkColumn = i;  assert( !withoutRowid );
102408          }
102409          break;
102410        }
102411      }
102412      if( j>=pTab->nCol ){
102413        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
102414          ipkColumn = i;
102415          bIdListInOrder = 0;
102416        }else{
102417          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
102418              pTabList, 0, pColumn->a[i].zName);
102419          pParse->checkSchema = 1;
102420          goto insert_cleanup;
102421        }
102422      }
102423    }
102424  }
102425
102426  /* Figure out how many columns of data are supplied.  If the data
102427  ** is coming from a SELECT statement, then generate a co-routine that
102428  ** produces a single row of the SELECT on each invocation.  The
102429  ** co-routine is the common header to the 3rd and 4th templates.
102430  */
102431  if( pSelect ){
102432    /* Data is coming from a SELECT or from a multi-row VALUES clause.
102433    ** Generate a co-routine to run the SELECT. */
102434    int regYield;       /* Register holding co-routine entry-point */
102435    int addrTop;        /* Top of the co-routine */
102436    int rc;             /* Result code */
102437
102438    regYield = ++pParse->nMem;
102439    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
102440    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
102441    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
102442    dest.iSdst = bIdListInOrder ? regData : 0;
102443    dest.nSdst = pTab->nCol;
102444    rc = sqlite3Select(pParse, pSelect, &dest);
102445    regFromSelect = dest.iSdst;
102446    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
102447    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
102448    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
102449    assert( pSelect->pEList );
102450    nColumn = pSelect->pEList->nExpr;
102451
102452    /* Set useTempTable to TRUE if the result of the SELECT statement
102453    ** should be written into a temporary table (template 4).  Set to
102454    ** FALSE if each output row of the SELECT can be written directly into
102455    ** the destination table (template 3).
102456    **
102457    ** A temp table must be used if the table being updated is also one
102458    ** of the tables being read by the SELECT statement.  Also use a
102459    ** temp table in the case of row triggers.
102460    */
102461    if( pTrigger || readsTable(pParse, iDb, pTab) ){
102462      useTempTable = 1;
102463    }
102464
102465    if( useTempTable ){
102466      /* Invoke the coroutine to extract information from the SELECT
102467      ** and add it to a transient table srcTab.  The code generated
102468      ** here is from the 4th template:
102469      **
102470      **      B: open temp table
102471      **      L: yield X, goto M at EOF
102472      **         insert row from R..R+n into temp table
102473      **         goto L
102474      **      M: ...
102475      */
102476      int regRec;          /* Register to hold packed record */
102477      int regTempRowid;    /* Register to hold temp table ROWID */
102478      int addrL;           /* Label "L" */
102479
102480      srcTab = pParse->nTab++;
102481      regRec = sqlite3GetTempReg(pParse);
102482      regTempRowid = sqlite3GetTempReg(pParse);
102483      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
102484      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
102485      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
102486      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
102487      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
102488      sqlite3VdbeGoto(v, addrL);
102489      sqlite3VdbeJumpHere(v, addrL);
102490      sqlite3ReleaseTempReg(pParse, regRec);
102491      sqlite3ReleaseTempReg(pParse, regTempRowid);
102492    }
102493  }else{
102494    /* This is the case if the data for the INSERT is coming from a
102495    ** single-row VALUES clause
102496    */
102497    NameContext sNC;
102498    memset(&sNC, 0, sizeof(sNC));
102499    sNC.pParse = pParse;
102500    srcTab = -1;
102501    assert( useTempTable==0 );
102502    if( pList ){
102503      nColumn = pList->nExpr;
102504      if( sqlite3ResolveExprListNames(&sNC, pList) ){
102505        goto insert_cleanup;
102506      }
102507    }else{
102508      nColumn = 0;
102509    }
102510  }
102511
102512  /* If there is no IDLIST term but the table has an integer primary
102513  ** key, the set the ipkColumn variable to the integer primary key
102514  ** column index in the original table definition.
102515  */
102516  if( pColumn==0 && nColumn>0 ){
102517    ipkColumn = pTab->iPKey;
102518  }
102519
102520  /* Make sure the number of columns in the source data matches the number
102521  ** of columns to be inserted into the table.
102522  */
102523  if( IsVirtual(pTab) ){
102524    for(i=0; i<pTab->nCol; i++){
102525      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
102526    }
102527  }
102528  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
102529    sqlite3ErrorMsg(pParse,
102530       "table %S has %d columns but %d values were supplied",
102531       pTabList, 0, pTab->nCol-nHidden, nColumn);
102532    goto insert_cleanup;
102533  }
102534  if( pColumn!=0 && nColumn!=pColumn->nId ){
102535    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
102536    goto insert_cleanup;
102537  }
102538
102539  /* Initialize the count of rows to be inserted
102540  */
102541  if( db->flags & SQLITE_CountRows ){
102542    regRowCount = ++pParse->nMem;
102543    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102544  }
102545
102546  /* If this is not a view, open the table and and all indices */
102547  if( !isView ){
102548    int nIdx;
102549    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
102550                                      &iDataCur, &iIdxCur);
102551    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
102552    if( aRegIdx==0 ){
102553      goto insert_cleanup;
102554    }
102555    for(i=0; i<nIdx; i++){
102556      aRegIdx[i] = ++pParse->nMem;
102557    }
102558  }
102559
102560  /* This is the top of the main insertion loop */
102561  if( useTempTable ){
102562    /* This block codes the top of loop only.  The complete loop is the
102563    ** following pseudocode (template 4):
102564    **
102565    **         rewind temp table, if empty goto D
102566    **      C: loop over rows of intermediate table
102567    **           transfer values form intermediate table into <table>
102568    **         end loop
102569    **      D: ...
102570    */
102571    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
102572    addrCont = sqlite3VdbeCurrentAddr(v);
102573  }else if( pSelect ){
102574    /* This block codes the top of loop only.  The complete loop is the
102575    ** following pseudocode (template 3):
102576    **
102577    **      C: yield X, at EOF goto D
102578    **         insert the select result into <table> from R..R+n
102579    **         goto C
102580    **      D: ...
102581    */
102582    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
102583    VdbeCoverage(v);
102584  }
102585
102586  /* Run the BEFORE and INSTEAD OF triggers, if there are any
102587  */
102588  endOfLoop = sqlite3VdbeMakeLabel(v);
102589  if( tmask & TRIGGER_BEFORE ){
102590    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
102591
102592    /* build the NEW.* reference row.  Note that if there is an INTEGER
102593    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
102594    ** translated into a unique ID for the row.  But on a BEFORE trigger,
102595    ** we do not know what the unique ID will be (because the insert has
102596    ** not happened yet) so we substitute a rowid of -1
102597    */
102598    if( ipkColumn<0 ){
102599      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
102600    }else{
102601      int addr1;
102602      assert( !withoutRowid );
102603      if( useTempTable ){
102604        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
102605      }else{
102606        assert( pSelect==0 );  /* Otherwise useTempTable is true */
102607        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
102608      }
102609      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
102610      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
102611      sqlite3VdbeJumpHere(v, addr1);
102612      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
102613    }
102614
102615    /* Cannot have triggers on a virtual table. If it were possible,
102616    ** this block would have to account for hidden column.
102617    */
102618    assert( !IsVirtual(pTab) );
102619
102620    /* Create the new column data
102621    */
102622    for(i=0; i<pTab->nCol; i++){
102623      if( pColumn==0 ){
102624        j = i;
102625      }else{
102626        for(j=0; j<pColumn->nId; j++){
102627          if( pColumn->a[j].idx==i ) break;
102628        }
102629      }
102630      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
102631        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
102632      }else if( useTempTable ){
102633        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
102634      }else{
102635        assert( pSelect==0 ); /* Otherwise useTempTable is true */
102636        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
102637      }
102638    }
102639
102640    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
102641    ** do not attempt any conversions before assembling the record.
102642    ** If this is a real table, attempt conversions as required by the
102643    ** table column affinities.
102644    */
102645    if( !isView ){
102646      sqlite3TableAffinity(v, pTab, regCols+1);
102647    }
102648
102649    /* Fire BEFORE or INSTEAD OF triggers */
102650    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
102651        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
102652
102653    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
102654  }
102655
102656  /* Compute the content of the next row to insert into a range of
102657  ** registers beginning at regIns.
102658  */
102659  if( !isView ){
102660    if( IsVirtual(pTab) ){
102661      /* The row that the VUpdate opcode will delete: none */
102662      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
102663    }
102664    if( ipkColumn>=0 ){
102665      if( useTempTable ){
102666        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
102667      }else if( pSelect ){
102668        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
102669      }else{
102670        VdbeOp *pOp;
102671        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
102672        pOp = sqlite3VdbeGetOp(v, -1);
102673        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
102674          appendFlag = 1;
102675          pOp->opcode = OP_NewRowid;
102676          pOp->p1 = iDataCur;
102677          pOp->p2 = regRowid;
102678          pOp->p3 = regAutoinc;
102679        }
102680      }
102681      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
102682      ** to generate a unique primary key value.
102683      */
102684      if( !appendFlag ){
102685        int addr1;
102686        if( !IsVirtual(pTab) ){
102687          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
102688          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
102689          sqlite3VdbeJumpHere(v, addr1);
102690        }else{
102691          addr1 = sqlite3VdbeCurrentAddr(v);
102692          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
102693        }
102694        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
102695      }
102696    }else if( IsVirtual(pTab) || withoutRowid ){
102697      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
102698    }else{
102699      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
102700      appendFlag = 1;
102701    }
102702    autoIncStep(pParse, regAutoinc, regRowid);
102703
102704    /* Compute data for all columns of the new entry, beginning
102705    ** with the first column.
102706    */
102707    nHidden = 0;
102708    for(i=0; i<pTab->nCol; i++){
102709      int iRegStore = regRowid+1+i;
102710      if( i==pTab->iPKey ){
102711        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
102712        ** Whenever this column is read, the rowid will be substituted
102713        ** in its place.  Hence, fill this column with a NULL to avoid
102714        ** taking up data space with information that will never be used.
102715        ** As there may be shallow copies of this value, make it a soft-NULL */
102716        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
102717        continue;
102718      }
102719      if( pColumn==0 ){
102720        if( IsHiddenColumn(&pTab->aCol[i]) ){
102721          assert( IsVirtual(pTab) );
102722          j = -1;
102723          nHidden++;
102724        }else{
102725          j = i - nHidden;
102726        }
102727      }else{
102728        for(j=0; j<pColumn->nId; j++){
102729          if( pColumn->a[j].idx==i ) break;
102730        }
102731      }
102732      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
102733        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
102734      }else if( useTempTable ){
102735        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
102736      }else if( pSelect ){
102737        if( regFromSelect!=regData ){
102738          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
102739        }
102740      }else{
102741        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
102742      }
102743    }
102744
102745    /* Generate code to check constraints and generate index keys and
102746    ** do the insertion.
102747    */
102748#ifndef SQLITE_OMIT_VIRTUALTABLE
102749    if( IsVirtual(pTab) ){
102750      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102751      sqlite3VtabMakeWritable(pParse, pTab);
102752      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
102753      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102754      sqlite3MayAbort(pParse);
102755    }else
102756#endif
102757    {
102758      int isReplace;    /* Set to true if constraints may cause a replace */
102759      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
102760          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
102761      );
102762      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
102763      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
102764                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
102765    }
102766  }
102767
102768  /* Update the count of rows that are inserted
102769  */
102770  if( (db->flags & SQLITE_CountRows)!=0 ){
102771    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102772  }
102773
102774  if( pTrigger ){
102775    /* Code AFTER triggers */
102776    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
102777        pTab, regData-2-pTab->nCol, onError, endOfLoop);
102778  }
102779
102780  /* The bottom of the main insertion loop, if the data source
102781  ** is a SELECT statement.
102782  */
102783  sqlite3VdbeResolveLabel(v, endOfLoop);
102784  if( useTempTable ){
102785    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
102786    sqlite3VdbeJumpHere(v, addrInsTop);
102787    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
102788  }else if( pSelect ){
102789    sqlite3VdbeGoto(v, addrCont);
102790    sqlite3VdbeJumpHere(v, addrInsTop);
102791  }
102792
102793  if( !IsVirtual(pTab) && !isView ){
102794    /* Close all tables opened */
102795    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102796    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
102797      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
102798    }
102799  }
102800
102801insert_end:
102802  /* Update the sqlite_sequence table by storing the content of the
102803  ** maximum rowid counter values recorded while inserting into
102804  ** autoincrement tables.
102805  */
102806  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102807    sqlite3AutoincrementEnd(pParse);
102808  }
102809
102810  /*
102811  ** Return the number of rows inserted. If this routine is
102812  ** generating code because of a call to sqlite3NestedParse(), do not
102813  ** invoke the callback function.
102814  */
102815  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102816    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102817    sqlite3VdbeSetNumCols(v, 1);
102818    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
102819  }
102820
102821insert_cleanup:
102822  sqlite3SrcListDelete(db, pTabList);
102823  sqlite3ExprListDelete(db, pList);
102824  sqlite3SelectDelete(db, pSelect);
102825  sqlite3IdListDelete(db, pColumn);
102826  sqlite3DbFree(db, aRegIdx);
102827}
102828
102829/* Make sure "isView" and other macros defined above are undefined. Otherwise
102830** they may interfere with compilation of other functions in this file
102831** (or in another file, if this file becomes part of the amalgamation).  */
102832#ifdef isView
102833 #undef isView
102834#endif
102835#ifdef pTrigger
102836 #undef pTrigger
102837#endif
102838#ifdef tmask
102839 #undef tmask
102840#endif
102841
102842/*
102843** Generate code to do constraint checks prior to an INSERT or an UPDATE
102844** on table pTab.
102845**
102846** The regNewData parameter is the first register in a range that contains
102847** the data to be inserted or the data after the update.  There will be
102848** pTab->nCol+1 registers in this range.  The first register (the one
102849** that regNewData points to) will contain the new rowid, or NULL in the
102850** case of a WITHOUT ROWID table.  The second register in the range will
102851** contain the content of the first table column.  The third register will
102852** contain the content of the second table column.  And so forth.
102853**
102854** The regOldData parameter is similar to regNewData except that it contains
102855** the data prior to an UPDATE rather than afterwards.  regOldData is zero
102856** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
102857** checking regOldData for zero.
102858**
102859** For an UPDATE, the pkChng boolean is true if the true primary key (the
102860** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
102861** might be modified by the UPDATE.  If pkChng is false, then the key of
102862** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
102863**
102864** For an INSERT, the pkChng boolean indicates whether or not the rowid
102865** was explicitly specified as part of the INSERT statement.  If pkChng
102866** is zero, it means that the either rowid is computed automatically or
102867** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
102868** pkChng will only be true if the INSERT statement provides an integer
102869** value for either the rowid column or its INTEGER PRIMARY KEY alias.
102870**
102871** The code generated by this routine will store new index entries into
102872** registers identified by aRegIdx[].  No index entry is created for
102873** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
102874** the same as the order of indices on the linked list of indices
102875** at pTab->pIndex.
102876**
102877** The caller must have already opened writeable cursors on the main
102878** table and all applicable indices (that is to say, all indices for which
102879** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
102880** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
102881** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
102882** for the first index in the pTab->pIndex list.  Cursors for other indices
102883** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
102884**
102885** This routine also generates code to check constraints.  NOT NULL,
102886** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
102887** then the appropriate action is performed.  There are five possible
102888** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
102889**
102890**  Constraint type  Action       What Happens
102891**  ---------------  ----------   ----------------------------------------
102892**  any              ROLLBACK     The current transaction is rolled back and
102893**                                sqlite3_step() returns immediately with a
102894**                                return code of SQLITE_CONSTRAINT.
102895**
102896**  any              ABORT        Back out changes from the current command
102897**                                only (do not do a complete rollback) then
102898**                                cause sqlite3_step() to return immediately
102899**                                with SQLITE_CONSTRAINT.
102900**
102901**  any              FAIL         Sqlite3_step() returns immediately with a
102902**                                return code of SQLITE_CONSTRAINT.  The
102903**                                transaction is not rolled back and any
102904**                                changes to prior rows are retained.
102905**
102906**  any              IGNORE       The attempt in insert or update the current
102907**                                row is skipped, without throwing an error.
102908**                                Processing continues with the next row.
102909**                                (There is an immediate jump to ignoreDest.)
102910**
102911**  NOT NULL         REPLACE      The NULL value is replace by the default
102912**                                value for that column.  If the default value
102913**                                is NULL, the action is the same as ABORT.
102914**
102915**  UNIQUE           REPLACE      The other row that conflicts with the row
102916**                                being inserted is removed.
102917**
102918**  CHECK            REPLACE      Illegal.  The results in an exception.
102919**
102920** Which action to take is determined by the overrideError parameter.
102921** Or if overrideError==OE_Default, then the pParse->onError parameter
102922** is used.  Or if pParse->onError==OE_Default then the onError value
102923** for the constraint is used.
102924*/
102925SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
102926  Parse *pParse,       /* The parser context */
102927  Table *pTab,         /* The table being inserted or updated */
102928  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
102929  int iDataCur,        /* Canonical data cursor (main table or PK index) */
102930  int iIdxCur,         /* First index cursor */
102931  int regNewData,      /* First register in a range holding values to insert */
102932  int regOldData,      /* Previous content.  0 for INSERTs */
102933  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
102934  u8 overrideError,    /* Override onError to this if not OE_Default */
102935  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
102936  int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
102937){
102938  Vdbe *v;             /* VDBE under constrution */
102939  Index *pIdx;         /* Pointer to one of the indices */
102940  Index *pPk = 0;      /* The PRIMARY KEY index */
102941  sqlite3 *db;         /* Database connection */
102942  int i;               /* loop counter */
102943  int ix;              /* Index loop counter */
102944  int nCol;            /* Number of columns */
102945  int onError;         /* Conflict resolution strategy */
102946  int addr1;           /* Address of jump instruction */
102947  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
102948  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
102949  int ipkTop = 0;      /* Top of the rowid change constraint check */
102950  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
102951  u8 isUpdate;         /* True if this is an UPDATE operation */
102952  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
102953  int regRowid = -1;   /* Register holding ROWID value */
102954
102955  isUpdate = regOldData!=0;
102956  db = pParse->db;
102957  v = sqlite3GetVdbe(pParse);
102958  assert( v!=0 );
102959  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
102960  nCol = pTab->nCol;
102961
102962  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
102963  ** normal rowid tables.  nPkField is the number of key fields in the
102964  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
102965  ** number of fields in the true primary key of the table. */
102966  if( HasRowid(pTab) ){
102967    pPk = 0;
102968    nPkField = 1;
102969  }else{
102970    pPk = sqlite3PrimaryKeyIndex(pTab);
102971    nPkField = pPk->nKeyCol;
102972  }
102973
102974  /* Record that this module has started */
102975  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
102976                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
102977
102978  /* Test all NOT NULL constraints.
102979  */
102980  for(i=0; i<nCol; i++){
102981    if( i==pTab->iPKey ){
102982      continue;
102983    }
102984    onError = pTab->aCol[i].notNull;
102985    if( onError==OE_None ) continue;
102986    if( overrideError!=OE_Default ){
102987      onError = overrideError;
102988    }else if( onError==OE_Default ){
102989      onError = OE_Abort;
102990    }
102991    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
102992      onError = OE_Abort;
102993    }
102994    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
102995        || onError==OE_Ignore || onError==OE_Replace );
102996    switch( onError ){
102997      case OE_Abort:
102998        sqlite3MayAbort(pParse);
102999        /* Fall through */
103000      case OE_Rollback:
103001      case OE_Fail: {
103002        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
103003                                    pTab->aCol[i].zName);
103004        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
103005                          regNewData+1+i, zMsg, P4_DYNAMIC);
103006        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
103007        VdbeCoverage(v);
103008        break;
103009      }
103010      case OE_Ignore: {
103011        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
103012        VdbeCoverage(v);
103013        break;
103014      }
103015      default: {
103016        assert( onError==OE_Replace );
103017        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
103018           VdbeCoverage(v);
103019        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
103020        sqlite3VdbeJumpHere(v, addr1);
103021        break;
103022      }
103023    }
103024  }
103025
103026  /* Test all CHECK constraints
103027  */
103028#ifndef SQLITE_OMIT_CHECK
103029  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
103030    ExprList *pCheck = pTab->pCheck;
103031    pParse->ckBase = regNewData+1;
103032    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
103033    for(i=0; i<pCheck->nExpr; i++){
103034      int allOk = sqlite3VdbeMakeLabel(v);
103035      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
103036      if( onError==OE_Ignore ){
103037        sqlite3VdbeGoto(v, ignoreDest);
103038      }else{
103039        char *zName = pCheck->a[i].zName;
103040        if( zName==0 ) zName = pTab->zName;
103041        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
103042        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
103043                              onError, zName, P4_TRANSIENT,
103044                              P5_ConstraintCheck);
103045      }
103046      sqlite3VdbeResolveLabel(v, allOk);
103047    }
103048  }
103049#endif /* !defined(SQLITE_OMIT_CHECK) */
103050
103051  /* If rowid is changing, make sure the new rowid does not previously
103052  ** exist in the table.
103053  */
103054  if( pkChng && pPk==0 ){
103055    int addrRowidOk = sqlite3VdbeMakeLabel(v);
103056
103057    /* Figure out what action to take in case of a rowid collision */
103058    onError = pTab->keyConf;
103059    if( overrideError!=OE_Default ){
103060      onError = overrideError;
103061    }else if( onError==OE_Default ){
103062      onError = OE_Abort;
103063    }
103064
103065    if( isUpdate ){
103066      /* pkChng!=0 does not mean that the rowid has change, only that
103067      ** it might have changed.  Skip the conflict logic below if the rowid
103068      ** is unchanged. */
103069      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
103070      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103071      VdbeCoverage(v);
103072    }
103073
103074    /* If the response to a rowid conflict is REPLACE but the response
103075    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
103076    ** to defer the running of the rowid conflict checking until after
103077    ** the UNIQUE constraints have run.
103078    */
103079    if( onError==OE_Replace && overrideError!=OE_Replace ){
103080      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103081        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
103082          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
103083          break;
103084        }
103085      }
103086    }
103087
103088    /* Check to see if the new rowid already exists in the table.  Skip
103089    ** the following conflict logic if it does not. */
103090    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
103091    VdbeCoverage(v);
103092
103093    /* Generate code that deals with a rowid collision */
103094    switch( onError ){
103095      default: {
103096        onError = OE_Abort;
103097        /* Fall thru into the next case */
103098      }
103099      case OE_Rollback:
103100      case OE_Abort:
103101      case OE_Fail: {
103102        sqlite3RowidConstraint(pParse, onError, pTab);
103103        break;
103104      }
103105      case OE_Replace: {
103106        /* If there are DELETE triggers on this table and the
103107        ** recursive-triggers flag is set, call GenerateRowDelete() to
103108        ** remove the conflicting row from the table. This will fire
103109        ** the triggers and remove both the table and index b-tree entries.
103110        **
103111        ** Otherwise, if there are no triggers or the recursive-triggers
103112        ** flag is not set, but the table has one or more indexes, call
103113        ** GenerateRowIndexDelete(). This removes the index b-tree entries
103114        ** only. The table b-tree entry will be replaced by the new entry
103115        ** when it is inserted.
103116        **
103117        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
103118        ** also invoke MultiWrite() to indicate that this VDBE may require
103119        ** statement rollback (if the statement is aborted after the delete
103120        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
103121        ** but being more selective here allows statements like:
103122        **
103123        **   REPLACE INTO t(rowid) VALUES($newrowid)
103124        **
103125        ** to run without a statement journal if there are no indexes on the
103126        ** table.
103127        */
103128        Trigger *pTrigger = 0;
103129        if( db->flags&SQLITE_RecTriggers ){
103130          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103131        }
103132        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
103133          sqlite3MultiWrite(pParse);
103134          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103135                                   regNewData, 1, 0, OE_Replace,
103136                                   ONEPASS_SINGLE, -1);
103137        }else{
103138          if( pTab->pIndex ){
103139            sqlite3MultiWrite(pParse);
103140            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
103141          }
103142        }
103143        seenReplace = 1;
103144        break;
103145      }
103146      case OE_Ignore: {
103147        /*assert( seenReplace==0 );*/
103148        sqlite3VdbeGoto(v, ignoreDest);
103149        break;
103150      }
103151    }
103152    sqlite3VdbeResolveLabel(v, addrRowidOk);
103153    if( ipkTop ){
103154      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
103155      sqlite3VdbeJumpHere(v, ipkTop);
103156    }
103157  }
103158
103159  /* Test all UNIQUE constraints by creating entries for each UNIQUE
103160  ** index and making sure that duplicate entries do not already exist.
103161  ** Compute the revised record entries for indices as we go.
103162  **
103163  ** This loop also handles the case of the PRIMARY KEY index for a
103164  ** WITHOUT ROWID table.
103165  */
103166  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
103167    int regIdx;          /* Range of registers hold conent for pIdx */
103168    int regR;            /* Range of registers holding conflicting PK */
103169    int iThisCur;        /* Cursor for this UNIQUE index */
103170    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
103171
103172    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
103173    if( bAffinityDone==0 ){
103174      sqlite3TableAffinity(v, pTab, regNewData+1);
103175      bAffinityDone = 1;
103176    }
103177    iThisCur = iIdxCur+ix;
103178    addrUniqueOk = sqlite3VdbeMakeLabel(v);
103179
103180    /* Skip partial indices for which the WHERE clause is not true */
103181    if( pIdx->pPartIdxWhere ){
103182      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
103183      pParse->ckBase = regNewData+1;
103184      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
103185                            SQLITE_JUMPIFNULL);
103186      pParse->ckBase = 0;
103187    }
103188
103189    /* Create a record for this index entry as it should appear after
103190    ** the insert or update.  Store that record in the aRegIdx[ix] register
103191    */
103192    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
103193    for(i=0; i<pIdx->nColumn; i++){
103194      int iField = pIdx->aiColumn[i];
103195      int x;
103196      if( iField==XN_EXPR ){
103197        pParse->ckBase = regNewData+1;
103198        sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
103199        pParse->ckBase = 0;
103200        VdbeComment((v, "%s column %d", pIdx->zName, i));
103201      }else{
103202        if( iField==XN_ROWID || iField==pTab->iPKey ){
103203          if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
103204          x = regNewData;
103205          regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
103206        }else{
103207          x = iField + regNewData + 1;
103208        }
103209        sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
103210        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
103211      }
103212    }
103213    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
103214    VdbeComment((v, "for %s", pIdx->zName));
103215    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
103216
103217    /* In an UPDATE operation, if this index is the PRIMARY KEY index
103218    ** of a WITHOUT ROWID table and there has been no change the
103219    ** primary key, then no collision is possible.  The collision detection
103220    ** logic below can all be skipped. */
103221    if( isUpdate && pPk==pIdx && pkChng==0 ){
103222      sqlite3VdbeResolveLabel(v, addrUniqueOk);
103223      continue;
103224    }
103225
103226    /* Find out what action to take in case there is a uniqueness conflict */
103227    onError = pIdx->onError;
103228    if( onError==OE_None ){
103229      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
103230      sqlite3VdbeResolveLabel(v, addrUniqueOk);
103231      continue;  /* pIdx is not a UNIQUE index */
103232    }
103233    if( overrideError!=OE_Default ){
103234      onError = overrideError;
103235    }else if( onError==OE_Default ){
103236      onError = OE_Abort;
103237    }
103238
103239    /* Check to see if the new index entry will be unique */
103240    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
103241                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
103242
103243    /* Generate code to handle collisions */
103244    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
103245    if( isUpdate || onError==OE_Replace ){
103246      if( HasRowid(pTab) ){
103247        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
103248        /* Conflict only if the rowid of the existing index entry
103249        ** is different from old-rowid */
103250        if( isUpdate ){
103251          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
103252          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103253          VdbeCoverage(v);
103254        }
103255      }else{
103256        int x;
103257        /* Extract the PRIMARY KEY from the end of the index entry and
103258        ** store it in registers regR..regR+nPk-1 */
103259        if( pIdx!=pPk ){
103260          for(i=0; i<pPk->nKeyCol; i++){
103261            assert( pPk->aiColumn[i]>=0 );
103262            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
103263            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
103264            VdbeComment((v, "%s.%s", pTab->zName,
103265                         pTab->aCol[pPk->aiColumn[i]].zName));
103266          }
103267        }
103268        if( isUpdate ){
103269          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
103270          ** table, only conflict if the new PRIMARY KEY values are actually
103271          ** different from the old.
103272          **
103273          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
103274          ** of the matched index row are different from the original PRIMARY
103275          ** KEY values of this row before the update.  */
103276          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
103277          int op = OP_Ne;
103278          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
103279
103280          for(i=0; i<pPk->nKeyCol; i++){
103281            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
103282            x = pPk->aiColumn[i];
103283            assert( x>=0 );
103284            if( i==(pPk->nKeyCol-1) ){
103285              addrJump = addrUniqueOk;
103286              op = OP_Eq;
103287            }
103288            sqlite3VdbeAddOp4(v, op,
103289                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
103290            );
103291            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103292            VdbeCoverageIf(v, op==OP_Eq);
103293            VdbeCoverageIf(v, op==OP_Ne);
103294          }
103295        }
103296      }
103297    }
103298
103299    /* Generate code that executes if the new index entry is not unique */
103300    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
103301        || onError==OE_Ignore || onError==OE_Replace );
103302    switch( onError ){
103303      case OE_Rollback:
103304      case OE_Abort:
103305      case OE_Fail: {
103306        sqlite3UniqueConstraint(pParse, onError, pIdx);
103307        break;
103308      }
103309      case OE_Ignore: {
103310        sqlite3VdbeGoto(v, ignoreDest);
103311        break;
103312      }
103313      default: {
103314        Trigger *pTrigger = 0;
103315        assert( onError==OE_Replace );
103316        sqlite3MultiWrite(pParse);
103317        if( db->flags&SQLITE_RecTriggers ){
103318          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103319        }
103320        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103321            regR, nPkField, 0, OE_Replace,
103322            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
103323        seenReplace = 1;
103324        break;
103325      }
103326    }
103327    sqlite3VdbeResolveLabel(v, addrUniqueOk);
103328    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
103329    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
103330  }
103331  if( ipkTop ){
103332    sqlite3VdbeGoto(v, ipkTop+1);
103333    sqlite3VdbeJumpHere(v, ipkBottom);
103334  }
103335
103336  *pbMayReplace = seenReplace;
103337  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
103338}
103339
103340/*
103341** This routine generates code to finish the INSERT or UPDATE operation
103342** that was started by a prior call to sqlite3GenerateConstraintChecks.
103343** A consecutive range of registers starting at regNewData contains the
103344** rowid and the content to be inserted.
103345**
103346** The arguments to this routine should be the same as the first six
103347** arguments to sqlite3GenerateConstraintChecks.
103348*/
103349SQLITE_PRIVATE void sqlite3CompleteInsertion(
103350  Parse *pParse,      /* The parser context */
103351  Table *pTab,        /* the table into which we are inserting */
103352  int iDataCur,       /* Cursor of the canonical data source */
103353  int iIdxCur,        /* First index cursor */
103354  int regNewData,     /* Range of content */
103355  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
103356  int isUpdate,       /* True for UPDATE, False for INSERT */
103357  int appendBias,     /* True if this is likely to be an append */
103358  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
103359){
103360  Vdbe *v;            /* Prepared statements under construction */
103361  Index *pIdx;        /* An index being inserted or updated */
103362  u8 pik_flags;       /* flag values passed to the btree insert */
103363  int regData;        /* Content registers (after the rowid) */
103364  int regRec;         /* Register holding assembled record for the table */
103365  int i;              /* Loop counter */
103366  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
103367
103368  v = sqlite3GetVdbe(pParse);
103369  assert( v!=0 );
103370  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
103371  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
103372    if( aRegIdx[i]==0 ) continue;
103373    bAffinityDone = 1;
103374    if( pIdx->pPartIdxWhere ){
103375      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
103376      VdbeCoverage(v);
103377    }
103378    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
103379    pik_flags = 0;
103380    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
103381    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
103382      assert( pParse->nested==0 );
103383      pik_flags |= OPFLAG_NCHANGE;
103384    }
103385    if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
103386  }
103387  if( !HasRowid(pTab) ) return;
103388  regData = regNewData + 1;
103389  regRec = sqlite3GetTempReg(pParse);
103390  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
103391  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
103392  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
103393  if( pParse->nested ){
103394    pik_flags = 0;
103395  }else{
103396    pik_flags = OPFLAG_NCHANGE;
103397    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
103398  }
103399  if( appendBias ){
103400    pik_flags |= OPFLAG_APPEND;
103401  }
103402  if( useSeekResult ){
103403    pik_flags |= OPFLAG_USESEEKRESULT;
103404  }
103405  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
103406  if( !pParse->nested ){
103407    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
103408  }
103409  sqlite3VdbeChangeP5(v, pik_flags);
103410}
103411
103412/*
103413** Allocate cursors for the pTab table and all its indices and generate
103414** code to open and initialized those cursors.
103415**
103416** The cursor for the object that contains the complete data (normally
103417** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
103418** ROWID table) is returned in *piDataCur.  The first index cursor is
103419** returned in *piIdxCur.  The number of indices is returned.
103420**
103421** Use iBase as the first cursor (either the *piDataCur for rowid tables
103422** or the first index for WITHOUT ROWID tables) if it is non-negative.
103423** If iBase is negative, then allocate the next available cursor.
103424**
103425** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
103426** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
103427** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
103428** pTab->pIndex list.
103429**
103430** If pTab is a virtual table, then this routine is a no-op and the
103431** *piDataCur and *piIdxCur values are left uninitialized.
103432*/
103433SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
103434  Parse *pParse,   /* Parsing context */
103435  Table *pTab,     /* Table to be opened */
103436  int op,          /* OP_OpenRead or OP_OpenWrite */
103437  int iBase,       /* Use this for the table cursor, if there is one */
103438  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
103439  int *piDataCur,  /* Write the database source cursor number here */
103440  int *piIdxCur    /* Write the first index cursor number here */
103441){
103442  int i;
103443  int iDb;
103444  int iDataCur;
103445  Index *pIdx;
103446  Vdbe *v;
103447
103448  assert( op==OP_OpenRead || op==OP_OpenWrite );
103449  if( IsVirtual(pTab) ){
103450    /* This routine is a no-op for virtual tables. Leave the output
103451    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
103452    ** can detect if they are used by mistake in the caller. */
103453    return 0;
103454  }
103455  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
103456  v = sqlite3GetVdbe(pParse);
103457  assert( v!=0 );
103458  if( iBase<0 ) iBase = pParse->nTab;
103459  iDataCur = iBase++;
103460  if( piDataCur ) *piDataCur = iDataCur;
103461  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
103462    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
103463  }else{
103464    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
103465  }
103466  if( piIdxCur ) *piIdxCur = iBase;
103467  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
103468    int iIdxCur = iBase++;
103469    assert( pIdx->pSchema==pTab->pSchema );
103470    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
103471      *piDataCur = iIdxCur;
103472    }
103473    if( aToOpen==0 || aToOpen[i+1] ){
103474      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
103475      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
103476      VdbeComment((v, "%s", pIdx->zName));
103477    }
103478  }
103479  if( iBase>pParse->nTab ) pParse->nTab = iBase;
103480  return i;
103481}
103482
103483
103484#ifdef SQLITE_TEST
103485/*
103486** The following global variable is incremented whenever the
103487** transfer optimization is used.  This is used for testing
103488** purposes only - to make sure the transfer optimization really
103489** is happening when it is supposed to.
103490*/
103491SQLITE_API int sqlite3_xferopt_count;
103492#endif /* SQLITE_TEST */
103493
103494
103495#ifndef SQLITE_OMIT_XFER_OPT
103496/*
103497** Check to collation names to see if they are compatible.
103498*/
103499static int xferCompatibleCollation(const char *z1, const char *z2){
103500  if( z1==0 ){
103501    return z2==0;
103502  }
103503  if( z2==0 ){
103504    return 0;
103505  }
103506  return sqlite3StrICmp(z1, z2)==0;
103507}
103508
103509
103510/*
103511** Check to see if index pSrc is compatible as a source of data
103512** for index pDest in an insert transfer optimization.  The rules
103513** for a compatible index:
103514**
103515**    *   The index is over the same set of columns
103516**    *   The same DESC and ASC markings occurs on all columns
103517**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
103518**    *   The same collating sequence on each column
103519**    *   The index has the exact same WHERE clause
103520*/
103521static int xferCompatibleIndex(Index *pDest, Index *pSrc){
103522  int i;
103523  assert( pDest && pSrc );
103524  assert( pDest->pTable!=pSrc->pTable );
103525  if( pDest->nKeyCol!=pSrc->nKeyCol ){
103526    return 0;   /* Different number of columns */
103527  }
103528  if( pDest->onError!=pSrc->onError ){
103529    return 0;   /* Different conflict resolution strategies */
103530  }
103531  for(i=0; i<pSrc->nKeyCol; i++){
103532    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
103533      return 0;   /* Different columns indexed */
103534    }
103535    if( pSrc->aiColumn[i]==XN_EXPR ){
103536      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
103537      if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
103538                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
103539        return 0;   /* Different expressions in the index */
103540      }
103541    }
103542    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
103543      return 0;   /* Different sort orders */
103544    }
103545    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
103546      return 0;   /* Different collating sequences */
103547    }
103548  }
103549  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
103550    return 0;     /* Different WHERE clauses */
103551  }
103552
103553  /* If no test above fails then the indices must be compatible */
103554  return 1;
103555}
103556
103557/*
103558** Attempt the transfer optimization on INSERTs of the form
103559**
103560**     INSERT INTO tab1 SELECT * FROM tab2;
103561**
103562** The xfer optimization transfers raw records from tab2 over to tab1.
103563** Columns are not decoded and reassembled, which greatly improves
103564** performance.  Raw index records are transferred in the same way.
103565**
103566** The xfer optimization is only attempted if tab1 and tab2 are compatible.
103567** There are lots of rules for determining compatibility - see comments
103568** embedded in the code for details.
103569**
103570** This routine returns TRUE if the optimization is guaranteed to be used.
103571** Sometimes the xfer optimization will only work if the destination table
103572** is empty - a factor that can only be determined at run-time.  In that
103573** case, this routine generates code for the xfer optimization but also
103574** does a test to see if the destination table is empty and jumps over the
103575** xfer optimization code if the test fails.  In that case, this routine
103576** returns FALSE so that the caller will know to go ahead and generate
103577** an unoptimized transfer.  This routine also returns FALSE if there
103578** is no chance that the xfer optimization can be applied.
103579**
103580** This optimization is particularly useful at making VACUUM run faster.
103581*/
103582static int xferOptimization(
103583  Parse *pParse,        /* Parser context */
103584  Table *pDest,         /* The table we are inserting into */
103585  Select *pSelect,      /* A SELECT statement to use as the data source */
103586  int onError,          /* How to handle constraint errors */
103587  int iDbDest           /* The database of pDest */
103588){
103589  sqlite3 *db = pParse->db;
103590  ExprList *pEList;                /* The result set of the SELECT */
103591  Table *pSrc;                     /* The table in the FROM clause of SELECT */
103592  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
103593  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
103594  int i;                           /* Loop counter */
103595  int iDbSrc;                      /* The database of pSrc */
103596  int iSrc, iDest;                 /* Cursors from source and destination */
103597  int addr1, addr2;                /* Loop addresses */
103598  int emptyDestTest = 0;           /* Address of test for empty pDest */
103599  int emptySrcTest = 0;            /* Address of test for empty pSrc */
103600  Vdbe *v;                         /* The VDBE we are building */
103601  int regAutoinc;                  /* Memory register used by AUTOINC */
103602  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
103603  int regData, regRowid;           /* Registers holding data and rowid */
103604
103605  if( pSelect==0 ){
103606    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
103607  }
103608  if( pParse->pWith || pSelect->pWith ){
103609    /* Do not attempt to process this query if there are an WITH clauses
103610    ** attached to it. Proceeding may generate a false "no such table: xxx"
103611    ** error if pSelect reads from a CTE named "xxx".  */
103612    return 0;
103613  }
103614  if( sqlite3TriggerList(pParse, pDest) ){
103615    return 0;   /* tab1 must not have triggers */
103616  }
103617#ifndef SQLITE_OMIT_VIRTUALTABLE
103618  if( pDest->tabFlags & TF_Virtual ){
103619    return 0;   /* tab1 must not be a virtual table */
103620  }
103621#endif
103622  if( onError==OE_Default ){
103623    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
103624    if( onError==OE_Default ) onError = OE_Abort;
103625  }
103626  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
103627  if( pSelect->pSrc->nSrc!=1 ){
103628    return 0;   /* FROM clause must have exactly one term */
103629  }
103630  if( pSelect->pSrc->a[0].pSelect ){
103631    return 0;   /* FROM clause cannot contain a subquery */
103632  }
103633  if( pSelect->pWhere ){
103634    return 0;   /* SELECT may not have a WHERE clause */
103635  }
103636  if( pSelect->pOrderBy ){
103637    return 0;   /* SELECT may not have an ORDER BY clause */
103638  }
103639  /* Do not need to test for a HAVING clause.  If HAVING is present but
103640  ** there is no ORDER BY, we will get an error. */
103641  if( pSelect->pGroupBy ){
103642    return 0;   /* SELECT may not have a GROUP BY clause */
103643  }
103644  if( pSelect->pLimit ){
103645    return 0;   /* SELECT may not have a LIMIT clause */
103646  }
103647  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
103648  if( pSelect->pPrior ){
103649    return 0;   /* SELECT may not be a compound query */
103650  }
103651  if( pSelect->selFlags & SF_Distinct ){
103652    return 0;   /* SELECT may not be DISTINCT */
103653  }
103654  pEList = pSelect->pEList;
103655  assert( pEList!=0 );
103656  if( pEList->nExpr!=1 ){
103657    return 0;   /* The result set must have exactly one column */
103658  }
103659  assert( pEList->a[0].pExpr );
103660  if( pEList->a[0].pExpr->op!=TK_ALL ){
103661    return 0;   /* The result set must be the special operator "*" */
103662  }
103663
103664  /* At this point we have established that the statement is of the
103665  ** correct syntactic form to participate in this optimization.  Now
103666  ** we have to check the semantics.
103667  */
103668  pItem = pSelect->pSrc->a;
103669  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
103670  if( pSrc==0 ){
103671    return 0;   /* FROM clause does not contain a real table */
103672  }
103673  if( pSrc==pDest ){
103674    return 0;   /* tab1 and tab2 may not be the same table */
103675  }
103676  if( HasRowid(pDest)!=HasRowid(pSrc) ){
103677    return 0;   /* source and destination must both be WITHOUT ROWID or not */
103678  }
103679#ifndef SQLITE_OMIT_VIRTUALTABLE
103680  if( pSrc->tabFlags & TF_Virtual ){
103681    return 0;   /* tab2 must not be a virtual table */
103682  }
103683#endif
103684  if( pSrc->pSelect ){
103685    return 0;   /* tab2 may not be a view */
103686  }
103687  if( pDest->nCol!=pSrc->nCol ){
103688    return 0;   /* Number of columns must be the same in tab1 and tab2 */
103689  }
103690  if( pDest->iPKey!=pSrc->iPKey ){
103691    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
103692  }
103693  for(i=0; i<pDest->nCol; i++){
103694    Column *pDestCol = &pDest->aCol[i];
103695    Column *pSrcCol = &pSrc->aCol[i];
103696    if( pDestCol->affinity!=pSrcCol->affinity ){
103697      return 0;    /* Affinity must be the same on all columns */
103698    }
103699    if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
103700      return 0;    /* Collating sequence must be the same on all columns */
103701    }
103702    if( pDestCol->notNull && !pSrcCol->notNull ){
103703      return 0;    /* tab2 must be NOT NULL if tab1 is */
103704    }
103705    /* Default values for second and subsequent columns need to match. */
103706    if( i>0
103707     && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
103708         || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
103709    ){
103710      return 0;    /* Default values must be the same for all columns */
103711    }
103712  }
103713  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
103714    if( IsUniqueIndex(pDestIdx) ){
103715      destHasUniqueIdx = 1;
103716    }
103717    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
103718      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
103719    }
103720    if( pSrcIdx==0 ){
103721      return 0;    /* pDestIdx has no corresponding index in pSrc */
103722    }
103723  }
103724#ifndef SQLITE_OMIT_CHECK
103725  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
103726    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
103727  }
103728#endif
103729#ifndef SQLITE_OMIT_FOREIGN_KEY
103730  /* Disallow the transfer optimization if the destination table constains
103731  ** any foreign key constraints.  This is more restrictive than necessary.
103732  ** But the main beneficiary of the transfer optimization is the VACUUM
103733  ** command, and the VACUUM command disables foreign key constraints.  So
103734  ** the extra complication to make this rule less restrictive is probably
103735  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
103736  */
103737  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
103738    return 0;
103739  }
103740#endif
103741  if( (db->flags & SQLITE_CountRows)!=0 ){
103742    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
103743  }
103744
103745  /* If we get this far, it means that the xfer optimization is at
103746  ** least a possibility, though it might only work if the destination
103747  ** table (tab1) is initially empty.
103748  */
103749#ifdef SQLITE_TEST
103750  sqlite3_xferopt_count++;
103751#endif
103752  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
103753  v = sqlite3GetVdbe(pParse);
103754  sqlite3CodeVerifySchema(pParse, iDbSrc);
103755  iSrc = pParse->nTab++;
103756  iDest = pParse->nTab++;
103757  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
103758  regData = sqlite3GetTempReg(pParse);
103759  regRowid = sqlite3GetTempReg(pParse);
103760  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
103761  assert( HasRowid(pDest) || destHasUniqueIdx );
103762  if( (db->flags & SQLITE_Vacuum)==0 && (
103763      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
103764   || destHasUniqueIdx                              /* (2) */
103765   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
103766  )){
103767    /* In some circumstances, we are able to run the xfer optimization
103768    ** only if the destination table is initially empty. Unless the
103769    ** SQLITE_Vacuum flag is set, this block generates code to make
103770    ** that determination. If SQLITE_Vacuum is set, then the destination
103771    ** table is always empty.
103772    **
103773    ** Conditions under which the destination must be empty:
103774    **
103775    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
103776    **     (If the destination is not initially empty, the rowid fields
103777    **     of index entries might need to change.)
103778    **
103779    ** (2) The destination has a unique index.  (The xfer optimization
103780    **     is unable to test uniqueness.)
103781    **
103782    ** (3) onError is something other than OE_Abort and OE_Rollback.
103783    */
103784    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
103785    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
103786    sqlite3VdbeJumpHere(v, addr1);
103787  }
103788  if( HasRowid(pSrc) ){
103789    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
103790    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
103791    if( pDest->iPKey>=0 ){
103792      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
103793      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
103794      VdbeCoverage(v);
103795      sqlite3RowidConstraint(pParse, onError, pDest);
103796      sqlite3VdbeJumpHere(v, addr2);
103797      autoIncStep(pParse, regAutoinc, regRowid);
103798    }else if( pDest->pIndex==0 ){
103799      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
103800    }else{
103801      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
103802      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
103803    }
103804    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
103805    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
103806    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
103807    sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
103808    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
103809    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
103810    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103811  }else{
103812    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
103813    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
103814  }
103815  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
103816    u8 idxInsFlags = 0;
103817    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
103818      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
103819    }
103820    assert( pSrcIdx );
103821    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
103822    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
103823    VdbeComment((v, "%s", pSrcIdx->zName));
103824    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
103825    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
103826    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
103827    VdbeComment((v, "%s", pDestIdx->zName));
103828    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
103829    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
103830    if( db->flags & SQLITE_Vacuum ){
103831      /* This INSERT command is part of a VACUUM operation, which guarantees
103832      ** that the destination table is empty. If all indexed columns use
103833      ** collation sequence BINARY, then it can also be assumed that the
103834      ** index will be populated by inserting keys in strictly sorted
103835      ** order. In this case, instead of seeking within the b-tree as part
103836      ** of every OP_IdxInsert opcode, an OP_Last is added before the
103837      ** OP_IdxInsert to seek to the point within the b-tree where each key
103838      ** should be inserted. This is faster.
103839      **
103840      ** If any of the indexed columns use a collation sequence other than
103841      ** BINARY, this optimization is disabled. This is because the user
103842      ** might change the definition of a collation sequence and then run
103843      ** a VACUUM command. In that case keys may not be written in strictly
103844      ** sorted order.  */
103845      for(i=0; i<pSrcIdx->nColumn; i++){
103846        char *zColl = pSrcIdx->azColl[i];
103847        assert( zColl!=0 );
103848        if( sqlite3_stricmp("BINARY", zColl) ) break;
103849      }
103850      if( i==pSrcIdx->nColumn ){
103851        idxInsFlags = OPFLAG_USESEEKRESULT;
103852        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
103853      }
103854    }
103855    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
103856      idxInsFlags |= OPFLAG_NCHANGE;
103857    }
103858    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
103859    sqlite3VdbeChangeP5(v, idxInsFlags);
103860    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
103861    sqlite3VdbeJumpHere(v, addr1);
103862    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
103863    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103864  }
103865  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
103866  sqlite3ReleaseTempReg(pParse, regRowid);
103867  sqlite3ReleaseTempReg(pParse, regData);
103868  if( emptyDestTest ){
103869    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
103870    sqlite3VdbeJumpHere(v, emptyDestTest);
103871    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103872    return 0;
103873  }else{
103874    return 1;
103875  }
103876}
103877#endif /* SQLITE_OMIT_XFER_OPT */
103878
103879/************** End of insert.c **********************************************/
103880/************** Begin file legacy.c ******************************************/
103881/*
103882** 2001 September 15
103883**
103884** The author disclaims copyright to this source code.  In place of
103885** a legal notice, here is a blessing:
103886**
103887**    May you do good and not evil.
103888**    May you find forgiveness for yourself and forgive others.
103889**    May you share freely, never taking more than you give.
103890**
103891*************************************************************************
103892** Main file for the SQLite library.  The routines in this file
103893** implement the programmer interface to the library.  Routines in
103894** other files are for internal use by SQLite and should not be
103895** accessed by users of the library.
103896*/
103897
103898/* #include "sqliteInt.h" */
103899
103900/*
103901** Execute SQL code.  Return one of the SQLITE_ success/failure
103902** codes.  Also write an error message into memory obtained from
103903** malloc() and make *pzErrMsg point to that message.
103904**
103905** If the SQL is a query, then for each row in the query result
103906** the xCallback() function is called.  pArg becomes the first
103907** argument to xCallback().  If xCallback=NULL then no callback
103908** is invoked, even for queries.
103909*/
103910SQLITE_API int SQLITE_STDCALL sqlite3_exec(
103911  sqlite3 *db,                /* The database on which the SQL executes */
103912  const char *zSql,           /* The SQL to be executed */
103913  sqlite3_callback xCallback, /* Invoke this callback routine */
103914  void *pArg,                 /* First argument to xCallback() */
103915  char **pzErrMsg             /* Write error messages here */
103916){
103917  int rc = SQLITE_OK;         /* Return code */
103918  const char *zLeftover;      /* Tail of unprocessed SQL */
103919  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
103920  char **azCols = 0;          /* Names of result columns */
103921  int callbackIsInit;         /* True if callback data is initialized */
103922
103923  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
103924  if( zSql==0 ) zSql = "";
103925
103926  sqlite3_mutex_enter(db->mutex);
103927  sqlite3Error(db, SQLITE_OK);
103928  while( rc==SQLITE_OK && zSql[0] ){
103929    int nCol;
103930    char **azVals = 0;
103931
103932    pStmt = 0;
103933    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
103934    assert( rc==SQLITE_OK || pStmt==0 );
103935    if( rc!=SQLITE_OK ){
103936      continue;
103937    }
103938    if( !pStmt ){
103939      /* this happens for a comment or white-space */
103940      zSql = zLeftover;
103941      continue;
103942    }
103943
103944    callbackIsInit = 0;
103945    nCol = sqlite3_column_count(pStmt);
103946
103947    while( 1 ){
103948      int i;
103949      rc = sqlite3_step(pStmt);
103950
103951      /* Invoke the callback function if required */
103952      if( xCallback && (SQLITE_ROW==rc ||
103953          (SQLITE_DONE==rc && !callbackIsInit
103954                           && db->flags&SQLITE_NullCallback)) ){
103955        if( !callbackIsInit ){
103956          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
103957          if( azCols==0 ){
103958            goto exec_out;
103959          }
103960          for(i=0; i<nCol; i++){
103961            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
103962            /* sqlite3VdbeSetColName() installs column names as UTF8
103963            ** strings so there is no way for sqlite3_column_name() to fail. */
103964            assert( azCols[i]!=0 );
103965          }
103966          callbackIsInit = 1;
103967        }
103968        if( rc==SQLITE_ROW ){
103969          azVals = &azCols[nCol];
103970          for(i=0; i<nCol; i++){
103971            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
103972            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
103973              db->mallocFailed = 1;
103974              goto exec_out;
103975            }
103976          }
103977        }
103978        if( xCallback(pArg, nCol, azVals, azCols) ){
103979          /* EVIDENCE-OF: R-38229-40159 If the callback function to
103980          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
103981          ** return SQLITE_ABORT. */
103982          rc = SQLITE_ABORT;
103983          sqlite3VdbeFinalize((Vdbe *)pStmt);
103984          pStmt = 0;
103985          sqlite3Error(db, SQLITE_ABORT);
103986          goto exec_out;
103987        }
103988      }
103989
103990      if( rc!=SQLITE_ROW ){
103991        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
103992        pStmt = 0;
103993        zSql = zLeftover;
103994        while( sqlite3Isspace(zSql[0]) ) zSql++;
103995        break;
103996      }
103997    }
103998
103999    sqlite3DbFree(db, azCols);
104000    azCols = 0;
104001  }
104002
104003exec_out:
104004  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
104005  sqlite3DbFree(db, azCols);
104006
104007  rc = sqlite3ApiExit(db, rc);
104008  if( rc!=SQLITE_OK && pzErrMsg ){
104009    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
104010    *pzErrMsg = sqlite3Malloc(nErrMsg);
104011    if( *pzErrMsg ){
104012      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
104013    }else{
104014      rc = SQLITE_NOMEM;
104015      sqlite3Error(db, SQLITE_NOMEM);
104016    }
104017  }else if( pzErrMsg ){
104018    *pzErrMsg = 0;
104019  }
104020
104021  assert( (rc&db->errMask)==rc );
104022  sqlite3_mutex_leave(db->mutex);
104023  return rc;
104024}
104025
104026/************** End of legacy.c **********************************************/
104027/************** Begin file loadext.c *****************************************/
104028/*
104029** 2006 June 7
104030**
104031** The author disclaims copyright to this source code.  In place of
104032** a legal notice, here is a blessing:
104033**
104034**    May you do good and not evil.
104035**    May you find forgiveness for yourself and forgive others.
104036**    May you share freely, never taking more than you give.
104037**
104038*************************************************************************
104039** This file contains code used to dynamically load extensions into
104040** the SQLite library.
104041*/
104042
104043#ifndef SQLITE_CORE
104044  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
104045#endif
104046/************** Include sqlite3ext.h in the middle of loadext.c **************/
104047/************** Begin file sqlite3ext.h **************************************/
104048/*
104049** 2006 June 7
104050**
104051** The author disclaims copyright to this source code.  In place of
104052** a legal notice, here is a blessing:
104053**
104054**    May you do good and not evil.
104055**    May you find forgiveness for yourself and forgive others.
104056**    May you share freely, never taking more than you give.
104057**
104058*************************************************************************
104059** This header file defines the SQLite interface for use by
104060** shared libraries that want to be imported as extensions into
104061** an SQLite instance.  Shared libraries that intend to be loaded
104062** as extensions by SQLite should #include this file instead of
104063** sqlite3.h.
104064*/
104065#ifndef _SQLITE3EXT_H_
104066#define _SQLITE3EXT_H_
104067/* #include "sqlite3.h" */
104068
104069typedef struct sqlite3_api_routines sqlite3_api_routines;
104070
104071/*
104072** The following structure holds pointers to all of the SQLite API
104073** routines.
104074**
104075** WARNING:  In order to maintain backwards compatibility, add new
104076** interfaces to the end of this structure only.  If you insert new
104077** interfaces in the middle of this structure, then older different
104078** versions of SQLite will not be able to load each other's shared
104079** libraries!
104080*/
104081struct sqlite3_api_routines {
104082  void * (*aggregate_context)(sqlite3_context*,int nBytes);
104083  int  (*aggregate_count)(sqlite3_context*);
104084  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
104085  int  (*bind_double)(sqlite3_stmt*,int,double);
104086  int  (*bind_int)(sqlite3_stmt*,int,int);
104087  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
104088  int  (*bind_null)(sqlite3_stmt*,int);
104089  int  (*bind_parameter_count)(sqlite3_stmt*);
104090  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
104091  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
104092  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
104093  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
104094  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
104095  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
104096  int  (*busy_timeout)(sqlite3*,int ms);
104097  int  (*changes)(sqlite3*);
104098  int  (*close)(sqlite3*);
104099  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
104100                           int eTextRep,const char*));
104101  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
104102                             int eTextRep,const void*));
104103  const void * (*column_blob)(sqlite3_stmt*,int iCol);
104104  int  (*column_bytes)(sqlite3_stmt*,int iCol);
104105  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
104106  int  (*column_count)(sqlite3_stmt*pStmt);
104107  const char * (*column_database_name)(sqlite3_stmt*,int);
104108  const void * (*column_database_name16)(sqlite3_stmt*,int);
104109  const char * (*column_decltype)(sqlite3_stmt*,int i);
104110  const void * (*column_decltype16)(sqlite3_stmt*,int);
104111  double  (*column_double)(sqlite3_stmt*,int iCol);
104112  int  (*column_int)(sqlite3_stmt*,int iCol);
104113  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
104114  const char * (*column_name)(sqlite3_stmt*,int);
104115  const void * (*column_name16)(sqlite3_stmt*,int);
104116  const char * (*column_origin_name)(sqlite3_stmt*,int);
104117  const void * (*column_origin_name16)(sqlite3_stmt*,int);
104118  const char * (*column_table_name)(sqlite3_stmt*,int);
104119  const void * (*column_table_name16)(sqlite3_stmt*,int);
104120  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
104121  const void * (*column_text16)(sqlite3_stmt*,int iCol);
104122  int  (*column_type)(sqlite3_stmt*,int iCol);
104123  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
104124  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
104125  int  (*complete)(const char*sql);
104126  int  (*complete16)(const void*sql);
104127  int  (*create_collation)(sqlite3*,const char*,int,void*,
104128                           int(*)(void*,int,const void*,int,const void*));
104129  int  (*create_collation16)(sqlite3*,const void*,int,void*,
104130                             int(*)(void*,int,const void*,int,const void*));
104131  int  (*create_function)(sqlite3*,const char*,int,int,void*,
104132                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104133                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104134                          void (*xFinal)(sqlite3_context*));
104135  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
104136                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104137                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104138                            void (*xFinal)(sqlite3_context*));
104139  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
104140  int  (*data_count)(sqlite3_stmt*pStmt);
104141  sqlite3 * (*db_handle)(sqlite3_stmt*);
104142  int (*declare_vtab)(sqlite3*,const char*);
104143  int  (*enable_shared_cache)(int);
104144  int  (*errcode)(sqlite3*db);
104145  const char * (*errmsg)(sqlite3*);
104146  const void * (*errmsg16)(sqlite3*);
104147  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
104148  int  (*expired)(sqlite3_stmt*);
104149  int  (*finalize)(sqlite3_stmt*pStmt);
104150  void  (*free)(void*);
104151  void  (*free_table)(char**result);
104152  int  (*get_autocommit)(sqlite3*);
104153  void * (*get_auxdata)(sqlite3_context*,int);
104154  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
104155  int  (*global_recover)(void);
104156  void  (*interruptx)(sqlite3*);
104157  sqlite_int64  (*last_insert_rowid)(sqlite3*);
104158  const char * (*libversion)(void);
104159  int  (*libversion_number)(void);
104160  void *(*malloc)(int);
104161  char * (*mprintf)(const char*,...);
104162  int  (*open)(const char*,sqlite3**);
104163  int  (*open16)(const void*,sqlite3**);
104164  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
104165  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
104166  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
104167  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
104168  void *(*realloc)(void*,int);
104169  int  (*reset)(sqlite3_stmt*pStmt);
104170  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
104171  void  (*result_double)(sqlite3_context*,double);
104172  void  (*result_error)(sqlite3_context*,const char*,int);
104173  void  (*result_error16)(sqlite3_context*,const void*,int);
104174  void  (*result_int)(sqlite3_context*,int);
104175  void  (*result_int64)(sqlite3_context*,sqlite_int64);
104176  void  (*result_null)(sqlite3_context*);
104177  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
104178  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
104179  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
104180  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
104181  void  (*result_value)(sqlite3_context*,sqlite3_value*);
104182  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
104183  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
104184                         const char*,const char*),void*);
104185  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
104186  char * (*snprintf)(int,char*,const char*,...);
104187  int  (*step)(sqlite3_stmt*);
104188  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
104189                                char const**,char const**,int*,int*,int*);
104190  void  (*thread_cleanup)(void);
104191  int  (*total_changes)(sqlite3*);
104192  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
104193  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
104194  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
104195                                         sqlite_int64),void*);
104196  void * (*user_data)(sqlite3_context*);
104197  const void * (*value_blob)(sqlite3_value*);
104198  int  (*value_bytes)(sqlite3_value*);
104199  int  (*value_bytes16)(sqlite3_value*);
104200  double  (*value_double)(sqlite3_value*);
104201  int  (*value_int)(sqlite3_value*);
104202  sqlite_int64  (*value_int64)(sqlite3_value*);
104203  int  (*value_numeric_type)(sqlite3_value*);
104204  const unsigned char * (*value_text)(sqlite3_value*);
104205  const void * (*value_text16)(sqlite3_value*);
104206  const void * (*value_text16be)(sqlite3_value*);
104207  const void * (*value_text16le)(sqlite3_value*);
104208  int  (*value_type)(sqlite3_value*);
104209  char *(*vmprintf)(const char*,va_list);
104210  /* Added ??? */
104211  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
104212  /* Added by 3.3.13 */
104213  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
104214  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
104215  int (*clear_bindings)(sqlite3_stmt*);
104216  /* Added by 3.4.1 */
104217  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
104218                          void (*xDestroy)(void *));
104219  /* Added by 3.5.0 */
104220  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
104221  int (*blob_bytes)(sqlite3_blob*);
104222  int (*blob_close)(sqlite3_blob*);
104223  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
104224                   int,sqlite3_blob**);
104225  int (*blob_read)(sqlite3_blob*,void*,int,int);
104226  int (*blob_write)(sqlite3_blob*,const void*,int,int);
104227  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
104228                             int(*)(void*,int,const void*,int,const void*),
104229                             void(*)(void*));
104230  int (*file_control)(sqlite3*,const char*,int,void*);
104231  sqlite3_int64 (*memory_highwater)(int);
104232  sqlite3_int64 (*memory_used)(void);
104233  sqlite3_mutex *(*mutex_alloc)(int);
104234  void (*mutex_enter)(sqlite3_mutex*);
104235  void (*mutex_free)(sqlite3_mutex*);
104236  void (*mutex_leave)(sqlite3_mutex*);
104237  int (*mutex_try)(sqlite3_mutex*);
104238  int (*open_v2)(const char*,sqlite3**,int,const char*);
104239  int (*release_memory)(int);
104240  void (*result_error_nomem)(sqlite3_context*);
104241  void (*result_error_toobig)(sqlite3_context*);
104242  int (*sleep)(int);
104243  void (*soft_heap_limit)(int);
104244  sqlite3_vfs *(*vfs_find)(const char*);
104245  int (*vfs_register)(sqlite3_vfs*,int);
104246  int (*vfs_unregister)(sqlite3_vfs*);
104247  int (*xthreadsafe)(void);
104248  void (*result_zeroblob)(sqlite3_context*,int);
104249  void (*result_error_code)(sqlite3_context*,int);
104250  int (*test_control)(int, ...);
104251  void (*randomness)(int,void*);
104252  sqlite3 *(*context_db_handle)(sqlite3_context*);
104253  int (*extended_result_codes)(sqlite3*,int);
104254  int (*limit)(sqlite3*,int,int);
104255  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
104256  const char *(*sql)(sqlite3_stmt*);
104257  int (*status)(int,int*,int*,int);
104258  int (*backup_finish)(sqlite3_backup*);
104259  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
104260  int (*backup_pagecount)(sqlite3_backup*);
104261  int (*backup_remaining)(sqlite3_backup*);
104262  int (*backup_step)(sqlite3_backup*,int);
104263  const char *(*compileoption_get)(int);
104264  int (*compileoption_used)(const char*);
104265  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
104266                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104267                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104268                            void (*xFinal)(sqlite3_context*),
104269                            void(*xDestroy)(void*));
104270  int (*db_config)(sqlite3*,int,...);
104271  sqlite3_mutex *(*db_mutex)(sqlite3*);
104272  int (*db_status)(sqlite3*,int,int*,int*,int);
104273  int (*extended_errcode)(sqlite3*);
104274  void (*log)(int,const char*,...);
104275  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
104276  const char *(*sourceid)(void);
104277  int (*stmt_status)(sqlite3_stmt*,int,int);
104278  int (*strnicmp)(const char*,const char*,int);
104279  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
104280  int (*wal_autocheckpoint)(sqlite3*,int);
104281  int (*wal_checkpoint)(sqlite3*,const char*);
104282  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
104283  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
104284  int (*vtab_config)(sqlite3*,int op,...);
104285  int (*vtab_on_conflict)(sqlite3*);
104286  /* Version 3.7.16 and later */
104287  int (*close_v2)(sqlite3*);
104288  const char *(*db_filename)(sqlite3*,const char*);
104289  int (*db_readonly)(sqlite3*,const char*);
104290  int (*db_release_memory)(sqlite3*);
104291  const char *(*errstr)(int);
104292  int (*stmt_busy)(sqlite3_stmt*);
104293  int (*stmt_readonly)(sqlite3_stmt*);
104294  int (*stricmp)(const char*,const char*);
104295  int (*uri_boolean)(const char*,const char*,int);
104296  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
104297  const char *(*uri_parameter)(const char*,const char*);
104298  char *(*vsnprintf)(int,char*,const char*,va_list);
104299  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
104300  /* Version 3.8.7 and later */
104301  int (*auto_extension)(void(*)(void));
104302  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
104303                     void(*)(void*));
104304  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
104305                      void(*)(void*),unsigned char);
104306  int (*cancel_auto_extension)(void(*)(void));
104307  int (*load_extension)(sqlite3*,const char*,const char*,char**);
104308  void *(*malloc64)(sqlite3_uint64);
104309  sqlite3_uint64 (*msize)(void*);
104310  void *(*realloc64)(void*,sqlite3_uint64);
104311  void (*reset_auto_extension)(void);
104312  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
104313                        void(*)(void*));
104314  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
104315                         void(*)(void*), unsigned char);
104316  int (*strglob)(const char*,const char*);
104317  /* Version 3.8.11 and later */
104318  sqlite3_value *(*value_dup)(const sqlite3_value*);
104319  void (*value_free)(sqlite3_value*);
104320  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
104321  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
104322  /* Version 3.9.0 and later */
104323  unsigned int (*value_subtype)(sqlite3_value*);
104324  void (*result_subtype)(sqlite3_context*,unsigned int);
104325};
104326
104327/*
104328** The following macros redefine the API routines so that they are
104329** redirected through the global sqlite3_api structure.
104330**
104331** This header file is also used by the loadext.c source file
104332** (part of the main SQLite library - not an extension) so that
104333** it can get access to the sqlite3_api_routines structure
104334** definition.  But the main library does not want to redefine
104335** the API.  So the redefinition macros are only valid if the
104336** SQLITE_CORE macros is undefined.
104337*/
104338#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
104339#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
104340#ifndef SQLITE_OMIT_DEPRECATED
104341#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
104342#endif
104343#define sqlite3_bind_blob              sqlite3_api->bind_blob
104344#define sqlite3_bind_double            sqlite3_api->bind_double
104345#define sqlite3_bind_int               sqlite3_api->bind_int
104346#define sqlite3_bind_int64             sqlite3_api->bind_int64
104347#define sqlite3_bind_null              sqlite3_api->bind_null
104348#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
104349#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
104350#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
104351#define sqlite3_bind_text              sqlite3_api->bind_text
104352#define sqlite3_bind_text16            sqlite3_api->bind_text16
104353#define sqlite3_bind_value             sqlite3_api->bind_value
104354#define sqlite3_busy_handler           sqlite3_api->busy_handler
104355#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
104356#define sqlite3_changes                sqlite3_api->changes
104357#define sqlite3_close                  sqlite3_api->close
104358#define sqlite3_collation_needed       sqlite3_api->collation_needed
104359#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
104360#define sqlite3_column_blob            sqlite3_api->column_blob
104361#define sqlite3_column_bytes           sqlite3_api->column_bytes
104362#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
104363#define sqlite3_column_count           sqlite3_api->column_count
104364#define sqlite3_column_database_name   sqlite3_api->column_database_name
104365#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
104366#define sqlite3_column_decltype        sqlite3_api->column_decltype
104367#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
104368#define sqlite3_column_double          sqlite3_api->column_double
104369#define sqlite3_column_int             sqlite3_api->column_int
104370#define sqlite3_column_int64           sqlite3_api->column_int64
104371#define sqlite3_column_name            sqlite3_api->column_name
104372#define sqlite3_column_name16          sqlite3_api->column_name16
104373#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
104374#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
104375#define sqlite3_column_table_name      sqlite3_api->column_table_name
104376#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
104377#define sqlite3_column_text            sqlite3_api->column_text
104378#define sqlite3_column_text16          sqlite3_api->column_text16
104379#define sqlite3_column_type            sqlite3_api->column_type
104380#define sqlite3_column_value           sqlite3_api->column_value
104381#define sqlite3_commit_hook            sqlite3_api->commit_hook
104382#define sqlite3_complete               sqlite3_api->complete
104383#define sqlite3_complete16             sqlite3_api->complete16
104384#define sqlite3_create_collation       sqlite3_api->create_collation
104385#define sqlite3_create_collation16     sqlite3_api->create_collation16
104386#define sqlite3_create_function        sqlite3_api->create_function
104387#define sqlite3_create_function16      sqlite3_api->create_function16
104388#define sqlite3_create_module          sqlite3_api->create_module
104389#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
104390#define sqlite3_data_count             sqlite3_api->data_count
104391#define sqlite3_db_handle              sqlite3_api->db_handle
104392#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
104393#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
104394#define sqlite3_errcode                sqlite3_api->errcode
104395#define sqlite3_errmsg                 sqlite3_api->errmsg
104396#define sqlite3_errmsg16               sqlite3_api->errmsg16
104397#define sqlite3_exec                   sqlite3_api->exec
104398#ifndef SQLITE_OMIT_DEPRECATED
104399#define sqlite3_expired                sqlite3_api->expired
104400#endif
104401#define sqlite3_finalize               sqlite3_api->finalize
104402#define sqlite3_free                   sqlite3_api->free
104403#define sqlite3_free_table             sqlite3_api->free_table
104404#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
104405#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
104406#define sqlite3_get_table              sqlite3_api->get_table
104407#ifndef SQLITE_OMIT_DEPRECATED
104408#define sqlite3_global_recover         sqlite3_api->global_recover
104409#endif
104410#define sqlite3_interrupt              sqlite3_api->interruptx
104411#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
104412#define sqlite3_libversion             sqlite3_api->libversion
104413#define sqlite3_libversion_number      sqlite3_api->libversion_number
104414#define sqlite3_malloc                 sqlite3_api->malloc
104415#define sqlite3_mprintf                sqlite3_api->mprintf
104416#define sqlite3_open                   sqlite3_api->open
104417#define sqlite3_open16                 sqlite3_api->open16
104418#define sqlite3_prepare                sqlite3_api->prepare
104419#define sqlite3_prepare16              sqlite3_api->prepare16
104420#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
104421#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
104422#define sqlite3_profile                sqlite3_api->profile
104423#define sqlite3_progress_handler       sqlite3_api->progress_handler
104424#define sqlite3_realloc                sqlite3_api->realloc
104425#define sqlite3_reset                  sqlite3_api->reset
104426#define sqlite3_result_blob            sqlite3_api->result_blob
104427#define sqlite3_result_double          sqlite3_api->result_double
104428#define sqlite3_result_error           sqlite3_api->result_error
104429#define sqlite3_result_error16         sqlite3_api->result_error16
104430#define sqlite3_result_int             sqlite3_api->result_int
104431#define sqlite3_result_int64           sqlite3_api->result_int64
104432#define sqlite3_result_null            sqlite3_api->result_null
104433#define sqlite3_result_text            sqlite3_api->result_text
104434#define sqlite3_result_text16          sqlite3_api->result_text16
104435#define sqlite3_result_text16be        sqlite3_api->result_text16be
104436#define sqlite3_result_text16le        sqlite3_api->result_text16le
104437#define sqlite3_result_value           sqlite3_api->result_value
104438#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
104439#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
104440#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
104441#define sqlite3_snprintf               sqlite3_api->snprintf
104442#define sqlite3_step                   sqlite3_api->step
104443#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
104444#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
104445#define sqlite3_total_changes          sqlite3_api->total_changes
104446#define sqlite3_trace                  sqlite3_api->trace
104447#ifndef SQLITE_OMIT_DEPRECATED
104448#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
104449#endif
104450#define sqlite3_update_hook            sqlite3_api->update_hook
104451#define sqlite3_user_data              sqlite3_api->user_data
104452#define sqlite3_value_blob             sqlite3_api->value_blob
104453#define sqlite3_value_bytes            sqlite3_api->value_bytes
104454#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
104455#define sqlite3_value_double           sqlite3_api->value_double
104456#define sqlite3_value_int              sqlite3_api->value_int
104457#define sqlite3_value_int64            sqlite3_api->value_int64
104458#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
104459#define sqlite3_value_text             sqlite3_api->value_text
104460#define sqlite3_value_text16           sqlite3_api->value_text16
104461#define sqlite3_value_text16be         sqlite3_api->value_text16be
104462#define sqlite3_value_text16le         sqlite3_api->value_text16le
104463#define sqlite3_value_type             sqlite3_api->value_type
104464#define sqlite3_vmprintf               sqlite3_api->vmprintf
104465#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
104466#define sqlite3_overload_function      sqlite3_api->overload_function
104467#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
104468#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
104469#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
104470#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
104471#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
104472#define sqlite3_blob_close             sqlite3_api->blob_close
104473#define sqlite3_blob_open              sqlite3_api->blob_open
104474#define sqlite3_blob_read              sqlite3_api->blob_read
104475#define sqlite3_blob_write             sqlite3_api->blob_write
104476#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
104477#define sqlite3_file_control           sqlite3_api->file_control
104478#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
104479#define sqlite3_memory_used            sqlite3_api->memory_used
104480#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
104481#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
104482#define sqlite3_mutex_free             sqlite3_api->mutex_free
104483#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
104484#define sqlite3_mutex_try              sqlite3_api->mutex_try
104485#define sqlite3_open_v2                sqlite3_api->open_v2
104486#define sqlite3_release_memory         sqlite3_api->release_memory
104487#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
104488#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
104489#define sqlite3_sleep                  sqlite3_api->sleep
104490#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
104491#define sqlite3_vfs_find               sqlite3_api->vfs_find
104492#define sqlite3_vfs_register           sqlite3_api->vfs_register
104493#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
104494#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
104495#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
104496#define sqlite3_result_error_code      sqlite3_api->result_error_code
104497#define sqlite3_test_control           sqlite3_api->test_control
104498#define sqlite3_randomness             sqlite3_api->randomness
104499#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
104500#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
104501#define sqlite3_limit                  sqlite3_api->limit
104502#define sqlite3_next_stmt              sqlite3_api->next_stmt
104503#define sqlite3_sql                    sqlite3_api->sql
104504#define sqlite3_status                 sqlite3_api->status
104505#define sqlite3_backup_finish          sqlite3_api->backup_finish
104506#define sqlite3_backup_init            sqlite3_api->backup_init
104507#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
104508#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
104509#define sqlite3_backup_step            sqlite3_api->backup_step
104510#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
104511#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
104512#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
104513#define sqlite3_db_config              sqlite3_api->db_config
104514#define sqlite3_db_mutex               sqlite3_api->db_mutex
104515#define sqlite3_db_status              sqlite3_api->db_status
104516#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
104517#define sqlite3_log                    sqlite3_api->log
104518#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
104519#define sqlite3_sourceid               sqlite3_api->sourceid
104520#define sqlite3_stmt_status            sqlite3_api->stmt_status
104521#define sqlite3_strnicmp               sqlite3_api->strnicmp
104522#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
104523#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
104524#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
104525#define sqlite3_wal_hook               sqlite3_api->wal_hook
104526#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
104527#define sqlite3_vtab_config            sqlite3_api->vtab_config
104528#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
104529/* Version 3.7.16 and later */
104530#define sqlite3_close_v2               sqlite3_api->close_v2
104531#define sqlite3_db_filename            sqlite3_api->db_filename
104532#define sqlite3_db_readonly            sqlite3_api->db_readonly
104533#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
104534#define sqlite3_errstr                 sqlite3_api->errstr
104535#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
104536#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
104537#define sqlite3_stricmp                sqlite3_api->stricmp
104538#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
104539#define sqlite3_uri_int64              sqlite3_api->uri_int64
104540#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
104541#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
104542#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
104543/* Version 3.8.7 and later */
104544#define sqlite3_auto_extension         sqlite3_api->auto_extension
104545#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
104546#define sqlite3_bind_text64            sqlite3_api->bind_text64
104547#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
104548#define sqlite3_load_extension         sqlite3_api->load_extension
104549#define sqlite3_malloc64               sqlite3_api->malloc64
104550#define sqlite3_msize                  sqlite3_api->msize
104551#define sqlite3_realloc64              sqlite3_api->realloc64
104552#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
104553#define sqlite3_result_blob64          sqlite3_api->result_blob64
104554#define sqlite3_result_text64          sqlite3_api->result_text64
104555#define sqlite3_strglob                sqlite3_api->strglob
104556/* Version 3.8.11 and later */
104557#define sqlite3_value_dup              sqlite3_api->value_dup
104558#define sqlite3_value_free             sqlite3_api->value_free
104559#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
104560#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
104561/* Version 3.9.0 and later */
104562#define sqlite3_value_subtype          sqlite3_api->value_subtype
104563#define sqlite3_result_subtype         sqlite3_api->result_subtype
104564#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
104565
104566#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
104567  /* This case when the file really is being compiled as a loadable
104568  ** extension */
104569# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
104570# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
104571# define SQLITE_EXTENSION_INIT3     \
104572    extern const sqlite3_api_routines *sqlite3_api;
104573#else
104574  /* This case when the file is being statically linked into the
104575  ** application */
104576# define SQLITE_EXTENSION_INIT1     /*no-op*/
104577# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
104578# define SQLITE_EXTENSION_INIT3     /*no-op*/
104579#endif
104580
104581#endif /* _SQLITE3EXT_H_ */
104582
104583/************** End of sqlite3ext.h ******************************************/
104584/************** Continuing where we left off in loadext.c ********************/
104585/* #include "sqliteInt.h" */
104586/* #include <string.h> */
104587
104588#ifndef SQLITE_OMIT_LOAD_EXTENSION
104589
104590/*
104591** Some API routines are omitted when various features are
104592** excluded from a build of SQLite.  Substitute a NULL pointer
104593** for any missing APIs.
104594*/
104595#ifndef SQLITE_ENABLE_COLUMN_METADATA
104596# define sqlite3_column_database_name   0
104597# define sqlite3_column_database_name16 0
104598# define sqlite3_column_table_name      0
104599# define sqlite3_column_table_name16    0
104600# define sqlite3_column_origin_name     0
104601# define sqlite3_column_origin_name16   0
104602#endif
104603
104604#ifdef SQLITE_OMIT_AUTHORIZATION
104605# define sqlite3_set_authorizer         0
104606#endif
104607
104608#ifdef SQLITE_OMIT_UTF16
104609# define sqlite3_bind_text16            0
104610# define sqlite3_collation_needed16     0
104611# define sqlite3_column_decltype16      0
104612# define sqlite3_column_name16          0
104613# define sqlite3_column_text16          0
104614# define sqlite3_complete16             0
104615# define sqlite3_create_collation16     0
104616# define sqlite3_create_function16      0
104617# define sqlite3_errmsg16               0
104618# define sqlite3_open16                 0
104619# define sqlite3_prepare16              0
104620# define sqlite3_prepare16_v2           0
104621# define sqlite3_result_error16         0
104622# define sqlite3_result_text16          0
104623# define sqlite3_result_text16be        0
104624# define sqlite3_result_text16le        0
104625# define sqlite3_value_text16           0
104626# define sqlite3_value_text16be         0
104627# define sqlite3_value_text16le         0
104628# define sqlite3_column_database_name16 0
104629# define sqlite3_column_table_name16    0
104630# define sqlite3_column_origin_name16   0
104631#endif
104632
104633#ifdef SQLITE_OMIT_COMPLETE
104634# define sqlite3_complete 0
104635# define sqlite3_complete16 0
104636#endif
104637
104638#ifdef SQLITE_OMIT_DECLTYPE
104639# define sqlite3_column_decltype16      0
104640# define sqlite3_column_decltype        0
104641#endif
104642
104643#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
104644# define sqlite3_progress_handler 0
104645#endif
104646
104647#ifdef SQLITE_OMIT_VIRTUALTABLE
104648# define sqlite3_create_module 0
104649# define sqlite3_create_module_v2 0
104650# define sqlite3_declare_vtab 0
104651# define sqlite3_vtab_config 0
104652# define sqlite3_vtab_on_conflict 0
104653#endif
104654
104655#ifdef SQLITE_OMIT_SHARED_CACHE
104656# define sqlite3_enable_shared_cache 0
104657#endif
104658
104659#ifdef SQLITE_OMIT_TRACE
104660# define sqlite3_profile       0
104661# define sqlite3_trace         0
104662#endif
104663
104664#ifdef SQLITE_OMIT_GET_TABLE
104665# define sqlite3_free_table    0
104666# define sqlite3_get_table     0
104667#endif
104668
104669#ifdef SQLITE_OMIT_INCRBLOB
104670#define sqlite3_bind_zeroblob  0
104671#define sqlite3_blob_bytes     0
104672#define sqlite3_blob_close     0
104673#define sqlite3_blob_open      0
104674#define sqlite3_blob_read      0
104675#define sqlite3_blob_write     0
104676#define sqlite3_blob_reopen    0
104677#endif
104678
104679/*
104680** The following structure contains pointers to all SQLite API routines.
104681** A pointer to this structure is passed into extensions when they are
104682** loaded so that the extension can make calls back into the SQLite
104683** library.
104684**
104685** When adding new APIs, add them to the bottom of this structure
104686** in order to preserve backwards compatibility.
104687**
104688** Extensions that use newer APIs should first call the
104689** sqlite3_libversion_number() to make sure that the API they
104690** intend to use is supported by the library.  Extensions should
104691** also check to make sure that the pointer to the function is
104692** not NULL before calling it.
104693*/
104694static const sqlite3_api_routines sqlite3Apis = {
104695  sqlite3_aggregate_context,
104696#ifndef SQLITE_OMIT_DEPRECATED
104697  sqlite3_aggregate_count,
104698#else
104699  0,
104700#endif
104701  sqlite3_bind_blob,
104702  sqlite3_bind_double,
104703  sqlite3_bind_int,
104704  sqlite3_bind_int64,
104705  sqlite3_bind_null,
104706  sqlite3_bind_parameter_count,
104707  sqlite3_bind_parameter_index,
104708  sqlite3_bind_parameter_name,
104709  sqlite3_bind_text,
104710  sqlite3_bind_text16,
104711  sqlite3_bind_value,
104712  sqlite3_busy_handler,
104713  sqlite3_busy_timeout,
104714  sqlite3_changes,
104715  sqlite3_close,
104716  sqlite3_collation_needed,
104717  sqlite3_collation_needed16,
104718  sqlite3_column_blob,
104719  sqlite3_column_bytes,
104720  sqlite3_column_bytes16,
104721  sqlite3_column_count,
104722  sqlite3_column_database_name,
104723  sqlite3_column_database_name16,
104724  sqlite3_column_decltype,
104725  sqlite3_column_decltype16,
104726  sqlite3_column_double,
104727  sqlite3_column_int,
104728  sqlite3_column_int64,
104729  sqlite3_column_name,
104730  sqlite3_column_name16,
104731  sqlite3_column_origin_name,
104732  sqlite3_column_origin_name16,
104733  sqlite3_column_table_name,
104734  sqlite3_column_table_name16,
104735  sqlite3_column_text,
104736  sqlite3_column_text16,
104737  sqlite3_column_type,
104738  sqlite3_column_value,
104739  sqlite3_commit_hook,
104740  sqlite3_complete,
104741  sqlite3_complete16,
104742  sqlite3_create_collation,
104743  sqlite3_create_collation16,
104744  sqlite3_create_function,
104745  sqlite3_create_function16,
104746  sqlite3_create_module,
104747  sqlite3_data_count,
104748  sqlite3_db_handle,
104749  sqlite3_declare_vtab,
104750  sqlite3_enable_shared_cache,
104751  sqlite3_errcode,
104752  sqlite3_errmsg,
104753  sqlite3_errmsg16,
104754  sqlite3_exec,
104755#ifndef SQLITE_OMIT_DEPRECATED
104756  sqlite3_expired,
104757#else
104758  0,
104759#endif
104760  sqlite3_finalize,
104761  sqlite3_free,
104762  sqlite3_free_table,
104763  sqlite3_get_autocommit,
104764  sqlite3_get_auxdata,
104765  sqlite3_get_table,
104766  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
104767  sqlite3_interrupt,
104768  sqlite3_last_insert_rowid,
104769  sqlite3_libversion,
104770  sqlite3_libversion_number,
104771  sqlite3_malloc,
104772  sqlite3_mprintf,
104773  sqlite3_open,
104774  sqlite3_open16,
104775  sqlite3_prepare,
104776  sqlite3_prepare16,
104777  sqlite3_profile,
104778  sqlite3_progress_handler,
104779  sqlite3_realloc,
104780  sqlite3_reset,
104781  sqlite3_result_blob,
104782  sqlite3_result_double,
104783  sqlite3_result_error,
104784  sqlite3_result_error16,
104785  sqlite3_result_int,
104786  sqlite3_result_int64,
104787  sqlite3_result_null,
104788  sqlite3_result_text,
104789  sqlite3_result_text16,
104790  sqlite3_result_text16be,
104791  sqlite3_result_text16le,
104792  sqlite3_result_value,
104793  sqlite3_rollback_hook,
104794  sqlite3_set_authorizer,
104795  sqlite3_set_auxdata,
104796  sqlite3_snprintf,
104797  sqlite3_step,
104798  sqlite3_table_column_metadata,
104799#ifndef SQLITE_OMIT_DEPRECATED
104800  sqlite3_thread_cleanup,
104801#else
104802  0,
104803#endif
104804  sqlite3_total_changes,
104805  sqlite3_trace,
104806#ifndef SQLITE_OMIT_DEPRECATED
104807  sqlite3_transfer_bindings,
104808#else
104809  0,
104810#endif
104811  sqlite3_update_hook,
104812  sqlite3_user_data,
104813  sqlite3_value_blob,
104814  sqlite3_value_bytes,
104815  sqlite3_value_bytes16,
104816  sqlite3_value_double,
104817  sqlite3_value_int,
104818  sqlite3_value_int64,
104819  sqlite3_value_numeric_type,
104820  sqlite3_value_text,
104821  sqlite3_value_text16,
104822  sqlite3_value_text16be,
104823  sqlite3_value_text16le,
104824  sqlite3_value_type,
104825  sqlite3_vmprintf,
104826  /*
104827  ** The original API set ends here.  All extensions can call any
104828  ** of the APIs above provided that the pointer is not NULL.  But
104829  ** before calling APIs that follow, extension should check the
104830  ** sqlite3_libversion_number() to make sure they are dealing with
104831  ** a library that is new enough to support that API.
104832  *************************************************************************
104833  */
104834  sqlite3_overload_function,
104835
104836  /*
104837  ** Added after 3.3.13
104838  */
104839  sqlite3_prepare_v2,
104840  sqlite3_prepare16_v2,
104841  sqlite3_clear_bindings,
104842
104843  /*
104844  ** Added for 3.4.1
104845  */
104846  sqlite3_create_module_v2,
104847
104848  /*
104849  ** Added for 3.5.0
104850  */
104851  sqlite3_bind_zeroblob,
104852  sqlite3_blob_bytes,
104853  sqlite3_blob_close,
104854  sqlite3_blob_open,
104855  sqlite3_blob_read,
104856  sqlite3_blob_write,
104857  sqlite3_create_collation_v2,
104858  sqlite3_file_control,
104859  sqlite3_memory_highwater,
104860  sqlite3_memory_used,
104861#ifdef SQLITE_MUTEX_OMIT
104862  0,
104863  0,
104864  0,
104865  0,
104866  0,
104867#else
104868  sqlite3_mutex_alloc,
104869  sqlite3_mutex_enter,
104870  sqlite3_mutex_free,
104871  sqlite3_mutex_leave,
104872  sqlite3_mutex_try,
104873#endif
104874  sqlite3_open_v2,
104875  sqlite3_release_memory,
104876  sqlite3_result_error_nomem,
104877  sqlite3_result_error_toobig,
104878  sqlite3_sleep,
104879  sqlite3_soft_heap_limit,
104880  sqlite3_vfs_find,
104881  sqlite3_vfs_register,
104882  sqlite3_vfs_unregister,
104883
104884  /*
104885  ** Added for 3.5.8
104886  */
104887  sqlite3_threadsafe,
104888  sqlite3_result_zeroblob,
104889  sqlite3_result_error_code,
104890  sqlite3_test_control,
104891  sqlite3_randomness,
104892  sqlite3_context_db_handle,
104893
104894  /*
104895  ** Added for 3.6.0
104896  */
104897  sqlite3_extended_result_codes,
104898  sqlite3_limit,
104899  sqlite3_next_stmt,
104900  sqlite3_sql,
104901  sqlite3_status,
104902
104903  /*
104904  ** Added for 3.7.4
104905  */
104906  sqlite3_backup_finish,
104907  sqlite3_backup_init,
104908  sqlite3_backup_pagecount,
104909  sqlite3_backup_remaining,
104910  sqlite3_backup_step,
104911#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104912  sqlite3_compileoption_get,
104913  sqlite3_compileoption_used,
104914#else
104915  0,
104916  0,
104917#endif
104918  sqlite3_create_function_v2,
104919  sqlite3_db_config,
104920  sqlite3_db_mutex,
104921  sqlite3_db_status,
104922  sqlite3_extended_errcode,
104923  sqlite3_log,
104924  sqlite3_soft_heap_limit64,
104925  sqlite3_sourceid,
104926  sqlite3_stmt_status,
104927  sqlite3_strnicmp,
104928#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
104929  sqlite3_unlock_notify,
104930#else
104931  0,
104932#endif
104933#ifndef SQLITE_OMIT_WAL
104934  sqlite3_wal_autocheckpoint,
104935  sqlite3_wal_checkpoint,
104936  sqlite3_wal_hook,
104937#else
104938  0,
104939  0,
104940  0,
104941#endif
104942  sqlite3_blob_reopen,
104943  sqlite3_vtab_config,
104944  sqlite3_vtab_on_conflict,
104945  sqlite3_close_v2,
104946  sqlite3_db_filename,
104947  sqlite3_db_readonly,
104948  sqlite3_db_release_memory,
104949  sqlite3_errstr,
104950  sqlite3_stmt_busy,
104951  sqlite3_stmt_readonly,
104952  sqlite3_stricmp,
104953  sqlite3_uri_boolean,
104954  sqlite3_uri_int64,
104955  sqlite3_uri_parameter,
104956  sqlite3_vsnprintf,
104957  sqlite3_wal_checkpoint_v2,
104958  /* Version 3.8.7 and later */
104959  sqlite3_auto_extension,
104960  sqlite3_bind_blob64,
104961  sqlite3_bind_text64,
104962  sqlite3_cancel_auto_extension,
104963  sqlite3_load_extension,
104964  sqlite3_malloc64,
104965  sqlite3_msize,
104966  sqlite3_realloc64,
104967  sqlite3_reset_auto_extension,
104968  sqlite3_result_blob64,
104969  sqlite3_result_text64,
104970  sqlite3_strglob,
104971  /* Version 3.8.11 and later */
104972  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
104973  sqlite3_value_free,
104974  sqlite3_result_zeroblob64,
104975  sqlite3_bind_zeroblob64,
104976  /* Version 3.9.0 and later */
104977  sqlite3_value_subtype,
104978  sqlite3_result_subtype
104979};
104980
104981/*
104982** Attempt to load an SQLite extension library contained in the file
104983** zFile.  The entry point is zProc.  zProc may be 0 in which case a
104984** default entry point name (sqlite3_extension_init) is used.  Use
104985** of the default name is recommended.
104986**
104987** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
104988**
104989** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
104990** error message text.  The calling function should free this memory
104991** by calling sqlite3DbFree(db, ).
104992*/
104993static int sqlite3LoadExtension(
104994  sqlite3 *db,          /* Load the extension into this database connection */
104995  const char *zFile,    /* Name of the shared library containing extension */
104996  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
104997  char **pzErrMsg       /* Put error message here if not 0 */
104998){
104999  sqlite3_vfs *pVfs = db->pVfs;
105000  void *handle;
105001  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
105002  char *zErrmsg = 0;
105003  const char *zEntry;
105004  char *zAltEntry = 0;
105005  void **aHandle;
105006  u64 nMsg = 300 + sqlite3Strlen30(zFile);
105007  int ii;
105008
105009  /* Shared library endings to try if zFile cannot be loaded as written */
105010  static const char *azEndings[] = {
105011#if SQLITE_OS_WIN
105012     "dll"
105013#elif defined(__APPLE__)
105014     "dylib"
105015#else
105016     "so"
105017#endif
105018  };
105019
105020
105021  if( pzErrMsg ) *pzErrMsg = 0;
105022
105023  /* Ticket #1863.  To avoid a creating security problems for older
105024  ** applications that relink against newer versions of SQLite, the
105025  ** ability to run load_extension is turned off by default.  One
105026  ** must call sqlite3_enable_load_extension() to turn on extension
105027  ** loading.  Otherwise you get the following error.
105028  */
105029  if( (db->flags & SQLITE_LoadExtension)==0 ){
105030    if( pzErrMsg ){
105031      *pzErrMsg = sqlite3_mprintf("not authorized");
105032    }
105033    return SQLITE_ERROR;
105034  }
105035
105036  zEntry = zProc ? zProc : "sqlite3_extension_init";
105037
105038  handle = sqlite3OsDlOpen(pVfs, zFile);
105039#if SQLITE_OS_UNIX || SQLITE_OS_WIN
105040  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
105041    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
105042    if( zAltFile==0 ) return SQLITE_NOMEM;
105043    handle = sqlite3OsDlOpen(pVfs, zAltFile);
105044    sqlite3_free(zAltFile);
105045  }
105046#endif
105047  if( handle==0 ){
105048    if( pzErrMsg ){
105049      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
105050      if( zErrmsg ){
105051        sqlite3_snprintf(nMsg, zErrmsg,
105052            "unable to open shared library [%s]", zFile);
105053        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
105054      }
105055    }
105056    return SQLITE_ERROR;
105057  }
105058  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105059                   sqlite3OsDlSym(pVfs, handle, zEntry);
105060
105061  /* If no entry point was specified and the default legacy
105062  ** entry point name "sqlite3_extension_init" was not found, then
105063  ** construct an entry point name "sqlite3_X_init" where the X is
105064  ** replaced by the lowercase value of every ASCII alphabetic
105065  ** character in the filename after the last "/" upto the first ".",
105066  ** and eliding the first three characters if they are "lib".
105067  ** Examples:
105068  **
105069  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
105070  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
105071  */
105072  if( xInit==0 && zProc==0 ){
105073    int iFile, iEntry, c;
105074    int ncFile = sqlite3Strlen30(zFile);
105075    zAltEntry = sqlite3_malloc64(ncFile+30);
105076    if( zAltEntry==0 ){
105077      sqlite3OsDlClose(pVfs, handle);
105078      return SQLITE_NOMEM;
105079    }
105080    memcpy(zAltEntry, "sqlite3_", 8);
105081    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
105082    iFile++;
105083    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
105084    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
105085      if( sqlite3Isalpha(c) ){
105086        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
105087      }
105088    }
105089    memcpy(zAltEntry+iEntry, "_init", 6);
105090    zEntry = zAltEntry;
105091    xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105092                     sqlite3OsDlSym(pVfs, handle, zEntry);
105093  }
105094  if( xInit==0 ){
105095    if( pzErrMsg ){
105096      nMsg += sqlite3Strlen30(zEntry);
105097      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
105098      if( zErrmsg ){
105099        sqlite3_snprintf(nMsg, zErrmsg,
105100            "no entry point [%s] in shared library [%s]", zEntry, zFile);
105101        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
105102      }
105103    }
105104    sqlite3OsDlClose(pVfs, handle);
105105    sqlite3_free(zAltEntry);
105106    return SQLITE_ERROR;
105107  }
105108  sqlite3_free(zAltEntry);
105109  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
105110    if( pzErrMsg ){
105111      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
105112    }
105113    sqlite3_free(zErrmsg);
105114    sqlite3OsDlClose(pVfs, handle);
105115    return SQLITE_ERROR;
105116  }
105117
105118  /* Append the new shared library handle to the db->aExtension array. */
105119  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
105120  if( aHandle==0 ){
105121    return SQLITE_NOMEM;
105122  }
105123  if( db->nExtension>0 ){
105124    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
105125  }
105126  sqlite3DbFree(db, db->aExtension);
105127  db->aExtension = aHandle;
105128
105129  db->aExtension[db->nExtension++] = handle;
105130  return SQLITE_OK;
105131}
105132SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
105133  sqlite3 *db,          /* Load the extension into this database connection */
105134  const char *zFile,    /* Name of the shared library containing extension */
105135  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
105136  char **pzErrMsg       /* Put error message here if not 0 */
105137){
105138  int rc;
105139  sqlite3_mutex_enter(db->mutex);
105140  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
105141  rc = sqlite3ApiExit(db, rc);
105142  sqlite3_mutex_leave(db->mutex);
105143  return rc;
105144}
105145
105146/*
105147** Call this routine when the database connection is closing in order
105148** to clean up loaded extensions
105149*/
105150SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
105151  int i;
105152  assert( sqlite3_mutex_held(db->mutex) );
105153  for(i=0; i<db->nExtension; i++){
105154    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
105155  }
105156  sqlite3DbFree(db, db->aExtension);
105157}
105158
105159/*
105160** Enable or disable extension loading.  Extension loading is disabled by
105161** default so as not to open security holes in older applications.
105162*/
105163SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
105164  sqlite3_mutex_enter(db->mutex);
105165  if( onoff ){
105166    db->flags |= SQLITE_LoadExtension;
105167  }else{
105168    db->flags &= ~SQLITE_LoadExtension;
105169  }
105170  sqlite3_mutex_leave(db->mutex);
105171  return SQLITE_OK;
105172}
105173
105174#endif /* SQLITE_OMIT_LOAD_EXTENSION */
105175
105176/*
105177** The auto-extension code added regardless of whether or not extension
105178** loading is supported.  We need a dummy sqlite3Apis pointer for that
105179** code if regular extension loading is not available.  This is that
105180** dummy pointer.
105181*/
105182#ifdef SQLITE_OMIT_LOAD_EXTENSION
105183static const sqlite3_api_routines sqlite3Apis;
105184#endif
105185
105186
105187/*
105188** The following object holds the list of automatically loaded
105189** extensions.
105190**
105191** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
105192** mutex must be held while accessing this list.
105193*/
105194typedef struct sqlite3AutoExtList sqlite3AutoExtList;
105195static SQLITE_WSD struct sqlite3AutoExtList {
105196  u32 nExt;              /* Number of entries in aExt[] */
105197  void (**aExt)(void);   /* Pointers to the extension init functions */
105198} sqlite3Autoext = { 0, 0 };
105199
105200/* The "wsdAutoext" macro will resolve to the autoextension
105201** state vector.  If writable static data is unsupported on the target,
105202** we have to locate the state vector at run-time.  In the more common
105203** case where writable static data is supported, wsdStat can refer directly
105204** to the "sqlite3Autoext" state vector declared above.
105205*/
105206#ifdef SQLITE_OMIT_WSD
105207# define wsdAutoextInit \
105208  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
105209# define wsdAutoext x[0]
105210#else
105211# define wsdAutoextInit
105212# define wsdAutoext sqlite3Autoext
105213#endif
105214
105215
105216/*
105217** Register a statically linked extension that is automatically
105218** loaded by every new database connection.
105219*/
105220SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
105221  int rc = SQLITE_OK;
105222#ifndef SQLITE_OMIT_AUTOINIT
105223  rc = sqlite3_initialize();
105224  if( rc ){
105225    return rc;
105226  }else
105227#endif
105228  {
105229    u32 i;
105230#if SQLITE_THREADSAFE
105231    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105232#endif
105233    wsdAutoextInit;
105234    sqlite3_mutex_enter(mutex);
105235    for(i=0; i<wsdAutoext.nExt; i++){
105236      if( wsdAutoext.aExt[i]==xInit ) break;
105237    }
105238    if( i==wsdAutoext.nExt ){
105239      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
105240      void (**aNew)(void);
105241      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
105242      if( aNew==0 ){
105243        rc = SQLITE_NOMEM;
105244      }else{
105245        wsdAutoext.aExt = aNew;
105246        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
105247        wsdAutoext.nExt++;
105248      }
105249    }
105250    sqlite3_mutex_leave(mutex);
105251    assert( (rc&0xff)==rc );
105252    return rc;
105253  }
105254}
105255
105256/*
105257** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
105258** set of routines that is invoked for each new database connection, if it
105259** is currently on the list.  If xInit is not on the list, then this
105260** routine is a no-op.
105261**
105262** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
105263** was not on the list.
105264*/
105265SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
105266#if SQLITE_THREADSAFE
105267  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105268#endif
105269  int i;
105270  int n = 0;
105271  wsdAutoextInit;
105272  sqlite3_mutex_enter(mutex);
105273  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
105274    if( wsdAutoext.aExt[i]==xInit ){
105275      wsdAutoext.nExt--;
105276      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
105277      n++;
105278      break;
105279    }
105280  }
105281  sqlite3_mutex_leave(mutex);
105282  return n;
105283}
105284
105285/*
105286** Reset the automatic extension loading mechanism.
105287*/
105288SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
105289#ifndef SQLITE_OMIT_AUTOINIT
105290  if( sqlite3_initialize()==SQLITE_OK )
105291#endif
105292  {
105293#if SQLITE_THREADSAFE
105294    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105295#endif
105296    wsdAutoextInit;
105297    sqlite3_mutex_enter(mutex);
105298    sqlite3_free(wsdAutoext.aExt);
105299    wsdAutoext.aExt = 0;
105300    wsdAutoext.nExt = 0;
105301    sqlite3_mutex_leave(mutex);
105302  }
105303}
105304
105305/*
105306** Load all automatic extensions.
105307**
105308** If anything goes wrong, set an error in the database connection.
105309*/
105310SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
105311  u32 i;
105312  int go = 1;
105313  int rc;
105314  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
105315
105316  wsdAutoextInit;
105317  if( wsdAutoext.nExt==0 ){
105318    /* Common case: early out without every having to acquire a mutex */
105319    return;
105320  }
105321  for(i=0; go; i++){
105322    char *zErrmsg;
105323#if SQLITE_THREADSAFE
105324    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105325#endif
105326    sqlite3_mutex_enter(mutex);
105327    if( i>=wsdAutoext.nExt ){
105328      xInit = 0;
105329      go = 0;
105330    }else{
105331      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105332              wsdAutoext.aExt[i];
105333    }
105334    sqlite3_mutex_leave(mutex);
105335    zErrmsg = 0;
105336    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
105337      sqlite3ErrorWithMsg(db, rc,
105338            "automatic extension loading failed: %s", zErrmsg);
105339      go = 0;
105340    }
105341    sqlite3_free(zErrmsg);
105342  }
105343}
105344
105345/************** End of loadext.c *********************************************/
105346/************** Begin file pragma.c ******************************************/
105347/*
105348** 2003 April 6
105349**
105350** The author disclaims copyright to this source code.  In place of
105351** a legal notice, here is a blessing:
105352**
105353**    May you do good and not evil.
105354**    May you find forgiveness for yourself and forgive others.
105355**    May you share freely, never taking more than you give.
105356**
105357*************************************************************************
105358** This file contains code used to implement the PRAGMA command.
105359*/
105360/* #include "sqliteInt.h" */
105361
105362#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
105363#  if defined(__APPLE__)
105364#    define SQLITE_ENABLE_LOCKING_STYLE 1
105365#  else
105366#    define SQLITE_ENABLE_LOCKING_STYLE 0
105367#  endif
105368#endif
105369
105370/***************************************************************************
105371** The "pragma.h" include file is an automatically generated file that
105372** that includes the PragType_XXXX macro definitions and the aPragmaName[]
105373** object.  This ensures that the aPragmaName[] table is arranged in
105374** lexicographical order to facility a binary search of the pragma name.
105375** Do not edit pragma.h directly.  Edit and rerun the script in at
105376** ../tool/mkpragmatab.tcl. */
105377/************** Include pragma.h in the middle of pragma.c *******************/
105378/************** Begin file pragma.h ******************************************/
105379/* DO NOT EDIT!
105380** This file is automatically generated by the script at
105381** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
105382** that script and rerun it.
105383*/
105384#define PragTyp_HEADER_VALUE                   0
105385#define PragTyp_AUTO_VACUUM                    1
105386#define PragTyp_FLAG                           2
105387#define PragTyp_BUSY_TIMEOUT                   3
105388#define PragTyp_CACHE_SIZE                     4
105389#define PragTyp_CASE_SENSITIVE_LIKE            5
105390#define PragTyp_COLLATION_LIST                 6
105391#define PragTyp_COMPILE_OPTIONS                7
105392#define PragTyp_DATA_STORE_DIRECTORY           8
105393#define PragTyp_DATABASE_LIST                  9
105394#define PragTyp_DEFAULT_CACHE_SIZE            10
105395#define PragTyp_ENCODING                      11
105396#define PragTyp_FOREIGN_KEY_CHECK             12
105397#define PragTyp_FOREIGN_KEY_LIST              13
105398#define PragTyp_INCREMENTAL_VACUUM            14
105399#define PragTyp_INDEX_INFO                    15
105400#define PragTyp_INDEX_LIST                    16
105401#define PragTyp_INTEGRITY_CHECK               17
105402#define PragTyp_JOURNAL_MODE                  18
105403#define PragTyp_JOURNAL_SIZE_LIMIT            19
105404#define PragTyp_LOCK_PROXY_FILE               20
105405#define PragTyp_LOCKING_MODE                  21
105406#define PragTyp_PAGE_COUNT                    22
105407#define PragTyp_MMAP_SIZE                     23
105408#define PragTyp_PAGE_SIZE                     24
105409#define PragTyp_SECURE_DELETE                 25
105410#define PragTyp_SHRINK_MEMORY                 26
105411#define PragTyp_SOFT_HEAP_LIMIT               27
105412#define PragTyp_STATS                         28
105413#define PragTyp_SYNCHRONOUS                   29
105414#define PragTyp_TABLE_INFO                    30
105415#define PragTyp_TEMP_STORE                    31
105416#define PragTyp_TEMP_STORE_DIRECTORY          32
105417#define PragTyp_THREADS                       33
105418#define PragTyp_WAL_AUTOCHECKPOINT            34
105419#define PragTyp_WAL_CHECKPOINT                35
105420#define PragTyp_ACTIVATE_EXTENSIONS           36
105421#define PragTyp_HEXKEY                        37
105422#define PragTyp_KEY                           38
105423#define PragTyp_REKEY                         39
105424#define PragTyp_LOCK_STATUS                   40
105425#define PragTyp_PARSER_TRACE                  41
105426#define PragFlag_NeedSchema           0x01
105427#define PragFlag_ReadOnly             0x02
105428static const struct sPragmaNames {
105429  const char *const zName;  /* Name of pragma */
105430  u8 ePragTyp;              /* PragTyp_XXX value */
105431  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
105432  u32 iArg;                 /* Extra argument */
105433} aPragmaNames[] = {
105434#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
105435  { /* zName:     */ "activate_extensions",
105436    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
105437    /* ePragFlag: */ 0,
105438    /* iArg:      */ 0 },
105439#endif
105440#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105441  { /* zName:     */ "application_id",
105442    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105443    /* ePragFlag: */ 0,
105444    /* iArg:      */ BTREE_APPLICATION_ID },
105445#endif
105446#if !defined(SQLITE_OMIT_AUTOVACUUM)
105447  { /* zName:     */ "auto_vacuum",
105448    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
105449    /* ePragFlag: */ PragFlag_NeedSchema,
105450    /* iArg:      */ 0 },
105451#endif
105452#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105453#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
105454  { /* zName:     */ "automatic_index",
105455    /* ePragTyp:  */ PragTyp_FLAG,
105456    /* ePragFlag: */ 0,
105457    /* iArg:      */ SQLITE_AutoIndex },
105458#endif
105459#endif
105460  { /* zName:     */ "busy_timeout",
105461    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
105462    /* ePragFlag: */ 0,
105463    /* iArg:      */ 0 },
105464#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105465  { /* zName:     */ "cache_size",
105466    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
105467    /* ePragFlag: */ 0,
105468    /* iArg:      */ 0 },
105469#endif
105470#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105471  { /* zName:     */ "cache_spill",
105472    /* ePragTyp:  */ PragTyp_FLAG,
105473    /* ePragFlag: */ 0,
105474    /* iArg:      */ SQLITE_CacheSpill },
105475#endif
105476  { /* zName:     */ "case_sensitive_like",
105477    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
105478    /* ePragFlag: */ 0,
105479    /* iArg:      */ 0 },
105480  { /* zName:     */ "cell_size_check",
105481    /* ePragTyp:  */ PragTyp_FLAG,
105482    /* ePragFlag: */ 0,
105483    /* iArg:      */ SQLITE_CellSizeCk },
105484#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105485  { /* zName:     */ "checkpoint_fullfsync",
105486    /* ePragTyp:  */ PragTyp_FLAG,
105487    /* ePragFlag: */ 0,
105488    /* iArg:      */ SQLITE_CkptFullFSync },
105489#endif
105490#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105491  { /* zName:     */ "collation_list",
105492    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
105493    /* ePragFlag: */ 0,
105494    /* iArg:      */ 0 },
105495#endif
105496#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
105497  { /* zName:     */ "compile_options",
105498    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
105499    /* ePragFlag: */ 0,
105500    /* iArg:      */ 0 },
105501#endif
105502#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105503  { /* zName:     */ "count_changes",
105504    /* ePragTyp:  */ PragTyp_FLAG,
105505    /* ePragFlag: */ 0,
105506    /* iArg:      */ SQLITE_CountRows },
105507#endif
105508#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
105509  { /* zName:     */ "data_store_directory",
105510    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
105511    /* ePragFlag: */ 0,
105512    /* iArg:      */ 0 },
105513#endif
105514#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105515  { /* zName:     */ "data_version",
105516    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105517    /* ePragFlag: */ PragFlag_ReadOnly,
105518    /* iArg:      */ BTREE_DATA_VERSION },
105519#endif
105520#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105521  { /* zName:     */ "database_list",
105522    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
105523    /* ePragFlag: */ PragFlag_NeedSchema,
105524    /* iArg:      */ 0 },
105525#endif
105526#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
105527  { /* zName:     */ "default_cache_size",
105528    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
105529    /* ePragFlag: */ PragFlag_NeedSchema,
105530    /* iArg:      */ 0 },
105531#endif
105532#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105533#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105534  { /* zName:     */ "defer_foreign_keys",
105535    /* ePragTyp:  */ PragTyp_FLAG,
105536    /* ePragFlag: */ 0,
105537    /* iArg:      */ SQLITE_DeferFKs },
105538#endif
105539#endif
105540#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105541  { /* zName:     */ "empty_result_callbacks",
105542    /* ePragTyp:  */ PragTyp_FLAG,
105543    /* ePragFlag: */ 0,
105544    /* iArg:      */ SQLITE_NullCallback },
105545#endif
105546#if !defined(SQLITE_OMIT_UTF16)
105547  { /* zName:     */ "encoding",
105548    /* ePragTyp:  */ PragTyp_ENCODING,
105549    /* ePragFlag: */ 0,
105550    /* iArg:      */ 0 },
105551#endif
105552#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105553  { /* zName:     */ "foreign_key_check",
105554    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
105555    /* ePragFlag: */ PragFlag_NeedSchema,
105556    /* iArg:      */ 0 },
105557#endif
105558#if !defined(SQLITE_OMIT_FOREIGN_KEY)
105559  { /* zName:     */ "foreign_key_list",
105560    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
105561    /* ePragFlag: */ PragFlag_NeedSchema,
105562    /* iArg:      */ 0 },
105563#endif
105564#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105565#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105566  { /* zName:     */ "foreign_keys",
105567    /* ePragTyp:  */ PragTyp_FLAG,
105568    /* ePragFlag: */ 0,
105569    /* iArg:      */ SQLITE_ForeignKeys },
105570#endif
105571#endif
105572#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105573  { /* zName:     */ "freelist_count",
105574    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105575    /* ePragFlag: */ PragFlag_ReadOnly,
105576    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
105577#endif
105578#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105579  { /* zName:     */ "full_column_names",
105580    /* ePragTyp:  */ PragTyp_FLAG,
105581    /* ePragFlag: */ 0,
105582    /* iArg:      */ SQLITE_FullColNames },
105583  { /* zName:     */ "fullfsync",
105584    /* ePragTyp:  */ PragTyp_FLAG,
105585    /* ePragFlag: */ 0,
105586    /* iArg:      */ SQLITE_FullFSync },
105587#endif
105588#if defined(SQLITE_HAS_CODEC)
105589  { /* zName:     */ "hexkey",
105590    /* ePragTyp:  */ PragTyp_HEXKEY,
105591    /* ePragFlag: */ 0,
105592    /* iArg:      */ 0 },
105593  { /* zName:     */ "hexrekey",
105594    /* ePragTyp:  */ PragTyp_HEXKEY,
105595    /* ePragFlag: */ 0,
105596    /* iArg:      */ 0 },
105597#endif
105598#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105599#if !defined(SQLITE_OMIT_CHECK)
105600  { /* zName:     */ "ignore_check_constraints",
105601    /* ePragTyp:  */ PragTyp_FLAG,
105602    /* ePragFlag: */ 0,
105603    /* iArg:      */ SQLITE_IgnoreChecks },
105604#endif
105605#endif
105606#if !defined(SQLITE_OMIT_AUTOVACUUM)
105607  { /* zName:     */ "incremental_vacuum",
105608    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
105609    /* ePragFlag: */ PragFlag_NeedSchema,
105610    /* iArg:      */ 0 },
105611#endif
105612#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105613  { /* zName:     */ "index_info",
105614    /* ePragTyp:  */ PragTyp_INDEX_INFO,
105615    /* ePragFlag: */ PragFlag_NeedSchema,
105616    /* iArg:      */ 0 },
105617  { /* zName:     */ "index_list",
105618    /* ePragTyp:  */ PragTyp_INDEX_LIST,
105619    /* ePragFlag: */ PragFlag_NeedSchema,
105620    /* iArg:      */ 0 },
105621  { /* zName:     */ "index_xinfo",
105622    /* ePragTyp:  */ PragTyp_INDEX_INFO,
105623    /* ePragFlag: */ PragFlag_NeedSchema,
105624    /* iArg:      */ 1 },
105625#endif
105626#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
105627  { /* zName:     */ "integrity_check",
105628    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
105629    /* ePragFlag: */ PragFlag_NeedSchema,
105630    /* iArg:      */ 0 },
105631#endif
105632#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105633  { /* zName:     */ "journal_mode",
105634    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
105635    /* ePragFlag: */ PragFlag_NeedSchema,
105636    /* iArg:      */ 0 },
105637  { /* zName:     */ "journal_size_limit",
105638    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
105639    /* ePragFlag: */ 0,
105640    /* iArg:      */ 0 },
105641#endif
105642#if defined(SQLITE_HAS_CODEC)
105643  { /* zName:     */ "key",
105644    /* ePragTyp:  */ PragTyp_KEY,
105645    /* ePragFlag: */ 0,
105646    /* iArg:      */ 0 },
105647#endif
105648#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105649  { /* zName:     */ "legacy_file_format",
105650    /* ePragTyp:  */ PragTyp_FLAG,
105651    /* ePragFlag: */ 0,
105652    /* iArg:      */ SQLITE_LegacyFileFmt },
105653#endif
105654#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
105655  { /* zName:     */ "lock_proxy_file",
105656    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
105657    /* ePragFlag: */ 0,
105658    /* iArg:      */ 0 },
105659#endif
105660#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
105661  { /* zName:     */ "lock_status",
105662    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
105663    /* ePragFlag: */ 0,
105664    /* iArg:      */ 0 },
105665#endif
105666#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105667  { /* zName:     */ "locking_mode",
105668    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
105669    /* ePragFlag: */ 0,
105670    /* iArg:      */ 0 },
105671  { /* zName:     */ "max_page_count",
105672    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
105673    /* ePragFlag: */ PragFlag_NeedSchema,
105674    /* iArg:      */ 0 },
105675  { /* zName:     */ "mmap_size",
105676    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
105677    /* ePragFlag: */ 0,
105678    /* iArg:      */ 0 },
105679  { /* zName:     */ "page_count",
105680    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
105681    /* ePragFlag: */ PragFlag_NeedSchema,
105682    /* iArg:      */ 0 },
105683  { /* zName:     */ "page_size",
105684    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
105685    /* ePragFlag: */ 0,
105686    /* iArg:      */ 0 },
105687#endif
105688#if defined(SQLITE_DEBUG)
105689  { /* zName:     */ "parser_trace",
105690    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
105691    /* ePragFlag: */ 0,
105692    /* iArg:      */ 0 },
105693#endif
105694#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105695  { /* zName:     */ "query_only",
105696    /* ePragTyp:  */ PragTyp_FLAG,
105697    /* ePragFlag: */ 0,
105698    /* iArg:      */ SQLITE_QueryOnly },
105699#endif
105700#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
105701  { /* zName:     */ "quick_check",
105702    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
105703    /* ePragFlag: */ PragFlag_NeedSchema,
105704    /* iArg:      */ 0 },
105705#endif
105706#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105707  { /* zName:     */ "read_uncommitted",
105708    /* ePragTyp:  */ PragTyp_FLAG,
105709    /* ePragFlag: */ 0,
105710    /* iArg:      */ SQLITE_ReadUncommitted },
105711  { /* zName:     */ "recursive_triggers",
105712    /* ePragTyp:  */ PragTyp_FLAG,
105713    /* ePragFlag: */ 0,
105714    /* iArg:      */ SQLITE_RecTriggers },
105715#endif
105716#if defined(SQLITE_HAS_CODEC)
105717  { /* zName:     */ "rekey",
105718    /* ePragTyp:  */ PragTyp_REKEY,
105719    /* ePragFlag: */ 0,
105720    /* iArg:      */ 0 },
105721#endif
105722#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105723  { /* zName:     */ "reverse_unordered_selects",
105724    /* ePragTyp:  */ PragTyp_FLAG,
105725    /* ePragFlag: */ 0,
105726    /* iArg:      */ SQLITE_ReverseOrder },
105727#endif
105728#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105729  { /* zName:     */ "schema_version",
105730    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105731    /* ePragFlag: */ 0,
105732    /* iArg:      */ BTREE_SCHEMA_VERSION },
105733#endif
105734#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105735  { /* zName:     */ "secure_delete",
105736    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
105737    /* ePragFlag: */ 0,
105738    /* iArg:      */ 0 },
105739#endif
105740#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105741  { /* zName:     */ "short_column_names",
105742    /* ePragTyp:  */ PragTyp_FLAG,
105743    /* ePragFlag: */ 0,
105744    /* iArg:      */ SQLITE_ShortColNames },
105745#endif
105746  { /* zName:     */ "shrink_memory",
105747    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
105748    /* ePragFlag: */ 0,
105749    /* iArg:      */ 0 },
105750  { /* zName:     */ "soft_heap_limit",
105751    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
105752    /* ePragFlag: */ 0,
105753    /* iArg:      */ 0 },
105754#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105755#if defined(SQLITE_DEBUG)
105756  { /* zName:     */ "sql_trace",
105757    /* ePragTyp:  */ PragTyp_FLAG,
105758    /* ePragFlag: */ 0,
105759    /* iArg:      */ SQLITE_SqlTrace },
105760#endif
105761#endif
105762#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105763  { /* zName:     */ "stats",
105764    /* ePragTyp:  */ PragTyp_STATS,
105765    /* ePragFlag: */ PragFlag_NeedSchema,
105766    /* iArg:      */ 0 },
105767#endif
105768#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105769  { /* zName:     */ "synchronous",
105770    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
105771    /* ePragFlag: */ PragFlag_NeedSchema,
105772    /* iArg:      */ 0 },
105773#endif
105774#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105775  { /* zName:     */ "table_info",
105776    /* ePragTyp:  */ PragTyp_TABLE_INFO,
105777    /* ePragFlag: */ PragFlag_NeedSchema,
105778    /* iArg:      */ 0 },
105779#endif
105780#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105781  { /* zName:     */ "temp_store",
105782    /* ePragTyp:  */ PragTyp_TEMP_STORE,
105783    /* ePragFlag: */ 0,
105784    /* iArg:      */ 0 },
105785  { /* zName:     */ "temp_store_directory",
105786    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
105787    /* ePragFlag: */ 0,
105788    /* iArg:      */ 0 },
105789#endif
105790  { /* zName:     */ "threads",
105791    /* ePragTyp:  */ PragTyp_THREADS,
105792    /* ePragFlag: */ 0,
105793    /* iArg:      */ 0 },
105794#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105795  { /* zName:     */ "user_version",
105796    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105797    /* ePragFlag: */ 0,
105798    /* iArg:      */ BTREE_USER_VERSION },
105799#endif
105800#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105801#if defined(SQLITE_DEBUG)
105802  { /* zName:     */ "vdbe_addoptrace",
105803    /* ePragTyp:  */ PragTyp_FLAG,
105804    /* ePragFlag: */ 0,
105805    /* iArg:      */ SQLITE_VdbeAddopTrace },
105806  { /* zName:     */ "vdbe_debug",
105807    /* ePragTyp:  */ PragTyp_FLAG,
105808    /* ePragFlag: */ 0,
105809    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
105810  { /* zName:     */ "vdbe_eqp",
105811    /* ePragTyp:  */ PragTyp_FLAG,
105812    /* ePragFlag: */ 0,
105813    /* iArg:      */ SQLITE_VdbeEQP },
105814  { /* zName:     */ "vdbe_listing",
105815    /* ePragTyp:  */ PragTyp_FLAG,
105816    /* ePragFlag: */ 0,
105817    /* iArg:      */ SQLITE_VdbeListing },
105818  { /* zName:     */ "vdbe_trace",
105819    /* ePragTyp:  */ PragTyp_FLAG,
105820    /* ePragFlag: */ 0,
105821    /* iArg:      */ SQLITE_VdbeTrace },
105822#endif
105823#endif
105824#if !defined(SQLITE_OMIT_WAL)
105825  { /* zName:     */ "wal_autocheckpoint",
105826    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
105827    /* ePragFlag: */ 0,
105828    /* iArg:      */ 0 },
105829  { /* zName:     */ "wal_checkpoint",
105830    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
105831    /* ePragFlag: */ PragFlag_NeedSchema,
105832    /* iArg:      */ 0 },
105833#endif
105834#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105835  { /* zName:     */ "writable_schema",
105836    /* ePragTyp:  */ PragTyp_FLAG,
105837    /* ePragFlag: */ 0,
105838    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
105839#endif
105840};
105841/* Number of pragmas: 60 on by default, 73 total. */
105842
105843/************** End of pragma.h **********************************************/
105844/************** Continuing where we left off in pragma.c *********************/
105845
105846/*
105847** Interpret the given string as a safety level.  Return 0 for OFF,
105848** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
105849** unrecognized string argument.  The FULL option is disallowed
105850** if the omitFull parameter it 1.
105851**
105852** Note that the values returned are one less that the values that
105853** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
105854** to support legacy SQL code.  The safety level used to be boolean
105855** and older scripts may have used numbers 0 for OFF and 1 for ON.
105856*/
105857static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
105858                             /* 123456789 123456789 */
105859  static const char zText[] = "onoffalseyestruefull";
105860  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
105861  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
105862  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
105863  int i, n;
105864  if( sqlite3Isdigit(*z) ){
105865    return (u8)sqlite3Atoi(z);
105866  }
105867  n = sqlite3Strlen30(z);
105868  for(i=0; i<ArraySize(iLength)-omitFull; i++){
105869    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
105870      return iValue[i];
105871    }
105872  }
105873  return dflt;
105874}
105875
105876/*
105877** Interpret the given string as a boolean value.
105878*/
105879SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
105880  return getSafetyLevel(z,1,dflt)!=0;
105881}
105882
105883/* The sqlite3GetBoolean() function is used by other modules but the
105884** remainder of this file is specific to PRAGMA processing.  So omit
105885** the rest of the file if PRAGMAs are omitted from the build.
105886*/
105887#if !defined(SQLITE_OMIT_PRAGMA)
105888
105889/*
105890** Interpret the given string as a locking mode value.
105891*/
105892static int getLockingMode(const char *z){
105893  if( z ){
105894    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
105895    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
105896  }
105897  return PAGER_LOCKINGMODE_QUERY;
105898}
105899
105900#ifndef SQLITE_OMIT_AUTOVACUUM
105901/*
105902** Interpret the given string as an auto-vacuum mode value.
105903**
105904** The following strings, "none", "full" and "incremental" are
105905** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
105906*/
105907static int getAutoVacuum(const char *z){
105908  int i;
105909  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
105910  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
105911  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
105912  i = sqlite3Atoi(z);
105913  return (u8)((i>=0&&i<=2)?i:0);
105914}
105915#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
105916
105917#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105918/*
105919** Interpret the given string as a temp db location. Return 1 for file
105920** backed temporary databases, 2 for the Red-Black tree in memory database
105921** and 0 to use the compile-time default.
105922*/
105923static int getTempStore(const char *z){
105924  if( z[0]>='0' && z[0]<='2' ){
105925    return z[0] - '0';
105926  }else if( sqlite3StrICmp(z, "file")==0 ){
105927    return 1;
105928  }else if( sqlite3StrICmp(z, "memory")==0 ){
105929    return 2;
105930  }else{
105931    return 0;
105932  }
105933}
105934#endif /* SQLITE_PAGER_PRAGMAS */
105935
105936#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105937/*
105938** Invalidate temp storage, either when the temp storage is changed
105939** from default, or when 'file' and the temp_store_directory has changed
105940*/
105941static int invalidateTempStorage(Parse *pParse){
105942  sqlite3 *db = pParse->db;
105943  if( db->aDb[1].pBt!=0 ){
105944    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
105945      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
105946        "from within a transaction");
105947      return SQLITE_ERROR;
105948    }
105949    sqlite3BtreeClose(db->aDb[1].pBt);
105950    db->aDb[1].pBt = 0;
105951    sqlite3ResetAllSchemasOfConnection(db);
105952  }
105953  return SQLITE_OK;
105954}
105955#endif /* SQLITE_PAGER_PRAGMAS */
105956
105957#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105958/*
105959** If the TEMP database is open, close it and mark the database schema
105960** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
105961** or DEFAULT_TEMP_STORE pragmas.
105962*/
105963static int changeTempStorage(Parse *pParse, const char *zStorageType){
105964  int ts = getTempStore(zStorageType);
105965  sqlite3 *db = pParse->db;
105966  if( db->temp_store==ts ) return SQLITE_OK;
105967  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
105968    return SQLITE_ERROR;
105969  }
105970  db->temp_store = (u8)ts;
105971  return SQLITE_OK;
105972}
105973#endif /* SQLITE_PAGER_PRAGMAS */
105974
105975/*
105976** Set the names of the first N columns to the values in azCol[]
105977*/
105978static void setAllColumnNames(
105979  Vdbe *v,               /* The query under construction */
105980  int N,                 /* Number of columns */
105981  const char **azCol     /* Names of columns */
105982){
105983  int i;
105984  sqlite3VdbeSetNumCols(v, N);
105985  for(i=0; i<N; i++){
105986    sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
105987  }
105988}
105989static void setOneColumnName(Vdbe *v, const char *z){
105990  setAllColumnNames(v, 1, &z);
105991}
105992
105993/*
105994** Generate code to return a single integer value.
105995*/
105996static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
105997  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
105998  setOneColumnName(v, zLabel);
105999  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106000}
106001
106002/*
106003** Generate code to return a single text value.
106004*/
106005static void returnSingleText(
106006  Vdbe *v,                /* Prepared statement under construction */
106007  const char *zLabel,     /* Name of the result column */
106008  const char *zValue      /* Value to be returned */
106009){
106010  if( zValue ){
106011    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
106012    setOneColumnName(v, zLabel);
106013    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106014  }
106015}
106016
106017
106018/*
106019** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
106020** set these values for all pagers.
106021*/
106022#ifndef SQLITE_OMIT_PAGER_PRAGMAS
106023static void setAllPagerFlags(sqlite3 *db){
106024  if( db->autoCommit ){
106025    Db *pDb = db->aDb;
106026    int n = db->nDb;
106027    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
106028    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
106029    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
106030    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
106031             ==  PAGER_FLAGS_MASK );
106032    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
106033    while( (n--) > 0 ){
106034      if( pDb->pBt ){
106035        sqlite3BtreeSetPagerFlags(pDb->pBt,
106036                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
106037      }
106038      pDb++;
106039    }
106040  }
106041}
106042#else
106043# define setAllPagerFlags(X)  /* no-op */
106044#endif
106045
106046
106047/*
106048** Return a human-readable name for a constraint resolution action.
106049*/
106050#ifndef SQLITE_OMIT_FOREIGN_KEY
106051static const char *actionName(u8 action){
106052  const char *zName;
106053  switch( action ){
106054    case OE_SetNull:  zName = "SET NULL";        break;
106055    case OE_SetDflt:  zName = "SET DEFAULT";     break;
106056    case OE_Cascade:  zName = "CASCADE";         break;
106057    case OE_Restrict: zName = "RESTRICT";        break;
106058    default:          zName = "NO ACTION";
106059                      assert( action==OE_None ); break;
106060  }
106061  return zName;
106062}
106063#endif
106064
106065
106066/*
106067** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
106068** defined in pager.h. This function returns the associated lowercase
106069** journal-mode name.
106070*/
106071SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
106072  static char * const azModeName[] = {
106073    "delete", "persist", "off", "truncate", "memory"
106074#ifndef SQLITE_OMIT_WAL
106075     , "wal"
106076#endif
106077  };
106078  assert( PAGER_JOURNALMODE_DELETE==0 );
106079  assert( PAGER_JOURNALMODE_PERSIST==1 );
106080  assert( PAGER_JOURNALMODE_OFF==2 );
106081  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
106082  assert( PAGER_JOURNALMODE_MEMORY==4 );
106083  assert( PAGER_JOURNALMODE_WAL==5 );
106084  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
106085
106086  if( eMode==ArraySize(azModeName) ) return 0;
106087  return azModeName[eMode];
106088}
106089
106090/*
106091** Process a pragma statement.
106092**
106093** Pragmas are of this form:
106094**
106095**      PRAGMA [database.]id [= value]
106096**
106097** The identifier might also be a string.  The value is a string, and
106098** identifier, or a number.  If minusFlag is true, then the value is
106099** a number that was preceded by a minus sign.
106100**
106101** If the left side is "database.id" then pId1 is the database name
106102** and pId2 is the id.  If the left side is just "id" then pId1 is the
106103** id and pId2 is any empty string.
106104*/
106105SQLITE_PRIVATE void sqlite3Pragma(
106106  Parse *pParse,
106107  Token *pId1,        /* First part of [database.]id field */
106108  Token *pId2,        /* Second part of [database.]id field, or NULL */
106109  Token *pValue,      /* Token for <value>, or NULL */
106110  int minusFlag       /* True if a '-' sign preceded <value> */
106111){
106112  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
106113  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
106114  const char *zDb = 0;   /* The database name */
106115  Token *pId;            /* Pointer to <id> token */
106116  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
106117  int iDb;               /* Database index for <database> */
106118  int lwr, upr, mid = 0;       /* Binary search bounds */
106119  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
106120  sqlite3 *db = pParse->db;    /* The database connection */
106121  Db *pDb;                     /* The specific database being pragmaed */
106122  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
106123  const struct sPragmaNames *pPragma;
106124
106125  if( v==0 ) return;
106126  sqlite3VdbeRunOnlyOnce(v);
106127  pParse->nMem = 2;
106128
106129  /* Interpret the [database.] part of the pragma statement. iDb is the
106130  ** index of the database this pragma is being applied to in db.aDb[]. */
106131  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
106132  if( iDb<0 ) return;
106133  pDb = &db->aDb[iDb];
106134
106135  /* If the temp database has been explicitly named as part of the
106136  ** pragma, make sure it is open.
106137  */
106138  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
106139    return;
106140  }
106141
106142  zLeft = sqlite3NameFromToken(db, pId);
106143  if( !zLeft ) return;
106144  if( minusFlag ){
106145    zRight = sqlite3MPrintf(db, "-%T", pValue);
106146  }else{
106147    zRight = sqlite3NameFromToken(db, pValue);
106148  }
106149
106150  assert( pId2 );
106151  zDb = pId2->n>0 ? pDb->zName : 0;
106152  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
106153    goto pragma_out;
106154  }
106155
106156  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
106157  ** connection.  If it returns SQLITE_OK, then assume that the VFS
106158  ** handled the pragma and generate a no-op prepared statement.
106159  **
106160  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
106161  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
106162  ** object corresponding to the database file to which the pragma
106163  ** statement refers.
106164  **
106165  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
106166  ** file control is an array of pointers to strings (char**) in which the
106167  ** second element of the array is the name of the pragma and the third
106168  ** element is the argument to the pragma or NULL if the pragma has no
106169  ** argument.
106170  */
106171  aFcntl[0] = 0;
106172  aFcntl[1] = zLeft;
106173  aFcntl[2] = zRight;
106174  aFcntl[3] = 0;
106175  db->busyHandler.nBusy = 0;
106176  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
106177  if( rc==SQLITE_OK ){
106178    returnSingleText(v, "result", aFcntl[0]);
106179    sqlite3_free(aFcntl[0]);
106180    goto pragma_out;
106181  }
106182  if( rc!=SQLITE_NOTFOUND ){
106183    if( aFcntl[0] ){
106184      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
106185      sqlite3_free(aFcntl[0]);
106186    }
106187    pParse->nErr++;
106188    pParse->rc = rc;
106189    goto pragma_out;
106190  }
106191
106192  /* Locate the pragma in the lookup table */
106193  lwr = 0;
106194  upr = ArraySize(aPragmaNames)-1;
106195  while( lwr<=upr ){
106196    mid = (lwr+upr)/2;
106197    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
106198    if( rc==0 ) break;
106199    if( rc<0 ){
106200      upr = mid - 1;
106201    }else{
106202      lwr = mid + 1;
106203    }
106204  }
106205  if( lwr>upr ) goto pragma_out;
106206  pPragma = &aPragmaNames[mid];
106207
106208  /* Make sure the database schema is loaded if the pragma requires that */
106209  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
106210    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106211  }
106212
106213  /* Jump to the appropriate pragma handler */
106214  switch( pPragma->ePragTyp ){
106215
106216#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
106217  /*
106218  **  PRAGMA [database.]default_cache_size
106219  **  PRAGMA [database.]default_cache_size=N
106220  **
106221  ** The first form reports the current persistent setting for the
106222  ** page cache size.  The value returned is the maximum number of
106223  ** pages in the page cache.  The second form sets both the current
106224  ** page cache size value and the persistent page cache size value
106225  ** stored in the database file.
106226  **
106227  ** Older versions of SQLite would set the default cache size to a
106228  ** negative number to indicate synchronous=OFF.  These days, synchronous
106229  ** is always on by default regardless of the sign of the default cache
106230  ** size.  But continue to take the absolute value of the default cache
106231  ** size of historical compatibility.
106232  */
106233  case PragTyp_DEFAULT_CACHE_SIZE: {
106234    static const int iLn = VDBE_OFFSET_LINENO(2);
106235    static const VdbeOpList getCacheSize[] = {
106236      { OP_Transaction, 0, 0,        0},                         /* 0 */
106237      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
106238      { OP_IfPos,       1, 8,        0},
106239      { OP_Integer,     0, 2,        0},
106240      { OP_Subtract,    1, 2,        1},
106241      { OP_IfPos,       1, 8,        0},
106242      { OP_Integer,     0, 1,        0},                         /* 6 */
106243      { OP_Noop,        0, 0,        0},
106244      { OP_ResultRow,   1, 1,        0},
106245    };
106246    int addr;
106247    sqlite3VdbeUsesBtree(v, iDb);
106248    if( !zRight ){
106249      setOneColumnName(v, "cache_size");
106250      pParse->nMem += 2;
106251      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
106252      sqlite3VdbeChangeP1(v, addr, iDb);
106253      sqlite3VdbeChangeP1(v, addr+1, iDb);
106254      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
106255    }else{
106256      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
106257      sqlite3BeginWriteOperation(pParse, 0, iDb);
106258      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
106259      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
106260      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106261      pDb->pSchema->cache_size = size;
106262      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
106263    }
106264    break;
106265  }
106266#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
106267
106268#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
106269  /*
106270  **  PRAGMA [database.]page_size
106271  **  PRAGMA [database.]page_size=N
106272  **
106273  ** The first form reports the current setting for the
106274  ** database page size in bytes.  The second form sets the
106275  ** database page size value.  The value can only be set if
106276  ** the database has not yet been created.
106277  */
106278  case PragTyp_PAGE_SIZE: {
106279    Btree *pBt = pDb->pBt;
106280    assert( pBt!=0 );
106281    if( !zRight ){
106282      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
106283      returnSingleInt(v, "page_size", size);
106284    }else{
106285      /* Malloc may fail when setting the page-size, as there is an internal
106286      ** buffer that the pager module resizes using sqlite3_realloc().
106287      */
106288      db->nextPagesize = sqlite3Atoi(zRight);
106289      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
106290        db->mallocFailed = 1;
106291      }
106292    }
106293    break;
106294  }
106295
106296  /*
106297  **  PRAGMA [database.]secure_delete
106298  **  PRAGMA [database.]secure_delete=ON/OFF
106299  **
106300  ** The first form reports the current setting for the
106301  ** secure_delete flag.  The second form changes the secure_delete
106302  ** flag setting and reports thenew value.
106303  */
106304  case PragTyp_SECURE_DELETE: {
106305    Btree *pBt = pDb->pBt;
106306    int b = -1;
106307    assert( pBt!=0 );
106308    if( zRight ){
106309      b = sqlite3GetBoolean(zRight, 0);
106310    }
106311    if( pId2->n==0 && b>=0 ){
106312      int ii;
106313      for(ii=0; ii<db->nDb; ii++){
106314        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
106315      }
106316    }
106317    b = sqlite3BtreeSecureDelete(pBt, b);
106318    returnSingleInt(v, "secure_delete", b);
106319    break;
106320  }
106321
106322  /*
106323  **  PRAGMA [database.]max_page_count
106324  **  PRAGMA [database.]max_page_count=N
106325  **
106326  ** The first form reports the current setting for the
106327  ** maximum number of pages in the database file.  The
106328  ** second form attempts to change this setting.  Both
106329  ** forms return the current setting.
106330  **
106331  ** The absolute value of N is used.  This is undocumented and might
106332  ** change.  The only purpose is to provide an easy way to test
106333  ** the sqlite3AbsInt32() function.
106334  **
106335  **  PRAGMA [database.]page_count
106336  **
106337  ** Return the number of pages in the specified database.
106338  */
106339  case PragTyp_PAGE_COUNT: {
106340    int iReg;
106341    sqlite3CodeVerifySchema(pParse, iDb);
106342    iReg = ++pParse->nMem;
106343    if( sqlite3Tolower(zLeft[0])=='p' ){
106344      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
106345    }else{
106346      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
106347                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
106348    }
106349    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
106350    sqlite3VdbeSetNumCols(v, 1);
106351    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
106352    break;
106353  }
106354
106355  /*
106356  **  PRAGMA [database.]locking_mode
106357  **  PRAGMA [database.]locking_mode = (normal|exclusive)
106358  */
106359  case PragTyp_LOCKING_MODE: {
106360    const char *zRet = "normal";
106361    int eMode = getLockingMode(zRight);
106362
106363    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
106364      /* Simple "PRAGMA locking_mode;" statement. This is a query for
106365      ** the current default locking mode (which may be different to
106366      ** the locking-mode of the main database).
106367      */
106368      eMode = db->dfltLockMode;
106369    }else{
106370      Pager *pPager;
106371      if( pId2->n==0 ){
106372        /* This indicates that no database name was specified as part
106373        ** of the PRAGMA command. In this case the locking-mode must be
106374        ** set on all attached databases, as well as the main db file.
106375        **
106376        ** Also, the sqlite3.dfltLockMode variable is set so that
106377        ** any subsequently attached databases also use the specified
106378        ** locking mode.
106379        */
106380        int ii;
106381        assert(pDb==&db->aDb[0]);
106382        for(ii=2; ii<db->nDb; ii++){
106383          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
106384          sqlite3PagerLockingMode(pPager, eMode);
106385        }
106386        db->dfltLockMode = (u8)eMode;
106387      }
106388      pPager = sqlite3BtreePager(pDb->pBt);
106389      eMode = sqlite3PagerLockingMode(pPager, eMode);
106390    }
106391
106392    assert( eMode==PAGER_LOCKINGMODE_NORMAL
106393            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
106394    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
106395      zRet = "exclusive";
106396    }
106397    returnSingleText(v, "locking_mode", zRet);
106398    break;
106399  }
106400
106401  /*
106402  **  PRAGMA [database.]journal_mode
106403  **  PRAGMA [database.]journal_mode =
106404  **                      (delete|persist|off|truncate|memory|wal|off)
106405  */
106406  case PragTyp_JOURNAL_MODE: {
106407    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
106408    int ii;           /* Loop counter */
106409
106410    setOneColumnName(v, "journal_mode");
106411    if( zRight==0 ){
106412      /* If there is no "=MODE" part of the pragma, do a query for the
106413      ** current mode */
106414      eMode = PAGER_JOURNALMODE_QUERY;
106415    }else{
106416      const char *zMode;
106417      int n = sqlite3Strlen30(zRight);
106418      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
106419        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
106420      }
106421      if( !zMode ){
106422        /* If the "=MODE" part does not match any known journal mode,
106423        ** then do a query */
106424        eMode = PAGER_JOURNALMODE_QUERY;
106425      }
106426    }
106427    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
106428      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
106429      iDb = 0;
106430      pId2->n = 1;
106431    }
106432    for(ii=db->nDb-1; ii>=0; ii--){
106433      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
106434        sqlite3VdbeUsesBtree(v, ii);
106435        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
106436      }
106437    }
106438    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106439    break;
106440  }
106441
106442  /*
106443  **  PRAGMA [database.]journal_size_limit
106444  **  PRAGMA [database.]journal_size_limit=N
106445  **
106446  ** Get or set the size limit on rollback journal files.
106447  */
106448  case PragTyp_JOURNAL_SIZE_LIMIT: {
106449    Pager *pPager = sqlite3BtreePager(pDb->pBt);
106450    i64 iLimit = -2;
106451    if( zRight ){
106452      sqlite3DecOrHexToI64(zRight, &iLimit);
106453      if( iLimit<-1 ) iLimit = -1;
106454    }
106455    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
106456    returnSingleInt(v, "journal_size_limit", iLimit);
106457    break;
106458  }
106459
106460#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
106461
106462  /*
106463  **  PRAGMA [database.]auto_vacuum
106464  **  PRAGMA [database.]auto_vacuum=N
106465  **
106466  ** Get or set the value of the database 'auto-vacuum' parameter.
106467  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
106468  */
106469#ifndef SQLITE_OMIT_AUTOVACUUM
106470  case PragTyp_AUTO_VACUUM: {
106471    Btree *pBt = pDb->pBt;
106472    assert( pBt!=0 );
106473    if( !zRight ){
106474      returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
106475    }else{
106476      int eAuto = getAutoVacuum(zRight);
106477      assert( eAuto>=0 && eAuto<=2 );
106478      db->nextAutovac = (u8)eAuto;
106479      /* Call SetAutoVacuum() to set initialize the internal auto and
106480      ** incr-vacuum flags. This is required in case this connection
106481      ** creates the database file. It is important that it is created
106482      ** as an auto-vacuum capable db.
106483      */
106484      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
106485      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
106486        /* When setting the auto_vacuum mode to either "full" or
106487        ** "incremental", write the value of meta[6] in the database
106488        ** file. Before writing to meta[6], check that meta[3] indicates
106489        ** that this really is an auto-vacuum capable database.
106490        */
106491        static const int iLn = VDBE_OFFSET_LINENO(2);
106492        static const VdbeOpList setMeta6[] = {
106493          { OP_Transaction,    0,         1,                 0},    /* 0 */
106494          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
106495          { OP_If,             1,         0,                 0},    /* 2 */
106496          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
106497          { OP_Integer,        0,         1,                 0},    /* 4 */
106498          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
106499        };
106500        int iAddr;
106501        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
106502        sqlite3VdbeChangeP1(v, iAddr, iDb);
106503        sqlite3VdbeChangeP1(v, iAddr+1, iDb);
106504        sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
106505        sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
106506        sqlite3VdbeChangeP1(v, iAddr+5, iDb);
106507        sqlite3VdbeUsesBtree(v, iDb);
106508      }
106509    }
106510    break;
106511  }
106512#endif
106513
106514  /*
106515  **  PRAGMA [database.]incremental_vacuum(N)
106516  **
106517  ** Do N steps of incremental vacuuming on a database.
106518  */
106519#ifndef SQLITE_OMIT_AUTOVACUUM
106520  case PragTyp_INCREMENTAL_VACUUM: {
106521    int iLimit, addr;
106522    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
106523      iLimit = 0x7fffffff;
106524    }
106525    sqlite3BeginWriteOperation(pParse, 0, iDb);
106526    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
106527    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
106528    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
106529    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
106530    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
106531    sqlite3VdbeJumpHere(v, addr);
106532    break;
106533  }
106534#endif
106535
106536#ifndef SQLITE_OMIT_PAGER_PRAGMAS
106537  /*
106538  **  PRAGMA [database.]cache_size
106539  **  PRAGMA [database.]cache_size=N
106540  **
106541  ** The first form reports the current local setting for the
106542  ** page cache size. The second form sets the local
106543  ** page cache size value.  If N is positive then that is the
106544  ** number of pages in the cache.  If N is negative, then the
106545  ** number of pages is adjusted so that the cache uses -N kibibytes
106546  ** of memory.
106547  */
106548  case PragTyp_CACHE_SIZE: {
106549    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106550    if( !zRight ){
106551      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106552      returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
106553    }else{
106554      int size = sqlite3Atoi(zRight);
106555      pDb->pSchema->cache_size = size;
106556      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
106557      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106558    }
106559    break;
106560  }
106561
106562  /*
106563  **  PRAGMA [database.]mmap_size(N)
106564  **
106565  ** Used to set mapping size limit. The mapping size limit is
106566  ** used to limit the aggregate size of all memory mapped regions of the
106567  ** database file. If this parameter is set to zero, then memory mapping
106568  ** is not used at all.  If N is negative, then the default memory map
106569  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
106570  ** The parameter N is measured in bytes.
106571  **
106572  ** This value is advisory.  The underlying VFS is free to memory map
106573  ** as little or as much as it wants.  Except, if N is set to 0 then the
106574  ** upper layers will never invoke the xFetch interfaces to the VFS.
106575  */
106576  case PragTyp_MMAP_SIZE: {
106577    sqlite3_int64 sz;
106578#if SQLITE_MAX_MMAP_SIZE>0
106579    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106580    if( zRight ){
106581      int ii;
106582      sqlite3DecOrHexToI64(zRight, &sz);
106583      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
106584      if( pId2->n==0 ) db->szMmap = sz;
106585      for(ii=db->nDb-1; ii>=0; ii--){
106586        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
106587          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
106588        }
106589      }
106590    }
106591    sz = -1;
106592    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
106593#else
106594    sz = 0;
106595    rc = SQLITE_OK;
106596#endif
106597    if( rc==SQLITE_OK ){
106598      returnSingleInt(v, "mmap_size", sz);
106599    }else if( rc!=SQLITE_NOTFOUND ){
106600      pParse->nErr++;
106601      pParse->rc = rc;
106602    }
106603    break;
106604  }
106605
106606  /*
106607  **   PRAGMA temp_store
106608  **   PRAGMA temp_store = "default"|"memory"|"file"
106609  **
106610  ** Return or set the local value of the temp_store flag.  Changing
106611  ** the local value does not make changes to the disk file and the default
106612  ** value will be restored the next time the database is opened.
106613  **
106614  ** Note that it is possible for the library compile-time options to
106615  ** override this setting
106616  */
106617  case PragTyp_TEMP_STORE: {
106618    if( !zRight ){
106619      returnSingleInt(v, "temp_store", db->temp_store);
106620    }else{
106621      changeTempStorage(pParse, zRight);
106622    }
106623    break;
106624  }
106625
106626  /*
106627  **   PRAGMA temp_store_directory
106628  **   PRAGMA temp_store_directory = ""|"directory_name"
106629  **
106630  ** Return or set the local value of the temp_store_directory flag.  Changing
106631  ** the value sets a specific directory to be used for temporary files.
106632  ** Setting to a null string reverts to the default temporary directory search.
106633  ** If temporary directory is changed, then invalidateTempStorage.
106634  **
106635  */
106636  case PragTyp_TEMP_STORE_DIRECTORY: {
106637    if( !zRight ){
106638      returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
106639    }else{
106640#ifndef SQLITE_OMIT_WSD
106641      if( zRight[0] ){
106642        int res;
106643        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
106644        if( rc!=SQLITE_OK || res==0 ){
106645          sqlite3ErrorMsg(pParse, "not a writable directory");
106646          goto pragma_out;
106647        }
106648      }
106649      if( SQLITE_TEMP_STORE==0
106650       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
106651       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
106652      ){
106653        invalidateTempStorage(pParse);
106654      }
106655      sqlite3_free(sqlite3_temp_directory);
106656      if( zRight[0] ){
106657        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
106658      }else{
106659        sqlite3_temp_directory = 0;
106660      }
106661#endif /* SQLITE_OMIT_WSD */
106662    }
106663    break;
106664  }
106665
106666#if SQLITE_OS_WIN
106667  /*
106668  **   PRAGMA data_store_directory
106669  **   PRAGMA data_store_directory = ""|"directory_name"
106670  **
106671  ** Return or set the local value of the data_store_directory flag.  Changing
106672  ** the value sets a specific directory to be used for database files that
106673  ** were specified with a relative pathname.  Setting to a null string reverts
106674  ** to the default database directory, which for database files specified with
106675  ** a relative path will probably be based on the current directory for the
106676  ** process.  Database file specified with an absolute path are not impacted
106677  ** by this setting, regardless of its value.
106678  **
106679  */
106680  case PragTyp_DATA_STORE_DIRECTORY: {
106681    if( !zRight ){
106682      returnSingleText(v, "data_store_directory", sqlite3_data_directory);
106683    }else{
106684#ifndef SQLITE_OMIT_WSD
106685      if( zRight[0] ){
106686        int res;
106687        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
106688        if( rc!=SQLITE_OK || res==0 ){
106689          sqlite3ErrorMsg(pParse, "not a writable directory");
106690          goto pragma_out;
106691        }
106692      }
106693      sqlite3_free(sqlite3_data_directory);
106694      if( zRight[0] ){
106695        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
106696      }else{
106697        sqlite3_data_directory = 0;
106698      }
106699#endif /* SQLITE_OMIT_WSD */
106700    }
106701    break;
106702  }
106703#endif
106704
106705#if SQLITE_ENABLE_LOCKING_STYLE
106706  /*
106707  **   PRAGMA [database.]lock_proxy_file
106708  **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
106709  **
106710  ** Return or set the value of the lock_proxy_file flag.  Changing
106711  ** the value sets a specific file to be used for database access locks.
106712  **
106713  */
106714  case PragTyp_LOCK_PROXY_FILE: {
106715    if( !zRight ){
106716      Pager *pPager = sqlite3BtreePager(pDb->pBt);
106717      char *proxy_file_path = NULL;
106718      sqlite3_file *pFile = sqlite3PagerFile(pPager);
106719      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
106720                           &proxy_file_path);
106721      returnSingleText(v, "lock_proxy_file", proxy_file_path);
106722    }else{
106723      Pager *pPager = sqlite3BtreePager(pDb->pBt);
106724      sqlite3_file *pFile = sqlite3PagerFile(pPager);
106725      int res;
106726      if( zRight[0] ){
106727        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
106728                                     zRight);
106729      } else {
106730        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
106731                                     NULL);
106732      }
106733      if( res!=SQLITE_OK ){
106734        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
106735        goto pragma_out;
106736      }
106737    }
106738    break;
106739  }
106740#endif /* SQLITE_ENABLE_LOCKING_STYLE */
106741
106742  /*
106743  **   PRAGMA [database.]synchronous
106744  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
106745  **
106746  ** Return or set the local value of the synchronous flag.  Changing
106747  ** the local value does not make changes to the disk file and the
106748  ** default value will be restored the next time the database is
106749  ** opened.
106750  */
106751  case PragTyp_SYNCHRONOUS: {
106752    if( !zRight ){
106753      returnSingleInt(v, "synchronous", pDb->safety_level-1);
106754    }else{
106755      if( !db->autoCommit ){
106756        sqlite3ErrorMsg(pParse,
106757            "Safety level may not be changed inside a transaction");
106758      }else{
106759        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
106760        if( iLevel==0 ) iLevel = 1;
106761        pDb->safety_level = iLevel;
106762        setAllPagerFlags(db);
106763      }
106764    }
106765    break;
106766  }
106767#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
106768
106769#ifndef SQLITE_OMIT_FLAG_PRAGMAS
106770  case PragTyp_FLAG: {
106771    if( zRight==0 ){
106772      returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
106773    }else{
106774      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
106775      if( db->autoCommit==0 ){
106776        /* Foreign key support may not be enabled or disabled while not
106777        ** in auto-commit mode.  */
106778        mask &= ~(SQLITE_ForeignKeys);
106779      }
106780#if SQLITE_USER_AUTHENTICATION
106781      if( db->auth.authLevel==UAUTH_User ){
106782        /* Do not allow non-admin users to modify the schema arbitrarily */
106783        mask &= ~(SQLITE_WriteSchema);
106784      }
106785#endif
106786
106787      if( sqlite3GetBoolean(zRight, 0) ){
106788        db->flags |= mask;
106789      }else{
106790        db->flags &= ~mask;
106791        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
106792      }
106793
106794      /* Many of the flag-pragmas modify the code generated by the SQL
106795      ** compiler (eg. count_changes). So add an opcode to expire all
106796      ** compiled SQL statements after modifying a pragma value.
106797      */
106798      sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
106799      setAllPagerFlags(db);
106800    }
106801    break;
106802  }
106803#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
106804
106805#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
106806  /*
106807  **   PRAGMA table_info(<table>)
106808  **
106809  ** Return a single row for each column of the named table. The columns of
106810  ** the returned data set are:
106811  **
106812  ** cid:        Column id (numbered from left to right, starting at 0)
106813  ** name:       Column name
106814  ** type:       Column declaration type.
106815  ** notnull:    True if 'NOT NULL' is part of column declaration
106816  ** dflt_value: The default value for the column, if any.
106817  */
106818  case PragTyp_TABLE_INFO: if( zRight ){
106819    Table *pTab;
106820    pTab = sqlite3FindTable(db, zRight, zDb);
106821    if( pTab ){
106822      static const char *azCol[] = {
106823         "cid", "name", "type", "notnull", "dflt_value", "pk"
106824      };
106825      int i, k;
106826      int nHidden = 0;
106827      Column *pCol;
106828      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106829      pParse->nMem = 6;
106830      sqlite3CodeVerifySchema(pParse, iDb);
106831      setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
106832      sqlite3ViewGetColumnNames(pParse, pTab);
106833      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
106834        if( IsHiddenColumn(pCol) ){
106835          nHidden++;
106836          continue;
106837        }
106838        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
106839          k = 0;
106840        }else if( pPk==0 ){
106841          k = 1;
106842        }else{
106843          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
106844        }
106845        sqlite3VdbeMultiLoad(v, 1, "issisi",
106846               i-nHidden,
106847               pCol->zName,
106848               pCol->zType ? pCol->zType : "",
106849               pCol->notNull ? 1 : 0,
106850               pCol->zDflt,
106851               k);
106852        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
106853      }
106854    }
106855  }
106856  break;
106857
106858  case PragTyp_STATS: {
106859    static const char *azCol[] = { "table", "index", "width", "height" };
106860    Index *pIdx;
106861    HashElem *i;
106862    v = sqlite3GetVdbe(pParse);
106863    pParse->nMem = 4;
106864    sqlite3CodeVerifySchema(pParse, iDb);
106865    setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
106866    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
106867      Table *pTab = sqliteHashData(i);
106868      sqlite3VdbeMultiLoad(v, 1, "ssii",
106869           pTab->zName,
106870           0,
106871           (int)sqlite3LogEstToInt(pTab->szTabRow),
106872           (int)sqlite3LogEstToInt(pTab->nRowLogEst));
106873      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
106874      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106875        sqlite3VdbeMultiLoad(v, 2, "sii",
106876           pIdx->zName,
106877           (int)sqlite3LogEstToInt(pIdx->szIdxRow),
106878           (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]));
106879        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
106880      }
106881    }
106882  }
106883  break;
106884
106885  case PragTyp_INDEX_INFO: if( zRight ){
106886    Index *pIdx;
106887    Table *pTab;
106888    pIdx = sqlite3FindIndex(db, zRight, zDb);
106889    if( pIdx ){
106890      static const char *azCol[] = {
106891         "seqno", "cid", "name", "desc", "coll", "key"
106892      };
106893      int i;
106894      int mx;
106895      if( pPragma->iArg ){
106896        /* PRAGMA index_xinfo (newer version with more rows and columns) */
106897        mx = pIdx->nColumn;
106898        pParse->nMem = 6;
106899      }else{
106900        /* PRAGMA index_info (legacy version) */
106901        mx = pIdx->nKeyCol;
106902        pParse->nMem = 3;
106903      }
106904      pTab = pIdx->pTable;
106905      sqlite3CodeVerifySchema(pParse, iDb);
106906      assert( pParse->nMem<=ArraySize(azCol) );
106907      setAllColumnNames(v, pParse->nMem, azCol);
106908      for(i=0; i<mx; i++){
106909        i16 cnum = pIdx->aiColumn[i];
106910        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
106911                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
106912        if( pPragma->iArg ){
106913          sqlite3VdbeMultiLoad(v, 4, "isi",
106914            pIdx->aSortOrder[i],
106915            pIdx->azColl[i],
106916            i<pIdx->nKeyCol);
106917        }
106918        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
106919      }
106920    }
106921  }
106922  break;
106923
106924  case PragTyp_INDEX_LIST: if( zRight ){
106925    Index *pIdx;
106926    Table *pTab;
106927    int i;
106928    pTab = sqlite3FindTable(db, zRight, zDb);
106929    if( pTab ){
106930      static const char *azCol[] = {
106931        "seq", "name", "unique", "origin", "partial"
106932      };
106933      v = sqlite3GetVdbe(pParse);
106934      pParse->nMem = 5;
106935      sqlite3CodeVerifySchema(pParse, iDb);
106936      setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
106937      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
106938        const char *azOrigin[] = { "c", "u", "pk" };
106939        sqlite3VdbeMultiLoad(v, 1, "isisi",
106940           i,
106941           pIdx->zName,
106942           IsUniqueIndex(pIdx),
106943           azOrigin[pIdx->idxType],
106944           pIdx->pPartIdxWhere!=0);
106945        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
106946      }
106947    }
106948  }
106949  break;
106950
106951  case PragTyp_DATABASE_LIST: {
106952    static const char *azCol[] = { "seq", "name", "file" };
106953    int i;
106954    pParse->nMem = 3;
106955    setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
106956    for(i=0; i<db->nDb; i++){
106957      if( db->aDb[i].pBt==0 ) continue;
106958      assert( db->aDb[i].zName!=0 );
106959      sqlite3VdbeMultiLoad(v, 1, "iss",
106960         i,
106961         db->aDb[i].zName,
106962         sqlite3BtreeGetFilename(db->aDb[i].pBt));
106963      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
106964    }
106965  }
106966  break;
106967
106968  case PragTyp_COLLATION_LIST: {
106969    static const char *azCol[] = { "seq", "name" };
106970    int i = 0;
106971    HashElem *p;
106972    pParse->nMem = 2;
106973    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
106974    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
106975      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
106976      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
106977      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
106978    }
106979  }
106980  break;
106981#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
106982
106983#ifndef SQLITE_OMIT_FOREIGN_KEY
106984  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
106985    FKey *pFK;
106986    Table *pTab;
106987    pTab = sqlite3FindTable(db, zRight, zDb);
106988    if( pTab ){
106989      v = sqlite3GetVdbe(pParse);
106990      pFK = pTab->pFKey;
106991      if( pFK ){
106992        static const char *azCol[] = {
106993           "id", "seq", "table", "from", "to", "on_update", "on_delete",
106994           "match"
106995        };
106996        int i = 0;
106997        pParse->nMem = 8;
106998        sqlite3CodeVerifySchema(pParse, iDb);
106999        setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
107000        while(pFK){
107001          int j;
107002          for(j=0; j<pFK->nCol; j++){
107003            sqlite3VdbeMultiLoad(v, 1, "iissssss",
107004                   i,
107005                   j,
107006                   pFK->zTo,
107007                   pTab->aCol[pFK->aCol[j].iFrom].zName,
107008                   pFK->aCol[j].zCol,
107009                   actionName(pFK->aAction[1]),  /* ON UPDATE */
107010                   actionName(pFK->aAction[0]),  /* ON DELETE */
107011                   "NONE");
107012            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
107013          }
107014          ++i;
107015          pFK = pFK->pNextFrom;
107016        }
107017      }
107018    }
107019  }
107020  break;
107021#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
107022
107023#ifndef SQLITE_OMIT_FOREIGN_KEY
107024#ifndef SQLITE_OMIT_TRIGGER
107025  case PragTyp_FOREIGN_KEY_CHECK: {
107026    FKey *pFK;             /* A foreign key constraint */
107027    Table *pTab;           /* Child table contain "REFERENCES" keyword */
107028    Table *pParent;        /* Parent table that child points to */
107029    Index *pIdx;           /* Index in the parent table */
107030    int i;                 /* Loop counter:  Foreign key number for pTab */
107031    int j;                 /* Loop counter:  Field of the foreign key */
107032    HashElem *k;           /* Loop counter:  Next table in schema */
107033    int x;                 /* result variable */
107034    int regResult;         /* 3 registers to hold a result row */
107035    int regKey;            /* Register to hold key for checking the FK */
107036    int regRow;            /* Registers to hold a row from pTab */
107037    int addrTop;           /* Top of a loop checking foreign keys */
107038    int addrOk;            /* Jump here if the key is OK */
107039    int *aiCols;           /* child to parent column mapping */
107040    static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
107041
107042    regResult = pParse->nMem+1;
107043    pParse->nMem += 4;
107044    regKey = ++pParse->nMem;
107045    regRow = ++pParse->nMem;
107046    v = sqlite3GetVdbe(pParse);
107047    setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
107048    sqlite3CodeVerifySchema(pParse, iDb);
107049    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
107050    while( k ){
107051      if( zRight ){
107052        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
107053        k = 0;
107054      }else{
107055        pTab = (Table*)sqliteHashData(k);
107056        k = sqliteHashNext(k);
107057      }
107058      if( pTab==0 || pTab->pFKey==0 ) continue;
107059      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107060      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
107061      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
107062      sqlite3VdbeLoadString(v, regResult, pTab->zName);
107063      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
107064        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
107065        if( pParent==0 ) continue;
107066        pIdx = 0;
107067        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
107068        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
107069        if( x==0 ){
107070          if( pIdx==0 ){
107071            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
107072          }else{
107073            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
107074            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
107075          }
107076        }else{
107077          k = 0;
107078          break;
107079        }
107080      }
107081      assert( pParse->nErr>0 || pFK==0 );
107082      if( pFK ) break;
107083      if( pParse->nTab<i ) pParse->nTab = i;
107084      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
107085      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
107086        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
107087        pIdx = 0;
107088        aiCols = 0;
107089        if( pParent ){
107090          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
107091          assert( x==0 );
107092        }
107093        addrOk = sqlite3VdbeMakeLabel(v);
107094        if( pParent && pIdx==0 ){
107095          int iKey = pFK->aCol[0].iFrom;
107096          assert( iKey>=0 && iKey<pTab->nCol );
107097          if( iKey!=pTab->iPKey ){
107098            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
107099            sqlite3ColumnDefault(v, pTab, iKey, regRow);
107100            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
107101            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
107102               sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
107103          }else{
107104            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
107105          }
107106          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
107107          sqlite3VdbeGoto(v, addrOk);
107108          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
107109        }else{
107110          for(j=0; j<pFK->nCol; j++){
107111            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
107112                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
107113            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
107114          }
107115          if( pParent ){
107116            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
107117                              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
107118            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
107119            VdbeCoverage(v);
107120          }
107121        }
107122        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
107123        sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
107124        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
107125        sqlite3VdbeResolveLabel(v, addrOk);
107126        sqlite3DbFree(db, aiCols);
107127      }
107128      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
107129      sqlite3VdbeJumpHere(v, addrTop);
107130    }
107131  }
107132  break;
107133#endif /* !defined(SQLITE_OMIT_TRIGGER) */
107134#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
107135
107136#ifndef NDEBUG
107137  case PragTyp_PARSER_TRACE: {
107138    if( zRight ){
107139      if( sqlite3GetBoolean(zRight, 0) ){
107140        sqlite3ParserTrace(stderr, "parser: ");
107141      }else{
107142        sqlite3ParserTrace(0, 0);
107143      }
107144    }
107145  }
107146  break;
107147#endif
107148
107149  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
107150  ** used will be case sensitive or not depending on the RHS.
107151  */
107152  case PragTyp_CASE_SENSITIVE_LIKE: {
107153    if( zRight ){
107154      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
107155    }
107156  }
107157  break;
107158
107159#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
107160# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
107161#endif
107162
107163#ifndef SQLITE_OMIT_INTEGRITY_CHECK
107164  /* Pragma "quick_check" is reduced version of
107165  ** integrity_check designed to detect most database corruption
107166  ** without most of the overhead of a full integrity-check.
107167  */
107168  case PragTyp_INTEGRITY_CHECK: {
107169    int i, j, addr, mxErr;
107170
107171    /* Code that appears at the end of the integrity check.  If no error
107172    ** messages have been generated, output OK.  Otherwise output the
107173    ** error message
107174    */
107175    static const int iLn = VDBE_OFFSET_LINENO(2);
107176    static const VdbeOpList endCode[] = {
107177      { OP_AddImm,      1, 0,        0},    /* 0 */
107178      { OP_If,          1, 0,        0},    /* 1 */
107179      { OP_String8,     0, 3,        0},    /* 2 */
107180      { OP_ResultRow,   3, 1,        0},
107181    };
107182
107183    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
107184
107185    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
107186    ** then iDb is set to the index of the database identified by <db>.
107187    ** In this case, the integrity of database iDb only is verified by
107188    ** the VDBE created below.
107189    **
107190    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
107191    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
107192    ** to -1 here, to indicate that the VDBE should verify the integrity
107193    ** of all attached databases.  */
107194    assert( iDb>=0 );
107195    assert( iDb==0 || pId2->z );
107196    if( pId2->z==0 ) iDb = -1;
107197
107198    /* Initialize the VDBE program */
107199    pParse->nMem = 6;
107200    setOneColumnName(v, "integrity_check");
107201
107202    /* Set the maximum error count */
107203    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
107204    if( zRight ){
107205      sqlite3GetInt32(zRight, &mxErr);
107206      if( mxErr<=0 ){
107207        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
107208      }
107209    }
107210    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
107211
107212    /* Do an integrity check on each database file */
107213    for(i=0; i<db->nDb; i++){
107214      HashElem *x;
107215      Hash *pTbls;
107216      int cnt = 0;
107217
107218      if( OMIT_TEMPDB && i==1 ) continue;
107219      if( iDb>=0 && i!=iDb ) continue;
107220
107221      sqlite3CodeVerifySchema(pParse, i);
107222      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
107223      VdbeCoverage(v);
107224      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107225      sqlite3VdbeJumpHere(v, addr);
107226
107227      /* Do an integrity check of the B-Tree
107228      **
107229      ** Begin by filling registers 2, 3, ... with the root pages numbers
107230      ** for all tables and indices in the database.
107231      */
107232      assert( sqlite3SchemaMutexHeld(db, i, 0) );
107233      pTbls = &db->aDb[i].pSchema->tblHash;
107234      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
107235        Table *pTab = sqliteHashData(x);
107236        Index *pIdx;
107237        if( HasRowid(pTab) ){
107238          sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
107239          VdbeComment((v, "%s", pTab->zName));
107240          cnt++;
107241        }
107242        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107243          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
107244          VdbeComment((v, "%s", pIdx->zName));
107245          cnt++;
107246        }
107247      }
107248
107249      /* Make sure sufficient number of registers have been allocated */
107250      pParse->nMem = MAX( pParse->nMem, cnt+8 );
107251
107252      /* Do the b-tree integrity checks */
107253      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
107254      sqlite3VdbeChangeP5(v, (u8)i);
107255      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
107256      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
107257         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
107258         P4_DYNAMIC);
107259      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
107260      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
107261      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
107262      sqlite3VdbeJumpHere(v, addr);
107263
107264      /* Make sure all the indices are constructed correctly.
107265      */
107266      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
107267        Table *pTab = sqliteHashData(x);
107268        Index *pIdx, *pPk;
107269        Index *pPrior = 0;
107270        int loopTop;
107271        int iDataCur, iIdxCur;
107272        int r1 = -1;
107273
107274        if( pTab->pIndex==0 ) continue;
107275        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
107276        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
107277        VdbeCoverage(v);
107278        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107279        sqlite3VdbeJumpHere(v, addr);
107280        sqlite3ExprCacheClear(pParse);
107281        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
107282                                   1, 0, &iDataCur, &iIdxCur);
107283        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
107284        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107285          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
107286        }
107287        pParse->nMem = MAX(pParse->nMem, 8+j);
107288        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
107289        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
107290        /* Verify that all NOT NULL columns really are NOT NULL */
107291        for(j=0; j<pTab->nCol; j++){
107292          char *zErr;
107293          int jmp2, jmp3;
107294          if( j==pTab->iPKey ) continue;
107295          if( pTab->aCol[j].notNull==0 ) continue;
107296          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
107297          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
107298          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
107299          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107300          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
107301                              pTab->aCol[j].zName);
107302          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
107303          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
107304          jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
107305          sqlite3VdbeAddOp0(v, OP_Halt);
107306          sqlite3VdbeJumpHere(v, jmp2);
107307          sqlite3VdbeJumpHere(v, jmp3);
107308        }
107309        /* Validate index entries for the current row */
107310        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107311          int jmp2, jmp3, jmp4, jmp5;
107312          int ckUniq = sqlite3VdbeMakeLabel(v);
107313          if( pPk==pIdx ) continue;
107314          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
107315                                       pPrior, r1);
107316          pPrior = pIdx;
107317          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
107318          /* Verify that an index entry exists for the current table row */
107319          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
107320                                      pIdx->nColumn); VdbeCoverage(v);
107321          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107322          sqlite3VdbeLoadString(v, 3, "row ");
107323          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
107324          sqlite3VdbeLoadString(v, 4, " missing from index ");
107325          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
107326          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
107327          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
107328          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
107329          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
107330          sqlite3VdbeAddOp0(v, OP_Halt);
107331          sqlite3VdbeJumpHere(v, jmp2);
107332          /* For UNIQUE indexes, verify that only one entry exists with the
107333          ** current key.  The entry is unique if (1) any column is NULL
107334          ** or (2) the next entry has a different key */
107335          if( IsUniqueIndex(pIdx) ){
107336            int uniqOk = sqlite3VdbeMakeLabel(v);
107337            int jmp6;
107338            int kk;
107339            for(kk=0; kk<pIdx->nKeyCol; kk++){
107340              int iCol = pIdx->aiColumn[kk];
107341              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
107342              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
107343              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
107344              VdbeCoverage(v);
107345            }
107346            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
107347            sqlite3VdbeGoto(v, uniqOk);
107348            sqlite3VdbeJumpHere(v, jmp6);
107349            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
107350                                 pIdx->nKeyCol); VdbeCoverage(v);
107351            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107352            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
107353            sqlite3VdbeGoto(v, jmp5);
107354            sqlite3VdbeResolveLabel(v, uniqOk);
107355          }
107356          sqlite3VdbeJumpHere(v, jmp4);
107357          sqlite3ResolvePartIdxLabel(pParse, jmp3);
107358        }
107359        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
107360        sqlite3VdbeJumpHere(v, loopTop-1);
107361#ifndef SQLITE_OMIT_BTREECOUNT
107362        sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
107363        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107364          if( pPk==pIdx ) continue;
107365          addr = sqlite3VdbeCurrentAddr(v);
107366          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
107367          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107368          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
107369          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
107370          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107371          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
107372          sqlite3VdbeLoadString(v, 3, pIdx->zName);
107373          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
107374          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
107375        }
107376#endif /* SQLITE_OMIT_BTREECOUNT */
107377      }
107378    }
107379    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
107380    sqlite3VdbeChangeP2(v, addr, -mxErr);
107381    sqlite3VdbeJumpHere(v, addr+1);
107382    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
107383  }
107384  break;
107385#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
107386
107387#ifndef SQLITE_OMIT_UTF16
107388  /*
107389  **   PRAGMA encoding
107390  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
107391  **
107392  ** In its first form, this pragma returns the encoding of the main
107393  ** database. If the database is not initialized, it is initialized now.
107394  **
107395  ** The second form of this pragma is a no-op if the main database file
107396  ** has not already been initialized. In this case it sets the default
107397  ** encoding that will be used for the main database file if a new file
107398  ** is created. If an existing main database file is opened, then the
107399  ** default text encoding for the existing database is used.
107400  **
107401  ** In all cases new databases created using the ATTACH command are
107402  ** created to use the same default text encoding as the main database. If
107403  ** the main database has not been initialized and/or created when ATTACH
107404  ** is executed, this is done before the ATTACH operation.
107405  **
107406  ** In the second form this pragma sets the text encoding to be used in
107407  ** new database files created using this database handle. It is only
107408  ** useful if invoked immediately after the main database i
107409  */
107410  case PragTyp_ENCODING: {
107411    static const struct EncName {
107412      char *zName;
107413      u8 enc;
107414    } encnames[] = {
107415      { "UTF8",     SQLITE_UTF8        },
107416      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
107417      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
107418      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
107419      { "UTF16le",  SQLITE_UTF16LE     },
107420      { "UTF16be",  SQLITE_UTF16BE     },
107421      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
107422      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
107423      { 0, 0 }
107424    };
107425    const struct EncName *pEnc;
107426    if( !zRight ){    /* "PRAGMA encoding" */
107427      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
107428      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
107429      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
107430      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
107431      returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
107432    }else{                        /* "PRAGMA encoding = XXX" */
107433      /* Only change the value of sqlite.enc if the database handle is not
107434      ** initialized. If the main database exists, the new sqlite.enc value
107435      ** will be overwritten when the schema is next loaded. If it does not
107436      ** already exists, it will be created to use the new encoding value.
107437      */
107438      if(
107439        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
107440        DbHasProperty(db, 0, DB_Empty)
107441      ){
107442        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
107443          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
107444            SCHEMA_ENC(db) = ENC(db) =
107445                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
107446            break;
107447          }
107448        }
107449        if( !pEnc->zName ){
107450          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
107451        }
107452      }
107453    }
107454  }
107455  break;
107456#endif /* SQLITE_OMIT_UTF16 */
107457
107458#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
107459  /*
107460  **   PRAGMA [database.]schema_version
107461  **   PRAGMA [database.]schema_version = <integer>
107462  **
107463  **   PRAGMA [database.]user_version
107464  **   PRAGMA [database.]user_version = <integer>
107465  **
107466  **   PRAGMA [database.]freelist_count = <integer>
107467  **
107468  **   PRAGMA [database.]application_id
107469  **   PRAGMA [database.]application_id = <integer>
107470  **
107471  ** The pragma's schema_version and user_version are used to set or get
107472  ** the value of the schema-version and user-version, respectively. Both
107473  ** the schema-version and the user-version are 32-bit signed integers
107474  ** stored in the database header.
107475  **
107476  ** The schema-cookie is usually only manipulated internally by SQLite. It
107477  ** is incremented by SQLite whenever the database schema is modified (by
107478  ** creating or dropping a table or index). The schema version is used by
107479  ** SQLite each time a query is executed to ensure that the internal cache
107480  ** of the schema used when compiling the SQL query matches the schema of
107481  ** the database against which the compiled query is actually executed.
107482  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
107483  ** the schema-version is potentially dangerous and may lead to program
107484  ** crashes or database corruption. Use with caution!
107485  **
107486  ** The user-version is not used internally by SQLite. It may be used by
107487  ** applications for any purpose.
107488  */
107489  case PragTyp_HEADER_VALUE: {
107490    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
107491    sqlite3VdbeUsesBtree(v, iDb);
107492    if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
107493      /* Write the specified cookie value */
107494      static const VdbeOpList setCookie[] = {
107495        { OP_Transaction,    0,  1,  0},    /* 0 */
107496        { OP_Integer,        0,  1,  0},    /* 1 */
107497        { OP_SetCookie,      0,  0,  1},    /* 2 */
107498      };
107499      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
107500      sqlite3VdbeChangeP1(v, addr, iDb);
107501      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
107502      sqlite3VdbeChangeP1(v, addr+2, iDb);
107503      sqlite3VdbeChangeP2(v, addr+2, iCookie);
107504    }else{
107505      /* Read the specified cookie value */
107506      static const VdbeOpList readCookie[] = {
107507        { OP_Transaction,     0,  0,  0},    /* 0 */
107508        { OP_ReadCookie,      0,  1,  0},    /* 1 */
107509        { OP_ResultRow,       1,  1,  0}
107510      };
107511      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
107512      sqlite3VdbeChangeP1(v, addr, iDb);
107513      sqlite3VdbeChangeP1(v, addr+1, iDb);
107514      sqlite3VdbeChangeP3(v, addr+1, iCookie);
107515      sqlite3VdbeSetNumCols(v, 1);
107516      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
107517    }
107518  }
107519  break;
107520#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
107521
107522#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107523  /*
107524  **   PRAGMA compile_options
107525  **
107526  ** Return the names of all compile-time options used in this build,
107527  ** one option per row.
107528  */
107529  case PragTyp_COMPILE_OPTIONS: {
107530    int i = 0;
107531    const char *zOpt;
107532    pParse->nMem = 1;
107533    setOneColumnName(v, "compile_option");
107534    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
107535      sqlite3VdbeLoadString(v, 1, zOpt);
107536      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
107537    }
107538  }
107539  break;
107540#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107541
107542#ifndef SQLITE_OMIT_WAL
107543  /*
107544  **   PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
107545  **
107546  ** Checkpoint the database.
107547  */
107548  case PragTyp_WAL_CHECKPOINT: {
107549    static const char *azCol[] = { "busy", "log", "checkpointed" };
107550    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
107551    int eMode = SQLITE_CHECKPOINT_PASSIVE;
107552    if( zRight ){
107553      if( sqlite3StrICmp(zRight, "full")==0 ){
107554        eMode = SQLITE_CHECKPOINT_FULL;
107555      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
107556        eMode = SQLITE_CHECKPOINT_RESTART;
107557      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
107558        eMode = SQLITE_CHECKPOINT_TRUNCATE;
107559      }
107560    }
107561    setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
107562    pParse->nMem = 3;
107563    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
107564    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
107565  }
107566  break;
107567
107568  /*
107569  **   PRAGMA wal_autocheckpoint
107570  **   PRAGMA wal_autocheckpoint = N
107571  **
107572  ** Configure a database connection to automatically checkpoint a database
107573  ** after accumulating N frames in the log. Or query for the current value
107574  ** of N.
107575  */
107576  case PragTyp_WAL_AUTOCHECKPOINT: {
107577    if( zRight ){
107578      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
107579    }
107580    returnSingleInt(v, "wal_autocheckpoint",
107581       db->xWalCallback==sqlite3WalDefaultHook ?
107582           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
107583  }
107584  break;
107585#endif
107586
107587  /*
107588  **  PRAGMA shrink_memory
107589  **
107590  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
107591  ** connection on which it is invoked to free up as much memory as it
107592  ** can, by calling sqlite3_db_release_memory().
107593  */
107594  case PragTyp_SHRINK_MEMORY: {
107595    sqlite3_db_release_memory(db);
107596    break;
107597  }
107598
107599  /*
107600  **   PRAGMA busy_timeout
107601  **   PRAGMA busy_timeout = N
107602  **
107603  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
107604  ** if one is set.  If no busy handler or a different busy handler is set
107605  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
107606  ** disables the timeout.
107607  */
107608  /*case PragTyp_BUSY_TIMEOUT*/ default: {
107609    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
107610    if( zRight ){
107611      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
107612    }
107613    returnSingleInt(v, "timeout",  db->busyTimeout);
107614    break;
107615  }
107616
107617  /*
107618  **   PRAGMA soft_heap_limit
107619  **   PRAGMA soft_heap_limit = N
107620  **
107621  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
107622  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
107623  ** specified and is a non-negative integer.
107624  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
107625  ** returns the same integer that would be returned by the
107626  ** sqlite3_soft_heap_limit64(-1) C-language function.
107627  */
107628  case PragTyp_SOFT_HEAP_LIMIT: {
107629    sqlite3_int64 N;
107630    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
107631      sqlite3_soft_heap_limit64(N);
107632    }
107633    returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
107634    break;
107635  }
107636
107637  /*
107638  **   PRAGMA threads
107639  **   PRAGMA threads = N
107640  **
107641  ** Configure the maximum number of worker threads.  Return the new
107642  ** maximum, which might be less than requested.
107643  */
107644  case PragTyp_THREADS: {
107645    sqlite3_int64 N;
107646    if( zRight
107647     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
107648     && N>=0
107649    ){
107650      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
107651    }
107652    returnSingleInt(v, "threads",
107653                    sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
107654    break;
107655  }
107656
107657#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
107658  /*
107659  ** Report the current state of file logs for all databases
107660  */
107661  case PragTyp_LOCK_STATUS: {
107662    static const char *const azLockName[] = {
107663      "unlocked", "shared", "reserved", "pending", "exclusive"
107664    };
107665    static const char *azCol[] = { "database", "status" };
107666    int i;
107667    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
107668    pParse->nMem = 2;
107669    for(i=0; i<db->nDb; i++){
107670      Btree *pBt;
107671      const char *zState = "unknown";
107672      int j;
107673      if( db->aDb[i].zName==0 ) continue;
107674      pBt = db->aDb[i].pBt;
107675      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
107676        zState = "closed";
107677      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
107678                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
107679         zState = azLockName[j];
107680      }
107681      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
107682      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
107683    }
107684    break;
107685  }
107686#endif
107687
107688#ifdef SQLITE_HAS_CODEC
107689  case PragTyp_KEY: {
107690    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
107691    break;
107692  }
107693  case PragTyp_REKEY: {
107694    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
107695    break;
107696  }
107697  case PragTyp_HEXKEY: {
107698    if( zRight ){
107699      u8 iByte;
107700      int i;
107701      char zKey[40];
107702      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
107703        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
107704        if( (i&1)!=0 ) zKey[i/2] = iByte;
107705      }
107706      if( (zLeft[3] & 0xf)==0xb ){
107707        sqlite3_key_v2(db, zDb, zKey, i/2);
107708      }else{
107709        sqlite3_rekey_v2(db, zDb, zKey, i/2);
107710      }
107711    }
107712    break;
107713  }
107714#endif
107715#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
107716  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
107717#ifdef SQLITE_HAS_CODEC
107718    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
107719      sqlite3_activate_see(&zRight[4]);
107720    }
107721#endif
107722#ifdef SQLITE_ENABLE_CEROD
107723    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
107724      sqlite3_activate_cerod(&zRight[6]);
107725    }
107726#endif
107727  }
107728  break;
107729#endif
107730
107731  } /* End of the PRAGMA switch */
107732
107733pragma_out:
107734  sqlite3DbFree(db, zLeft);
107735  sqlite3DbFree(db, zRight);
107736}
107737
107738#endif /* SQLITE_OMIT_PRAGMA */
107739
107740/************** End of pragma.c **********************************************/
107741/************** Begin file prepare.c *****************************************/
107742/*
107743** 2005 May 25
107744**
107745** The author disclaims copyright to this source code.  In place of
107746** a legal notice, here is a blessing:
107747**
107748**    May you do good and not evil.
107749**    May you find forgiveness for yourself and forgive others.
107750**    May you share freely, never taking more than you give.
107751**
107752*************************************************************************
107753** This file contains the implementation of the sqlite3_prepare()
107754** interface, and routines that contribute to loading the database schema
107755** from disk.
107756*/
107757/* #include "sqliteInt.h" */
107758
107759/*
107760** Fill the InitData structure with an error message that indicates
107761** that the database is corrupt.
107762*/
107763static void corruptSchema(
107764  InitData *pData,     /* Initialization context */
107765  const char *zObj,    /* Object being parsed at the point of error */
107766  const char *zExtra   /* Error information */
107767){
107768  sqlite3 *db = pData->db;
107769  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
107770    char *z;
107771    if( zObj==0 ) zObj = "?";
107772    z = sqlite3_mprintf("malformed database schema (%s)", zObj);
107773    if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
107774    sqlite3DbFree(db, *pData->pzErrMsg);
107775    *pData->pzErrMsg = z;
107776    if( z==0 ) db->mallocFailed = 1;
107777  }
107778  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
107779}
107780
107781/*
107782** This is the callback routine for the code that initializes the
107783** database.  See sqlite3Init() below for additional information.
107784** This routine is also called from the OP_ParseSchema opcode of the VDBE.
107785**
107786** Each callback contains the following information:
107787**
107788**     argv[0] = name of thing being created
107789**     argv[1] = root page number for table or index. 0 for trigger or view.
107790**     argv[2] = SQL text for the CREATE statement.
107791**
107792*/
107793SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
107794  InitData *pData = (InitData*)pInit;
107795  sqlite3 *db = pData->db;
107796  int iDb = pData->iDb;
107797
107798  assert( argc==3 );
107799  UNUSED_PARAMETER2(NotUsed, argc);
107800  assert( sqlite3_mutex_held(db->mutex) );
107801  DbClearProperty(db, iDb, DB_Empty);
107802  if( db->mallocFailed ){
107803    corruptSchema(pData, argv[0], 0);
107804    return 1;
107805  }
107806
107807  assert( iDb>=0 && iDb<db->nDb );
107808  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
107809  if( argv[1]==0 ){
107810    corruptSchema(pData, argv[0], 0);
107811  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
107812    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
107813    ** But because db->init.busy is set to 1, no VDBE code is generated
107814    ** or executed.  All the parser does is build the internal data
107815    ** structures that describe the table, index, or view.
107816    */
107817    int rc;
107818    sqlite3_stmt *pStmt;
107819    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
107820
107821    assert( db->init.busy );
107822    db->init.iDb = iDb;
107823    db->init.newTnum = sqlite3Atoi(argv[1]);
107824    db->init.orphanTrigger = 0;
107825    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
107826    rc = db->errCode;
107827    assert( (rc&0xFF)==(rcp&0xFF) );
107828    db->init.iDb = 0;
107829    if( SQLITE_OK!=rc ){
107830      if( db->init.orphanTrigger ){
107831        assert( iDb==1 );
107832      }else{
107833        pData->rc = rc;
107834        if( rc==SQLITE_NOMEM ){
107835          db->mallocFailed = 1;
107836        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
107837          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
107838        }
107839      }
107840    }
107841    sqlite3_finalize(pStmt);
107842  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
107843    corruptSchema(pData, argv[0], 0);
107844  }else{
107845    /* If the SQL column is blank it means this is an index that
107846    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
107847    ** constraint for a CREATE TABLE.  The index should have already
107848    ** been created when we processed the CREATE TABLE.  All we have
107849    ** to do here is record the root page number for that index.
107850    */
107851    Index *pIndex;
107852    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
107853    if( pIndex==0 ){
107854      /* This can occur if there exists an index on a TEMP table which
107855      ** has the same name as another index on a permanent index.  Since
107856      ** the permanent table is hidden by the TEMP table, we can also
107857      ** safely ignore the index on the permanent table.
107858      */
107859      /* Do Nothing */;
107860    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
107861      corruptSchema(pData, argv[0], "invalid rootpage");
107862    }
107863  }
107864  return 0;
107865}
107866
107867/*
107868** Attempt to read the database schema and initialize internal
107869** data structures for a single database file.  The index of the
107870** database file is given by iDb.  iDb==0 is used for the main
107871** database.  iDb==1 should never be used.  iDb>=2 is used for
107872** auxiliary databases.  Return one of the SQLITE_ error codes to
107873** indicate success or failure.
107874*/
107875static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
107876  int rc;
107877  int i;
107878#ifndef SQLITE_OMIT_DEPRECATED
107879  int size;
107880#endif
107881  Table *pTab;
107882  Db *pDb;
107883  char const *azArg[4];
107884  int meta[5];
107885  InitData initData;
107886  char const *zMasterSchema;
107887  char const *zMasterName;
107888  int openedTransaction = 0;
107889
107890  /*
107891  ** The master database table has a structure like this
107892  */
107893  static const char master_schema[] =
107894     "CREATE TABLE sqlite_master(\n"
107895     "  type text,\n"
107896     "  name text,\n"
107897     "  tbl_name text,\n"
107898     "  rootpage integer,\n"
107899     "  sql text\n"
107900     ")"
107901  ;
107902#ifndef SQLITE_OMIT_TEMPDB
107903  static const char temp_master_schema[] =
107904     "CREATE TEMP TABLE sqlite_temp_master(\n"
107905     "  type text,\n"
107906     "  name text,\n"
107907     "  tbl_name text,\n"
107908     "  rootpage integer,\n"
107909     "  sql text\n"
107910     ")"
107911  ;
107912#else
107913  #define temp_master_schema 0
107914#endif
107915
107916  assert( iDb>=0 && iDb<db->nDb );
107917  assert( db->aDb[iDb].pSchema );
107918  assert( sqlite3_mutex_held(db->mutex) );
107919  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
107920
107921  /* zMasterSchema and zInitScript are set to point at the master schema
107922  ** and initialisation script appropriate for the database being
107923  ** initialized. zMasterName is the name of the master table.
107924  */
107925  if( !OMIT_TEMPDB && iDb==1 ){
107926    zMasterSchema = temp_master_schema;
107927  }else{
107928    zMasterSchema = master_schema;
107929  }
107930  zMasterName = SCHEMA_TABLE(iDb);
107931
107932  /* Construct the schema tables.  */
107933  azArg[0] = zMasterName;
107934  azArg[1] = "1";
107935  azArg[2] = zMasterSchema;
107936  azArg[3] = 0;
107937  initData.db = db;
107938  initData.iDb = iDb;
107939  initData.rc = SQLITE_OK;
107940  initData.pzErrMsg = pzErrMsg;
107941  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
107942  if( initData.rc ){
107943    rc = initData.rc;
107944    goto error_out;
107945  }
107946  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
107947  if( ALWAYS(pTab) ){
107948    pTab->tabFlags |= TF_Readonly;
107949  }
107950
107951  /* Create a cursor to hold the database open
107952  */
107953  pDb = &db->aDb[iDb];
107954  if( pDb->pBt==0 ){
107955    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
107956      DbSetProperty(db, 1, DB_SchemaLoaded);
107957    }
107958    return SQLITE_OK;
107959  }
107960
107961  /* If there is not already a read-only (or read-write) transaction opened
107962  ** on the b-tree database, open one now. If a transaction is opened, it
107963  ** will be closed before this function returns.  */
107964  sqlite3BtreeEnter(pDb->pBt);
107965  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
107966    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
107967    if( rc!=SQLITE_OK ){
107968      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
107969      goto initone_error_out;
107970    }
107971    openedTransaction = 1;
107972  }
107973
107974  /* Get the database meta information.
107975  **
107976  ** Meta values are as follows:
107977  **    meta[0]   Schema cookie.  Changes with each schema change.
107978  **    meta[1]   File format of schema layer.
107979  **    meta[2]   Size of the page cache.
107980  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
107981  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
107982  **    meta[5]   User version
107983  **    meta[6]   Incremental vacuum mode
107984  **    meta[7]   unused
107985  **    meta[8]   unused
107986  **    meta[9]   unused
107987  **
107988  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
107989  ** the possible values of meta[4].
107990  */
107991  for(i=0; i<ArraySize(meta); i++){
107992    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
107993  }
107994  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
107995
107996  /* If opening a non-empty database, check the text encoding. For the
107997  ** main database, set sqlite3.enc to the encoding of the main database.
107998  ** For an attached db, it is an error if the encoding is not the same
107999  ** as sqlite3.enc.
108000  */
108001  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
108002    if( iDb==0 ){
108003#ifndef SQLITE_OMIT_UTF16
108004      u8 encoding;
108005      /* If opening the main database, set ENC(db). */
108006      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
108007      if( encoding==0 ) encoding = SQLITE_UTF8;
108008      ENC(db) = encoding;
108009#else
108010      ENC(db) = SQLITE_UTF8;
108011#endif
108012    }else{
108013      /* If opening an attached database, the encoding much match ENC(db) */
108014      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
108015        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
108016            " text encoding as main database");
108017        rc = SQLITE_ERROR;
108018        goto initone_error_out;
108019      }
108020    }
108021  }else{
108022    DbSetProperty(db, iDb, DB_Empty);
108023  }
108024  pDb->pSchema->enc = ENC(db);
108025
108026  if( pDb->pSchema->cache_size==0 ){
108027#ifndef SQLITE_OMIT_DEPRECATED
108028    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
108029    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
108030    pDb->pSchema->cache_size = size;
108031#else
108032    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
108033#endif
108034    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
108035  }
108036
108037  /*
108038  ** file_format==1    Version 3.0.0.
108039  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
108040  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
108041  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
108042  */
108043  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
108044  if( pDb->pSchema->file_format==0 ){
108045    pDb->pSchema->file_format = 1;
108046  }
108047  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
108048    sqlite3SetString(pzErrMsg, db, "unsupported file format");
108049    rc = SQLITE_ERROR;
108050    goto initone_error_out;
108051  }
108052
108053  /* Ticket #2804:  When we open a database in the newer file format,
108054  ** clear the legacy_file_format pragma flag so that a VACUUM will
108055  ** not downgrade the database and thus invalidate any descending
108056  ** indices that the user might have created.
108057  */
108058  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
108059    db->flags &= ~SQLITE_LegacyFileFmt;
108060  }
108061
108062  /* Read the schema information out of the schema tables
108063  */
108064  assert( db->init.busy );
108065  {
108066    char *zSql;
108067    zSql = sqlite3MPrintf(db,
108068        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
108069        db->aDb[iDb].zName, zMasterName);
108070#ifndef SQLITE_OMIT_AUTHORIZATION
108071    {
108072      sqlite3_xauth xAuth;
108073      xAuth = db->xAuth;
108074      db->xAuth = 0;
108075#endif
108076      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
108077#ifndef SQLITE_OMIT_AUTHORIZATION
108078      db->xAuth = xAuth;
108079    }
108080#endif
108081    if( rc==SQLITE_OK ) rc = initData.rc;
108082    sqlite3DbFree(db, zSql);
108083#ifndef SQLITE_OMIT_ANALYZE
108084    if( rc==SQLITE_OK ){
108085      sqlite3AnalysisLoad(db, iDb);
108086    }
108087#endif
108088  }
108089  if( db->mallocFailed ){
108090    rc = SQLITE_NOMEM;
108091    sqlite3ResetAllSchemasOfConnection(db);
108092  }
108093  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
108094    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
108095    ** the schema loaded, even if errors occurred. In this situation the
108096    ** current sqlite3_prepare() operation will fail, but the following one
108097    ** will attempt to compile the supplied statement against whatever subset
108098    ** of the schema was loaded before the error occurred. The primary
108099    ** purpose of this is to allow access to the sqlite_master table
108100    ** even when its contents have been corrupted.
108101    */
108102    DbSetProperty(db, iDb, DB_SchemaLoaded);
108103    rc = SQLITE_OK;
108104  }
108105
108106  /* Jump here for an error that occurs after successfully allocating
108107  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
108108  ** before that point, jump to error_out.
108109  */
108110initone_error_out:
108111  if( openedTransaction ){
108112    sqlite3BtreeCommit(pDb->pBt);
108113  }
108114  sqlite3BtreeLeave(pDb->pBt);
108115
108116error_out:
108117  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
108118    db->mallocFailed = 1;
108119  }
108120  return rc;
108121}
108122
108123/*
108124** Initialize all database files - the main database file, the file
108125** used to store temporary tables, and any additional database files
108126** created using ATTACH statements.  Return a success code.  If an
108127** error occurs, write an error message into *pzErrMsg.
108128**
108129** After a database is initialized, the DB_SchemaLoaded bit is set
108130** bit is set in the flags field of the Db structure. If the database
108131** file was of zero-length, then the DB_Empty flag is also set.
108132*/
108133SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
108134  int i, rc;
108135  int commit_internal = !(db->flags&SQLITE_InternChanges);
108136
108137  assert( sqlite3_mutex_held(db->mutex) );
108138  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
108139  assert( db->init.busy==0 );
108140  rc = SQLITE_OK;
108141  db->init.busy = 1;
108142  ENC(db) = SCHEMA_ENC(db);
108143  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
108144    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
108145    rc = sqlite3InitOne(db, i, pzErrMsg);
108146    if( rc ){
108147      sqlite3ResetOneSchema(db, i);
108148    }
108149  }
108150
108151  /* Once all the other databases have been initialized, load the schema
108152  ** for the TEMP database. This is loaded last, as the TEMP database
108153  ** schema may contain references to objects in other databases.
108154  */
108155#ifndef SQLITE_OMIT_TEMPDB
108156  assert( db->nDb>1 );
108157  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
108158    rc = sqlite3InitOne(db, 1, pzErrMsg);
108159    if( rc ){
108160      sqlite3ResetOneSchema(db, 1);
108161    }
108162  }
108163#endif
108164
108165  db->init.busy = 0;
108166  if( rc==SQLITE_OK && commit_internal ){
108167    sqlite3CommitInternalChanges(db);
108168  }
108169
108170  return rc;
108171}
108172
108173/*
108174** This routine is a no-op if the database schema is already initialized.
108175** Otherwise, the schema is loaded. An error code is returned.
108176*/
108177SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
108178  int rc = SQLITE_OK;
108179  sqlite3 *db = pParse->db;
108180  assert( sqlite3_mutex_held(db->mutex) );
108181  if( !db->init.busy ){
108182    rc = sqlite3Init(db, &pParse->zErrMsg);
108183  }
108184  if( rc!=SQLITE_OK ){
108185    pParse->rc = rc;
108186    pParse->nErr++;
108187  }
108188  return rc;
108189}
108190
108191
108192/*
108193** Check schema cookies in all databases.  If any cookie is out
108194** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
108195** make no changes to pParse->rc.
108196*/
108197static void schemaIsValid(Parse *pParse){
108198  sqlite3 *db = pParse->db;
108199  int iDb;
108200  int rc;
108201  int cookie;
108202
108203  assert( pParse->checkSchema );
108204  assert( sqlite3_mutex_held(db->mutex) );
108205  for(iDb=0; iDb<db->nDb; iDb++){
108206    int openedTransaction = 0;         /* True if a transaction is opened */
108207    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
108208    if( pBt==0 ) continue;
108209
108210    /* If there is not already a read-only (or read-write) transaction opened
108211    ** on the b-tree database, open one now. If a transaction is opened, it
108212    ** will be closed immediately after reading the meta-value. */
108213    if( !sqlite3BtreeIsInReadTrans(pBt) ){
108214      rc = sqlite3BtreeBeginTrans(pBt, 0);
108215      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
108216        db->mallocFailed = 1;
108217      }
108218      if( rc!=SQLITE_OK ) return;
108219      openedTransaction = 1;
108220    }
108221
108222    /* Read the schema cookie from the database. If it does not match the
108223    ** value stored as part of the in-memory schema representation,
108224    ** set Parse.rc to SQLITE_SCHEMA. */
108225    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
108226    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
108227    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
108228      sqlite3ResetOneSchema(db, iDb);
108229      pParse->rc = SQLITE_SCHEMA;
108230    }
108231
108232    /* Close the transaction, if one was opened. */
108233    if( openedTransaction ){
108234      sqlite3BtreeCommit(pBt);
108235    }
108236  }
108237}
108238
108239/*
108240** Convert a schema pointer into the iDb index that indicates
108241** which database file in db->aDb[] the schema refers to.
108242**
108243** If the same database is attached more than once, the first
108244** attached database is returned.
108245*/
108246SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
108247  int i = -1000000;
108248
108249  /* If pSchema is NULL, then return -1000000. This happens when code in
108250  ** expr.c is trying to resolve a reference to a transient table (i.e. one
108251  ** created by a sub-select). In this case the return value of this
108252  ** function should never be used.
108253  **
108254  ** We return -1000000 instead of the more usual -1 simply because using
108255  ** -1000000 as the incorrect index into db->aDb[] is much
108256  ** more likely to cause a segfault than -1 (of course there are assert()
108257  ** statements too, but it never hurts to play the odds).
108258  */
108259  assert( sqlite3_mutex_held(db->mutex) );
108260  if( pSchema ){
108261    for(i=0; ALWAYS(i<db->nDb); i++){
108262      if( db->aDb[i].pSchema==pSchema ){
108263        break;
108264      }
108265    }
108266    assert( i>=0 && i<db->nDb );
108267  }
108268  return i;
108269}
108270
108271/*
108272** Free all memory allocations in the pParse object
108273*/
108274SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
108275  if( pParse ){
108276    sqlite3 *db = pParse->db;
108277    sqlite3DbFree(db, pParse->aLabel);
108278    sqlite3ExprListDelete(db, pParse->pConstExpr);
108279  }
108280}
108281
108282/*
108283** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
108284*/
108285static int sqlite3Prepare(
108286  sqlite3 *db,              /* Database handle. */
108287  const char *zSql,         /* UTF-8 encoded SQL statement. */
108288  int nBytes,               /* Length of zSql in bytes. */
108289  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
108290  Vdbe *pReprepare,         /* VM being reprepared */
108291  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108292  const char **pzTail       /* OUT: End of parsed string */
108293){
108294  Parse *pParse;            /* Parsing context */
108295  char *zErrMsg = 0;        /* Error message */
108296  int rc = SQLITE_OK;       /* Result code */
108297  int i;                    /* Loop counter */
108298
108299  /* Allocate the parsing context */
108300  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
108301  if( pParse==0 ){
108302    rc = SQLITE_NOMEM;
108303    goto end_prepare;
108304  }
108305  pParse->pReprepare = pReprepare;
108306  assert( ppStmt && *ppStmt==0 );
108307  assert( !db->mallocFailed );
108308  assert( sqlite3_mutex_held(db->mutex) );
108309
108310  /* Check to verify that it is possible to get a read lock on all
108311  ** database schemas.  The inability to get a read lock indicates that
108312  ** some other database connection is holding a write-lock, which in
108313  ** turn means that the other connection has made uncommitted changes
108314  ** to the schema.
108315  **
108316  ** Were we to proceed and prepare the statement against the uncommitted
108317  ** schema changes and if those schema changes are subsequently rolled
108318  ** back and different changes are made in their place, then when this
108319  ** prepared statement goes to run the schema cookie would fail to detect
108320  ** the schema change.  Disaster would follow.
108321  **
108322  ** This thread is currently holding mutexes on all Btrees (because
108323  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
108324  ** is not possible for another thread to start a new schema change
108325  ** while this routine is running.  Hence, we do not need to hold
108326  ** locks on the schema, we just need to make sure nobody else is
108327  ** holding them.
108328  **
108329  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
108330  ** but it does *not* override schema lock detection, so this all still
108331  ** works even if READ_UNCOMMITTED is set.
108332  */
108333  for(i=0; i<db->nDb; i++) {
108334    Btree *pBt = db->aDb[i].pBt;
108335    if( pBt ){
108336      assert( sqlite3BtreeHoldsMutex(pBt) );
108337      rc = sqlite3BtreeSchemaLocked(pBt);
108338      if( rc ){
108339        const char *zDb = db->aDb[i].zName;
108340        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
108341        testcase( db->flags & SQLITE_ReadUncommitted );
108342        goto end_prepare;
108343      }
108344    }
108345  }
108346
108347  sqlite3VtabUnlockList(db);
108348
108349  pParse->db = db;
108350  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
108351  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
108352    char *zSqlCopy;
108353    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
108354    testcase( nBytes==mxLen );
108355    testcase( nBytes==mxLen+1 );
108356    if( nBytes>mxLen ){
108357      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
108358      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
108359      goto end_prepare;
108360    }
108361    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
108362    if( zSqlCopy ){
108363      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
108364      sqlite3DbFree(db, zSqlCopy);
108365      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
108366    }else{
108367      pParse->zTail = &zSql[nBytes];
108368    }
108369  }else{
108370    sqlite3RunParser(pParse, zSql, &zErrMsg);
108371  }
108372  assert( 0==pParse->nQueryLoop );
108373
108374  if( db->mallocFailed ){
108375    pParse->rc = SQLITE_NOMEM;
108376  }
108377  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
108378  if( pParse->checkSchema ){
108379    schemaIsValid(pParse);
108380  }
108381  if( db->mallocFailed ){
108382    pParse->rc = SQLITE_NOMEM;
108383  }
108384  if( pzTail ){
108385    *pzTail = pParse->zTail;
108386  }
108387  rc = pParse->rc;
108388
108389#ifndef SQLITE_OMIT_EXPLAIN
108390  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
108391    static const char * const azColName[] = {
108392       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
108393       "selectid", "order", "from", "detail"
108394    };
108395    int iFirst, mx;
108396    if( pParse->explain==2 ){
108397      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
108398      iFirst = 8;
108399      mx = 12;
108400    }else{
108401      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
108402      iFirst = 0;
108403      mx = 8;
108404    }
108405    for(i=iFirst; i<mx; i++){
108406      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
108407                            azColName[i], SQLITE_STATIC);
108408    }
108409  }
108410#endif
108411
108412  if( db->init.busy==0 ){
108413    Vdbe *pVdbe = pParse->pVdbe;
108414    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
108415  }
108416  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
108417    sqlite3VdbeFinalize(pParse->pVdbe);
108418    assert(!(*ppStmt));
108419  }else{
108420    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
108421  }
108422
108423  if( zErrMsg ){
108424    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
108425    sqlite3DbFree(db, zErrMsg);
108426  }else{
108427    sqlite3Error(db, rc);
108428  }
108429
108430  /* Delete any TriggerPrg structures allocated while parsing this statement. */
108431  while( pParse->pTriggerPrg ){
108432    TriggerPrg *pT = pParse->pTriggerPrg;
108433    pParse->pTriggerPrg = pT->pNext;
108434    sqlite3DbFree(db, pT);
108435  }
108436
108437end_prepare:
108438
108439  sqlite3ParserReset(pParse);
108440  sqlite3StackFree(db, pParse);
108441  rc = sqlite3ApiExit(db, rc);
108442  assert( (rc&db->errMask)==rc );
108443  return rc;
108444}
108445static int sqlite3LockAndPrepare(
108446  sqlite3 *db,              /* Database handle. */
108447  const char *zSql,         /* UTF-8 encoded SQL statement. */
108448  int nBytes,               /* Length of zSql in bytes. */
108449  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
108450  Vdbe *pOld,               /* VM being reprepared */
108451  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108452  const char **pzTail       /* OUT: End of parsed string */
108453){
108454  int rc;
108455
108456#ifdef SQLITE_ENABLE_API_ARMOR
108457  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
108458#endif
108459  *ppStmt = 0;
108460  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
108461    return SQLITE_MISUSE_BKPT;
108462  }
108463  sqlite3_mutex_enter(db->mutex);
108464  sqlite3BtreeEnterAll(db);
108465  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
108466  if( rc==SQLITE_SCHEMA ){
108467    sqlite3_finalize(*ppStmt);
108468    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
108469  }
108470  sqlite3BtreeLeaveAll(db);
108471  sqlite3_mutex_leave(db->mutex);
108472  assert( rc==SQLITE_OK || *ppStmt==0 );
108473  return rc;
108474}
108475
108476/*
108477** Rerun the compilation of a statement after a schema change.
108478**
108479** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
108480** if the statement cannot be recompiled because another connection has
108481** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
108482** occurs, return SQLITE_SCHEMA.
108483*/
108484SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
108485  int rc;
108486  sqlite3_stmt *pNew;
108487  const char *zSql;
108488  sqlite3 *db;
108489
108490  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
108491  zSql = sqlite3_sql((sqlite3_stmt *)p);
108492  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
108493  db = sqlite3VdbeDb(p);
108494  assert( sqlite3_mutex_held(db->mutex) );
108495  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
108496  if( rc ){
108497    if( rc==SQLITE_NOMEM ){
108498      db->mallocFailed = 1;
108499    }
108500    assert( pNew==0 );
108501    return rc;
108502  }else{
108503    assert( pNew!=0 );
108504  }
108505  sqlite3VdbeSwap((Vdbe*)pNew, p);
108506  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
108507  sqlite3VdbeResetStepResult((Vdbe*)pNew);
108508  sqlite3VdbeFinalize((Vdbe*)pNew);
108509  return SQLITE_OK;
108510}
108511
108512
108513/*
108514** Two versions of the official API.  Legacy and new use.  In the legacy
108515** version, the original SQL text is not saved in the prepared statement
108516** and so if a schema change occurs, SQLITE_SCHEMA is returned by
108517** sqlite3_step().  In the new version, the original SQL text is retained
108518** and the statement is automatically recompiled if an schema change
108519** occurs.
108520*/
108521SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
108522  sqlite3 *db,              /* Database handle. */
108523  const char *zSql,         /* UTF-8 encoded SQL statement. */
108524  int nBytes,               /* Length of zSql in bytes. */
108525  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108526  const char **pzTail       /* OUT: End of parsed string */
108527){
108528  int rc;
108529  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
108530  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108531  return rc;
108532}
108533SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
108534  sqlite3 *db,              /* Database handle. */
108535  const char *zSql,         /* UTF-8 encoded SQL statement. */
108536  int nBytes,               /* Length of zSql in bytes. */
108537  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108538  const char **pzTail       /* OUT: End of parsed string */
108539){
108540  int rc;
108541  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
108542  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108543  return rc;
108544}
108545
108546
108547#ifndef SQLITE_OMIT_UTF16
108548/*
108549** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
108550*/
108551static int sqlite3Prepare16(
108552  sqlite3 *db,              /* Database handle. */
108553  const void *zSql,         /* UTF-16 encoded SQL statement. */
108554  int nBytes,               /* Length of zSql in bytes. */
108555  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
108556  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108557  const void **pzTail       /* OUT: End of parsed string */
108558){
108559  /* This function currently works by first transforming the UTF-16
108560  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
108561  ** tricky bit is figuring out the pointer to return in *pzTail.
108562  */
108563  char *zSql8;
108564  const char *zTail8 = 0;
108565  int rc = SQLITE_OK;
108566
108567#ifdef SQLITE_ENABLE_API_ARMOR
108568  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
108569#endif
108570  *ppStmt = 0;
108571  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
108572    return SQLITE_MISUSE_BKPT;
108573  }
108574  if( nBytes>=0 ){
108575    int sz;
108576    const char *z = (const char*)zSql;
108577    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
108578    nBytes = sz;
108579  }
108580  sqlite3_mutex_enter(db->mutex);
108581  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
108582  if( zSql8 ){
108583    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
108584  }
108585
108586  if( zTail8 && pzTail ){
108587    /* If sqlite3_prepare returns a tail pointer, we calculate the
108588    ** equivalent pointer into the UTF-16 string by counting the unicode
108589    ** characters between zSql8 and zTail8, and then returning a pointer
108590    ** the same number of characters into the UTF-16 string.
108591    */
108592    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
108593    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
108594  }
108595  sqlite3DbFree(db, zSql8);
108596  rc = sqlite3ApiExit(db, rc);
108597  sqlite3_mutex_leave(db->mutex);
108598  return rc;
108599}
108600
108601/*
108602** Two versions of the official API.  Legacy and new use.  In the legacy
108603** version, the original SQL text is not saved in the prepared statement
108604** and so if a schema change occurs, SQLITE_SCHEMA is returned by
108605** sqlite3_step().  In the new version, the original SQL text is retained
108606** and the statement is automatically recompiled if an schema change
108607** occurs.
108608*/
108609SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
108610  sqlite3 *db,              /* Database handle. */
108611  const void *zSql,         /* UTF-16 encoded SQL statement. */
108612  int nBytes,               /* Length of zSql in bytes. */
108613  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108614  const void **pzTail       /* OUT: End of parsed string */
108615){
108616  int rc;
108617  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
108618  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108619  return rc;
108620}
108621SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
108622  sqlite3 *db,              /* Database handle. */
108623  const void *zSql,         /* UTF-16 encoded SQL statement. */
108624  int nBytes,               /* Length of zSql in bytes. */
108625  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108626  const void **pzTail       /* OUT: End of parsed string */
108627){
108628  int rc;
108629  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
108630  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108631  return rc;
108632}
108633
108634#endif /* SQLITE_OMIT_UTF16 */
108635
108636/************** End of prepare.c *********************************************/
108637/************** Begin file select.c ******************************************/
108638/*
108639** 2001 September 15
108640**
108641** The author disclaims copyright to this source code.  In place of
108642** a legal notice, here is a blessing:
108643**
108644**    May you do good and not evil.
108645**    May you find forgiveness for yourself and forgive others.
108646**    May you share freely, never taking more than you give.
108647**
108648*************************************************************************
108649** This file contains C code routines that are called by the parser
108650** to handle SELECT statements in SQLite.
108651*/
108652/* #include "sqliteInt.h" */
108653
108654/*
108655** Trace output macros
108656*/
108657#if SELECTTRACE_ENABLED
108658/***/ int sqlite3SelectTrace = 0;
108659# define SELECTTRACE(K,P,S,X)  \
108660  if(sqlite3SelectTrace&(K))   \
108661    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
108662        (S)->zSelName,(S)),\
108663    sqlite3DebugPrintf X
108664#else
108665# define SELECTTRACE(K,P,S,X)
108666#endif
108667
108668
108669/*
108670** An instance of the following object is used to record information about
108671** how to process the DISTINCT keyword, to simplify passing that information
108672** into the selectInnerLoop() routine.
108673*/
108674typedef struct DistinctCtx DistinctCtx;
108675struct DistinctCtx {
108676  u8 isTnct;      /* True if the DISTINCT keyword is present */
108677  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
108678  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
108679  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
108680};
108681
108682/*
108683** An instance of the following object is used to record information about
108684** the ORDER BY (or GROUP BY) clause of query is being coded.
108685*/
108686typedef struct SortCtx SortCtx;
108687struct SortCtx {
108688  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
108689  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
108690  int iECursor;         /* Cursor number for the sorter */
108691  int regReturn;        /* Register holding block-output return address */
108692  int labelBkOut;       /* Start label for the block-output subroutine */
108693  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
108694  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
108695};
108696#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
108697
108698/*
108699** Delete all the content of a Select structure.  Deallocate the structure
108700** itself only if bFree is true.
108701*/
108702static void clearSelect(sqlite3 *db, Select *p, int bFree){
108703  while( p ){
108704    Select *pPrior = p->pPrior;
108705    sqlite3ExprListDelete(db, p->pEList);
108706    sqlite3SrcListDelete(db, p->pSrc);
108707    sqlite3ExprDelete(db, p->pWhere);
108708    sqlite3ExprListDelete(db, p->pGroupBy);
108709    sqlite3ExprDelete(db, p->pHaving);
108710    sqlite3ExprListDelete(db, p->pOrderBy);
108711    sqlite3ExprDelete(db, p->pLimit);
108712    sqlite3ExprDelete(db, p->pOffset);
108713    sqlite3WithDelete(db, p->pWith);
108714    if( bFree ) sqlite3DbFree(db, p);
108715    p = pPrior;
108716    bFree = 1;
108717  }
108718}
108719
108720/*
108721** Initialize a SelectDest structure.
108722*/
108723SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
108724  pDest->eDest = (u8)eDest;
108725  pDest->iSDParm = iParm;
108726  pDest->affSdst = 0;
108727  pDest->iSdst = 0;
108728  pDest->nSdst = 0;
108729}
108730
108731
108732/*
108733** Allocate a new Select structure and return a pointer to that
108734** structure.
108735*/
108736SQLITE_PRIVATE Select *sqlite3SelectNew(
108737  Parse *pParse,        /* Parsing context */
108738  ExprList *pEList,     /* which columns to include in the result */
108739  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
108740  Expr *pWhere,         /* the WHERE clause */
108741  ExprList *pGroupBy,   /* the GROUP BY clause */
108742  Expr *pHaving,        /* the HAVING clause */
108743  ExprList *pOrderBy,   /* the ORDER BY clause */
108744  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
108745  Expr *pLimit,         /* LIMIT value.  NULL means not used */
108746  Expr *pOffset         /* OFFSET value.  NULL means no offset */
108747){
108748  Select *pNew;
108749  Select standin;
108750  sqlite3 *db = pParse->db;
108751  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
108752  if( pNew==0 ){
108753    assert( db->mallocFailed );
108754    pNew = &standin;
108755    memset(pNew, 0, sizeof(*pNew));
108756  }
108757  if( pEList==0 ){
108758    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
108759  }
108760  pNew->pEList = pEList;
108761  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
108762  pNew->pSrc = pSrc;
108763  pNew->pWhere = pWhere;
108764  pNew->pGroupBy = pGroupBy;
108765  pNew->pHaving = pHaving;
108766  pNew->pOrderBy = pOrderBy;
108767  pNew->selFlags = selFlags;
108768  pNew->op = TK_SELECT;
108769  pNew->pLimit = pLimit;
108770  pNew->pOffset = pOffset;
108771  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
108772  pNew->addrOpenEphm[0] = -1;
108773  pNew->addrOpenEphm[1] = -1;
108774  if( db->mallocFailed ) {
108775    clearSelect(db, pNew, pNew!=&standin);
108776    pNew = 0;
108777  }else{
108778    assert( pNew->pSrc!=0 || pParse->nErr>0 );
108779  }
108780  assert( pNew!=&standin );
108781  return pNew;
108782}
108783
108784#if SELECTTRACE_ENABLED
108785/*
108786** Set the name of a Select object
108787*/
108788SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
108789  if( p && zName ){
108790    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
108791  }
108792}
108793#endif
108794
108795
108796/*
108797** Delete the given Select structure and all of its substructures.
108798*/
108799SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
108800  clearSelect(db, p, 1);
108801}
108802
108803/*
108804** Return a pointer to the right-most SELECT statement in a compound.
108805*/
108806static Select *findRightmost(Select *p){
108807  while( p->pNext ) p = p->pNext;
108808  return p;
108809}
108810
108811/*
108812** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
108813** type of join.  Return an integer constant that expresses that type
108814** in terms of the following bit values:
108815**
108816**     JT_INNER
108817**     JT_CROSS
108818**     JT_OUTER
108819**     JT_NATURAL
108820**     JT_LEFT
108821**     JT_RIGHT
108822**
108823** A full outer join is the combination of JT_LEFT and JT_RIGHT.
108824**
108825** If an illegal or unsupported join type is seen, then still return
108826** a join type, but put an error in the pParse structure.
108827*/
108828SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
108829  int jointype = 0;
108830  Token *apAll[3];
108831  Token *p;
108832                             /*   0123456789 123456789 123456789 123 */
108833  static const char zKeyText[] = "naturaleftouterightfullinnercross";
108834  static const struct {
108835    u8 i;        /* Beginning of keyword text in zKeyText[] */
108836    u8 nChar;    /* Length of the keyword in characters */
108837    u8 code;     /* Join type mask */
108838  } aKeyword[] = {
108839    /* natural */ { 0,  7, JT_NATURAL                },
108840    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
108841    /* outer   */ { 10, 5, JT_OUTER                  },
108842    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
108843    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
108844    /* inner   */ { 23, 5, JT_INNER                  },
108845    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
108846  };
108847  int i, j;
108848  apAll[0] = pA;
108849  apAll[1] = pB;
108850  apAll[2] = pC;
108851  for(i=0; i<3 && apAll[i]; i++){
108852    p = apAll[i];
108853    for(j=0; j<ArraySize(aKeyword); j++){
108854      if( p->n==aKeyword[j].nChar
108855          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
108856        jointype |= aKeyword[j].code;
108857        break;
108858      }
108859    }
108860    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
108861    if( j>=ArraySize(aKeyword) ){
108862      jointype |= JT_ERROR;
108863      break;
108864    }
108865  }
108866  if(
108867     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
108868     (jointype & JT_ERROR)!=0
108869  ){
108870    const char *zSp = " ";
108871    assert( pB!=0 );
108872    if( pC==0 ){ zSp++; }
108873    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
108874       "%T %T%s%T", pA, pB, zSp, pC);
108875    jointype = JT_INNER;
108876  }else if( (jointype & JT_OUTER)!=0
108877         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
108878    sqlite3ErrorMsg(pParse,
108879      "RIGHT and FULL OUTER JOINs are not currently supported");
108880    jointype = JT_INNER;
108881  }
108882  return jointype;
108883}
108884
108885/*
108886** Return the index of a column in a table.  Return -1 if the column
108887** is not contained in the table.
108888*/
108889static int columnIndex(Table *pTab, const char *zCol){
108890  int i;
108891  for(i=0; i<pTab->nCol; i++){
108892    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
108893  }
108894  return -1;
108895}
108896
108897/*
108898** Search the first N tables in pSrc, from left to right, looking for a
108899** table that has a column named zCol.
108900**
108901** When found, set *piTab and *piCol to the table index and column index
108902** of the matching column and return TRUE.
108903**
108904** If not found, return FALSE.
108905*/
108906static int tableAndColumnIndex(
108907  SrcList *pSrc,       /* Array of tables to search */
108908  int N,               /* Number of tables in pSrc->a[] to search */
108909  const char *zCol,    /* Name of the column we are looking for */
108910  int *piTab,          /* Write index of pSrc->a[] here */
108911  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
108912){
108913  int i;               /* For looping over tables in pSrc */
108914  int iCol;            /* Index of column matching zCol */
108915
108916  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
108917  for(i=0; i<N; i++){
108918    iCol = columnIndex(pSrc->a[i].pTab, zCol);
108919    if( iCol>=0 ){
108920      if( piTab ){
108921        *piTab = i;
108922        *piCol = iCol;
108923      }
108924      return 1;
108925    }
108926  }
108927  return 0;
108928}
108929
108930/*
108931** This function is used to add terms implied by JOIN syntax to the
108932** WHERE clause expression of a SELECT statement. The new term, which
108933** is ANDed with the existing WHERE clause, is of the form:
108934**
108935**    (tab1.col1 = tab2.col2)
108936**
108937** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
108938** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
108939** column iColRight of tab2.
108940*/
108941static void addWhereTerm(
108942  Parse *pParse,                  /* Parsing context */
108943  SrcList *pSrc,                  /* List of tables in FROM clause */
108944  int iLeft,                      /* Index of first table to join in pSrc */
108945  int iColLeft,                   /* Index of column in first table */
108946  int iRight,                     /* Index of second table in pSrc */
108947  int iColRight,                  /* Index of column in second table */
108948  int isOuterJoin,                /* True if this is an OUTER join */
108949  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
108950){
108951  sqlite3 *db = pParse->db;
108952  Expr *pE1;
108953  Expr *pE2;
108954  Expr *pEq;
108955
108956  assert( iLeft<iRight );
108957  assert( pSrc->nSrc>iRight );
108958  assert( pSrc->a[iLeft].pTab );
108959  assert( pSrc->a[iRight].pTab );
108960
108961  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
108962  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
108963
108964  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
108965  if( pEq && isOuterJoin ){
108966    ExprSetProperty(pEq, EP_FromJoin);
108967    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
108968    ExprSetVVAProperty(pEq, EP_NoReduce);
108969    pEq->iRightJoinTable = (i16)pE2->iTable;
108970  }
108971  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
108972}
108973
108974/*
108975** Set the EP_FromJoin property on all terms of the given expression.
108976** And set the Expr.iRightJoinTable to iTable for every term in the
108977** expression.
108978**
108979** The EP_FromJoin property is used on terms of an expression to tell
108980** the LEFT OUTER JOIN processing logic that this term is part of the
108981** join restriction specified in the ON or USING clause and not a part
108982** of the more general WHERE clause.  These terms are moved over to the
108983** WHERE clause during join processing but we need to remember that they
108984** originated in the ON or USING clause.
108985**
108986** The Expr.iRightJoinTable tells the WHERE clause processing that the
108987** expression depends on table iRightJoinTable even if that table is not
108988** explicitly mentioned in the expression.  That information is needed
108989** for cases like this:
108990**
108991**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
108992**
108993** The where clause needs to defer the handling of the t1.x=5
108994** term until after the t2 loop of the join.  In that way, a
108995** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
108996** defer the handling of t1.x=5, it will be processed immediately
108997** after the t1 loop and rows with t1.x!=5 will never appear in
108998** the output, which is incorrect.
108999*/
109000static void setJoinExpr(Expr *p, int iTable){
109001  while( p ){
109002    ExprSetProperty(p, EP_FromJoin);
109003    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
109004    ExprSetVVAProperty(p, EP_NoReduce);
109005    p->iRightJoinTable = (i16)iTable;
109006    if( p->op==TK_FUNCTION && p->x.pList ){
109007      int i;
109008      for(i=0; i<p->x.pList->nExpr; i++){
109009        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
109010      }
109011    }
109012    setJoinExpr(p->pLeft, iTable);
109013    p = p->pRight;
109014  }
109015}
109016
109017/*
109018** This routine processes the join information for a SELECT statement.
109019** ON and USING clauses are converted into extra terms of the WHERE clause.
109020** NATURAL joins also create extra WHERE clause terms.
109021**
109022** The terms of a FROM clause are contained in the Select.pSrc structure.
109023** The left most table is the first entry in Select.pSrc.  The right-most
109024** table is the last entry.  The join operator is held in the entry to
109025** the left.  Thus entry 0 contains the join operator for the join between
109026** entries 0 and 1.  Any ON or USING clauses associated with the join are
109027** also attached to the left entry.
109028**
109029** This routine returns the number of errors encountered.
109030*/
109031static int sqliteProcessJoin(Parse *pParse, Select *p){
109032  SrcList *pSrc;                  /* All tables in the FROM clause */
109033  int i, j;                       /* Loop counters */
109034  struct SrcList_item *pLeft;     /* Left table being joined */
109035  struct SrcList_item *pRight;    /* Right table being joined */
109036
109037  pSrc = p->pSrc;
109038  pLeft = &pSrc->a[0];
109039  pRight = &pLeft[1];
109040  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
109041    Table *pLeftTab = pLeft->pTab;
109042    Table *pRightTab = pRight->pTab;
109043    int isOuter;
109044
109045    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
109046    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
109047
109048    /* When the NATURAL keyword is present, add WHERE clause terms for
109049    ** every column that the two tables have in common.
109050    */
109051    if( pRight->fg.jointype & JT_NATURAL ){
109052      if( pRight->pOn || pRight->pUsing ){
109053        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
109054           "an ON or USING clause", 0);
109055        return 1;
109056      }
109057      for(j=0; j<pRightTab->nCol; j++){
109058        char *zName;   /* Name of column in the right table */
109059        int iLeft;     /* Matching left table */
109060        int iLeftCol;  /* Matching column in the left table */
109061
109062        zName = pRightTab->aCol[j].zName;
109063        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
109064          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
109065                       isOuter, &p->pWhere);
109066        }
109067      }
109068    }
109069
109070    /* Disallow both ON and USING clauses in the same join
109071    */
109072    if( pRight->pOn && pRight->pUsing ){
109073      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
109074        "clauses in the same join");
109075      return 1;
109076    }
109077
109078    /* Add the ON clause to the end of the WHERE clause, connected by
109079    ** an AND operator.
109080    */
109081    if( pRight->pOn ){
109082      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
109083      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
109084      pRight->pOn = 0;
109085    }
109086
109087    /* Create extra terms on the WHERE clause for each column named
109088    ** in the USING clause.  Example: If the two tables to be joined are
109089    ** A and B and the USING clause names X, Y, and Z, then add this
109090    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
109091    ** Report an error if any column mentioned in the USING clause is
109092    ** not contained in both tables to be joined.
109093    */
109094    if( pRight->pUsing ){
109095      IdList *pList = pRight->pUsing;
109096      for(j=0; j<pList->nId; j++){
109097        char *zName;     /* Name of the term in the USING clause */
109098        int iLeft;       /* Table on the left with matching column name */
109099        int iLeftCol;    /* Column number of matching column on the left */
109100        int iRightCol;   /* Column number of matching column on the right */
109101
109102        zName = pList->a[j].zName;
109103        iRightCol = columnIndex(pRightTab, zName);
109104        if( iRightCol<0
109105         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
109106        ){
109107          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
109108            "not present in both tables", zName);
109109          return 1;
109110        }
109111        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
109112                     isOuter, &p->pWhere);
109113      }
109114    }
109115  }
109116  return 0;
109117}
109118
109119/* Forward reference */
109120static KeyInfo *keyInfoFromExprList(
109121  Parse *pParse,       /* Parsing context */
109122  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
109123  int iStart,          /* Begin with this column of pList */
109124  int nExtra           /* Add this many extra columns to the end */
109125);
109126
109127/*
109128** Generate code that will push the record in registers regData
109129** through regData+nData-1 onto the sorter.
109130*/
109131static void pushOntoSorter(
109132  Parse *pParse,         /* Parser context */
109133  SortCtx *pSort,        /* Information about the ORDER BY clause */
109134  Select *pSelect,       /* The whole SELECT statement */
109135  int regData,           /* First register holding data to be sorted */
109136  int regOrigData,       /* First register holding data before packing */
109137  int nData,             /* Number of elements in the data array */
109138  int nPrefixReg         /* No. of reg prior to regData available for use */
109139){
109140  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
109141  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
109142  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
109143  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
109144  int regBase;                                     /* Regs for sorter record */
109145  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
109146  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
109147  int op;                            /* Opcode to add sorter record to sorter */
109148
109149  assert( bSeq==0 || bSeq==1 );
109150  assert( nData==1 || regData==regOrigData );
109151  if( nPrefixReg ){
109152    assert( nPrefixReg==nExpr+bSeq );
109153    regBase = regData - nExpr - bSeq;
109154  }else{
109155    regBase = pParse->nMem + 1;
109156    pParse->nMem += nBase;
109157  }
109158  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
109159                          SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
109160  if( bSeq ){
109161    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
109162  }
109163  if( nPrefixReg==0 ){
109164    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
109165  }
109166
109167  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
109168  if( nOBSat>0 ){
109169    int regPrevKey;   /* The first nOBSat columns of the previous row */
109170    int addrFirst;    /* Address of the OP_IfNot opcode */
109171    int addrJmp;      /* Address of the OP_Jump opcode */
109172    VdbeOp *pOp;      /* Opcode that opens the sorter */
109173    int nKey;         /* Number of sorting key columns, including OP_Sequence */
109174    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
109175
109176    regPrevKey = pParse->nMem+1;
109177    pParse->nMem += pSort->nOBSat;
109178    nKey = nExpr - pSort->nOBSat + bSeq;
109179    if( bSeq ){
109180      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
109181    }else{
109182      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
109183    }
109184    VdbeCoverage(v);
109185    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
109186    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
109187    if( pParse->db->mallocFailed ) return;
109188    pOp->p2 = nKey + nData;
109189    pKI = pOp->p4.pKeyInfo;
109190    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
109191    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
109192    testcase( pKI->nXField>2 );
109193    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
109194                                           pKI->nXField-1);
109195    addrJmp = sqlite3VdbeCurrentAddr(v);
109196    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
109197    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
109198    pSort->regReturn = ++pParse->nMem;
109199    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
109200    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
109201    sqlite3VdbeJumpHere(v, addrFirst);
109202    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
109203    sqlite3VdbeJumpHere(v, addrJmp);
109204  }
109205  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109206    op = OP_SorterInsert;
109207  }else{
109208    op = OP_IdxInsert;
109209  }
109210  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
109211  if( pSelect->iLimit ){
109212    int addr;
109213    int iLimit;
109214    if( pSelect->iOffset ){
109215      iLimit = pSelect->iOffset+1;
109216    }else{
109217      iLimit = pSelect->iLimit;
109218    }
109219    addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
109220    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
109221    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
109222    sqlite3VdbeJumpHere(v, addr);
109223  }
109224}
109225
109226/*
109227** Add code to implement the OFFSET
109228*/
109229static void codeOffset(
109230  Vdbe *v,          /* Generate code into this VM */
109231  int iOffset,      /* Register holding the offset counter */
109232  int iContinue     /* Jump here to skip the current record */
109233){
109234  if( iOffset>0 ){
109235    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
109236    VdbeComment((v, "OFFSET"));
109237  }
109238}
109239
109240/*
109241** Add code that will check to make sure the N registers starting at iMem
109242** form a distinct entry.  iTab is a sorting index that holds previously
109243** seen combinations of the N values.  A new entry is made in iTab
109244** if the current N values are new.
109245**
109246** A jump to addrRepeat is made and the N+1 values are popped from the
109247** stack if the top N elements are not distinct.
109248*/
109249static void codeDistinct(
109250  Parse *pParse,     /* Parsing and code generating context */
109251  int iTab,          /* A sorting index used to test for distinctness */
109252  int addrRepeat,    /* Jump to here if not distinct */
109253  int N,             /* Number of elements */
109254  int iMem           /* First element */
109255){
109256  Vdbe *v;
109257  int r1;
109258
109259  v = pParse->pVdbe;
109260  r1 = sqlite3GetTempReg(pParse);
109261  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
109262  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
109263  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
109264  sqlite3ReleaseTempReg(pParse, r1);
109265}
109266
109267#ifndef SQLITE_OMIT_SUBQUERY
109268/*
109269** Generate an error message when a SELECT is used within a subexpression
109270** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
109271** column.  We do this in a subroutine because the error used to occur
109272** in multiple places.  (The error only occurs in one place now, but we
109273** retain the subroutine to minimize code disruption.)
109274*/
109275static int checkForMultiColumnSelectError(
109276  Parse *pParse,       /* Parse context. */
109277  SelectDest *pDest,   /* Destination of SELECT results */
109278  int nExpr            /* Number of result columns returned by SELECT */
109279){
109280  int eDest = pDest->eDest;
109281  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
109282    sqlite3ErrorMsg(pParse, "only a single result allowed for "
109283       "a SELECT that is part of an expression");
109284    return 1;
109285  }else{
109286    return 0;
109287  }
109288}
109289#endif
109290
109291/*
109292** This routine generates the code for the inside of the inner loop
109293** of a SELECT.
109294**
109295** If srcTab is negative, then the pEList expressions
109296** are evaluated in order to get the data for this row.  If srcTab is
109297** zero or more, then data is pulled from srcTab and pEList is used only
109298** to get number columns and the datatype for each column.
109299*/
109300static void selectInnerLoop(
109301  Parse *pParse,          /* The parser context */
109302  Select *p,              /* The complete select statement being coded */
109303  ExprList *pEList,       /* List of values being extracted */
109304  int srcTab,             /* Pull data from this table */
109305  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
109306  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
109307  SelectDest *pDest,      /* How to dispose of the results */
109308  int iContinue,          /* Jump here to continue with next row */
109309  int iBreak              /* Jump here to break out of the inner loop */
109310){
109311  Vdbe *v = pParse->pVdbe;
109312  int i;
109313  int hasDistinct;        /* True if the DISTINCT keyword is present */
109314  int regResult;              /* Start of memory holding result set */
109315  int eDest = pDest->eDest;   /* How to dispose of results */
109316  int iParm = pDest->iSDParm; /* First argument to disposal method */
109317  int nResultCol;             /* Number of result columns */
109318  int nPrefixReg = 0;         /* Number of extra registers before regResult */
109319
109320  assert( v );
109321  assert( pEList!=0 );
109322  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
109323  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
109324  if( pSort==0 && !hasDistinct ){
109325    assert( iContinue!=0 );
109326    codeOffset(v, p->iOffset, iContinue);
109327  }
109328
109329  /* Pull the requested columns.
109330  */
109331  nResultCol = pEList->nExpr;
109332
109333  if( pDest->iSdst==0 ){
109334    if( pSort ){
109335      nPrefixReg = pSort->pOrderBy->nExpr;
109336      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
109337      pParse->nMem += nPrefixReg;
109338    }
109339    pDest->iSdst = pParse->nMem+1;
109340    pParse->nMem += nResultCol;
109341  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
109342    /* This is an error condition that can result, for example, when a SELECT
109343    ** on the right-hand side of an INSERT contains more result columns than
109344    ** there are columns in the table on the left.  The error will be caught
109345    ** and reported later.  But we need to make sure enough memory is allocated
109346    ** to avoid other spurious errors in the meantime. */
109347    pParse->nMem += nResultCol;
109348  }
109349  pDest->nSdst = nResultCol;
109350  regResult = pDest->iSdst;
109351  if( srcTab>=0 ){
109352    for(i=0; i<nResultCol; i++){
109353      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
109354      VdbeComment((v, "%s", pEList->a[i].zName));
109355    }
109356  }else if( eDest!=SRT_Exists ){
109357    /* If the destination is an EXISTS(...) expression, the actual
109358    ** values returned by the SELECT are not required.
109359    */
109360    u8 ecelFlags;
109361    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
109362      ecelFlags = SQLITE_ECEL_DUP;
109363    }else{
109364      ecelFlags = 0;
109365    }
109366    sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
109367  }
109368
109369  /* If the DISTINCT keyword was present on the SELECT statement
109370  ** and this row has been seen before, then do not make this row
109371  ** part of the result.
109372  */
109373  if( hasDistinct ){
109374    switch( pDistinct->eTnctType ){
109375      case WHERE_DISTINCT_ORDERED: {
109376        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
109377        int iJump;              /* Jump destination */
109378        int regPrev;            /* Previous row content */
109379
109380        /* Allocate space for the previous row */
109381        regPrev = pParse->nMem+1;
109382        pParse->nMem += nResultCol;
109383
109384        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
109385        ** sets the MEM_Cleared bit on the first register of the
109386        ** previous value.  This will cause the OP_Ne below to always
109387        ** fail on the first iteration of the loop even if the first
109388        ** row is all NULLs.
109389        */
109390        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
109391        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
109392        pOp->opcode = OP_Null;
109393        pOp->p1 = 1;
109394        pOp->p2 = regPrev;
109395
109396        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
109397        for(i=0; i<nResultCol; i++){
109398          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
109399          if( i<nResultCol-1 ){
109400            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
109401            VdbeCoverage(v);
109402          }else{
109403            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
109404            VdbeCoverage(v);
109405           }
109406          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
109407          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
109408        }
109409        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
109410        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
109411        break;
109412      }
109413
109414      case WHERE_DISTINCT_UNIQUE: {
109415        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
109416        break;
109417      }
109418
109419      default: {
109420        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
109421        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
109422                     regResult);
109423        break;
109424      }
109425    }
109426    if( pSort==0 ){
109427      codeOffset(v, p->iOffset, iContinue);
109428    }
109429  }
109430
109431  switch( eDest ){
109432    /* In this mode, write each query result to the key of the temporary
109433    ** table iParm.
109434    */
109435#ifndef SQLITE_OMIT_COMPOUND_SELECT
109436    case SRT_Union: {
109437      int r1;
109438      r1 = sqlite3GetTempReg(pParse);
109439      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
109440      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109441      sqlite3ReleaseTempReg(pParse, r1);
109442      break;
109443    }
109444
109445    /* Construct a record from the query result, but instead of
109446    ** saving that record, use it as a key to delete elements from
109447    ** the temporary table iParm.
109448    */
109449    case SRT_Except: {
109450      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
109451      break;
109452    }
109453#endif /* SQLITE_OMIT_COMPOUND_SELECT */
109454
109455    /* Store the result as data using a unique key.
109456    */
109457    case SRT_Fifo:
109458    case SRT_DistFifo:
109459    case SRT_Table:
109460    case SRT_EphemTab: {
109461      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
109462      testcase( eDest==SRT_Table );
109463      testcase( eDest==SRT_EphemTab );
109464      testcase( eDest==SRT_Fifo );
109465      testcase( eDest==SRT_DistFifo );
109466      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
109467#ifndef SQLITE_OMIT_CTE
109468      if( eDest==SRT_DistFifo ){
109469        /* If the destination is DistFifo, then cursor (iParm+1) is open
109470        ** on an ephemeral index. If the current row is already present
109471        ** in the index, do not write it to the output. If not, add the
109472        ** current row to the index and proceed with writing it to the
109473        ** output table as well.  */
109474        int addr = sqlite3VdbeCurrentAddr(v) + 4;
109475        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
109476        VdbeCoverage(v);
109477        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
109478        assert( pSort==0 );
109479      }
109480#endif
109481      if( pSort ){
109482        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
109483      }else{
109484        int r2 = sqlite3GetTempReg(pParse);
109485        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
109486        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
109487        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
109488        sqlite3ReleaseTempReg(pParse, r2);
109489      }
109490      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
109491      break;
109492    }
109493
109494#ifndef SQLITE_OMIT_SUBQUERY
109495    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
109496    ** then there should be a single item on the stack.  Write this
109497    ** item into the set table with bogus data.
109498    */
109499    case SRT_Set: {
109500      assert( nResultCol==1 );
109501      pDest->affSdst =
109502                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
109503      if( pSort ){
109504        /* At first glance you would think we could optimize out the
109505        ** ORDER BY in this case since the order of entries in the set
109506        ** does not matter.  But there might be a LIMIT clause, in which
109507        ** case the order does matter */
109508        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
109509      }else{
109510        int r1 = sqlite3GetTempReg(pParse);
109511        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
109512        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
109513        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109514        sqlite3ReleaseTempReg(pParse, r1);
109515      }
109516      break;
109517    }
109518
109519    /* If any row exist in the result set, record that fact and abort.
109520    */
109521    case SRT_Exists: {
109522      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
109523      /* The LIMIT clause will terminate the loop for us */
109524      break;
109525    }
109526
109527    /* If this is a scalar select that is part of an expression, then
109528    ** store the results in the appropriate memory cell and break out
109529    ** of the scan loop.
109530    */
109531    case SRT_Mem: {
109532      assert( nResultCol==1 );
109533      if( pSort ){
109534        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
109535      }else{
109536        assert( regResult==iParm );
109537        /* The LIMIT clause will jump out of the loop for us */
109538      }
109539      break;
109540    }
109541#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
109542
109543    case SRT_Coroutine:       /* Send data to a co-routine */
109544    case SRT_Output: {        /* Return the results */
109545      testcase( eDest==SRT_Coroutine );
109546      testcase( eDest==SRT_Output );
109547      if( pSort ){
109548        pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
109549                       nPrefixReg);
109550      }else if( eDest==SRT_Coroutine ){
109551        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
109552      }else{
109553        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
109554        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
109555      }
109556      break;
109557    }
109558
109559#ifndef SQLITE_OMIT_CTE
109560    /* Write the results into a priority queue that is order according to
109561    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
109562    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
109563    ** pSO->nExpr columns, then make sure all keys are unique by adding a
109564    ** final OP_Sequence column.  The last column is the record as a blob.
109565    */
109566    case SRT_DistQueue:
109567    case SRT_Queue: {
109568      int nKey;
109569      int r1, r2, r3;
109570      int addrTest = 0;
109571      ExprList *pSO;
109572      pSO = pDest->pOrderBy;
109573      assert( pSO );
109574      nKey = pSO->nExpr;
109575      r1 = sqlite3GetTempReg(pParse);
109576      r2 = sqlite3GetTempRange(pParse, nKey+2);
109577      r3 = r2+nKey+1;
109578      if( eDest==SRT_DistQueue ){
109579        /* If the destination is DistQueue, then cursor (iParm+1) is open
109580        ** on a second ephemeral index that holds all values every previously
109581        ** added to the queue. */
109582        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
109583                                        regResult, nResultCol);
109584        VdbeCoverage(v);
109585      }
109586      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
109587      if( eDest==SRT_DistQueue ){
109588        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
109589        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
109590      }
109591      for(i=0; i<nKey; i++){
109592        sqlite3VdbeAddOp2(v, OP_SCopy,
109593                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
109594                          r2+i);
109595      }
109596      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
109597      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
109598      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109599      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
109600      sqlite3ReleaseTempReg(pParse, r1);
109601      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
109602      break;
109603    }
109604#endif /* SQLITE_OMIT_CTE */
109605
109606
109607
109608#if !defined(SQLITE_OMIT_TRIGGER)
109609    /* Discard the results.  This is used for SELECT statements inside
109610    ** the body of a TRIGGER.  The purpose of such selects is to call
109611    ** user-defined functions that have side effects.  We do not care
109612    ** about the actual results of the select.
109613    */
109614    default: {
109615      assert( eDest==SRT_Discard );
109616      break;
109617    }
109618#endif
109619  }
109620
109621  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
109622  ** there is a sorter, in which case the sorter has already limited
109623  ** the output for us.
109624  */
109625  if( pSort==0 && p->iLimit ){
109626    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
109627  }
109628}
109629
109630/*
109631** Allocate a KeyInfo object sufficient for an index of N key columns and
109632** X extra columns.
109633*/
109634SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
109635  KeyInfo *p = sqlite3DbMallocZero(0,
109636                   sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
109637  if( p ){
109638    p->aSortOrder = (u8*)&p->aColl[N+X];
109639    p->nField = (u16)N;
109640    p->nXField = (u16)X;
109641    p->enc = ENC(db);
109642    p->db = db;
109643    p->nRef = 1;
109644  }else{
109645    db->mallocFailed = 1;
109646  }
109647  return p;
109648}
109649
109650/*
109651** Deallocate a KeyInfo object
109652*/
109653SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
109654  if( p ){
109655    assert( p->nRef>0 );
109656    p->nRef--;
109657    if( p->nRef==0 ) sqlite3DbFree(0, p);
109658  }
109659}
109660
109661/*
109662** Make a new pointer to a KeyInfo object
109663*/
109664SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
109665  if( p ){
109666    assert( p->nRef>0 );
109667    p->nRef++;
109668  }
109669  return p;
109670}
109671
109672#ifdef SQLITE_DEBUG
109673/*
109674** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
109675** can only be changed if this is just a single reference to the object.
109676**
109677** This routine is used only inside of assert() statements.
109678*/
109679SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
109680#endif /* SQLITE_DEBUG */
109681
109682/*
109683** Given an expression list, generate a KeyInfo structure that records
109684** the collating sequence for each expression in that expression list.
109685**
109686** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
109687** KeyInfo structure is appropriate for initializing a virtual index to
109688** implement that clause.  If the ExprList is the result set of a SELECT
109689** then the KeyInfo structure is appropriate for initializing a virtual
109690** index to implement a DISTINCT test.
109691**
109692** Space to hold the KeyInfo structure is obtained from malloc.  The calling
109693** function is responsible for seeing that this structure is eventually
109694** freed.
109695*/
109696static KeyInfo *keyInfoFromExprList(
109697  Parse *pParse,       /* Parsing context */
109698  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
109699  int iStart,          /* Begin with this column of pList */
109700  int nExtra           /* Add this many extra columns to the end */
109701){
109702  int nExpr;
109703  KeyInfo *pInfo;
109704  struct ExprList_item *pItem;
109705  sqlite3 *db = pParse->db;
109706  int i;
109707
109708  nExpr = pList->nExpr;
109709  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
109710  if( pInfo ){
109711    assert( sqlite3KeyInfoIsWriteable(pInfo) );
109712    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
109713      CollSeq *pColl;
109714      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
109715      if( !pColl ) pColl = db->pDfltColl;
109716      pInfo->aColl[i-iStart] = pColl;
109717      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
109718    }
109719  }
109720  return pInfo;
109721}
109722
109723/*
109724** Name of the connection operator, used for error messages.
109725*/
109726static const char *selectOpName(int id){
109727  char *z;
109728  switch( id ){
109729    case TK_ALL:       z = "UNION ALL";   break;
109730    case TK_INTERSECT: z = "INTERSECT";   break;
109731    case TK_EXCEPT:    z = "EXCEPT";      break;
109732    default:           z = "UNION";       break;
109733  }
109734  return z;
109735}
109736
109737#ifndef SQLITE_OMIT_EXPLAIN
109738/*
109739** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
109740** is a no-op. Otherwise, it adds a single row of output to the EQP result,
109741** where the caption is of the form:
109742**
109743**   "USE TEMP B-TREE FOR xxx"
109744**
109745** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
109746** is determined by the zUsage argument.
109747*/
109748static void explainTempTable(Parse *pParse, const char *zUsage){
109749  if( pParse->explain==2 ){
109750    Vdbe *v = pParse->pVdbe;
109751    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
109752    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
109753  }
109754}
109755
109756/*
109757** Assign expression b to lvalue a. A second, no-op, version of this macro
109758** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
109759** in sqlite3Select() to assign values to structure member variables that
109760** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
109761** code with #ifndef directives.
109762*/
109763# define explainSetInteger(a, b) a = b
109764
109765#else
109766/* No-op versions of the explainXXX() functions and macros. */
109767# define explainTempTable(y,z)
109768# define explainSetInteger(y,z)
109769#endif
109770
109771#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
109772/*
109773** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
109774** is a no-op. Otherwise, it adds a single row of output to the EQP result,
109775** where the caption is of one of the two forms:
109776**
109777**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
109778**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
109779**
109780** where iSub1 and iSub2 are the integers passed as the corresponding
109781** function parameters, and op is the text representation of the parameter
109782** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
109783** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
109784** false, or the second form if it is true.
109785*/
109786static void explainComposite(
109787  Parse *pParse,                  /* Parse context */
109788  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
109789  int iSub1,                      /* Subquery id 1 */
109790  int iSub2,                      /* Subquery id 2 */
109791  int bUseTmp                     /* True if a temp table was used */
109792){
109793  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
109794  if( pParse->explain==2 ){
109795    Vdbe *v = pParse->pVdbe;
109796    char *zMsg = sqlite3MPrintf(
109797        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
109798        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
109799    );
109800    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
109801  }
109802}
109803#else
109804/* No-op versions of the explainXXX() functions and macros. */
109805# define explainComposite(v,w,x,y,z)
109806#endif
109807
109808/*
109809** If the inner loop was generated using a non-null pOrderBy argument,
109810** then the results were placed in a sorter.  After the loop is terminated
109811** we need to run the sorter and output the results.  The following
109812** routine generates the code needed to do that.
109813*/
109814static void generateSortTail(
109815  Parse *pParse,    /* Parsing context */
109816  Select *p,        /* The SELECT statement */
109817  SortCtx *pSort,   /* Information on the ORDER BY clause */
109818  int nColumn,      /* Number of columns of data */
109819  SelectDest *pDest /* Write the sorted results here */
109820){
109821  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
109822  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
109823  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
109824  int addr;
109825  int addrOnce = 0;
109826  int iTab;
109827  ExprList *pOrderBy = pSort->pOrderBy;
109828  int eDest = pDest->eDest;
109829  int iParm = pDest->iSDParm;
109830  int regRow;
109831  int regRowid;
109832  int nKey;
109833  int iSortTab;                   /* Sorter cursor to read from */
109834  int nSortData;                  /* Trailing values to read from sorter */
109835  int i;
109836  int bSeq;                       /* True if sorter record includes seq. no. */
109837#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
109838  struct ExprList_item *aOutEx = p->pEList->a;
109839#endif
109840
109841  if( pSort->labelBkOut ){
109842    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
109843    sqlite3VdbeGoto(v, addrBreak);
109844    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
109845  }
109846  iTab = pSort->iECursor;
109847  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
109848    regRowid = 0;
109849    regRow = pDest->iSdst;
109850    nSortData = nColumn;
109851  }else{
109852    regRowid = sqlite3GetTempReg(pParse);
109853    regRow = sqlite3GetTempReg(pParse);
109854    nSortData = 1;
109855  }
109856  nKey = pOrderBy->nExpr - pSort->nOBSat;
109857  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109858    int regSortOut = ++pParse->nMem;
109859    iSortTab = pParse->nTab++;
109860    if( pSort->labelBkOut ){
109861      addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
109862    }
109863    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
109864    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
109865    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
109866    VdbeCoverage(v);
109867    codeOffset(v, p->iOffset, addrContinue);
109868    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
109869    bSeq = 0;
109870  }else{
109871    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
109872    codeOffset(v, p->iOffset, addrContinue);
109873    iSortTab = iTab;
109874    bSeq = 1;
109875  }
109876  for(i=0; i<nSortData; i++){
109877    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
109878    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
109879  }
109880  switch( eDest ){
109881    case SRT_EphemTab: {
109882      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
109883      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
109884      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
109885      break;
109886    }
109887#ifndef SQLITE_OMIT_SUBQUERY
109888    case SRT_Set: {
109889      assert( nColumn==1 );
109890      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
109891                        &pDest->affSdst, 1);
109892      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
109893      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
109894      break;
109895    }
109896    case SRT_Mem: {
109897      assert( nColumn==1 );
109898      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
109899      /* The LIMIT clause will terminate the loop for us */
109900      break;
109901    }
109902#endif
109903    default: {
109904      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
109905      testcase( eDest==SRT_Output );
109906      testcase( eDest==SRT_Coroutine );
109907      if( eDest==SRT_Output ){
109908        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
109909        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
109910      }else{
109911        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
109912      }
109913      break;
109914    }
109915  }
109916  if( regRowid ){
109917    sqlite3ReleaseTempReg(pParse, regRow);
109918    sqlite3ReleaseTempReg(pParse, regRowid);
109919  }
109920  /* The bottom of the loop
109921  */
109922  sqlite3VdbeResolveLabel(v, addrContinue);
109923  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109924    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
109925  }else{
109926    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
109927  }
109928  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
109929  sqlite3VdbeResolveLabel(v, addrBreak);
109930}
109931
109932/*
109933** Return a pointer to a string containing the 'declaration type' of the
109934** expression pExpr. The string may be treated as static by the caller.
109935**
109936** Also try to estimate the size of the returned value and return that
109937** result in *pEstWidth.
109938**
109939** The declaration type is the exact datatype definition extracted from the
109940** original CREATE TABLE statement if the expression is a column. The
109941** declaration type for a ROWID field is INTEGER. Exactly when an expression
109942** is considered a column can be complex in the presence of subqueries. The
109943** result-set expression in all of the following SELECT statements is
109944** considered a column by this function.
109945**
109946**   SELECT col FROM tbl;
109947**   SELECT (SELECT col FROM tbl;
109948**   SELECT (SELECT col FROM tbl);
109949**   SELECT abc FROM (SELECT col AS abc FROM tbl);
109950**
109951** The declaration type for any expression other than a column is NULL.
109952**
109953** This routine has either 3 or 6 parameters depending on whether or not
109954** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
109955*/
109956#ifdef SQLITE_ENABLE_COLUMN_METADATA
109957# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
109958#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
109959# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
109960#endif
109961static const char *columnTypeImpl(
109962  NameContext *pNC,
109963  Expr *pExpr,
109964#ifdef SQLITE_ENABLE_COLUMN_METADATA
109965  const char **pzOrigDb,
109966  const char **pzOrigTab,
109967  const char **pzOrigCol,
109968#endif
109969  u8 *pEstWidth
109970){
109971  char const *zType = 0;
109972  int j;
109973  u8 estWidth = 1;
109974#ifdef SQLITE_ENABLE_COLUMN_METADATA
109975  char const *zOrigDb = 0;
109976  char const *zOrigTab = 0;
109977  char const *zOrigCol = 0;
109978#endif
109979
109980  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
109981  switch( pExpr->op ){
109982    case TK_AGG_COLUMN:
109983    case TK_COLUMN: {
109984      /* The expression is a column. Locate the table the column is being
109985      ** extracted from in NameContext.pSrcList. This table may be real
109986      ** database table or a subquery.
109987      */
109988      Table *pTab = 0;            /* Table structure column is extracted from */
109989      Select *pS = 0;             /* Select the column is extracted from */
109990      int iCol = pExpr->iColumn;  /* Index of column in pTab */
109991      testcase( pExpr->op==TK_AGG_COLUMN );
109992      testcase( pExpr->op==TK_COLUMN );
109993      while( pNC && !pTab ){
109994        SrcList *pTabList = pNC->pSrcList;
109995        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
109996        if( j<pTabList->nSrc ){
109997          pTab = pTabList->a[j].pTab;
109998          pS = pTabList->a[j].pSelect;
109999        }else{
110000          pNC = pNC->pNext;
110001        }
110002      }
110003
110004      if( pTab==0 ){
110005        /* At one time, code such as "SELECT new.x" within a trigger would
110006        ** cause this condition to run.  Since then, we have restructured how
110007        ** trigger code is generated and so this condition is no longer
110008        ** possible. However, it can still be true for statements like
110009        ** the following:
110010        **
110011        **   CREATE TABLE t1(col INTEGER);
110012        **   SELECT (SELECT t1.col) FROM FROM t1;
110013        **
110014        ** when columnType() is called on the expression "t1.col" in the
110015        ** sub-select. In this case, set the column type to NULL, even
110016        ** though it should really be "INTEGER".
110017        **
110018        ** This is not a problem, as the column type of "t1.col" is never
110019        ** used. When columnType() is called on the expression
110020        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
110021        ** branch below.  */
110022        break;
110023      }
110024
110025      assert( pTab && pExpr->pTab==pTab );
110026      if( pS ){
110027        /* The "table" is actually a sub-select or a view in the FROM clause
110028        ** of the SELECT statement. Return the declaration type and origin
110029        ** data for the result-set column of the sub-select.
110030        */
110031        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
110032          /* If iCol is less than zero, then the expression requests the
110033          ** rowid of the sub-select or view. This expression is legal (see
110034          ** test case misc2.2.2) - it always evaluates to NULL.
110035          **
110036          ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
110037          ** caught already by name resolution.
110038          */
110039          NameContext sNC;
110040          Expr *p = pS->pEList->a[iCol].pExpr;
110041          sNC.pSrcList = pS->pSrc;
110042          sNC.pNext = pNC;
110043          sNC.pParse = pNC->pParse;
110044          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
110045        }
110046      }else if( pTab->pSchema ){
110047        /* A real table */
110048        assert( !pS );
110049        if( iCol<0 ) iCol = pTab->iPKey;
110050        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
110051#ifdef SQLITE_ENABLE_COLUMN_METADATA
110052        if( iCol<0 ){
110053          zType = "INTEGER";
110054          zOrigCol = "rowid";
110055        }else{
110056          zType = pTab->aCol[iCol].zType;
110057          zOrigCol = pTab->aCol[iCol].zName;
110058          estWidth = pTab->aCol[iCol].szEst;
110059        }
110060        zOrigTab = pTab->zName;
110061        if( pNC->pParse ){
110062          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
110063          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
110064        }
110065#else
110066        if( iCol<0 ){
110067          zType = "INTEGER";
110068        }else{
110069          zType = pTab->aCol[iCol].zType;
110070          estWidth = pTab->aCol[iCol].szEst;
110071        }
110072#endif
110073      }
110074      break;
110075    }
110076#ifndef SQLITE_OMIT_SUBQUERY
110077    case TK_SELECT: {
110078      /* The expression is a sub-select. Return the declaration type and
110079      ** origin info for the single column in the result set of the SELECT
110080      ** statement.
110081      */
110082      NameContext sNC;
110083      Select *pS = pExpr->x.pSelect;
110084      Expr *p = pS->pEList->a[0].pExpr;
110085      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
110086      sNC.pSrcList = pS->pSrc;
110087      sNC.pNext = pNC;
110088      sNC.pParse = pNC->pParse;
110089      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
110090      break;
110091    }
110092#endif
110093  }
110094
110095#ifdef SQLITE_ENABLE_COLUMN_METADATA
110096  if( pzOrigDb ){
110097    assert( pzOrigTab && pzOrigCol );
110098    *pzOrigDb = zOrigDb;
110099    *pzOrigTab = zOrigTab;
110100    *pzOrigCol = zOrigCol;
110101  }
110102#endif
110103  if( pEstWidth ) *pEstWidth = estWidth;
110104  return zType;
110105}
110106
110107/*
110108** Generate code that will tell the VDBE the declaration types of columns
110109** in the result set.
110110*/
110111static void generateColumnTypes(
110112  Parse *pParse,      /* Parser context */
110113  SrcList *pTabList,  /* List of tables */
110114  ExprList *pEList    /* Expressions defining the result set */
110115){
110116#ifndef SQLITE_OMIT_DECLTYPE
110117  Vdbe *v = pParse->pVdbe;
110118  int i;
110119  NameContext sNC;
110120  sNC.pSrcList = pTabList;
110121  sNC.pParse = pParse;
110122  for(i=0; i<pEList->nExpr; i++){
110123    Expr *p = pEList->a[i].pExpr;
110124    const char *zType;
110125#ifdef SQLITE_ENABLE_COLUMN_METADATA
110126    const char *zOrigDb = 0;
110127    const char *zOrigTab = 0;
110128    const char *zOrigCol = 0;
110129    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
110130
110131    /* The vdbe must make its own copy of the column-type and other
110132    ** column specific strings, in case the schema is reset before this
110133    ** virtual machine is deleted.
110134    */
110135    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
110136    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
110137    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
110138#else
110139    zType = columnType(&sNC, p, 0, 0, 0, 0);
110140#endif
110141    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
110142  }
110143#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
110144}
110145
110146/*
110147** Generate code that will tell the VDBE the names of columns
110148** in the result set.  This information is used to provide the
110149** azCol[] values in the callback.
110150*/
110151static void generateColumnNames(
110152  Parse *pParse,      /* Parser context */
110153  SrcList *pTabList,  /* List of tables */
110154  ExprList *pEList    /* Expressions defining the result set */
110155){
110156  Vdbe *v = pParse->pVdbe;
110157  int i, j;
110158  sqlite3 *db = pParse->db;
110159  int fullNames, shortNames;
110160
110161#ifndef SQLITE_OMIT_EXPLAIN
110162  /* If this is an EXPLAIN, skip this step */
110163  if( pParse->explain ){
110164    return;
110165  }
110166#endif
110167
110168  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
110169  pParse->colNamesSet = 1;
110170  fullNames = (db->flags & SQLITE_FullColNames)!=0;
110171  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
110172  sqlite3VdbeSetNumCols(v, pEList->nExpr);
110173  for(i=0; i<pEList->nExpr; i++){
110174    Expr *p;
110175    p = pEList->a[i].pExpr;
110176    if( NEVER(p==0) ) continue;
110177    if( pEList->a[i].zName ){
110178      char *zName = pEList->a[i].zName;
110179      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
110180    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
110181      Table *pTab;
110182      char *zCol;
110183      int iCol = p->iColumn;
110184      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
110185        if( pTabList->a[j].iCursor==p->iTable ) break;
110186      }
110187      assert( j<pTabList->nSrc );
110188      pTab = pTabList->a[j].pTab;
110189      if( iCol<0 ) iCol = pTab->iPKey;
110190      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
110191      if( iCol<0 ){
110192        zCol = "rowid";
110193      }else{
110194        zCol = pTab->aCol[iCol].zName;
110195      }
110196      if( !shortNames && !fullNames ){
110197        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
110198            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
110199      }else if( fullNames ){
110200        char *zName = 0;
110201        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
110202        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
110203      }else{
110204        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
110205      }
110206    }else{
110207      const char *z = pEList->a[i].zSpan;
110208      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
110209      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
110210    }
110211  }
110212  generateColumnTypes(pParse, pTabList, pEList);
110213}
110214
110215/*
110216** Given an expression list (which is really the list of expressions
110217** that form the result set of a SELECT statement) compute appropriate
110218** column names for a table that would hold the expression list.
110219**
110220** All column names will be unique.
110221**
110222** Only the column names are computed.  Column.zType, Column.zColl,
110223** and other fields of Column are zeroed.
110224**
110225** Return SQLITE_OK on success.  If a memory allocation error occurs,
110226** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
110227*/
110228SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
110229  Parse *pParse,          /* Parsing context */
110230  ExprList *pEList,       /* Expr list from which to derive column names */
110231  i16 *pnCol,             /* Write the number of columns here */
110232  Column **paCol          /* Write the new column list here */
110233){
110234  sqlite3 *db = pParse->db;   /* Database connection */
110235  int i, j;                   /* Loop counters */
110236  int cnt;                    /* Index added to make the name unique */
110237  Column *aCol, *pCol;        /* For looping over result columns */
110238  int nCol;                   /* Number of columns in the result set */
110239  Expr *p;                    /* Expression for a single result column */
110240  char *zName;                /* Column name */
110241  int nName;                  /* Size of name in zName[] */
110242
110243  if( pEList ){
110244    nCol = pEList->nExpr;
110245    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
110246    testcase( aCol==0 );
110247  }else{
110248    nCol = 0;
110249    aCol = 0;
110250  }
110251  *pnCol = nCol;
110252  *paCol = aCol;
110253
110254  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
110255    /* Get an appropriate name for the column
110256    */
110257    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
110258    if( (zName = pEList->a[i].zName)!=0 ){
110259      /* If the column contains an "AS <name>" phrase, use <name> as the name */
110260      zName = sqlite3DbStrDup(db, zName);
110261    }else{
110262      Expr *pColExpr = p;  /* The expression that is the result column name */
110263      Table *pTab;         /* Table associated with this expression */
110264      while( pColExpr->op==TK_DOT ){
110265        pColExpr = pColExpr->pRight;
110266        assert( pColExpr!=0 );
110267      }
110268      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
110269        /* For columns use the column name name */
110270        int iCol = pColExpr->iColumn;
110271        pTab = pColExpr->pTab;
110272        if( iCol<0 ) iCol = pTab->iPKey;
110273        zName = sqlite3MPrintf(db, "%s",
110274                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
110275      }else if( pColExpr->op==TK_ID ){
110276        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
110277        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
110278      }else{
110279        /* Use the original text of the column expression as its name */
110280        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
110281      }
110282    }
110283    if( db->mallocFailed ){
110284      sqlite3DbFree(db, zName);
110285      break;
110286    }
110287
110288    /* Make sure the column name is unique.  If the name is not unique,
110289    ** append an integer to the name so that it becomes unique.
110290    */
110291    nName = sqlite3Strlen30(zName);
110292    for(j=cnt=0; j<i; j++){
110293      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
110294        char *zNewName;
110295        int k;
110296        for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
110297        if( k>=0 && zName[k]==':' ) nName = k;
110298        zName[nName] = 0;
110299        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
110300        sqlite3DbFree(db, zName);
110301        zName = zNewName;
110302        j = -1;
110303        if( zName==0 ) break;
110304      }
110305    }
110306    pCol->zName = zName;
110307  }
110308  if( db->mallocFailed ){
110309    for(j=0; j<i; j++){
110310      sqlite3DbFree(db, aCol[j].zName);
110311    }
110312    sqlite3DbFree(db, aCol);
110313    *paCol = 0;
110314    *pnCol = 0;
110315    return SQLITE_NOMEM;
110316  }
110317  return SQLITE_OK;
110318}
110319
110320/*
110321** Add type and collation information to a column list based on
110322** a SELECT statement.
110323**
110324** The column list presumably came from selectColumnNamesFromExprList().
110325** The column list has only names, not types or collations.  This
110326** routine goes through and adds the types and collations.
110327**
110328** This routine requires that all identifiers in the SELECT
110329** statement be resolved.
110330*/
110331static void selectAddColumnTypeAndCollation(
110332  Parse *pParse,        /* Parsing contexts */
110333  Table *pTab,          /* Add column type information to this table */
110334  Select *pSelect       /* SELECT used to determine types and collations */
110335){
110336  sqlite3 *db = pParse->db;
110337  NameContext sNC;
110338  Column *pCol;
110339  CollSeq *pColl;
110340  int i;
110341  Expr *p;
110342  struct ExprList_item *a;
110343  u64 szAll = 0;
110344
110345  assert( pSelect!=0 );
110346  assert( (pSelect->selFlags & SF_Resolved)!=0 );
110347  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
110348  if( db->mallocFailed ) return;
110349  memset(&sNC, 0, sizeof(sNC));
110350  sNC.pSrcList = pSelect->pSrc;
110351  a = pSelect->pEList->a;
110352  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
110353    p = a[i].pExpr;
110354    if( pCol->zType==0 ){
110355      pCol->zType = sqlite3DbStrDup(db,
110356                        columnType(&sNC, p,0,0,0, &pCol->szEst));
110357    }
110358    szAll += pCol->szEst;
110359    pCol->affinity = sqlite3ExprAffinity(p);
110360    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
110361    pColl = sqlite3ExprCollSeq(pParse, p);
110362    if( pColl && pCol->zColl==0 ){
110363      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
110364    }
110365  }
110366  pTab->szTabRow = sqlite3LogEst(szAll*4);
110367}
110368
110369/*
110370** Given a SELECT statement, generate a Table structure that describes
110371** the result set of that SELECT.
110372*/
110373SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
110374  Table *pTab;
110375  sqlite3 *db = pParse->db;
110376  int savedFlags;
110377
110378  savedFlags = db->flags;
110379  db->flags &= ~SQLITE_FullColNames;
110380  db->flags |= SQLITE_ShortColNames;
110381  sqlite3SelectPrep(pParse, pSelect, 0);
110382  if( pParse->nErr ) return 0;
110383  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
110384  db->flags = savedFlags;
110385  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
110386  if( pTab==0 ){
110387    return 0;
110388  }
110389  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
110390  ** is disabled */
110391  assert( db->lookaside.bEnabled==0 );
110392  pTab->nRef = 1;
110393  pTab->zName = 0;
110394  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110395  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
110396  selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
110397  pTab->iPKey = -1;
110398  if( db->mallocFailed ){
110399    sqlite3DeleteTable(db, pTab);
110400    return 0;
110401  }
110402  return pTab;
110403}
110404
110405/*
110406** Get a VDBE for the given parser context.  Create a new one if necessary.
110407** If an error occurs, return NULL and leave a message in pParse.
110408*/
110409SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
110410  Vdbe *v = pParse->pVdbe;
110411  if( v==0 ){
110412    v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
110413    if( v ) sqlite3VdbeAddOp0(v, OP_Init);
110414    if( pParse->pToplevel==0
110415     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
110416    ){
110417      pParse->okConstFactor = 1;
110418    }
110419
110420  }
110421  return v;
110422}
110423
110424
110425/*
110426** Compute the iLimit and iOffset fields of the SELECT based on the
110427** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
110428** that appear in the original SQL statement after the LIMIT and OFFSET
110429** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
110430** are the integer memory register numbers for counters used to compute
110431** the limit and offset.  If there is no limit and/or offset, then
110432** iLimit and iOffset are negative.
110433**
110434** This routine changes the values of iLimit and iOffset only if
110435** a limit or offset is defined by pLimit and pOffset.  iLimit and
110436** iOffset should have been preset to appropriate default values (zero)
110437** prior to calling this routine.
110438**
110439** The iOffset register (if it exists) is initialized to the value
110440** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
110441** iOffset+1 is initialized to LIMIT+OFFSET.
110442**
110443** Only if pLimit!=0 or pOffset!=0 do the limit registers get
110444** redefined.  The UNION ALL operator uses this property to force
110445** the reuse of the same limit and offset registers across multiple
110446** SELECT statements.
110447*/
110448static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
110449  Vdbe *v = 0;
110450  int iLimit = 0;
110451  int iOffset;
110452  int n;
110453  if( p->iLimit ) return;
110454
110455  /*
110456  ** "LIMIT -1" always shows all rows.  There is some
110457  ** controversy about what the correct behavior should be.
110458  ** The current implementation interprets "LIMIT 0" to mean
110459  ** no rows.
110460  */
110461  sqlite3ExprCacheClear(pParse);
110462  assert( p->pOffset==0 || p->pLimit!=0 );
110463  if( p->pLimit ){
110464    p->iLimit = iLimit = ++pParse->nMem;
110465    v = sqlite3GetVdbe(pParse);
110466    assert( v!=0 );
110467    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
110468      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
110469      VdbeComment((v, "LIMIT counter"));
110470      if( n==0 ){
110471        sqlite3VdbeGoto(v, iBreak);
110472      }else if( n>=0 && p->nSelectRow>(u64)n ){
110473        p->nSelectRow = n;
110474      }
110475    }else{
110476      sqlite3ExprCode(pParse, p->pLimit, iLimit);
110477      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
110478      VdbeComment((v, "LIMIT counter"));
110479      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
110480    }
110481    if( p->pOffset ){
110482      p->iOffset = iOffset = ++pParse->nMem;
110483      pParse->nMem++;   /* Allocate an extra register for limit+offset */
110484      sqlite3ExprCode(pParse, p->pOffset, iOffset);
110485      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
110486      VdbeComment((v, "OFFSET counter"));
110487      sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
110488      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
110489      VdbeComment((v, "LIMIT+OFFSET"));
110490      sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
110491    }
110492  }
110493}
110494
110495#ifndef SQLITE_OMIT_COMPOUND_SELECT
110496/*
110497** Return the appropriate collating sequence for the iCol-th column of
110498** the result set for the compound-select statement "p".  Return NULL if
110499** the column has no default collating sequence.
110500**
110501** The collating sequence for the compound select is taken from the
110502** left-most term of the select that has a collating sequence.
110503*/
110504static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
110505  CollSeq *pRet;
110506  if( p->pPrior ){
110507    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
110508  }else{
110509    pRet = 0;
110510  }
110511  assert( iCol>=0 );
110512  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
110513  ** have been thrown during name resolution and we would not have gotten
110514  ** this far */
110515  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
110516    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
110517  }
110518  return pRet;
110519}
110520
110521/*
110522** The select statement passed as the second parameter is a compound SELECT
110523** with an ORDER BY clause. This function allocates and returns a KeyInfo
110524** structure suitable for implementing the ORDER BY.
110525**
110526** Space to hold the KeyInfo structure is obtained from malloc. The calling
110527** function is responsible for ensuring that this structure is eventually
110528** freed.
110529*/
110530static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
110531  ExprList *pOrderBy = p->pOrderBy;
110532  int nOrderBy = p->pOrderBy->nExpr;
110533  sqlite3 *db = pParse->db;
110534  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
110535  if( pRet ){
110536    int i;
110537    for(i=0; i<nOrderBy; i++){
110538      struct ExprList_item *pItem = &pOrderBy->a[i];
110539      Expr *pTerm = pItem->pExpr;
110540      CollSeq *pColl;
110541
110542      if( pTerm->flags & EP_Collate ){
110543        pColl = sqlite3ExprCollSeq(pParse, pTerm);
110544      }else{
110545        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
110546        if( pColl==0 ) pColl = db->pDfltColl;
110547        pOrderBy->a[i].pExpr =
110548          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
110549      }
110550      assert( sqlite3KeyInfoIsWriteable(pRet) );
110551      pRet->aColl[i] = pColl;
110552      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
110553    }
110554  }
110555
110556  return pRet;
110557}
110558
110559#ifndef SQLITE_OMIT_CTE
110560/*
110561** This routine generates VDBE code to compute the content of a WITH RECURSIVE
110562** query of the form:
110563**
110564**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
110565**                         \___________/             \_______________/
110566**                           p->pPrior                      p
110567**
110568**
110569** There is exactly one reference to the recursive-table in the FROM clause
110570** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
110571**
110572** The setup-query runs once to generate an initial set of rows that go
110573** into a Queue table.  Rows are extracted from the Queue table one by
110574** one.  Each row extracted from Queue is output to pDest.  Then the single
110575** extracted row (now in the iCurrent table) becomes the content of the
110576** recursive-table for a recursive-query run.  The output of the recursive-query
110577** is added back into the Queue table.  Then another row is extracted from Queue
110578** and the iteration continues until the Queue table is empty.
110579**
110580** If the compound query operator is UNION then no duplicate rows are ever
110581** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
110582** that have ever been inserted into Queue and causes duplicates to be
110583** discarded.  If the operator is UNION ALL, then duplicates are allowed.
110584**
110585** If the query has an ORDER BY, then entries in the Queue table are kept in
110586** ORDER BY order and the first entry is extracted for each cycle.  Without
110587** an ORDER BY, the Queue table is just a FIFO.
110588**
110589** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
110590** have been output to pDest.  A LIMIT of zero means to output no rows and a
110591** negative LIMIT means to output all rows.  If there is also an OFFSET clause
110592** with a positive value, then the first OFFSET outputs are discarded rather
110593** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
110594** rows have been skipped.
110595*/
110596static void generateWithRecursiveQuery(
110597  Parse *pParse,        /* Parsing context */
110598  Select *p,            /* The recursive SELECT to be coded */
110599  SelectDest *pDest     /* What to do with query results */
110600){
110601  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
110602  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
110603  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
110604  Select *pSetup = p->pPrior;   /* The setup query */
110605  int addrTop;                  /* Top of the loop */
110606  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
110607  int iCurrent = 0;             /* The Current table */
110608  int regCurrent;               /* Register holding Current table */
110609  int iQueue;                   /* The Queue table */
110610  int iDistinct = 0;            /* To ensure unique results if UNION */
110611  int eDest = SRT_Fifo;         /* How to write to Queue */
110612  SelectDest destQueue;         /* SelectDest targetting the Queue table */
110613  int i;                        /* Loop counter */
110614  int rc;                       /* Result code */
110615  ExprList *pOrderBy;           /* The ORDER BY clause */
110616  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
110617  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
110618
110619  /* Obtain authorization to do a recursive query */
110620  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
110621
110622  /* Process the LIMIT and OFFSET clauses, if they exist */
110623  addrBreak = sqlite3VdbeMakeLabel(v);
110624  computeLimitRegisters(pParse, p, addrBreak);
110625  pLimit = p->pLimit;
110626  pOffset = p->pOffset;
110627  regLimit = p->iLimit;
110628  regOffset = p->iOffset;
110629  p->pLimit = p->pOffset = 0;
110630  p->iLimit = p->iOffset = 0;
110631  pOrderBy = p->pOrderBy;
110632
110633  /* Locate the cursor number of the Current table */
110634  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
110635    if( pSrc->a[i].fg.isRecursive ){
110636      iCurrent = pSrc->a[i].iCursor;
110637      break;
110638    }
110639  }
110640
110641  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
110642  ** the Distinct table must be exactly one greater than Queue in order
110643  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
110644  iQueue = pParse->nTab++;
110645  if( p->op==TK_UNION ){
110646    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
110647    iDistinct = pParse->nTab++;
110648  }else{
110649    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
110650  }
110651  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
110652
110653  /* Allocate cursors for Current, Queue, and Distinct. */
110654  regCurrent = ++pParse->nMem;
110655  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
110656  if( pOrderBy ){
110657    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
110658    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
110659                      (char*)pKeyInfo, P4_KEYINFO);
110660    destQueue.pOrderBy = pOrderBy;
110661  }else{
110662    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
110663  }
110664  VdbeComment((v, "Queue table"));
110665  if( iDistinct ){
110666    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
110667    p->selFlags |= SF_UsesEphemeral;
110668  }
110669
110670  /* Detach the ORDER BY clause from the compound SELECT */
110671  p->pOrderBy = 0;
110672
110673  /* Store the results of the setup-query in Queue. */
110674  pSetup->pNext = 0;
110675  rc = sqlite3Select(pParse, pSetup, &destQueue);
110676  pSetup->pNext = p;
110677  if( rc ) goto end_of_recursive_query;
110678
110679  /* Find the next row in the Queue and output that row */
110680  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
110681
110682  /* Transfer the next row in Queue over to Current */
110683  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
110684  if( pOrderBy ){
110685    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
110686  }else{
110687    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
110688  }
110689  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
110690
110691  /* Output the single row in Current */
110692  addrCont = sqlite3VdbeMakeLabel(v);
110693  codeOffset(v, regOffset, addrCont);
110694  selectInnerLoop(pParse, p, p->pEList, iCurrent,
110695      0, 0, pDest, addrCont, addrBreak);
110696  if( regLimit ){
110697    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
110698    VdbeCoverage(v);
110699  }
110700  sqlite3VdbeResolveLabel(v, addrCont);
110701
110702  /* Execute the recursive SELECT taking the single row in Current as
110703  ** the value for the recursive-table. Store the results in the Queue.
110704  */
110705  if( p->selFlags & SF_Aggregate ){
110706    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
110707  }else{
110708    p->pPrior = 0;
110709    sqlite3Select(pParse, p, &destQueue);
110710    assert( p->pPrior==0 );
110711    p->pPrior = pSetup;
110712  }
110713
110714  /* Keep running the loop until the Queue is empty */
110715  sqlite3VdbeGoto(v, addrTop);
110716  sqlite3VdbeResolveLabel(v, addrBreak);
110717
110718end_of_recursive_query:
110719  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
110720  p->pOrderBy = pOrderBy;
110721  p->pLimit = pLimit;
110722  p->pOffset = pOffset;
110723  return;
110724}
110725#endif /* SQLITE_OMIT_CTE */
110726
110727/* Forward references */
110728static int multiSelectOrderBy(
110729  Parse *pParse,        /* Parsing context */
110730  Select *p,            /* The right-most of SELECTs to be coded */
110731  SelectDest *pDest     /* What to do with query results */
110732);
110733
110734/*
110735** Handle the special case of a compound-select that originates from a
110736** VALUES clause.  By handling this as a special case, we avoid deep
110737** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
110738** on a VALUES clause.
110739**
110740** Because the Select object originates from a VALUES clause:
110741**   (1) It has no LIMIT or OFFSET
110742**   (2) All terms are UNION ALL
110743**   (3) There is no ORDER BY clause
110744*/
110745static int multiSelectValues(
110746  Parse *pParse,        /* Parsing context */
110747  Select *p,            /* The right-most of SELECTs to be coded */
110748  SelectDest *pDest     /* What to do with query results */
110749){
110750  Select *pPrior;
110751  int nRow = 1;
110752  int rc = 0;
110753  assert( p->selFlags & SF_MultiValue );
110754  do{
110755    assert( p->selFlags & SF_Values );
110756    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
110757    assert( p->pLimit==0 );
110758    assert( p->pOffset==0 );
110759    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
110760    if( p->pPrior==0 ) break;
110761    assert( p->pPrior->pNext==p );
110762    p = p->pPrior;
110763    nRow++;
110764  }while(1);
110765  while( p ){
110766    pPrior = p->pPrior;
110767    p->pPrior = 0;
110768    rc = sqlite3Select(pParse, p, pDest);
110769    p->pPrior = pPrior;
110770    if( rc ) break;
110771    p->nSelectRow = nRow;
110772    p = p->pNext;
110773  }
110774  return rc;
110775}
110776
110777/*
110778** This routine is called to process a compound query form from
110779** two or more separate queries using UNION, UNION ALL, EXCEPT, or
110780** INTERSECT
110781**
110782** "p" points to the right-most of the two queries.  the query on the
110783** left is p->pPrior.  The left query could also be a compound query
110784** in which case this routine will be called recursively.
110785**
110786** The results of the total query are to be written into a destination
110787** of type eDest with parameter iParm.
110788**
110789** Example 1:  Consider a three-way compound SQL statement.
110790**
110791**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
110792**
110793** This statement is parsed up as follows:
110794**
110795**     SELECT c FROM t3
110796**      |
110797**      `----->  SELECT b FROM t2
110798**                |
110799**                `------>  SELECT a FROM t1
110800**
110801** The arrows in the diagram above represent the Select.pPrior pointer.
110802** So if this routine is called with p equal to the t3 query, then
110803** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
110804**
110805** Notice that because of the way SQLite parses compound SELECTs, the
110806** individual selects always group from left to right.
110807*/
110808static int multiSelect(
110809  Parse *pParse,        /* Parsing context */
110810  Select *p,            /* The right-most of SELECTs to be coded */
110811  SelectDest *pDest     /* What to do with query results */
110812){
110813  int rc = SQLITE_OK;   /* Success code from a subroutine */
110814  Select *pPrior;       /* Another SELECT immediately to our left */
110815  Vdbe *v;              /* Generate code to this VDBE */
110816  SelectDest dest;      /* Alternative data destination */
110817  Select *pDelete = 0;  /* Chain of simple selects to delete */
110818  sqlite3 *db;          /* Database connection */
110819#ifndef SQLITE_OMIT_EXPLAIN
110820  int iSub1 = 0;        /* EQP id of left-hand query */
110821  int iSub2 = 0;        /* EQP id of right-hand query */
110822#endif
110823
110824  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
110825  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
110826  */
110827  assert( p && p->pPrior );  /* Calling function guarantees this much */
110828  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
110829  db = pParse->db;
110830  pPrior = p->pPrior;
110831  dest = *pDest;
110832  if( pPrior->pOrderBy ){
110833    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
110834      selectOpName(p->op));
110835    rc = 1;
110836    goto multi_select_end;
110837  }
110838  if( pPrior->pLimit ){
110839    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
110840      selectOpName(p->op));
110841    rc = 1;
110842    goto multi_select_end;
110843  }
110844
110845  v = sqlite3GetVdbe(pParse);
110846  assert( v!=0 );  /* The VDBE already created by calling function */
110847
110848  /* Create the destination temporary table if necessary
110849  */
110850  if( dest.eDest==SRT_EphemTab ){
110851    assert( p->pEList );
110852    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
110853    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
110854    dest.eDest = SRT_Table;
110855  }
110856
110857  /* Special handling for a compound-select that originates as a VALUES clause.
110858  */
110859  if( p->selFlags & SF_MultiValue ){
110860    rc = multiSelectValues(pParse, p, &dest);
110861    goto multi_select_end;
110862  }
110863
110864  /* Make sure all SELECTs in the statement have the same number of elements
110865  ** in their result sets.
110866  */
110867  assert( p->pEList && pPrior->pEList );
110868  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
110869
110870#ifndef SQLITE_OMIT_CTE
110871  if( p->selFlags & SF_Recursive ){
110872    generateWithRecursiveQuery(pParse, p, &dest);
110873  }else
110874#endif
110875
110876  /* Compound SELECTs that have an ORDER BY clause are handled separately.
110877  */
110878  if( p->pOrderBy ){
110879    return multiSelectOrderBy(pParse, p, pDest);
110880  }else
110881
110882  /* Generate code for the left and right SELECT statements.
110883  */
110884  switch( p->op ){
110885    case TK_ALL: {
110886      int addr = 0;
110887      int nLimit;
110888      assert( !pPrior->pLimit );
110889      pPrior->iLimit = p->iLimit;
110890      pPrior->iOffset = p->iOffset;
110891      pPrior->pLimit = p->pLimit;
110892      pPrior->pOffset = p->pOffset;
110893      explainSetInteger(iSub1, pParse->iNextSelectId);
110894      rc = sqlite3Select(pParse, pPrior, &dest);
110895      p->pLimit = 0;
110896      p->pOffset = 0;
110897      if( rc ){
110898        goto multi_select_end;
110899      }
110900      p->pPrior = 0;
110901      p->iLimit = pPrior->iLimit;
110902      p->iOffset = pPrior->iOffset;
110903      if( p->iLimit ){
110904        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
110905        VdbeComment((v, "Jump ahead if LIMIT reached"));
110906        if( p->iOffset ){
110907          sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
110908          sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
110909          sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
110910        }
110911      }
110912      explainSetInteger(iSub2, pParse->iNextSelectId);
110913      rc = sqlite3Select(pParse, p, &dest);
110914      testcase( rc!=SQLITE_OK );
110915      pDelete = p->pPrior;
110916      p->pPrior = pPrior;
110917      p->nSelectRow += pPrior->nSelectRow;
110918      if( pPrior->pLimit
110919       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
110920       && nLimit>0 && p->nSelectRow > (u64)nLimit
110921      ){
110922        p->nSelectRow = nLimit;
110923      }
110924      if( addr ){
110925        sqlite3VdbeJumpHere(v, addr);
110926      }
110927      break;
110928    }
110929    case TK_EXCEPT:
110930    case TK_UNION: {
110931      int unionTab;    /* Cursor number of the temporary table holding result */
110932      u8 op = 0;       /* One of the SRT_ operations to apply to self */
110933      int priorOp;     /* The SRT_ operation to apply to prior selects */
110934      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
110935      int addr;
110936      SelectDest uniondest;
110937
110938      testcase( p->op==TK_EXCEPT );
110939      testcase( p->op==TK_UNION );
110940      priorOp = SRT_Union;
110941      if( dest.eDest==priorOp ){
110942        /* We can reuse a temporary table generated by a SELECT to our
110943        ** right.
110944        */
110945        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
110946        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
110947        unionTab = dest.iSDParm;
110948      }else{
110949        /* We will need to create our own temporary table to hold the
110950        ** intermediate results.
110951        */
110952        unionTab = pParse->nTab++;
110953        assert( p->pOrderBy==0 );
110954        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
110955        assert( p->addrOpenEphm[0] == -1 );
110956        p->addrOpenEphm[0] = addr;
110957        findRightmost(p)->selFlags |= SF_UsesEphemeral;
110958        assert( p->pEList );
110959      }
110960
110961      /* Code the SELECT statements to our left
110962      */
110963      assert( !pPrior->pOrderBy );
110964      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
110965      explainSetInteger(iSub1, pParse->iNextSelectId);
110966      rc = sqlite3Select(pParse, pPrior, &uniondest);
110967      if( rc ){
110968        goto multi_select_end;
110969      }
110970
110971      /* Code the current SELECT statement
110972      */
110973      if( p->op==TK_EXCEPT ){
110974        op = SRT_Except;
110975      }else{
110976        assert( p->op==TK_UNION );
110977        op = SRT_Union;
110978      }
110979      p->pPrior = 0;
110980      pLimit = p->pLimit;
110981      p->pLimit = 0;
110982      pOffset = p->pOffset;
110983      p->pOffset = 0;
110984      uniondest.eDest = op;
110985      explainSetInteger(iSub2, pParse->iNextSelectId);
110986      rc = sqlite3Select(pParse, p, &uniondest);
110987      testcase( rc!=SQLITE_OK );
110988      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
110989      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
110990      sqlite3ExprListDelete(db, p->pOrderBy);
110991      pDelete = p->pPrior;
110992      p->pPrior = pPrior;
110993      p->pOrderBy = 0;
110994      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
110995      sqlite3ExprDelete(db, p->pLimit);
110996      p->pLimit = pLimit;
110997      p->pOffset = pOffset;
110998      p->iLimit = 0;
110999      p->iOffset = 0;
111000
111001      /* Convert the data in the temporary table into whatever form
111002      ** it is that we currently need.
111003      */
111004      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
111005      if( dest.eDest!=priorOp ){
111006        int iCont, iBreak, iStart;
111007        assert( p->pEList );
111008        if( dest.eDest==SRT_Output ){
111009          Select *pFirst = p;
111010          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111011          generateColumnNames(pParse, 0, pFirst->pEList);
111012        }
111013        iBreak = sqlite3VdbeMakeLabel(v);
111014        iCont = sqlite3VdbeMakeLabel(v);
111015        computeLimitRegisters(pParse, p, iBreak);
111016        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
111017        iStart = sqlite3VdbeCurrentAddr(v);
111018        selectInnerLoop(pParse, p, p->pEList, unionTab,
111019                        0, 0, &dest, iCont, iBreak);
111020        sqlite3VdbeResolveLabel(v, iCont);
111021        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
111022        sqlite3VdbeResolveLabel(v, iBreak);
111023        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
111024      }
111025      break;
111026    }
111027    default: assert( p->op==TK_INTERSECT ); {
111028      int tab1, tab2;
111029      int iCont, iBreak, iStart;
111030      Expr *pLimit, *pOffset;
111031      int addr;
111032      SelectDest intersectdest;
111033      int r1;
111034
111035      /* INTERSECT is different from the others since it requires
111036      ** two temporary tables.  Hence it has its own case.  Begin
111037      ** by allocating the tables we will need.
111038      */
111039      tab1 = pParse->nTab++;
111040      tab2 = pParse->nTab++;
111041      assert( p->pOrderBy==0 );
111042
111043      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
111044      assert( p->addrOpenEphm[0] == -1 );
111045      p->addrOpenEphm[0] = addr;
111046      findRightmost(p)->selFlags |= SF_UsesEphemeral;
111047      assert( p->pEList );
111048
111049      /* Code the SELECTs to our left into temporary table "tab1".
111050      */
111051      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
111052      explainSetInteger(iSub1, pParse->iNextSelectId);
111053      rc = sqlite3Select(pParse, pPrior, &intersectdest);
111054      if( rc ){
111055        goto multi_select_end;
111056      }
111057
111058      /* Code the current SELECT into temporary table "tab2"
111059      */
111060      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
111061      assert( p->addrOpenEphm[1] == -1 );
111062      p->addrOpenEphm[1] = addr;
111063      p->pPrior = 0;
111064      pLimit = p->pLimit;
111065      p->pLimit = 0;
111066      pOffset = p->pOffset;
111067      p->pOffset = 0;
111068      intersectdest.iSDParm = tab2;
111069      explainSetInteger(iSub2, pParse->iNextSelectId);
111070      rc = sqlite3Select(pParse, p, &intersectdest);
111071      testcase( rc!=SQLITE_OK );
111072      pDelete = p->pPrior;
111073      p->pPrior = pPrior;
111074      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
111075      sqlite3ExprDelete(db, p->pLimit);
111076      p->pLimit = pLimit;
111077      p->pOffset = pOffset;
111078
111079      /* Generate code to take the intersection of the two temporary
111080      ** tables.
111081      */
111082      assert( p->pEList );
111083      if( dest.eDest==SRT_Output ){
111084        Select *pFirst = p;
111085        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111086        generateColumnNames(pParse, 0, pFirst->pEList);
111087      }
111088      iBreak = sqlite3VdbeMakeLabel(v);
111089      iCont = sqlite3VdbeMakeLabel(v);
111090      computeLimitRegisters(pParse, p, iBreak);
111091      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
111092      r1 = sqlite3GetTempReg(pParse);
111093      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
111094      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
111095      sqlite3ReleaseTempReg(pParse, r1);
111096      selectInnerLoop(pParse, p, p->pEList, tab1,
111097                      0, 0, &dest, iCont, iBreak);
111098      sqlite3VdbeResolveLabel(v, iCont);
111099      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
111100      sqlite3VdbeResolveLabel(v, iBreak);
111101      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
111102      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
111103      break;
111104    }
111105  }
111106
111107  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
111108
111109  /* Compute collating sequences used by
111110  ** temporary tables needed to implement the compound select.
111111  ** Attach the KeyInfo structure to all temporary tables.
111112  **
111113  ** This section is run by the right-most SELECT statement only.
111114  ** SELECT statements to the left always skip this part.  The right-most
111115  ** SELECT might also skip this part if it has no ORDER BY clause and
111116  ** no temp tables are required.
111117  */
111118  if( p->selFlags & SF_UsesEphemeral ){
111119    int i;                        /* Loop counter */
111120    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
111121    Select *pLoop;                /* For looping through SELECT statements */
111122    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
111123    int nCol;                     /* Number of columns in result set */
111124
111125    assert( p->pNext==0 );
111126    nCol = p->pEList->nExpr;
111127    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
111128    if( !pKeyInfo ){
111129      rc = SQLITE_NOMEM;
111130      goto multi_select_end;
111131    }
111132    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
111133      *apColl = multiSelectCollSeq(pParse, p, i);
111134      if( 0==*apColl ){
111135        *apColl = db->pDfltColl;
111136      }
111137    }
111138
111139    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
111140      for(i=0; i<2; i++){
111141        int addr = pLoop->addrOpenEphm[i];
111142        if( addr<0 ){
111143          /* If [0] is unused then [1] is also unused.  So we can
111144          ** always safely abort as soon as the first unused slot is found */
111145          assert( pLoop->addrOpenEphm[1]<0 );
111146          break;
111147        }
111148        sqlite3VdbeChangeP2(v, addr, nCol);
111149        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
111150                            P4_KEYINFO);
111151        pLoop->addrOpenEphm[i] = -1;
111152      }
111153    }
111154    sqlite3KeyInfoUnref(pKeyInfo);
111155  }
111156
111157multi_select_end:
111158  pDest->iSdst = dest.iSdst;
111159  pDest->nSdst = dest.nSdst;
111160  sqlite3SelectDelete(db, pDelete);
111161  return rc;
111162}
111163#endif /* SQLITE_OMIT_COMPOUND_SELECT */
111164
111165/*
111166** Error message for when two or more terms of a compound select have different
111167** size result sets.
111168*/
111169SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
111170  if( p->selFlags & SF_Values ){
111171    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
111172  }else{
111173    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
111174      " do not have the same number of result columns", selectOpName(p->op));
111175  }
111176}
111177
111178/*
111179** Code an output subroutine for a coroutine implementation of a
111180** SELECT statment.
111181**
111182** The data to be output is contained in pIn->iSdst.  There are
111183** pIn->nSdst columns to be output.  pDest is where the output should
111184** be sent.
111185**
111186** regReturn is the number of the register holding the subroutine
111187** return address.
111188**
111189** If regPrev>0 then it is the first register in a vector that
111190** records the previous output.  mem[regPrev] is a flag that is false
111191** if there has been no previous output.  If regPrev>0 then code is
111192** generated to suppress duplicates.  pKeyInfo is used for comparing
111193** keys.
111194**
111195** If the LIMIT found in p->iLimit is reached, jump immediately to
111196** iBreak.
111197*/
111198static int generateOutputSubroutine(
111199  Parse *pParse,          /* Parsing context */
111200  Select *p,              /* The SELECT statement */
111201  SelectDest *pIn,        /* Coroutine supplying data */
111202  SelectDest *pDest,      /* Where to send the data */
111203  int regReturn,          /* The return address register */
111204  int regPrev,            /* Previous result register.  No uniqueness if 0 */
111205  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
111206  int iBreak              /* Jump here if we hit the LIMIT */
111207){
111208  Vdbe *v = pParse->pVdbe;
111209  int iContinue;
111210  int addr;
111211
111212  addr = sqlite3VdbeCurrentAddr(v);
111213  iContinue = sqlite3VdbeMakeLabel(v);
111214
111215  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
111216  */
111217  if( regPrev ){
111218    int addr1, addr2;
111219    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
111220    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
111221                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
111222    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
111223    sqlite3VdbeJumpHere(v, addr1);
111224    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
111225    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
111226  }
111227  if( pParse->db->mallocFailed ) return 0;
111228
111229  /* Suppress the first OFFSET entries if there is an OFFSET clause
111230  */
111231  codeOffset(v, p->iOffset, iContinue);
111232
111233  assert( pDest->eDest!=SRT_Exists );
111234  assert( pDest->eDest!=SRT_Table );
111235  switch( pDest->eDest ){
111236    /* Store the result as data using a unique key.
111237    */
111238    case SRT_EphemTab: {
111239      int r1 = sqlite3GetTempReg(pParse);
111240      int r2 = sqlite3GetTempReg(pParse);
111241      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
111242      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
111243      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
111244      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
111245      sqlite3ReleaseTempReg(pParse, r2);
111246      sqlite3ReleaseTempReg(pParse, r1);
111247      break;
111248    }
111249
111250#ifndef SQLITE_OMIT_SUBQUERY
111251    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
111252    ** then there should be a single item on the stack.  Write this
111253    ** item into the set table with bogus data.
111254    */
111255    case SRT_Set: {
111256      int r1;
111257      assert( pIn->nSdst==1 || pParse->nErr>0 );
111258      pDest->affSdst =
111259         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
111260      r1 = sqlite3GetTempReg(pParse);
111261      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
111262      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
111263      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
111264      sqlite3ReleaseTempReg(pParse, r1);
111265      break;
111266    }
111267
111268    /* If this is a scalar select that is part of an expression, then
111269    ** store the results in the appropriate memory cell and break out
111270    ** of the scan loop.
111271    */
111272    case SRT_Mem: {
111273      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
111274      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
111275      /* The LIMIT clause will jump out of the loop for us */
111276      break;
111277    }
111278#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
111279
111280    /* The results are stored in a sequence of registers
111281    ** starting at pDest->iSdst.  Then the co-routine yields.
111282    */
111283    case SRT_Coroutine: {
111284      if( pDest->iSdst==0 ){
111285        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
111286        pDest->nSdst = pIn->nSdst;
111287      }
111288      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
111289      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
111290      break;
111291    }
111292
111293    /* If none of the above, then the result destination must be
111294    ** SRT_Output.  This routine is never called with any other
111295    ** destination other than the ones handled above or SRT_Output.
111296    **
111297    ** For SRT_Output, results are stored in a sequence of registers.
111298    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
111299    ** return the next row of result.
111300    */
111301    default: {
111302      assert( pDest->eDest==SRT_Output );
111303      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
111304      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
111305      break;
111306    }
111307  }
111308
111309  /* Jump to the end of the loop if the LIMIT is reached.
111310  */
111311  if( p->iLimit ){
111312    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
111313  }
111314
111315  /* Generate the subroutine return
111316  */
111317  sqlite3VdbeResolveLabel(v, iContinue);
111318  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
111319
111320  return addr;
111321}
111322
111323/*
111324** Alternative compound select code generator for cases when there
111325** is an ORDER BY clause.
111326**
111327** We assume a query of the following form:
111328**
111329**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
111330**
111331** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
111332** is to code both <selectA> and <selectB> with the ORDER BY clause as
111333** co-routines.  Then run the co-routines in parallel and merge the results
111334** into the output.  In addition to the two coroutines (called selectA and
111335** selectB) there are 7 subroutines:
111336**
111337**    outA:    Move the output of the selectA coroutine into the output
111338**             of the compound query.
111339**
111340**    outB:    Move the output of the selectB coroutine into the output
111341**             of the compound query.  (Only generated for UNION and
111342**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
111343**             appears only in B.)
111344**
111345**    AltB:    Called when there is data from both coroutines and A<B.
111346**
111347**    AeqB:    Called when there is data from both coroutines and A==B.
111348**
111349**    AgtB:    Called when there is data from both coroutines and A>B.
111350**
111351**    EofA:    Called when data is exhausted from selectA.
111352**
111353**    EofB:    Called when data is exhausted from selectB.
111354**
111355** The implementation of the latter five subroutines depend on which
111356** <operator> is used:
111357**
111358**
111359**             UNION ALL         UNION            EXCEPT          INTERSECT
111360**          -------------  -----------------  --------------  -----------------
111361**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
111362**
111363**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
111364**
111365**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
111366**
111367**   EofA:   outB, nextB      outB, nextB          halt             halt
111368**
111369**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
111370**
111371** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
111372** causes an immediate jump to EofA and an EOF on B following nextB causes
111373** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
111374** following nextX causes a jump to the end of the select processing.
111375**
111376** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
111377** within the output subroutine.  The regPrev register set holds the previously
111378** output value.  A comparison is made against this value and the output
111379** is skipped if the next results would be the same as the previous.
111380**
111381** The implementation plan is to implement the two coroutines and seven
111382** subroutines first, then put the control logic at the bottom.  Like this:
111383**
111384**          goto Init
111385**     coA: coroutine for left query (A)
111386**     coB: coroutine for right query (B)
111387**    outA: output one row of A
111388**    outB: output one row of B (UNION and UNION ALL only)
111389**    EofA: ...
111390**    EofB: ...
111391**    AltB: ...
111392**    AeqB: ...
111393**    AgtB: ...
111394**    Init: initialize coroutine registers
111395**          yield coA
111396**          if eof(A) goto EofA
111397**          yield coB
111398**          if eof(B) goto EofB
111399**    Cmpr: Compare A, B
111400**          Jump AltB, AeqB, AgtB
111401**     End: ...
111402**
111403** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
111404** actually called using Gosub and they do not Return.  EofA and EofB loop
111405** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
111406** and AgtB jump to either L2 or to one of EofA or EofB.
111407*/
111408#ifndef SQLITE_OMIT_COMPOUND_SELECT
111409static int multiSelectOrderBy(
111410  Parse *pParse,        /* Parsing context */
111411  Select *p,            /* The right-most of SELECTs to be coded */
111412  SelectDest *pDest     /* What to do with query results */
111413){
111414  int i, j;             /* Loop counters */
111415  Select *pPrior;       /* Another SELECT immediately to our left */
111416  Vdbe *v;              /* Generate code to this VDBE */
111417  SelectDest destA;     /* Destination for coroutine A */
111418  SelectDest destB;     /* Destination for coroutine B */
111419  int regAddrA;         /* Address register for select-A coroutine */
111420  int regAddrB;         /* Address register for select-B coroutine */
111421  int addrSelectA;      /* Address of the select-A coroutine */
111422  int addrSelectB;      /* Address of the select-B coroutine */
111423  int regOutA;          /* Address register for the output-A subroutine */
111424  int regOutB;          /* Address register for the output-B subroutine */
111425  int addrOutA;         /* Address of the output-A subroutine */
111426  int addrOutB = 0;     /* Address of the output-B subroutine */
111427  int addrEofA;         /* Address of the select-A-exhausted subroutine */
111428  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
111429  int addrEofB;         /* Address of the select-B-exhausted subroutine */
111430  int addrAltB;         /* Address of the A<B subroutine */
111431  int addrAeqB;         /* Address of the A==B subroutine */
111432  int addrAgtB;         /* Address of the A>B subroutine */
111433  int regLimitA;        /* Limit register for select-A */
111434  int regLimitB;        /* Limit register for select-A */
111435  int regPrev;          /* A range of registers to hold previous output */
111436  int savedLimit;       /* Saved value of p->iLimit */
111437  int savedOffset;      /* Saved value of p->iOffset */
111438  int labelCmpr;        /* Label for the start of the merge algorithm */
111439  int labelEnd;         /* Label for the end of the overall SELECT stmt */
111440  int addr1;            /* Jump instructions that get retargetted */
111441  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
111442  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
111443  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
111444  sqlite3 *db;          /* Database connection */
111445  ExprList *pOrderBy;   /* The ORDER BY clause */
111446  int nOrderBy;         /* Number of terms in the ORDER BY clause */
111447  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
111448#ifndef SQLITE_OMIT_EXPLAIN
111449  int iSub1;            /* EQP id of left-hand query */
111450  int iSub2;            /* EQP id of right-hand query */
111451#endif
111452
111453  assert( p->pOrderBy!=0 );
111454  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
111455  db = pParse->db;
111456  v = pParse->pVdbe;
111457  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
111458  labelEnd = sqlite3VdbeMakeLabel(v);
111459  labelCmpr = sqlite3VdbeMakeLabel(v);
111460
111461
111462  /* Patch up the ORDER BY clause
111463  */
111464  op = p->op;
111465  pPrior = p->pPrior;
111466  assert( pPrior->pOrderBy==0 );
111467  pOrderBy = p->pOrderBy;
111468  assert( pOrderBy );
111469  nOrderBy = pOrderBy->nExpr;
111470
111471  /* For operators other than UNION ALL we have to make sure that
111472  ** the ORDER BY clause covers every term of the result set.  Add
111473  ** terms to the ORDER BY clause as necessary.
111474  */
111475  if( op!=TK_ALL ){
111476    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
111477      struct ExprList_item *pItem;
111478      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
111479        assert( pItem->u.x.iOrderByCol>0 );
111480        if( pItem->u.x.iOrderByCol==i ) break;
111481      }
111482      if( j==nOrderBy ){
111483        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
111484        if( pNew==0 ) return SQLITE_NOMEM;
111485        pNew->flags |= EP_IntValue;
111486        pNew->u.iValue = i;
111487        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
111488        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
111489      }
111490    }
111491  }
111492
111493  /* Compute the comparison permutation and keyinfo that is used with
111494  ** the permutation used to determine if the next
111495  ** row of results comes from selectA or selectB.  Also add explicit
111496  ** collations to the ORDER BY clause terms so that when the subqueries
111497  ** to the right and the left are evaluated, they use the correct
111498  ** collation.
111499  */
111500  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
111501  if( aPermute ){
111502    struct ExprList_item *pItem;
111503    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
111504      assert( pItem->u.x.iOrderByCol>0 );
111505      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
111506      aPermute[i] = pItem->u.x.iOrderByCol - 1;
111507    }
111508    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
111509  }else{
111510    pKeyMerge = 0;
111511  }
111512
111513  /* Reattach the ORDER BY clause to the query.
111514  */
111515  p->pOrderBy = pOrderBy;
111516  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
111517
111518  /* Allocate a range of temporary registers and the KeyInfo needed
111519  ** for the logic that removes duplicate result rows when the
111520  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
111521  */
111522  if( op==TK_ALL ){
111523    regPrev = 0;
111524  }else{
111525    int nExpr = p->pEList->nExpr;
111526    assert( nOrderBy>=nExpr || db->mallocFailed );
111527    regPrev = pParse->nMem+1;
111528    pParse->nMem += nExpr+1;
111529    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
111530    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
111531    if( pKeyDup ){
111532      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
111533      for(i=0; i<nExpr; i++){
111534        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
111535        pKeyDup->aSortOrder[i] = 0;
111536      }
111537    }
111538  }
111539
111540  /* Separate the left and the right query from one another
111541  */
111542  p->pPrior = 0;
111543  pPrior->pNext = 0;
111544  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
111545  if( pPrior->pPrior==0 ){
111546    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
111547  }
111548
111549  /* Compute the limit registers */
111550  computeLimitRegisters(pParse, p, labelEnd);
111551  if( p->iLimit && op==TK_ALL ){
111552    regLimitA = ++pParse->nMem;
111553    regLimitB = ++pParse->nMem;
111554    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
111555                                  regLimitA);
111556    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
111557  }else{
111558    regLimitA = regLimitB = 0;
111559  }
111560  sqlite3ExprDelete(db, p->pLimit);
111561  p->pLimit = 0;
111562  sqlite3ExprDelete(db, p->pOffset);
111563  p->pOffset = 0;
111564
111565  regAddrA = ++pParse->nMem;
111566  regAddrB = ++pParse->nMem;
111567  regOutA = ++pParse->nMem;
111568  regOutB = ++pParse->nMem;
111569  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
111570  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
111571
111572  /* Generate a coroutine to evaluate the SELECT statement to the
111573  ** left of the compound operator - the "A" select.
111574  */
111575  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
111576  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
111577  VdbeComment((v, "left SELECT"));
111578  pPrior->iLimit = regLimitA;
111579  explainSetInteger(iSub1, pParse->iNextSelectId);
111580  sqlite3Select(pParse, pPrior, &destA);
111581  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
111582  sqlite3VdbeJumpHere(v, addr1);
111583
111584  /* Generate a coroutine to evaluate the SELECT statement on
111585  ** the right - the "B" select
111586  */
111587  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
111588  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
111589  VdbeComment((v, "right SELECT"));
111590  savedLimit = p->iLimit;
111591  savedOffset = p->iOffset;
111592  p->iLimit = regLimitB;
111593  p->iOffset = 0;
111594  explainSetInteger(iSub2, pParse->iNextSelectId);
111595  sqlite3Select(pParse, p, &destB);
111596  p->iLimit = savedLimit;
111597  p->iOffset = savedOffset;
111598  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
111599
111600  /* Generate a subroutine that outputs the current row of the A
111601  ** select as the next output row of the compound select.
111602  */
111603  VdbeNoopComment((v, "Output routine for A"));
111604  addrOutA = generateOutputSubroutine(pParse,
111605                 p, &destA, pDest, regOutA,
111606                 regPrev, pKeyDup, labelEnd);
111607
111608  /* Generate a subroutine that outputs the current row of the B
111609  ** select as the next output row of the compound select.
111610  */
111611  if( op==TK_ALL || op==TK_UNION ){
111612    VdbeNoopComment((v, "Output routine for B"));
111613    addrOutB = generateOutputSubroutine(pParse,
111614                 p, &destB, pDest, regOutB,
111615                 regPrev, pKeyDup, labelEnd);
111616  }
111617  sqlite3KeyInfoUnref(pKeyDup);
111618
111619  /* Generate a subroutine to run when the results from select A
111620  ** are exhausted and only data in select B remains.
111621  */
111622  if( op==TK_EXCEPT || op==TK_INTERSECT ){
111623    addrEofA_noB = addrEofA = labelEnd;
111624  }else{
111625    VdbeNoopComment((v, "eof-A subroutine"));
111626    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
111627    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
111628                                     VdbeCoverage(v);
111629    sqlite3VdbeGoto(v, addrEofA);
111630    p->nSelectRow += pPrior->nSelectRow;
111631  }
111632
111633  /* Generate a subroutine to run when the results from select B
111634  ** are exhausted and only data in select A remains.
111635  */
111636  if( op==TK_INTERSECT ){
111637    addrEofB = addrEofA;
111638    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
111639  }else{
111640    VdbeNoopComment((v, "eof-B subroutine"));
111641    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
111642    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
111643    sqlite3VdbeGoto(v, addrEofB);
111644  }
111645
111646  /* Generate code to handle the case of A<B
111647  */
111648  VdbeNoopComment((v, "A-lt-B subroutine"));
111649  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
111650  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
111651  sqlite3VdbeGoto(v, labelCmpr);
111652
111653  /* Generate code to handle the case of A==B
111654  */
111655  if( op==TK_ALL ){
111656    addrAeqB = addrAltB;
111657  }else if( op==TK_INTERSECT ){
111658    addrAeqB = addrAltB;
111659    addrAltB++;
111660  }else{
111661    VdbeNoopComment((v, "A-eq-B subroutine"));
111662    addrAeqB =
111663    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
111664    sqlite3VdbeGoto(v, labelCmpr);
111665  }
111666
111667  /* Generate code to handle the case of A>B
111668  */
111669  VdbeNoopComment((v, "A-gt-B subroutine"));
111670  addrAgtB = sqlite3VdbeCurrentAddr(v);
111671  if( op==TK_ALL || op==TK_UNION ){
111672    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
111673  }
111674  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
111675  sqlite3VdbeGoto(v, labelCmpr);
111676
111677  /* This code runs once to initialize everything.
111678  */
111679  sqlite3VdbeJumpHere(v, addr1);
111680  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
111681  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
111682
111683  /* Implement the main merge loop
111684  */
111685  sqlite3VdbeResolveLabel(v, labelCmpr);
111686  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
111687  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
111688                         (char*)pKeyMerge, P4_KEYINFO);
111689  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
111690  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
111691
111692  /* Jump to the this point in order to terminate the query.
111693  */
111694  sqlite3VdbeResolveLabel(v, labelEnd);
111695
111696  /* Set the number of output columns
111697  */
111698  if( pDest->eDest==SRT_Output ){
111699    Select *pFirst = pPrior;
111700    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111701    generateColumnNames(pParse, 0, pFirst->pEList);
111702  }
111703
111704  /* Reassembly the compound query so that it will be freed correctly
111705  ** by the calling function */
111706  if( p->pPrior ){
111707    sqlite3SelectDelete(db, p->pPrior);
111708  }
111709  p->pPrior = pPrior;
111710  pPrior->pNext = p;
111711
111712  /*** TBD:  Insert subroutine calls to close cursors on incomplete
111713  **** subqueries ****/
111714  explainComposite(pParse, p->op, iSub1, iSub2, 0);
111715  return pParse->nErr!=0;
111716}
111717#endif
111718
111719#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
111720/* Forward Declarations */
111721static void substExprList(sqlite3*, ExprList*, int, ExprList*);
111722static void substSelect(sqlite3*, Select *, int, ExprList*, int);
111723
111724/*
111725** Scan through the expression pExpr.  Replace every reference to
111726** a column in table number iTable with a copy of the iColumn-th
111727** entry in pEList.  (But leave references to the ROWID column
111728** unchanged.)
111729**
111730** This routine is part of the flattening procedure.  A subquery
111731** whose result set is defined by pEList appears as entry in the
111732** FROM clause of a SELECT such that the VDBE cursor assigned to that
111733** FORM clause entry is iTable.  This routine make the necessary
111734** changes to pExpr so that it refers directly to the source table
111735** of the subquery rather the result set of the subquery.
111736*/
111737static Expr *substExpr(
111738  sqlite3 *db,        /* Report malloc errors to this connection */
111739  Expr *pExpr,        /* Expr in which substitution occurs */
111740  int iTable,         /* Table to be substituted */
111741  ExprList *pEList    /* Substitute expressions */
111742){
111743  if( pExpr==0 ) return 0;
111744  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
111745    if( pExpr->iColumn<0 ){
111746      pExpr->op = TK_NULL;
111747    }else{
111748      Expr *pNew;
111749      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
111750      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
111751      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
111752      sqlite3ExprDelete(db, pExpr);
111753      pExpr = pNew;
111754    }
111755  }else{
111756    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
111757    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
111758    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
111759      substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
111760    }else{
111761      substExprList(db, pExpr->x.pList, iTable, pEList);
111762    }
111763  }
111764  return pExpr;
111765}
111766static void substExprList(
111767  sqlite3 *db,         /* Report malloc errors here */
111768  ExprList *pList,     /* List to scan and in which to make substitutes */
111769  int iTable,          /* Table to be substituted */
111770  ExprList *pEList     /* Substitute values */
111771){
111772  int i;
111773  if( pList==0 ) return;
111774  for(i=0; i<pList->nExpr; i++){
111775    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
111776  }
111777}
111778static void substSelect(
111779  sqlite3 *db,         /* Report malloc errors here */
111780  Select *p,           /* SELECT statement in which to make substitutions */
111781  int iTable,          /* Table to be replaced */
111782  ExprList *pEList,    /* Substitute values */
111783  int doPrior          /* Do substitutes on p->pPrior too */
111784){
111785  SrcList *pSrc;
111786  struct SrcList_item *pItem;
111787  int i;
111788  if( !p ) return;
111789  do{
111790    substExprList(db, p->pEList, iTable, pEList);
111791    substExprList(db, p->pGroupBy, iTable, pEList);
111792    substExprList(db, p->pOrderBy, iTable, pEList);
111793    p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
111794    p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
111795    pSrc = p->pSrc;
111796    assert( pSrc!=0 );
111797    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
111798      substSelect(db, pItem->pSelect, iTable, pEList, 1);
111799      if( pItem->fg.isTabFunc ){
111800        substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
111801      }
111802    }
111803  }while( doPrior && (p = p->pPrior)!=0 );
111804}
111805#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
111806
111807#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
111808/*
111809** This routine attempts to flatten subqueries as a performance optimization.
111810** This routine returns 1 if it makes changes and 0 if no flattening occurs.
111811**
111812** To understand the concept of flattening, consider the following
111813** query:
111814**
111815**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
111816**
111817** The default way of implementing this query is to execute the
111818** subquery first and store the results in a temporary table, then
111819** run the outer query on that temporary table.  This requires two
111820** passes over the data.  Furthermore, because the temporary table
111821** has no indices, the WHERE clause on the outer query cannot be
111822** optimized.
111823**
111824** This routine attempts to rewrite queries such as the above into
111825** a single flat select, like this:
111826**
111827**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
111828**
111829** The code generated for this simplification gives the same result
111830** but only has to scan the data once.  And because indices might
111831** exist on the table t1, a complete scan of the data might be
111832** avoided.
111833**
111834** Flattening is only attempted if all of the following are true:
111835**
111836**   (1)  The subquery and the outer query do not both use aggregates.
111837**
111838**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
111839**        and (2b) the outer query does not use subqueries other than the one
111840**        FROM-clause subquery that is a candidate for flattening.  (2b is
111841**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
111842**
111843**   (3)  The subquery is not the right operand of a left outer join
111844**        (Originally ticket #306.  Strengthened by ticket #3300)
111845**
111846**   (4)  The subquery is not DISTINCT.
111847**
111848**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
111849**        sub-queries that were excluded from this optimization. Restriction
111850**        (4) has since been expanded to exclude all DISTINCT subqueries.
111851**
111852**   (6)  The subquery does not use aggregates or the outer query is not
111853**        DISTINCT.
111854**
111855**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
111856**        A FROM clause, consider adding a FROM close with the special
111857**        table sqlite_once that consists of a single row containing a
111858**        single NULL.
111859**
111860**   (8)  The subquery does not use LIMIT or the outer query is not a join.
111861**
111862**   (9)  The subquery does not use LIMIT or the outer query does not use
111863**        aggregates.
111864**
111865**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
111866**        accidently carried the comment forward until 2014-09-15.  Original
111867**        text: "The subquery does not use aggregates or the outer query
111868**        does not use LIMIT."
111869**
111870**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
111871**
111872**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
111873**        a separate restriction deriving from ticket #350.
111874**
111875**  (13)  The subquery and outer query do not both use LIMIT.
111876**
111877**  (14)  The subquery does not use OFFSET.
111878**
111879**  (15)  The outer query is not part of a compound select or the
111880**        subquery does not have a LIMIT clause.
111881**        (See ticket #2339 and ticket [02a8e81d44]).
111882**
111883**  (16)  The outer query is not an aggregate or the subquery does
111884**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
111885**        until we introduced the group_concat() function.
111886**
111887**  (17)  The sub-query is not a compound select, or it is a UNION ALL
111888**        compound clause made up entirely of non-aggregate queries, and
111889**        the parent query:
111890**
111891**          * is not itself part of a compound select,
111892**          * is not an aggregate or DISTINCT query, and
111893**          * is not a join
111894**
111895**        The parent and sub-query may contain WHERE clauses. Subject to
111896**        rules (11), (13) and (14), they may also contain ORDER BY,
111897**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
111898**        operator other than UNION ALL because all the other compound
111899**        operators have an implied DISTINCT which is disallowed by
111900**        restriction (4).
111901**
111902**        Also, each component of the sub-query must return the same number
111903**        of result columns. This is actually a requirement for any compound
111904**        SELECT statement, but all the code here does is make sure that no
111905**        such (illegal) sub-query is flattened. The caller will detect the
111906**        syntax error and return a detailed message.
111907**
111908**  (18)  If the sub-query is a compound select, then all terms of the
111909**        ORDER by clause of the parent must be simple references to
111910**        columns of the sub-query.
111911**
111912**  (19)  The subquery does not use LIMIT or the outer query does not
111913**        have a WHERE clause.
111914**
111915**  (20)  If the sub-query is a compound select, then it must not use
111916**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
111917**        somewhat by saying that the terms of the ORDER BY clause must
111918**        appear as unmodified result columns in the outer query.  But we
111919**        have other optimizations in mind to deal with that case.
111920**
111921**  (21)  The subquery does not use LIMIT or the outer query is not
111922**        DISTINCT.  (See ticket [752e1646fc]).
111923**
111924**  (22)  The subquery is not a recursive CTE.
111925**
111926**  (23)  The parent is not a recursive CTE, or the sub-query is not a
111927**        compound query. This restriction is because transforming the
111928**        parent to a compound query confuses the code that handles
111929**        recursive queries in multiSelect().
111930**
111931**  (24)  The subquery is not an aggregate that uses the built-in min() or
111932**        or max() functions.  (Without this restriction, a query like:
111933**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
111934**        return the value X for which Y was maximal.)
111935**
111936**
111937** In this routine, the "p" parameter is a pointer to the outer query.
111938** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
111939** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
111940**
111941** If flattening is not attempted, this routine is a no-op and returns 0.
111942** If flattening is attempted this routine returns 1.
111943**
111944** All of the expression analysis must occur on both the outer query and
111945** the subquery before this routine runs.
111946*/
111947static int flattenSubquery(
111948  Parse *pParse,       /* Parsing context */
111949  Select *p,           /* The parent or outer SELECT statement */
111950  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
111951  int isAgg,           /* True if outer SELECT uses aggregate functions */
111952  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
111953){
111954  const char *zSavedAuthContext = pParse->zAuthContext;
111955  Select *pParent;    /* Current UNION ALL term of the other query */
111956  Select *pSub;       /* The inner query or "subquery" */
111957  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
111958  SrcList *pSrc;      /* The FROM clause of the outer query */
111959  SrcList *pSubSrc;   /* The FROM clause of the subquery */
111960  ExprList *pList;    /* The result set of the outer query */
111961  int iParent;        /* VDBE cursor number of the pSub result set temp table */
111962  int i;              /* Loop counter */
111963  Expr *pWhere;                    /* The WHERE clause */
111964  struct SrcList_item *pSubitem;   /* The subquery */
111965  sqlite3 *db = pParse->db;
111966
111967  /* Check to see if flattening is permitted.  Return 0 if not.
111968  */
111969  assert( p!=0 );
111970  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
111971  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
111972  pSrc = p->pSrc;
111973  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
111974  pSubitem = &pSrc->a[iFrom];
111975  iParent = pSubitem->iCursor;
111976  pSub = pSubitem->pSelect;
111977  assert( pSub!=0 );
111978  if( subqueryIsAgg ){
111979    if( isAgg ) return 0;                                /* Restriction (1)   */
111980    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
111981    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
111982     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
111983     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
111984    ){
111985      return 0;                                          /* Restriction (2b)  */
111986    }
111987  }
111988
111989  pSubSrc = pSub->pSrc;
111990  assert( pSubSrc );
111991  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
111992  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
111993  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
111994  ** became arbitrary expressions, we were forced to add restrictions (13)
111995  ** and (14). */
111996  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
111997  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
111998  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
111999    return 0;                                            /* Restriction (15) */
112000  }
112001  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
112002  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
112003  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
112004     return 0;         /* Restrictions (8)(9) */
112005  }
112006  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
112007     return 0;         /* Restriction (6)  */
112008  }
112009  if( p->pOrderBy && pSub->pOrderBy ){
112010     return 0;                                           /* Restriction (11) */
112011  }
112012  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
112013  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
112014  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
112015     return 0;         /* Restriction (21) */
112016  }
112017  testcase( pSub->selFlags & SF_Recursive );
112018  testcase( pSub->selFlags & SF_MinMaxAgg );
112019  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
112020    return 0; /* Restrictions (22) and (24) */
112021  }
112022  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
112023    return 0; /* Restriction (23) */
112024  }
112025
112026  /* OBSOLETE COMMENT 1:
112027  ** Restriction 3:  If the subquery is a join, make sure the subquery is
112028  ** not used as the right operand of an outer join.  Examples of why this
112029  ** is not allowed:
112030  **
112031  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
112032  **
112033  ** If we flatten the above, we would get
112034  **
112035  **         (t1 LEFT OUTER JOIN t2) JOIN t3
112036  **
112037  ** which is not at all the same thing.
112038  **
112039  ** OBSOLETE COMMENT 2:
112040  ** Restriction 12:  If the subquery is the right operand of a left outer
112041  ** join, make sure the subquery has no WHERE clause.
112042  ** An examples of why this is not allowed:
112043  **
112044  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
112045  **
112046  ** If we flatten the above, we would get
112047  **
112048  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
112049  **
112050  ** But the t2.x>0 test will always fail on a NULL row of t2, which
112051  ** effectively converts the OUTER JOIN into an INNER JOIN.
112052  **
112053  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
112054  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
112055  ** is fraught with danger.  Best to avoid the whole thing.  If the
112056  ** subquery is the right term of a LEFT JOIN, then do not flatten.
112057  */
112058  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
112059    return 0;
112060  }
112061
112062  /* Restriction 17: If the sub-query is a compound SELECT, then it must
112063  ** use only the UNION ALL operator. And none of the simple select queries
112064  ** that make up the compound SELECT are allowed to be aggregate or distinct
112065  ** queries.
112066  */
112067  if( pSub->pPrior ){
112068    if( pSub->pOrderBy ){
112069      return 0;  /* Restriction 20 */
112070    }
112071    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
112072      return 0;
112073    }
112074    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
112075      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
112076      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
112077      assert( pSub->pSrc!=0 );
112078      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
112079      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
112080       || (pSub1->pPrior && pSub1->op!=TK_ALL)
112081       || pSub1->pSrc->nSrc<1
112082      ){
112083        return 0;
112084      }
112085      testcase( pSub1->pSrc->nSrc>1 );
112086    }
112087
112088    /* Restriction 18. */
112089    if( p->pOrderBy ){
112090      int ii;
112091      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
112092        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
112093      }
112094    }
112095  }
112096
112097  /***** If we reach this point, flattening is permitted. *****/
112098  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
112099                   pSub->zSelName, pSub, iFrom));
112100
112101  /* Authorize the subquery */
112102  pParse->zAuthContext = pSubitem->zName;
112103  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
112104  testcase( i==SQLITE_DENY );
112105  pParse->zAuthContext = zSavedAuthContext;
112106
112107  /* If the sub-query is a compound SELECT statement, then (by restrictions
112108  ** 17 and 18 above) it must be a UNION ALL and the parent query must
112109  ** be of the form:
112110  **
112111  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
112112  **
112113  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
112114  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
112115  ** OFFSET clauses and joins them to the left-hand-side of the original
112116  ** using UNION ALL operators. In this case N is the number of simple
112117  ** select statements in the compound sub-query.
112118  **
112119  ** Example:
112120  **
112121  **     SELECT a+1 FROM (
112122  **        SELECT x FROM tab
112123  **        UNION ALL
112124  **        SELECT y FROM tab
112125  **        UNION ALL
112126  **        SELECT abs(z*2) FROM tab2
112127  **     ) WHERE a!=5 ORDER BY 1
112128  **
112129  ** Transformed into:
112130  **
112131  **     SELECT x+1 FROM tab WHERE x+1!=5
112132  **     UNION ALL
112133  **     SELECT y+1 FROM tab WHERE y+1!=5
112134  **     UNION ALL
112135  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
112136  **     ORDER BY 1
112137  **
112138  ** We call this the "compound-subquery flattening".
112139  */
112140  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
112141    Select *pNew;
112142    ExprList *pOrderBy = p->pOrderBy;
112143    Expr *pLimit = p->pLimit;
112144    Expr *pOffset = p->pOffset;
112145    Select *pPrior = p->pPrior;
112146    p->pOrderBy = 0;
112147    p->pSrc = 0;
112148    p->pPrior = 0;
112149    p->pLimit = 0;
112150    p->pOffset = 0;
112151    pNew = sqlite3SelectDup(db, p, 0);
112152    sqlite3SelectSetName(pNew, pSub->zSelName);
112153    p->pOffset = pOffset;
112154    p->pLimit = pLimit;
112155    p->pOrderBy = pOrderBy;
112156    p->pSrc = pSrc;
112157    p->op = TK_ALL;
112158    if( pNew==0 ){
112159      p->pPrior = pPrior;
112160    }else{
112161      pNew->pPrior = pPrior;
112162      if( pPrior ) pPrior->pNext = pNew;
112163      pNew->pNext = p;
112164      p->pPrior = pNew;
112165      SELECTTRACE(2,pParse,p,
112166         ("compound-subquery flattener creates %s.%p as peer\n",
112167         pNew->zSelName, pNew));
112168    }
112169    if( db->mallocFailed ) return 1;
112170  }
112171
112172  /* Begin flattening the iFrom-th entry of the FROM clause
112173  ** in the outer query.
112174  */
112175  pSub = pSub1 = pSubitem->pSelect;
112176
112177  /* Delete the transient table structure associated with the
112178  ** subquery
112179  */
112180  sqlite3DbFree(db, pSubitem->zDatabase);
112181  sqlite3DbFree(db, pSubitem->zName);
112182  sqlite3DbFree(db, pSubitem->zAlias);
112183  pSubitem->zDatabase = 0;
112184  pSubitem->zName = 0;
112185  pSubitem->zAlias = 0;
112186  pSubitem->pSelect = 0;
112187
112188  /* Defer deleting the Table object associated with the
112189  ** subquery until code generation is
112190  ** complete, since there may still exist Expr.pTab entries that
112191  ** refer to the subquery even after flattening.  Ticket #3346.
112192  **
112193  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
112194  */
112195  if( ALWAYS(pSubitem->pTab!=0) ){
112196    Table *pTabToDel = pSubitem->pTab;
112197    if( pTabToDel->nRef==1 ){
112198      Parse *pToplevel = sqlite3ParseToplevel(pParse);
112199      pTabToDel->pNextZombie = pToplevel->pZombieTab;
112200      pToplevel->pZombieTab = pTabToDel;
112201    }else{
112202      pTabToDel->nRef--;
112203    }
112204    pSubitem->pTab = 0;
112205  }
112206
112207  /* The following loop runs once for each term in a compound-subquery
112208  ** flattening (as described above).  If we are doing a different kind
112209  ** of flattening - a flattening other than a compound-subquery flattening -
112210  ** then this loop only runs once.
112211  **
112212  ** This loop moves all of the FROM elements of the subquery into the
112213  ** the FROM clause of the outer query.  Before doing this, remember
112214  ** the cursor number for the original outer query FROM element in
112215  ** iParent.  The iParent cursor will never be used.  Subsequent code
112216  ** will scan expressions looking for iParent references and replace
112217  ** those references with expressions that resolve to the subquery FROM
112218  ** elements we are now copying in.
112219  */
112220  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
112221    int nSubSrc;
112222    u8 jointype = 0;
112223    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
112224    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
112225    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
112226
112227    if( pSrc ){
112228      assert( pParent==p );  /* First time through the loop */
112229      jointype = pSubitem->fg.jointype;
112230    }else{
112231      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
112232      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
112233      if( pSrc==0 ){
112234        assert( db->mallocFailed );
112235        break;
112236      }
112237    }
112238
112239    /* The subquery uses a single slot of the FROM clause of the outer
112240    ** query.  If the subquery has more than one element in its FROM clause,
112241    ** then expand the outer query to make space for it to hold all elements
112242    ** of the subquery.
112243    **
112244    ** Example:
112245    **
112246    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
112247    **
112248    ** The outer query has 3 slots in its FROM clause.  One slot of the
112249    ** outer query (the middle slot) is used by the subquery.  The next
112250    ** block of code will expand the outer query FROM clause to 4 slots.
112251    ** The middle slot is expanded to two slots in order to make space
112252    ** for the two elements in the FROM clause of the subquery.
112253    */
112254    if( nSubSrc>1 ){
112255      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
112256      if( db->mallocFailed ){
112257        break;
112258      }
112259    }
112260
112261    /* Transfer the FROM clause terms from the subquery into the
112262    ** outer query.
112263    */
112264    for(i=0; i<nSubSrc; i++){
112265      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
112266      pSrc->a[i+iFrom] = pSubSrc->a[i];
112267      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
112268    }
112269    pSrc->a[iFrom].fg.jointype = jointype;
112270
112271    /* Now begin substituting subquery result set expressions for
112272    ** references to the iParent in the outer query.
112273    **
112274    ** Example:
112275    **
112276    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
112277    **   \                     \_____________ subquery __________/          /
112278    **    \_____________________ outer query ______________________________/
112279    **
112280    ** We look at every expression in the outer query and every place we see
112281    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
112282    */
112283    pList = pParent->pEList;
112284    for(i=0; i<pList->nExpr; i++){
112285      if( pList->a[i].zName==0 ){
112286        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
112287        sqlite3Dequote(zName);
112288        pList->a[i].zName = zName;
112289      }
112290    }
112291    if( pSub->pOrderBy ){
112292      /* At this point, any non-zero iOrderByCol values indicate that the
112293      ** ORDER BY column expression is identical to the iOrderByCol'th
112294      ** expression returned by SELECT statement pSub. Since these values
112295      ** do not necessarily correspond to columns in SELECT statement pParent,
112296      ** zero them before transfering the ORDER BY clause.
112297      **
112298      ** Not doing this may cause an error if a subsequent call to this
112299      ** function attempts to flatten a compound sub-query into pParent
112300      ** (the only way this can happen is if the compound sub-query is
112301      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
112302      ExprList *pOrderBy = pSub->pOrderBy;
112303      for(i=0; i<pOrderBy->nExpr; i++){
112304        pOrderBy->a[i].u.x.iOrderByCol = 0;
112305      }
112306      assert( pParent->pOrderBy==0 );
112307      assert( pSub->pPrior==0 );
112308      pParent->pOrderBy = pOrderBy;
112309      pSub->pOrderBy = 0;
112310    }
112311    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
112312    if( subqueryIsAgg ){
112313      assert( pParent->pHaving==0 );
112314      pParent->pHaving = pParent->pWhere;
112315      pParent->pWhere = pWhere;
112316      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
112317                                  sqlite3ExprDup(db, pSub->pHaving, 0));
112318      assert( pParent->pGroupBy==0 );
112319      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
112320    }else{
112321      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
112322    }
112323    substSelect(db, pParent, iParent, pSub->pEList, 0);
112324
112325    /* The flattened query is distinct if either the inner or the
112326    ** outer query is distinct.
112327    */
112328    pParent->selFlags |= pSub->selFlags & SF_Distinct;
112329
112330    /*
112331    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
112332    **
112333    ** One is tempted to try to add a and b to combine the limits.  But this
112334    ** does not work if either limit is negative.
112335    */
112336    if( pSub->pLimit ){
112337      pParent->pLimit = pSub->pLimit;
112338      pSub->pLimit = 0;
112339    }
112340  }
112341
112342  /* Finially, delete what is left of the subquery and return
112343  ** success.
112344  */
112345  sqlite3SelectDelete(db, pSub1);
112346
112347#if SELECTTRACE_ENABLED
112348  if( sqlite3SelectTrace & 0x100 ){
112349    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
112350    sqlite3TreeViewSelect(0, p, 0);
112351  }
112352#endif
112353
112354  return 1;
112355}
112356#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
112357
112358
112359
112360#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
112361/*
112362** Make copies of relevant WHERE clause terms of the outer query into
112363** the WHERE clause of subquery.  Example:
112364**
112365**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
112366**
112367** Transformed into:
112368**
112369**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
112370**     WHERE x=5 AND y=10;
112371**
112372** The hope is that the terms added to the inner query will make it more
112373** efficient.
112374**
112375** Do not attempt this optimization if:
112376**
112377**   (1) The inner query is an aggregate.  (In that case, we'd really want
112378**       to copy the outer WHERE-clause terms onto the HAVING clause of the
112379**       inner query.  But they probably won't help there so do not bother.)
112380**
112381**   (2) The inner query is the recursive part of a common table expression.
112382**
112383**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
112384**       close would change the meaning of the LIMIT).
112385**
112386**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
112387**       enforces this restriction since this routine does not have enough
112388**       information to know.)
112389**
112390**   (5) The WHERE clause expression originates in the ON or USING clause
112391**       of a LEFT JOIN.
112392**
112393** Return 0 if no changes are made and non-zero if one or more WHERE clause
112394** terms are duplicated into the subquery.
112395*/
112396static int pushDownWhereTerms(
112397  sqlite3 *db,          /* The database connection (for malloc()) */
112398  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
112399  Expr *pWhere,         /* The WHERE clause of the outer query */
112400  int iCursor           /* Cursor number of the subquery */
112401){
112402  Expr *pNew;
112403  int nChng = 0;
112404  if( pWhere==0 ) return 0;
112405  if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
112406     return 0; /* restrictions (1) and (2) */
112407  }
112408  if( pSubq->pLimit!=0 ){
112409     return 0; /* restriction (3) */
112410  }
112411  while( pWhere->op==TK_AND ){
112412    nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
112413    pWhere = pWhere->pLeft;
112414  }
112415  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
112416  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
112417    nChng++;
112418    while( pSubq ){
112419      pNew = sqlite3ExprDup(db, pWhere, 0);
112420      pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
112421      pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
112422      pSubq = pSubq->pPrior;
112423    }
112424  }
112425  return nChng;
112426}
112427#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
112428
112429/*
112430** Based on the contents of the AggInfo structure indicated by the first
112431** argument, this function checks if the following are true:
112432**
112433**    * the query contains just a single aggregate function,
112434**    * the aggregate function is either min() or max(), and
112435**    * the argument to the aggregate function is a column value.
112436**
112437** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
112438** is returned as appropriate. Also, *ppMinMax is set to point to the
112439** list of arguments passed to the aggregate before returning.
112440**
112441** Or, if the conditions above are not met, *ppMinMax is set to 0 and
112442** WHERE_ORDERBY_NORMAL is returned.
112443*/
112444static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
112445  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
112446
112447  *ppMinMax = 0;
112448  if( pAggInfo->nFunc==1 ){
112449    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
112450    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
112451
112452    assert( pExpr->op==TK_AGG_FUNCTION );
112453    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
112454      const char *zFunc = pExpr->u.zToken;
112455      if( sqlite3StrICmp(zFunc, "min")==0 ){
112456        eRet = WHERE_ORDERBY_MIN;
112457        *ppMinMax = pEList;
112458      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
112459        eRet = WHERE_ORDERBY_MAX;
112460        *ppMinMax = pEList;
112461      }
112462    }
112463  }
112464
112465  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
112466  return eRet;
112467}
112468
112469/*
112470** The select statement passed as the first argument is an aggregate query.
112471** The second argument is the associated aggregate-info object. This
112472** function tests if the SELECT is of the form:
112473**
112474**   SELECT count(*) FROM <tbl>
112475**
112476** where table is a database table, not a sub-select or view. If the query
112477** does match this pattern, then a pointer to the Table object representing
112478** <tbl> is returned. Otherwise, 0 is returned.
112479*/
112480static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
112481  Table *pTab;
112482  Expr *pExpr;
112483
112484  assert( !p->pGroupBy );
112485
112486  if( p->pWhere || p->pEList->nExpr!=1
112487   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
112488  ){
112489    return 0;
112490  }
112491  pTab = p->pSrc->a[0].pTab;
112492  pExpr = p->pEList->a[0].pExpr;
112493  assert( pTab && !pTab->pSelect && pExpr );
112494
112495  if( IsVirtual(pTab) ) return 0;
112496  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
112497  if( NEVER(pAggInfo->nFunc==0) ) return 0;
112498  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
112499  if( pExpr->flags&EP_Distinct ) return 0;
112500
112501  return pTab;
112502}
112503
112504/*
112505** If the source-list item passed as an argument was augmented with an
112506** INDEXED BY clause, then try to locate the specified index. If there
112507** was such a clause and the named index cannot be found, return
112508** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
112509** pFrom->pIndex and return SQLITE_OK.
112510*/
112511SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
112512  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
112513    Table *pTab = pFrom->pTab;
112514    char *zIndexedBy = pFrom->u1.zIndexedBy;
112515    Index *pIdx;
112516    for(pIdx=pTab->pIndex;
112517        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
112518        pIdx=pIdx->pNext
112519    );
112520    if( !pIdx ){
112521      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
112522      pParse->checkSchema = 1;
112523      return SQLITE_ERROR;
112524    }
112525    pFrom->pIBIndex = pIdx;
112526  }
112527  return SQLITE_OK;
112528}
112529/*
112530** Detect compound SELECT statements that use an ORDER BY clause with
112531** an alternative collating sequence.
112532**
112533**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
112534**
112535** These are rewritten as a subquery:
112536**
112537**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
112538**     ORDER BY ... COLLATE ...
112539**
112540** This transformation is necessary because the multiSelectOrderBy() routine
112541** above that generates the code for a compound SELECT with an ORDER BY clause
112542** uses a merge algorithm that requires the same collating sequence on the
112543** result columns as on the ORDER BY clause.  See ticket
112544** http://www.sqlite.org/src/info/6709574d2a
112545**
112546** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
112547** The UNION ALL operator works fine with multiSelectOrderBy() even when
112548** there are COLLATE terms in the ORDER BY.
112549*/
112550static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
112551  int i;
112552  Select *pNew;
112553  Select *pX;
112554  sqlite3 *db;
112555  struct ExprList_item *a;
112556  SrcList *pNewSrc;
112557  Parse *pParse;
112558  Token dummy;
112559
112560  if( p->pPrior==0 ) return WRC_Continue;
112561  if( p->pOrderBy==0 ) return WRC_Continue;
112562  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
112563  if( pX==0 ) return WRC_Continue;
112564  a = p->pOrderBy->a;
112565  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
112566    if( a[i].pExpr->flags & EP_Collate ) break;
112567  }
112568  if( i<0 ) return WRC_Continue;
112569
112570  /* If we reach this point, that means the transformation is required. */
112571
112572  pParse = pWalker->pParse;
112573  db = pParse->db;
112574  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
112575  if( pNew==0 ) return WRC_Abort;
112576  memset(&dummy, 0, sizeof(dummy));
112577  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
112578  if( pNewSrc==0 ) return WRC_Abort;
112579  *pNew = *p;
112580  p->pSrc = pNewSrc;
112581  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
112582  p->op = TK_SELECT;
112583  p->pWhere = 0;
112584  pNew->pGroupBy = 0;
112585  pNew->pHaving = 0;
112586  pNew->pOrderBy = 0;
112587  p->pPrior = 0;
112588  p->pNext = 0;
112589  p->pWith = 0;
112590  p->selFlags &= ~SF_Compound;
112591  assert( (p->selFlags & SF_Converted)==0 );
112592  p->selFlags |= SF_Converted;
112593  assert( pNew->pPrior!=0 );
112594  pNew->pPrior->pNext = pNew;
112595  pNew->pLimit = 0;
112596  pNew->pOffset = 0;
112597  return WRC_Continue;
112598}
112599
112600#ifndef SQLITE_OMIT_CTE
112601/*
112602** Argument pWith (which may be NULL) points to a linked list of nested
112603** WITH contexts, from inner to outermost. If the table identified by
112604** FROM clause element pItem is really a common-table-expression (CTE)
112605** then return a pointer to the CTE definition for that table. Otherwise
112606** return NULL.
112607**
112608** If a non-NULL value is returned, set *ppContext to point to the With
112609** object that the returned CTE belongs to.
112610*/
112611static struct Cte *searchWith(
112612  With *pWith,                    /* Current outermost WITH clause */
112613  struct SrcList_item *pItem,     /* FROM clause element to resolve */
112614  With **ppContext                /* OUT: WITH clause return value belongs to */
112615){
112616  const char *zName;
112617  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
112618    With *p;
112619    for(p=pWith; p; p=p->pOuter){
112620      int i;
112621      for(i=0; i<p->nCte; i++){
112622        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
112623          *ppContext = p;
112624          return &p->a[i];
112625        }
112626      }
112627    }
112628  }
112629  return 0;
112630}
112631
112632/* The code generator maintains a stack of active WITH clauses
112633** with the inner-most WITH clause being at the top of the stack.
112634**
112635** This routine pushes the WITH clause passed as the second argument
112636** onto the top of the stack. If argument bFree is true, then this
112637** WITH clause will never be popped from the stack. In this case it
112638** should be freed along with the Parse object. In other cases, when
112639** bFree==0, the With object will be freed along with the SELECT
112640** statement with which it is associated.
112641*/
112642SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
112643  assert( bFree==0 || pParse->pWith==0 );
112644  if( pWith ){
112645    pWith->pOuter = pParse->pWith;
112646    pParse->pWith = pWith;
112647    pParse->bFreeWith = bFree;
112648  }
112649}
112650
112651/*
112652** This function checks if argument pFrom refers to a CTE declared by
112653** a WITH clause on the stack currently maintained by the parser. And,
112654** if currently processing a CTE expression, if it is a recursive
112655** reference to the current CTE.
112656**
112657** If pFrom falls into either of the two categories above, pFrom->pTab
112658** and other fields are populated accordingly. The caller should check
112659** (pFrom->pTab!=0) to determine whether or not a successful match
112660** was found.
112661**
112662** Whether or not a match is found, SQLITE_OK is returned if no error
112663** occurs. If an error does occur, an error message is stored in the
112664** parser and some error code other than SQLITE_OK returned.
112665*/
112666static int withExpand(
112667  Walker *pWalker,
112668  struct SrcList_item *pFrom
112669){
112670  Parse *pParse = pWalker->pParse;
112671  sqlite3 *db = pParse->db;
112672  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
112673  With *pWith;                    /* WITH clause that pCte belongs to */
112674
112675  assert( pFrom->pTab==0 );
112676
112677  pCte = searchWith(pParse->pWith, pFrom, &pWith);
112678  if( pCte ){
112679    Table *pTab;
112680    ExprList *pEList;
112681    Select *pSel;
112682    Select *pLeft;                /* Left-most SELECT statement */
112683    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
112684    With *pSavedWith;             /* Initial value of pParse->pWith */
112685
112686    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
112687    ** recursive reference to CTE pCte. Leave an error in pParse and return
112688    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
112689    ** In this case, proceed.  */
112690    if( pCte->zCteErr ){
112691      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
112692      return SQLITE_ERROR;
112693    }
112694
112695    assert( pFrom->pTab==0 );
112696    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
112697    if( pTab==0 ) return WRC_Abort;
112698    pTab->nRef = 1;
112699    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
112700    pTab->iPKey = -1;
112701    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
112702    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
112703    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
112704    if( db->mallocFailed ) return SQLITE_NOMEM;
112705    assert( pFrom->pSelect );
112706
112707    /* Check if this is a recursive CTE. */
112708    pSel = pFrom->pSelect;
112709    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
112710    if( bMayRecursive ){
112711      int i;
112712      SrcList *pSrc = pFrom->pSelect->pSrc;
112713      for(i=0; i<pSrc->nSrc; i++){
112714        struct SrcList_item *pItem = &pSrc->a[i];
112715        if( pItem->zDatabase==0
112716         && pItem->zName!=0
112717         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
112718          ){
112719          pItem->pTab = pTab;
112720          pItem->fg.isRecursive = 1;
112721          pTab->nRef++;
112722          pSel->selFlags |= SF_Recursive;
112723        }
112724      }
112725    }
112726
112727    /* Only one recursive reference is permitted. */
112728    if( pTab->nRef>2 ){
112729      sqlite3ErrorMsg(
112730          pParse, "multiple references to recursive table: %s", pCte->zName
112731      );
112732      return SQLITE_ERROR;
112733    }
112734    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
112735
112736    pCte->zCteErr = "circular reference: %s";
112737    pSavedWith = pParse->pWith;
112738    pParse->pWith = pWith;
112739    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
112740
112741    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
112742    pEList = pLeft->pEList;
112743    if( pCte->pCols ){
112744      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
112745        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
112746            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
112747        );
112748        pParse->pWith = pSavedWith;
112749        return SQLITE_ERROR;
112750      }
112751      pEList = pCte->pCols;
112752    }
112753
112754    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
112755    if( bMayRecursive ){
112756      if( pSel->selFlags & SF_Recursive ){
112757        pCte->zCteErr = "multiple recursive references: %s";
112758      }else{
112759        pCte->zCteErr = "recursive reference in a subquery: %s";
112760      }
112761      sqlite3WalkSelect(pWalker, pSel);
112762    }
112763    pCte->zCteErr = 0;
112764    pParse->pWith = pSavedWith;
112765  }
112766
112767  return SQLITE_OK;
112768}
112769#endif
112770
112771#ifndef SQLITE_OMIT_CTE
112772/*
112773** If the SELECT passed as the second argument has an associated WITH
112774** clause, pop it from the stack stored as part of the Parse object.
112775**
112776** This function is used as the xSelectCallback2() callback by
112777** sqlite3SelectExpand() when walking a SELECT tree to resolve table
112778** names and other FROM clause elements.
112779*/
112780static void selectPopWith(Walker *pWalker, Select *p){
112781  Parse *pParse = pWalker->pParse;
112782  With *pWith = findRightmost(p)->pWith;
112783  if( pWith!=0 ){
112784    assert( pParse->pWith==pWith );
112785    pParse->pWith = pWith->pOuter;
112786  }
112787}
112788#else
112789#define selectPopWith 0
112790#endif
112791
112792/*
112793** This routine is a Walker callback for "expanding" a SELECT statement.
112794** "Expanding" means to do the following:
112795**
112796**    (1)  Make sure VDBE cursor numbers have been assigned to every
112797**         element of the FROM clause.
112798**
112799**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
112800**         defines FROM clause.  When views appear in the FROM clause,
112801**         fill pTabList->a[].pSelect with a copy of the SELECT statement
112802**         that implements the view.  A copy is made of the view's SELECT
112803**         statement so that we can freely modify or delete that statement
112804**         without worrying about messing up the persistent representation
112805**         of the view.
112806**
112807**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
112808**         on joins and the ON and USING clause of joins.
112809**
112810**    (4)  Scan the list of columns in the result set (pEList) looking
112811**         for instances of the "*" operator or the TABLE.* operator.
112812**         If found, expand each "*" to be every column in every table
112813**         and TABLE.* to be every column in TABLE.
112814**
112815*/
112816static int selectExpander(Walker *pWalker, Select *p){
112817  Parse *pParse = pWalker->pParse;
112818  int i, j, k;
112819  SrcList *pTabList;
112820  ExprList *pEList;
112821  struct SrcList_item *pFrom;
112822  sqlite3 *db = pParse->db;
112823  Expr *pE, *pRight, *pExpr;
112824  u16 selFlags = p->selFlags;
112825
112826  p->selFlags |= SF_Expanded;
112827  if( db->mallocFailed  ){
112828    return WRC_Abort;
112829  }
112830  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
112831    return WRC_Prune;
112832  }
112833  pTabList = p->pSrc;
112834  pEList = p->pEList;
112835  if( pWalker->xSelectCallback2==selectPopWith ){
112836    sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
112837  }
112838
112839  /* Make sure cursor numbers have been assigned to all entries in
112840  ** the FROM clause of the SELECT statement.
112841  */
112842  sqlite3SrcListAssignCursors(pParse, pTabList);
112843
112844  /* Look up every table named in the FROM clause of the select.  If
112845  ** an entry of the FROM clause is a subquery instead of a table or view,
112846  ** then create a transient table structure to describe the subquery.
112847  */
112848  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
112849    Table *pTab;
112850    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
112851    if( pFrom->fg.isRecursive ) continue;
112852    assert( pFrom->pTab==0 );
112853#ifndef SQLITE_OMIT_CTE
112854    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
112855    if( pFrom->pTab ) {} else
112856#endif
112857    if( pFrom->zName==0 ){
112858#ifndef SQLITE_OMIT_SUBQUERY
112859      Select *pSel = pFrom->pSelect;
112860      /* A sub-query in the FROM clause of a SELECT */
112861      assert( pSel!=0 );
112862      assert( pFrom->pTab==0 );
112863      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
112864      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
112865      if( pTab==0 ) return WRC_Abort;
112866      pTab->nRef = 1;
112867      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
112868      while( pSel->pPrior ){ pSel = pSel->pPrior; }
112869      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
112870      pTab->iPKey = -1;
112871      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
112872      pTab->tabFlags |= TF_Ephemeral;
112873#endif
112874    }else{
112875      /* An ordinary table or view name in the FROM clause */
112876      assert( pFrom->pTab==0 );
112877      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
112878      if( pTab==0 ) return WRC_Abort;
112879      if( pTab->nRef==0xffff ){
112880        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
112881           pTab->zName);
112882        pFrom->pTab = 0;
112883        return WRC_Abort;
112884      }
112885      pTab->nRef++;
112886#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
112887      if( pTab->pSelect || IsVirtual(pTab) ){
112888        i16 nCol;
112889        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
112890        assert( pFrom->pSelect==0 );
112891        if( pFrom->fg.isTabFunc && !IsVirtual(pTab) ){
112892          sqlite3ErrorMsg(pParse, "'%s' is not a function", pTab->zName);
112893          return WRC_Abort;
112894        }
112895        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
112896        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
112897        nCol = pTab->nCol;
112898        pTab->nCol = -1;
112899        sqlite3WalkSelect(pWalker, pFrom->pSelect);
112900        pTab->nCol = nCol;
112901      }
112902#endif
112903    }
112904
112905    /* Locate the index named by the INDEXED BY clause, if any. */
112906    if( sqlite3IndexedByLookup(pParse, pFrom) ){
112907      return WRC_Abort;
112908    }
112909  }
112910
112911  /* Process NATURAL keywords, and ON and USING clauses of joins.
112912  */
112913  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
112914    return WRC_Abort;
112915  }
112916
112917  /* For every "*" that occurs in the column list, insert the names of
112918  ** all columns in all tables.  And for every TABLE.* insert the names
112919  ** of all columns in TABLE.  The parser inserted a special expression
112920  ** with the TK_ALL operator for each "*" that it found in the column list.
112921  ** The following code just has to locate the TK_ALL expressions and expand
112922  ** each one to the list of all columns in all tables.
112923  **
112924  ** The first loop just checks to see if there are any "*" operators
112925  ** that need expanding.
112926  */
112927  for(k=0; k<pEList->nExpr; k++){
112928    pE = pEList->a[k].pExpr;
112929    if( pE->op==TK_ALL ) break;
112930    assert( pE->op!=TK_DOT || pE->pRight!=0 );
112931    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
112932    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
112933  }
112934  if( k<pEList->nExpr ){
112935    /*
112936    ** If we get here it means the result set contains one or more "*"
112937    ** operators that need to be expanded.  Loop through each expression
112938    ** in the result set and expand them one by one.
112939    */
112940    struct ExprList_item *a = pEList->a;
112941    ExprList *pNew = 0;
112942    int flags = pParse->db->flags;
112943    int longNames = (flags & SQLITE_FullColNames)!=0
112944                      && (flags & SQLITE_ShortColNames)==0;
112945
112946    for(k=0; k<pEList->nExpr; k++){
112947      pE = a[k].pExpr;
112948      pRight = pE->pRight;
112949      assert( pE->op!=TK_DOT || pRight!=0 );
112950      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
112951        /* This particular expression does not need to be expanded.
112952        */
112953        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
112954        if( pNew ){
112955          pNew->a[pNew->nExpr-1].zName = a[k].zName;
112956          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
112957          a[k].zName = 0;
112958          a[k].zSpan = 0;
112959        }
112960        a[k].pExpr = 0;
112961      }else{
112962        /* This expression is a "*" or a "TABLE.*" and needs to be
112963        ** expanded. */
112964        int tableSeen = 0;      /* Set to 1 when TABLE matches */
112965        char *zTName = 0;       /* text of name of TABLE */
112966        if( pE->op==TK_DOT ){
112967          assert( pE->pLeft!=0 );
112968          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
112969          zTName = pE->pLeft->u.zToken;
112970        }
112971        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
112972          Table *pTab = pFrom->pTab;
112973          Select *pSub = pFrom->pSelect;
112974          char *zTabName = pFrom->zAlias;
112975          const char *zSchemaName = 0;
112976          int iDb;
112977          if( zTabName==0 ){
112978            zTabName = pTab->zName;
112979          }
112980          if( db->mallocFailed ) break;
112981          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
112982            pSub = 0;
112983            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
112984              continue;
112985            }
112986            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112987            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
112988          }
112989          for(j=0; j<pTab->nCol; j++){
112990            char *zName = pTab->aCol[j].zName;
112991            char *zColname;  /* The computed column name */
112992            char *zToFree;   /* Malloced string that needs to be freed */
112993            Token sColname;  /* Computed column name as a token */
112994
112995            assert( zName );
112996            if( zTName && pSub
112997             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
112998            ){
112999              continue;
113000            }
113001
113002            /* If a column is marked as 'hidden' (currently only possible
113003            ** for virtual tables), do not include it in the expanded
113004            ** result-set list.
113005            */
113006            if( IsHiddenColumn(&pTab->aCol[j]) ){
113007              assert(IsVirtual(pTab));
113008              continue;
113009            }
113010            tableSeen = 1;
113011
113012            if( i>0 && zTName==0 ){
113013              if( (pFrom->fg.jointype & JT_NATURAL)!=0
113014                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
113015              ){
113016                /* In a NATURAL join, omit the join columns from the
113017                ** table to the right of the join */
113018                continue;
113019              }
113020              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
113021                /* In a join with a USING clause, omit columns in the
113022                ** using clause from the table on the right. */
113023                continue;
113024              }
113025            }
113026            pRight = sqlite3Expr(db, TK_ID, zName);
113027            zColname = zName;
113028            zToFree = 0;
113029            if( longNames || pTabList->nSrc>1 ){
113030              Expr *pLeft;
113031              pLeft = sqlite3Expr(db, TK_ID, zTabName);
113032              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
113033              if( zSchemaName ){
113034                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
113035                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
113036              }
113037              if( longNames ){
113038                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
113039                zToFree = zColname;
113040              }
113041            }else{
113042              pExpr = pRight;
113043            }
113044            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
113045            sColname.z = zColname;
113046            sColname.n = sqlite3Strlen30(zColname);
113047            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
113048            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
113049              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
113050              if( pSub ){
113051                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
113052                testcase( pX->zSpan==0 );
113053              }else{
113054                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
113055                                           zSchemaName, zTabName, zColname);
113056                testcase( pX->zSpan==0 );
113057              }
113058              pX->bSpanIsTab = 1;
113059            }
113060            sqlite3DbFree(db, zToFree);
113061          }
113062        }
113063        if( !tableSeen ){
113064          if( zTName ){
113065            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
113066          }else{
113067            sqlite3ErrorMsg(pParse, "no tables specified");
113068          }
113069        }
113070      }
113071    }
113072    sqlite3ExprListDelete(db, pEList);
113073    p->pEList = pNew;
113074  }
113075#if SQLITE_MAX_COLUMN
113076  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
113077    sqlite3ErrorMsg(pParse, "too many columns in result set");
113078  }
113079#endif
113080  return WRC_Continue;
113081}
113082
113083/*
113084** No-op routine for the parse-tree walker.
113085**
113086** When this routine is the Walker.xExprCallback then expression trees
113087** are walked without any actions being taken at each node.  Presumably,
113088** when this routine is used for Walker.xExprCallback then
113089** Walker.xSelectCallback is set to do something useful for every
113090** subquery in the parser tree.
113091*/
113092static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
113093  UNUSED_PARAMETER2(NotUsed, NotUsed2);
113094  return WRC_Continue;
113095}
113096
113097/*
113098** This routine "expands" a SELECT statement and all of its subqueries.
113099** For additional information on what it means to "expand" a SELECT
113100** statement, see the comment on the selectExpand worker callback above.
113101**
113102** Expanding a SELECT statement is the first step in processing a
113103** SELECT statement.  The SELECT statement must be expanded before
113104** name resolution is performed.
113105**
113106** If anything goes wrong, an error message is written into pParse.
113107** The calling function can detect the problem by looking at pParse->nErr
113108** and/or pParse->db->mallocFailed.
113109*/
113110static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
113111  Walker w;
113112  memset(&w, 0, sizeof(w));
113113  w.xExprCallback = exprWalkNoop;
113114  w.pParse = pParse;
113115  if( pParse->hasCompound ){
113116    w.xSelectCallback = convertCompoundSelectToSubquery;
113117    sqlite3WalkSelect(&w, pSelect);
113118  }
113119  w.xSelectCallback = selectExpander;
113120  if( (pSelect->selFlags & SF_MultiValue)==0 ){
113121    w.xSelectCallback2 = selectPopWith;
113122  }
113123  sqlite3WalkSelect(&w, pSelect);
113124}
113125
113126
113127#ifndef SQLITE_OMIT_SUBQUERY
113128/*
113129** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
113130** interface.
113131**
113132** For each FROM-clause subquery, add Column.zType and Column.zColl
113133** information to the Table structure that represents the result set
113134** of that subquery.
113135**
113136** The Table structure that represents the result set was constructed
113137** by selectExpander() but the type and collation information was omitted
113138** at that point because identifiers had not yet been resolved.  This
113139** routine is called after identifier resolution.
113140*/
113141static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
113142  Parse *pParse;
113143  int i;
113144  SrcList *pTabList;
113145  struct SrcList_item *pFrom;
113146
113147  assert( p->selFlags & SF_Resolved );
113148  assert( (p->selFlags & SF_HasTypeInfo)==0 );
113149  p->selFlags |= SF_HasTypeInfo;
113150  pParse = pWalker->pParse;
113151  pTabList = p->pSrc;
113152  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
113153    Table *pTab = pFrom->pTab;
113154    assert( pTab!=0 );
113155    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
113156      /* A sub-query in the FROM clause of a SELECT */
113157      Select *pSel = pFrom->pSelect;
113158      if( pSel ){
113159        while( pSel->pPrior ) pSel = pSel->pPrior;
113160        selectAddColumnTypeAndCollation(pParse, pTab, pSel);
113161      }
113162    }
113163  }
113164}
113165#endif
113166
113167
113168/*
113169** This routine adds datatype and collating sequence information to
113170** the Table structures of all FROM-clause subqueries in a
113171** SELECT statement.
113172**
113173** Use this routine after name resolution.
113174*/
113175static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
113176#ifndef SQLITE_OMIT_SUBQUERY
113177  Walker w;
113178  memset(&w, 0, sizeof(w));
113179  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
113180  w.xExprCallback = exprWalkNoop;
113181  w.pParse = pParse;
113182  sqlite3WalkSelect(&w, pSelect);
113183#endif
113184}
113185
113186
113187/*
113188** This routine sets up a SELECT statement for processing.  The
113189** following is accomplished:
113190**
113191**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
113192**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
113193**     *  ON and USING clauses are shifted into WHERE statements
113194**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
113195**     *  Identifiers in expression are matched to tables.
113196**
113197** This routine acts recursively on all subqueries within the SELECT.
113198*/
113199SQLITE_PRIVATE void sqlite3SelectPrep(
113200  Parse *pParse,         /* The parser context */
113201  Select *p,             /* The SELECT statement being coded. */
113202  NameContext *pOuterNC  /* Name context for container */
113203){
113204  sqlite3 *db;
113205  if( NEVER(p==0) ) return;
113206  db = pParse->db;
113207  if( db->mallocFailed ) return;
113208  if( p->selFlags & SF_HasTypeInfo ) return;
113209  sqlite3SelectExpand(pParse, p);
113210  if( pParse->nErr || db->mallocFailed ) return;
113211  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
113212  if( pParse->nErr || db->mallocFailed ) return;
113213  sqlite3SelectAddTypeInfo(pParse, p);
113214}
113215
113216/*
113217** Reset the aggregate accumulator.
113218**
113219** The aggregate accumulator is a set of memory cells that hold
113220** intermediate results while calculating an aggregate.  This
113221** routine generates code that stores NULLs in all of those memory
113222** cells.
113223*/
113224static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
113225  Vdbe *v = pParse->pVdbe;
113226  int i;
113227  struct AggInfo_func *pFunc;
113228  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
113229  if( nReg==0 ) return;
113230#ifdef SQLITE_DEBUG
113231  /* Verify that all AggInfo registers are within the range specified by
113232  ** AggInfo.mnReg..AggInfo.mxReg */
113233  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
113234  for(i=0; i<pAggInfo->nColumn; i++){
113235    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
113236         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
113237  }
113238  for(i=0; i<pAggInfo->nFunc; i++){
113239    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
113240         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
113241  }
113242#endif
113243  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
113244  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
113245    if( pFunc->iDistinct>=0 ){
113246      Expr *pE = pFunc->pExpr;
113247      assert( !ExprHasProperty(pE, EP_xIsSelect) );
113248      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
113249        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
113250           "argument");
113251        pFunc->iDistinct = -1;
113252      }else{
113253        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
113254        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
113255                          (char*)pKeyInfo, P4_KEYINFO);
113256      }
113257    }
113258  }
113259}
113260
113261/*
113262** Invoke the OP_AggFinalize opcode for every aggregate function
113263** in the AggInfo structure.
113264*/
113265static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
113266  Vdbe *v = pParse->pVdbe;
113267  int i;
113268  struct AggInfo_func *pF;
113269  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
113270    ExprList *pList = pF->pExpr->x.pList;
113271    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
113272    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
113273                      (void*)pF->pFunc, P4_FUNCDEF);
113274  }
113275}
113276
113277/*
113278** Update the accumulator memory cells for an aggregate based on
113279** the current cursor position.
113280*/
113281static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
113282  Vdbe *v = pParse->pVdbe;
113283  int i;
113284  int regHit = 0;
113285  int addrHitTest = 0;
113286  struct AggInfo_func *pF;
113287  struct AggInfo_col *pC;
113288
113289  pAggInfo->directMode = 1;
113290  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
113291    int nArg;
113292    int addrNext = 0;
113293    int regAgg;
113294    ExprList *pList = pF->pExpr->x.pList;
113295    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
113296    if( pList ){
113297      nArg = pList->nExpr;
113298      regAgg = sqlite3GetTempRange(pParse, nArg);
113299      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
113300    }else{
113301      nArg = 0;
113302      regAgg = 0;
113303    }
113304    if( pF->iDistinct>=0 ){
113305      addrNext = sqlite3VdbeMakeLabel(v);
113306      testcase( nArg==0 );  /* Error condition */
113307      testcase( nArg>1 );   /* Also an error */
113308      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
113309    }
113310    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
113311      CollSeq *pColl = 0;
113312      struct ExprList_item *pItem;
113313      int j;
113314      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
113315      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
113316        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
113317      }
113318      if( !pColl ){
113319        pColl = pParse->db->pDfltColl;
113320      }
113321      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
113322      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
113323    }
113324    sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
113325                      (void*)pF->pFunc, P4_FUNCDEF);
113326    sqlite3VdbeChangeP5(v, (u8)nArg);
113327    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
113328    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
113329    if( addrNext ){
113330      sqlite3VdbeResolveLabel(v, addrNext);
113331      sqlite3ExprCacheClear(pParse);
113332    }
113333  }
113334
113335  /* Before populating the accumulator registers, clear the column cache.
113336  ** Otherwise, if any of the required column values are already present
113337  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
113338  ** to pC->iMem. But by the time the value is used, the original register
113339  ** may have been used, invalidating the underlying buffer holding the
113340  ** text or blob value. See ticket [883034dcb5].
113341  **
113342  ** Another solution would be to change the OP_SCopy used to copy cached
113343  ** values to an OP_Copy.
113344  */
113345  if( regHit ){
113346    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
113347  }
113348  sqlite3ExprCacheClear(pParse);
113349  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
113350    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
113351  }
113352  pAggInfo->directMode = 0;
113353  sqlite3ExprCacheClear(pParse);
113354  if( addrHitTest ){
113355    sqlite3VdbeJumpHere(v, addrHitTest);
113356  }
113357}
113358
113359/*
113360** Add a single OP_Explain instruction to the VDBE to explain a simple
113361** count(*) query ("SELECT count(*) FROM pTab").
113362*/
113363#ifndef SQLITE_OMIT_EXPLAIN
113364static void explainSimpleCount(
113365  Parse *pParse,                  /* Parse context */
113366  Table *pTab,                    /* Table being queried */
113367  Index *pIdx                     /* Index used to optimize scan, or NULL */
113368){
113369  if( pParse->explain==2 ){
113370    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
113371    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
113372        pTab->zName,
113373        bCover ? " USING COVERING INDEX " : "",
113374        bCover ? pIdx->zName : ""
113375    );
113376    sqlite3VdbeAddOp4(
113377        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
113378    );
113379  }
113380}
113381#else
113382# define explainSimpleCount(a,b,c)
113383#endif
113384
113385/*
113386** Generate code for the SELECT statement given in the p argument.
113387**
113388** The results are returned according to the SelectDest structure.
113389** See comments in sqliteInt.h for further information.
113390**
113391** This routine returns the number of errors.  If any errors are
113392** encountered, then an appropriate error message is left in
113393** pParse->zErrMsg.
113394**
113395** This routine does NOT free the Select structure passed in.  The
113396** calling function needs to do that.
113397*/
113398SQLITE_PRIVATE int sqlite3Select(
113399  Parse *pParse,         /* The parser context */
113400  Select *p,             /* The SELECT statement being coded. */
113401  SelectDest *pDest      /* What to do with the query results */
113402){
113403  int i, j;              /* Loop counters */
113404  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
113405  Vdbe *v;               /* The virtual machine under construction */
113406  int isAgg;             /* True for select lists like "count(*)" */
113407  ExprList *pEList = 0;  /* List of columns to extract. */
113408  SrcList *pTabList;     /* List of tables to select from */
113409  Expr *pWhere;          /* The WHERE clause.  May be NULL */
113410  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
113411  Expr *pHaving;         /* The HAVING clause.  May be NULL */
113412  int rc = 1;            /* Value to return from this function */
113413  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
113414  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
113415  AggInfo sAggInfo;      /* Information used by aggregate queries */
113416  int iEnd;              /* Address of the end of the query */
113417  sqlite3 *db;           /* The database connection */
113418
113419#ifndef SQLITE_OMIT_EXPLAIN
113420  int iRestoreSelectId = pParse->iSelectId;
113421  pParse->iSelectId = pParse->iNextSelectId++;
113422#endif
113423
113424  db = pParse->db;
113425  if( p==0 || db->mallocFailed || pParse->nErr ){
113426    return 1;
113427  }
113428  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
113429  memset(&sAggInfo, 0, sizeof(sAggInfo));
113430#if SELECTTRACE_ENABLED
113431  pParse->nSelectIndent++;
113432  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
113433  if( sqlite3SelectTrace & 0x100 ){
113434    sqlite3TreeViewSelect(0, p, 0);
113435  }
113436#endif
113437
113438  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
113439  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
113440  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
113441  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
113442  if( IgnorableOrderby(pDest) ){
113443    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
113444           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
113445           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
113446           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
113447    /* If ORDER BY makes no difference in the output then neither does
113448    ** DISTINCT so it can be removed too. */
113449    sqlite3ExprListDelete(db, p->pOrderBy);
113450    p->pOrderBy = 0;
113451    p->selFlags &= ~SF_Distinct;
113452  }
113453  sqlite3SelectPrep(pParse, p, 0);
113454  memset(&sSort, 0, sizeof(sSort));
113455  sSort.pOrderBy = p->pOrderBy;
113456  pTabList = p->pSrc;
113457  if( pParse->nErr || db->mallocFailed ){
113458    goto select_end;
113459  }
113460  assert( p->pEList!=0 );
113461  isAgg = (p->selFlags & SF_Aggregate)!=0;
113462#if SELECTTRACE_ENABLED
113463  if( sqlite3SelectTrace & 0x100 ){
113464    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
113465    sqlite3TreeViewSelect(0, p, 0);
113466  }
113467#endif
113468
113469
113470  /* If writing to memory or generating a set
113471  ** only a single column may be output.
113472  */
113473#ifndef SQLITE_OMIT_SUBQUERY
113474  if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
113475    goto select_end;
113476  }
113477#endif
113478
113479  /* Try to flatten subqueries in the FROM clause up into the main query
113480  */
113481#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
113482  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
113483    struct SrcList_item *pItem = &pTabList->a[i];
113484    Select *pSub = pItem->pSelect;
113485    int isAggSub;
113486    Table *pTab = pItem->pTab;
113487    if( pSub==0 ) continue;
113488
113489    /* Catch mismatch in the declared columns of a view and the number of
113490    ** columns in the SELECT on the RHS */
113491    if( pTab->nCol!=pSub->pEList->nExpr ){
113492      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
113493                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
113494      goto select_end;
113495    }
113496
113497    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
113498    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
113499      /* This subquery can be absorbed into its parent. */
113500      if( isAggSub ){
113501        isAgg = 1;
113502        p->selFlags |= SF_Aggregate;
113503      }
113504      i = -1;
113505    }
113506    pTabList = p->pSrc;
113507    if( db->mallocFailed ) goto select_end;
113508    if( !IgnorableOrderby(pDest) ){
113509      sSort.pOrderBy = p->pOrderBy;
113510    }
113511  }
113512#endif
113513
113514  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
113515  ** does not already exist */
113516  v = sqlite3GetVdbe(pParse);
113517  if( v==0 ) goto select_end;
113518
113519#ifndef SQLITE_OMIT_COMPOUND_SELECT
113520  /* Handle compound SELECT statements using the separate multiSelect()
113521  ** procedure.
113522  */
113523  if( p->pPrior ){
113524    rc = multiSelect(pParse, p, pDest);
113525    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
113526#if SELECTTRACE_ENABLED
113527    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
113528    pParse->nSelectIndent--;
113529#endif
113530    return rc;
113531  }
113532#endif
113533
113534  /* Generate code for all sub-queries in the FROM clause
113535  */
113536#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
113537  for(i=0; i<pTabList->nSrc; i++){
113538    struct SrcList_item *pItem = &pTabList->a[i];
113539    SelectDest dest;
113540    Select *pSub = pItem->pSelect;
113541    if( pSub==0 ) continue;
113542
113543    /* Sometimes the code for a subquery will be generated more than
113544    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
113545    ** for example.  In that case, do not regenerate the code to manifest
113546    ** a view or the co-routine to implement a view.  The first instance
113547    ** is sufficient, though the subroutine to manifest the view does need
113548    ** to be invoked again. */
113549    if( pItem->addrFillSub ){
113550      if( pItem->fg.viaCoroutine==0 ){
113551        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
113552      }
113553      continue;
113554    }
113555
113556    /* Increment Parse.nHeight by the height of the largest expression
113557    ** tree referred to by this, the parent select. The child select
113558    ** may contain expression trees of at most
113559    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
113560    ** more conservative than necessary, but much easier than enforcing
113561    ** an exact limit.
113562    */
113563    pParse->nHeight += sqlite3SelectExprHeight(p);
113564
113565    /* Make copies of constant WHERE-clause terms in the outer query down
113566    ** inside the subquery.  This can help the subquery to run more efficiently.
113567    */
113568    if( (pItem->fg.jointype & JT_OUTER)==0
113569     && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
113570    ){
113571#if SELECTTRACE_ENABLED
113572      if( sqlite3SelectTrace & 0x100 ){
113573        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
113574        sqlite3TreeViewSelect(0, p, 0);
113575      }
113576#endif
113577    }
113578
113579    /* Generate code to implement the subquery
113580    */
113581    if( pTabList->nSrc==1
113582     && (p->selFlags & SF_All)==0
113583     && OptimizationEnabled(db, SQLITE_SubqCoroutine)
113584    ){
113585      /* Implement a co-routine that will return a single row of the result
113586      ** set on each invocation.
113587      */
113588      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
113589      pItem->regReturn = ++pParse->nMem;
113590      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
113591      VdbeComment((v, "%s", pItem->pTab->zName));
113592      pItem->addrFillSub = addrTop;
113593      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
113594      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
113595      sqlite3Select(pParse, pSub, &dest);
113596      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
113597      pItem->fg.viaCoroutine = 1;
113598      pItem->regResult = dest.iSdst;
113599      sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
113600      sqlite3VdbeJumpHere(v, addrTop-1);
113601      sqlite3ClearTempRegCache(pParse);
113602    }else{
113603      /* Generate a subroutine that will fill an ephemeral table with
113604      ** the content of this subquery.  pItem->addrFillSub will point
113605      ** to the address of the generated subroutine.  pItem->regReturn
113606      ** is a register allocated to hold the subroutine return address
113607      */
113608      int topAddr;
113609      int onceAddr = 0;
113610      int retAddr;
113611      assert( pItem->addrFillSub==0 );
113612      pItem->regReturn = ++pParse->nMem;
113613      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
113614      pItem->addrFillSub = topAddr+1;
113615      if( pItem->fg.isCorrelated==0 ){
113616        /* If the subquery is not correlated and if we are not inside of
113617        ** a trigger, then we only need to compute the value of the subquery
113618        ** once. */
113619        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
113620        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
113621      }else{
113622        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
113623      }
113624      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
113625      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
113626      sqlite3Select(pParse, pSub, &dest);
113627      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
113628      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
113629      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
113630      VdbeComment((v, "end %s", pItem->pTab->zName));
113631      sqlite3VdbeChangeP1(v, topAddr, retAddr);
113632      sqlite3ClearTempRegCache(pParse);
113633    }
113634    if( db->mallocFailed ) goto select_end;
113635    pParse->nHeight -= sqlite3SelectExprHeight(p);
113636  }
113637#endif
113638
113639  /* Various elements of the SELECT copied into local variables for
113640  ** convenience */
113641  pEList = p->pEList;
113642  pWhere = p->pWhere;
113643  pGroupBy = p->pGroupBy;
113644  pHaving = p->pHaving;
113645  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
113646
113647#if SELECTTRACE_ENABLED
113648  if( sqlite3SelectTrace & 0x400 ){
113649    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
113650    sqlite3TreeViewSelect(0, p, 0);
113651  }
113652#endif
113653
113654  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
113655  ** if the select-list is the same as the ORDER BY list, then this query
113656  ** can be rewritten as a GROUP BY. In other words, this:
113657  **
113658  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
113659  **
113660  ** is transformed to:
113661  **
113662  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
113663  **
113664  ** The second form is preferred as a single index (or temp-table) may be
113665  ** used for both the ORDER BY and DISTINCT processing. As originally
113666  ** written the query must use a temp-table for at least one of the ORDER
113667  ** BY and DISTINCT, and an index or separate temp-table for the other.
113668  */
113669  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
113670   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
113671  ){
113672    p->selFlags &= ~SF_Distinct;
113673    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
113674    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
113675    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
113676    ** original setting of the SF_Distinct flag, not the current setting */
113677    assert( sDistinct.isTnct );
113678  }
113679
113680  /* If there is an ORDER BY clause, then create an ephemeral index to
113681  ** do the sorting.  But this sorting ephemeral index might end up
113682  ** being unused if the data can be extracted in pre-sorted order.
113683  ** If that is the case, then the OP_OpenEphemeral instruction will be
113684  ** changed to an OP_Noop once we figure out that the sorting index is
113685  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
113686  ** that change.
113687  */
113688  if( sSort.pOrderBy ){
113689    KeyInfo *pKeyInfo;
113690    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
113691    sSort.iECursor = pParse->nTab++;
113692    sSort.addrSortIndex =
113693      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
113694          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
113695          (char*)pKeyInfo, P4_KEYINFO
113696      );
113697  }else{
113698    sSort.addrSortIndex = -1;
113699  }
113700
113701  /* If the output is destined for a temporary table, open that table.
113702  */
113703  if( pDest->eDest==SRT_EphemTab ){
113704    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
113705  }
113706
113707  /* Set the limiter.
113708  */
113709  iEnd = sqlite3VdbeMakeLabel(v);
113710  p->nSelectRow = LARGEST_INT64;
113711  computeLimitRegisters(pParse, p, iEnd);
113712  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
113713    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
113714    sSort.sortFlags |= SORTFLAG_UseSorter;
113715  }
113716
113717  /* Open an ephemeral index to use for the distinct set.
113718  */
113719  if( p->selFlags & SF_Distinct ){
113720    sDistinct.tabTnct = pParse->nTab++;
113721    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
113722                             sDistinct.tabTnct, 0, 0,
113723                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
113724                             P4_KEYINFO);
113725    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
113726    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
113727  }else{
113728    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
113729  }
113730
113731  if( !isAgg && pGroupBy==0 ){
113732    /* No aggregate functions and no GROUP BY clause */
113733    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
113734
113735    /* Begin the database scan. */
113736    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
113737                               p->pEList, wctrlFlags, 0);
113738    if( pWInfo==0 ) goto select_end;
113739    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
113740      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
113741    }
113742    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
113743      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
113744    }
113745    if( sSort.pOrderBy ){
113746      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
113747      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
113748        sSort.pOrderBy = 0;
113749      }
113750    }
113751
113752    /* If sorting index that was created by a prior OP_OpenEphemeral
113753    ** instruction ended up not being needed, then change the OP_OpenEphemeral
113754    ** into an OP_Noop.
113755    */
113756    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
113757      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
113758    }
113759
113760    /* Use the standard inner loop. */
113761    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
113762                    sqlite3WhereContinueLabel(pWInfo),
113763                    sqlite3WhereBreakLabel(pWInfo));
113764
113765    /* End the database scan loop.
113766    */
113767    sqlite3WhereEnd(pWInfo);
113768  }else{
113769    /* This case when there exist aggregate functions or a GROUP BY clause
113770    ** or both */
113771    NameContext sNC;    /* Name context for processing aggregate information */
113772    int iAMem;          /* First Mem address for storing current GROUP BY */
113773    int iBMem;          /* First Mem address for previous GROUP BY */
113774    int iUseFlag;       /* Mem address holding flag indicating that at least
113775                        ** one row of the input to the aggregator has been
113776                        ** processed */
113777    int iAbortFlag;     /* Mem address which causes query abort if positive */
113778    int groupBySort;    /* Rows come from source in GROUP BY order */
113779    int addrEnd;        /* End of processing for this SELECT */
113780    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
113781    int sortOut = 0;    /* Output register from the sorter */
113782    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
113783
113784    /* Remove any and all aliases between the result set and the
113785    ** GROUP BY clause.
113786    */
113787    if( pGroupBy ){
113788      int k;                        /* Loop counter */
113789      struct ExprList_item *pItem;  /* For looping over expression in a list */
113790
113791      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
113792        pItem->u.x.iAlias = 0;
113793      }
113794      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
113795        pItem->u.x.iAlias = 0;
113796      }
113797      if( p->nSelectRow>100 ) p->nSelectRow = 100;
113798    }else{
113799      p->nSelectRow = 1;
113800    }
113801
113802    /* If there is both a GROUP BY and an ORDER BY clause and they are
113803    ** identical, then it may be possible to disable the ORDER BY clause
113804    ** on the grounds that the GROUP BY will cause elements to come out
113805    ** in the correct order. It also may not - the GROUP BY might use a
113806    ** database index that causes rows to be grouped together as required
113807    ** but not actually sorted. Either way, record the fact that the
113808    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
113809    ** variable.  */
113810    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
113811      orderByGrp = 1;
113812    }
113813
113814    /* Create a label to jump to when we want to abort the query */
113815    addrEnd = sqlite3VdbeMakeLabel(v);
113816
113817    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
113818    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
113819    ** SELECT statement.
113820    */
113821    memset(&sNC, 0, sizeof(sNC));
113822    sNC.pParse = pParse;
113823    sNC.pSrcList = pTabList;
113824    sNC.pAggInfo = &sAggInfo;
113825    sAggInfo.mnReg = pParse->nMem+1;
113826    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
113827    sAggInfo.pGroupBy = pGroupBy;
113828    sqlite3ExprAnalyzeAggList(&sNC, pEList);
113829    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
113830    if( pHaving ){
113831      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
113832    }
113833    sAggInfo.nAccumulator = sAggInfo.nColumn;
113834    for(i=0; i<sAggInfo.nFunc; i++){
113835      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
113836      sNC.ncFlags |= NC_InAggFunc;
113837      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
113838      sNC.ncFlags &= ~NC_InAggFunc;
113839    }
113840    sAggInfo.mxReg = pParse->nMem;
113841    if( db->mallocFailed ) goto select_end;
113842
113843    /* Processing for aggregates with GROUP BY is very different and
113844    ** much more complex than aggregates without a GROUP BY.
113845    */
113846    if( pGroupBy ){
113847      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
113848      int addr1;          /* A-vs-B comparision jump */
113849      int addrOutputRow;  /* Start of subroutine that outputs a result row */
113850      int regOutputRow;   /* Return address register for output subroutine */
113851      int addrSetAbort;   /* Set the abort flag and return */
113852      int addrTopOfLoop;  /* Top of the input loop */
113853      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
113854      int addrReset;      /* Subroutine for resetting the accumulator */
113855      int regReset;       /* Return address register for reset subroutine */
113856
113857      /* If there is a GROUP BY clause we might need a sorting index to
113858      ** implement it.  Allocate that sorting index now.  If it turns out
113859      ** that we do not need it after all, the OP_SorterOpen instruction
113860      ** will be converted into a Noop.
113861      */
113862      sAggInfo.sortingIdx = pParse->nTab++;
113863      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
113864      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
113865          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
113866          0, (char*)pKeyInfo, P4_KEYINFO);
113867
113868      /* Initialize memory locations used by GROUP BY aggregate processing
113869      */
113870      iUseFlag = ++pParse->nMem;
113871      iAbortFlag = ++pParse->nMem;
113872      regOutputRow = ++pParse->nMem;
113873      addrOutputRow = sqlite3VdbeMakeLabel(v);
113874      regReset = ++pParse->nMem;
113875      addrReset = sqlite3VdbeMakeLabel(v);
113876      iAMem = pParse->nMem + 1;
113877      pParse->nMem += pGroupBy->nExpr;
113878      iBMem = pParse->nMem + 1;
113879      pParse->nMem += pGroupBy->nExpr;
113880      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
113881      VdbeComment((v, "clear abort flag"));
113882      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
113883      VdbeComment((v, "indicate accumulator empty"));
113884      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
113885
113886      /* Begin a loop that will extract all source rows in GROUP BY order.
113887      ** This might involve two separate loops with an OP_Sort in between, or
113888      ** it might be a single loop that uses an index to extract information
113889      ** in the right order to begin with.
113890      */
113891      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
113892      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
113893          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
113894      );
113895      if( pWInfo==0 ) goto select_end;
113896      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
113897        /* The optimizer is able to deliver rows in group by order so
113898        ** we do not have to sort.  The OP_OpenEphemeral table will be
113899        ** cancelled later because we still need to use the pKeyInfo
113900        */
113901        groupBySort = 0;
113902      }else{
113903        /* Rows are coming out in undetermined order.  We have to push
113904        ** each row into a sorting index, terminate the first loop,
113905        ** then loop over the sorting index in order to get the output
113906        ** in sorted order
113907        */
113908        int regBase;
113909        int regRecord;
113910        int nCol;
113911        int nGroupBy;
113912
113913        explainTempTable(pParse,
113914            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
113915                    "DISTINCT" : "GROUP BY");
113916
113917        groupBySort = 1;
113918        nGroupBy = pGroupBy->nExpr;
113919        nCol = nGroupBy;
113920        j = nGroupBy;
113921        for(i=0; i<sAggInfo.nColumn; i++){
113922          if( sAggInfo.aCol[i].iSorterColumn>=j ){
113923            nCol++;
113924            j++;
113925          }
113926        }
113927        regBase = sqlite3GetTempRange(pParse, nCol);
113928        sqlite3ExprCacheClear(pParse);
113929        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
113930        j = nGroupBy;
113931        for(i=0; i<sAggInfo.nColumn; i++){
113932          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
113933          if( pCol->iSorterColumn>=j ){
113934            int r1 = j + regBase;
113935            int r2;
113936
113937            r2 = sqlite3ExprCodeGetColumn(pParse,
113938                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
113939            if( r1!=r2 ){
113940              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
113941            }
113942            j++;
113943          }
113944        }
113945        regRecord = sqlite3GetTempReg(pParse);
113946        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
113947        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
113948        sqlite3ReleaseTempReg(pParse, regRecord);
113949        sqlite3ReleaseTempRange(pParse, regBase, nCol);
113950        sqlite3WhereEnd(pWInfo);
113951        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
113952        sortOut = sqlite3GetTempReg(pParse);
113953        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
113954        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
113955        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
113956        sAggInfo.useSortingIdx = 1;
113957        sqlite3ExprCacheClear(pParse);
113958
113959      }
113960
113961      /* If the index or temporary table used by the GROUP BY sort
113962      ** will naturally deliver rows in the order required by the ORDER BY
113963      ** clause, cancel the ephemeral table open coded earlier.
113964      **
113965      ** This is an optimization - the correct answer should result regardless.
113966      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
113967      ** disable this optimization for testing purposes.  */
113968      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
113969       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
113970      ){
113971        sSort.pOrderBy = 0;
113972        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
113973      }
113974
113975      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
113976      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
113977      ** Then compare the current GROUP BY terms against the GROUP BY terms
113978      ** from the previous row currently stored in a0, a1, a2...
113979      */
113980      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
113981      sqlite3ExprCacheClear(pParse);
113982      if( groupBySort ){
113983        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
113984                          sortOut, sortPTab);
113985      }
113986      for(j=0; j<pGroupBy->nExpr; j++){
113987        if( groupBySort ){
113988          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
113989        }else{
113990          sAggInfo.directMode = 1;
113991          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
113992        }
113993      }
113994      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
113995                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
113996      addr1 = sqlite3VdbeCurrentAddr(v);
113997      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
113998
113999      /* Generate code that runs whenever the GROUP BY changes.
114000      ** Changes in the GROUP BY are detected by the previous code
114001      ** block.  If there were no changes, this block is skipped.
114002      **
114003      ** This code copies current group by terms in b0,b1,b2,...
114004      ** over to a0,a1,a2.  It then calls the output subroutine
114005      ** and resets the aggregate accumulator registers in preparation
114006      ** for the next GROUP BY batch.
114007      */
114008      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
114009      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
114010      VdbeComment((v, "output one row"));
114011      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
114012      VdbeComment((v, "check abort flag"));
114013      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
114014      VdbeComment((v, "reset accumulator"));
114015
114016      /* Update the aggregate accumulators based on the content of
114017      ** the current row
114018      */
114019      sqlite3VdbeJumpHere(v, addr1);
114020      updateAccumulator(pParse, &sAggInfo);
114021      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
114022      VdbeComment((v, "indicate data in accumulator"));
114023
114024      /* End of the loop
114025      */
114026      if( groupBySort ){
114027        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
114028        VdbeCoverage(v);
114029      }else{
114030        sqlite3WhereEnd(pWInfo);
114031        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
114032      }
114033
114034      /* Output the final row of result
114035      */
114036      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
114037      VdbeComment((v, "output final row"));
114038
114039      /* Jump over the subroutines
114040      */
114041      sqlite3VdbeGoto(v, addrEnd);
114042
114043      /* Generate a subroutine that outputs a single row of the result
114044      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
114045      ** is less than or equal to zero, the subroutine is a no-op.  If
114046      ** the processing calls for the query to abort, this subroutine
114047      ** increments the iAbortFlag memory location before returning in
114048      ** order to signal the caller to abort.
114049      */
114050      addrSetAbort = sqlite3VdbeCurrentAddr(v);
114051      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
114052      VdbeComment((v, "set abort flag"));
114053      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114054      sqlite3VdbeResolveLabel(v, addrOutputRow);
114055      addrOutputRow = sqlite3VdbeCurrentAddr(v);
114056      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
114057      VdbeCoverage(v);
114058      VdbeComment((v, "Groupby result generator entry point"));
114059      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114060      finalizeAggFunctions(pParse, &sAggInfo);
114061      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
114062      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
114063                      &sDistinct, pDest,
114064                      addrOutputRow+1, addrSetAbort);
114065      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114066      VdbeComment((v, "end groupby result generator"));
114067
114068      /* Generate a subroutine that will reset the group-by accumulator
114069      */
114070      sqlite3VdbeResolveLabel(v, addrReset);
114071      resetAccumulator(pParse, &sAggInfo);
114072      sqlite3VdbeAddOp1(v, OP_Return, regReset);
114073
114074    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
114075    else {
114076      ExprList *pDel = 0;
114077#ifndef SQLITE_OMIT_BTREECOUNT
114078      Table *pTab;
114079      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
114080        /* If isSimpleCount() returns a pointer to a Table structure, then
114081        ** the SQL statement is of the form:
114082        **
114083        **   SELECT count(*) FROM <tbl>
114084        **
114085        ** where the Table structure returned represents table <tbl>.
114086        **
114087        ** This statement is so common that it is optimized specially. The
114088        ** OP_Count instruction is executed either on the intkey table that
114089        ** contains the data for table <tbl> or on one of its indexes. It
114090        ** is better to execute the op on an index, as indexes are almost
114091        ** always spread across less pages than their corresponding tables.
114092        */
114093        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
114094        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
114095        Index *pIdx;                         /* Iterator variable */
114096        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
114097        Index *pBest = 0;                    /* Best index found so far */
114098        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
114099
114100        sqlite3CodeVerifySchema(pParse, iDb);
114101        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
114102
114103        /* Search for the index that has the lowest scan cost.
114104        **
114105        ** (2011-04-15) Do not do a full scan of an unordered index.
114106        **
114107        ** (2013-10-03) Do not count the entries in a partial index.
114108        **
114109        ** In practice the KeyInfo structure will not be used. It is only
114110        ** passed to keep OP_OpenRead happy.
114111        */
114112        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
114113        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114114          if( pIdx->bUnordered==0
114115           && pIdx->szIdxRow<pTab->szTabRow
114116           && pIdx->pPartIdxWhere==0
114117           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
114118          ){
114119            pBest = pIdx;
114120          }
114121        }
114122        if( pBest ){
114123          iRoot = pBest->tnum;
114124          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
114125        }
114126
114127        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
114128        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
114129        if( pKeyInfo ){
114130          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
114131        }
114132        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
114133        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
114134        explainSimpleCount(pParse, pTab, pBest);
114135      }else
114136#endif /* SQLITE_OMIT_BTREECOUNT */
114137      {
114138        /* Check if the query is of one of the following forms:
114139        **
114140        **   SELECT min(x) FROM ...
114141        **   SELECT max(x) FROM ...
114142        **
114143        ** If it is, then ask the code in where.c to attempt to sort results
114144        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
114145        ** If where.c is able to produce results sorted in this order, then
114146        ** add vdbe code to break out of the processing loop after the
114147        ** first iteration (since the first iteration of the loop is
114148        ** guaranteed to operate on the row with the minimum or maximum
114149        ** value of x, the only row required).
114150        **
114151        ** A special flag must be passed to sqlite3WhereBegin() to slightly
114152        ** modify behavior as follows:
114153        **
114154        **   + If the query is a "SELECT min(x)", then the loop coded by
114155        **     where.c should not iterate over any values with a NULL value
114156        **     for x.
114157        **
114158        **   + The optimizer code in where.c (the thing that decides which
114159        **     index or indices to use) should place a different priority on
114160        **     satisfying the 'ORDER BY' clause than it does in other cases.
114161        **     Refer to code and comments in where.c for details.
114162        */
114163        ExprList *pMinMax = 0;
114164        u8 flag = WHERE_ORDERBY_NORMAL;
114165
114166        assert( p->pGroupBy==0 );
114167        assert( flag==0 );
114168        if( p->pHaving==0 ){
114169          flag = minMaxQuery(&sAggInfo, &pMinMax);
114170        }
114171        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
114172
114173        if( flag ){
114174          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
114175          pDel = pMinMax;
114176          if( pMinMax && !db->mallocFailed ){
114177            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
114178            pMinMax->a[0].pExpr->op = TK_COLUMN;
114179          }
114180        }
114181
114182        /* This case runs if the aggregate has no GROUP BY clause.  The
114183        ** processing is much simpler since there is only a single row
114184        ** of output.
114185        */
114186        resetAccumulator(pParse, &sAggInfo);
114187        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
114188        if( pWInfo==0 ){
114189          sqlite3ExprListDelete(db, pDel);
114190          goto select_end;
114191        }
114192        updateAccumulator(pParse, &sAggInfo);
114193        assert( pMinMax==0 || pMinMax->nExpr==1 );
114194        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
114195          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
114196          VdbeComment((v, "%s() by index",
114197                (flag==WHERE_ORDERBY_MIN?"min":"max")));
114198        }
114199        sqlite3WhereEnd(pWInfo);
114200        finalizeAggFunctions(pParse, &sAggInfo);
114201      }
114202
114203      sSort.pOrderBy = 0;
114204      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
114205      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
114206                      pDest, addrEnd, addrEnd);
114207      sqlite3ExprListDelete(db, pDel);
114208    }
114209    sqlite3VdbeResolveLabel(v, addrEnd);
114210
114211  } /* endif aggregate query */
114212
114213  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
114214    explainTempTable(pParse, "DISTINCT");
114215  }
114216
114217  /* If there is an ORDER BY clause, then we need to sort the results
114218  ** and send them to the callback one by one.
114219  */
114220  if( sSort.pOrderBy ){
114221    explainTempTable(pParse,
114222                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
114223    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
114224  }
114225
114226  /* Jump here to skip this query
114227  */
114228  sqlite3VdbeResolveLabel(v, iEnd);
114229
114230  /* The SELECT has been coded. If there is an error in the Parse structure,
114231  ** set the return code to 1. Otherwise 0. */
114232  rc = (pParse->nErr>0);
114233
114234  /* Control jumps to here if an error is encountered above, or upon
114235  ** successful coding of the SELECT.
114236  */
114237select_end:
114238  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
114239
114240  /* Identify column names if results of the SELECT are to be output.
114241  */
114242  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
114243    generateColumnNames(pParse, pTabList, pEList);
114244  }
114245
114246  sqlite3DbFree(db, sAggInfo.aCol);
114247  sqlite3DbFree(db, sAggInfo.aFunc);
114248#if SELECTTRACE_ENABLED
114249  SELECTTRACE(1,pParse,p,("end processing\n"));
114250  pParse->nSelectIndent--;
114251#endif
114252  return rc;
114253}
114254
114255/************** End of select.c **********************************************/
114256/************** Begin file table.c *******************************************/
114257/*
114258** 2001 September 15
114259**
114260** The author disclaims copyright to this source code.  In place of
114261** a legal notice, here is a blessing:
114262**
114263**    May you do good and not evil.
114264**    May you find forgiveness for yourself and forgive others.
114265**    May you share freely, never taking more than you give.
114266**
114267*************************************************************************
114268** This file contains the sqlite3_get_table() and sqlite3_free_table()
114269** interface routines.  These are just wrappers around the main
114270** interface routine of sqlite3_exec().
114271**
114272** These routines are in a separate files so that they will not be linked
114273** if they are not used.
114274*/
114275/* #include "sqliteInt.h" */
114276/* #include <stdlib.h> */
114277/* #include <string.h> */
114278
114279#ifndef SQLITE_OMIT_GET_TABLE
114280
114281/*
114282** This structure is used to pass data from sqlite3_get_table() through
114283** to the callback function is uses to build the result.
114284*/
114285typedef struct TabResult {
114286  char **azResult;   /* Accumulated output */
114287  char *zErrMsg;     /* Error message text, if an error occurs */
114288  u32 nAlloc;        /* Slots allocated for azResult[] */
114289  u32 nRow;          /* Number of rows in the result */
114290  u32 nColumn;       /* Number of columns in the result */
114291  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
114292  int rc;            /* Return code from sqlite3_exec() */
114293} TabResult;
114294
114295/*
114296** This routine is called once for each row in the result table.  Its job
114297** is to fill in the TabResult structure appropriately, allocating new
114298** memory as necessary.
114299*/
114300static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
114301  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
114302  int need;                         /* Slots needed in p->azResult[] */
114303  int i;                            /* Loop counter */
114304  char *z;                          /* A single column of result */
114305
114306  /* Make sure there is enough space in p->azResult to hold everything
114307  ** we need to remember from this invocation of the callback.
114308  */
114309  if( p->nRow==0 && argv!=0 ){
114310    need = nCol*2;
114311  }else{
114312    need = nCol;
114313  }
114314  if( p->nData + need > p->nAlloc ){
114315    char **azNew;
114316    p->nAlloc = p->nAlloc*2 + need;
114317    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
114318    if( azNew==0 ) goto malloc_failed;
114319    p->azResult = azNew;
114320  }
114321
114322  /* If this is the first row, then generate an extra row containing
114323  ** the names of all columns.
114324  */
114325  if( p->nRow==0 ){
114326    p->nColumn = nCol;
114327    for(i=0; i<nCol; i++){
114328      z = sqlite3_mprintf("%s", colv[i]);
114329      if( z==0 ) goto malloc_failed;
114330      p->azResult[p->nData++] = z;
114331    }
114332  }else if( (int)p->nColumn!=nCol ){
114333    sqlite3_free(p->zErrMsg);
114334    p->zErrMsg = sqlite3_mprintf(
114335       "sqlite3_get_table() called with two or more incompatible queries"
114336    );
114337    p->rc = SQLITE_ERROR;
114338    return 1;
114339  }
114340
114341  /* Copy over the row data
114342  */
114343  if( argv!=0 ){
114344    for(i=0; i<nCol; i++){
114345      if( argv[i]==0 ){
114346        z = 0;
114347      }else{
114348        int n = sqlite3Strlen30(argv[i])+1;
114349        z = sqlite3_malloc64( n );
114350        if( z==0 ) goto malloc_failed;
114351        memcpy(z, argv[i], n);
114352      }
114353      p->azResult[p->nData++] = z;
114354    }
114355    p->nRow++;
114356  }
114357  return 0;
114358
114359malloc_failed:
114360  p->rc = SQLITE_NOMEM;
114361  return 1;
114362}
114363
114364/*
114365** Query the database.  But instead of invoking a callback for each row,
114366** malloc() for space to hold the result and return the entire results
114367** at the conclusion of the call.
114368**
114369** The result that is written to ***pazResult is held in memory obtained
114370** from malloc().  But the caller cannot free this memory directly.
114371** Instead, the entire table should be passed to sqlite3_free_table() when
114372** the calling procedure is finished using it.
114373*/
114374SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
114375  sqlite3 *db,                /* The database on which the SQL executes */
114376  const char *zSql,           /* The SQL to be executed */
114377  char ***pazResult,          /* Write the result table here */
114378  int *pnRow,                 /* Write the number of rows in the result here */
114379  int *pnColumn,              /* Write the number of columns of result here */
114380  char **pzErrMsg             /* Write error messages here */
114381){
114382  int rc;
114383  TabResult res;
114384
114385#ifdef SQLITE_ENABLE_API_ARMOR
114386  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
114387#endif
114388  *pazResult = 0;
114389  if( pnColumn ) *pnColumn = 0;
114390  if( pnRow ) *pnRow = 0;
114391  if( pzErrMsg ) *pzErrMsg = 0;
114392  res.zErrMsg = 0;
114393  res.nRow = 0;
114394  res.nColumn = 0;
114395  res.nData = 1;
114396  res.nAlloc = 20;
114397  res.rc = SQLITE_OK;
114398  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
114399  if( res.azResult==0 ){
114400     db->errCode = SQLITE_NOMEM;
114401     return SQLITE_NOMEM;
114402  }
114403  res.azResult[0] = 0;
114404  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
114405  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
114406  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
114407  if( (rc&0xff)==SQLITE_ABORT ){
114408    sqlite3_free_table(&res.azResult[1]);
114409    if( res.zErrMsg ){
114410      if( pzErrMsg ){
114411        sqlite3_free(*pzErrMsg);
114412        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
114413      }
114414      sqlite3_free(res.zErrMsg);
114415    }
114416    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
114417    return res.rc;
114418  }
114419  sqlite3_free(res.zErrMsg);
114420  if( rc!=SQLITE_OK ){
114421    sqlite3_free_table(&res.azResult[1]);
114422    return rc;
114423  }
114424  if( res.nAlloc>res.nData ){
114425    char **azNew;
114426    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
114427    if( azNew==0 ){
114428      sqlite3_free_table(&res.azResult[1]);
114429      db->errCode = SQLITE_NOMEM;
114430      return SQLITE_NOMEM;
114431    }
114432    res.azResult = azNew;
114433  }
114434  *pazResult = &res.azResult[1];
114435  if( pnColumn ) *pnColumn = res.nColumn;
114436  if( pnRow ) *pnRow = res.nRow;
114437  return rc;
114438}
114439
114440/*
114441** This routine frees the space the sqlite3_get_table() malloced.
114442*/
114443SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
114444  char **azResult            /* Result returned from sqlite3_get_table() */
114445){
114446  if( azResult ){
114447    int i, n;
114448    azResult--;
114449    assert( azResult!=0 );
114450    n = SQLITE_PTR_TO_INT(azResult[0]);
114451    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
114452    sqlite3_free(azResult);
114453  }
114454}
114455
114456#endif /* SQLITE_OMIT_GET_TABLE */
114457
114458/************** End of table.c ***********************************************/
114459/************** Begin file trigger.c *****************************************/
114460/*
114461**
114462** The author disclaims copyright to this source code.  In place of
114463** a legal notice, here is a blessing:
114464**
114465**    May you do good and not evil.
114466**    May you find forgiveness for yourself and forgive others.
114467**    May you share freely, never taking more than you give.
114468**
114469*************************************************************************
114470** This file contains the implementation for TRIGGERs
114471*/
114472/* #include "sqliteInt.h" */
114473
114474#ifndef SQLITE_OMIT_TRIGGER
114475/*
114476** Delete a linked list of TriggerStep structures.
114477*/
114478SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
114479  while( pTriggerStep ){
114480    TriggerStep * pTmp = pTriggerStep;
114481    pTriggerStep = pTriggerStep->pNext;
114482
114483    sqlite3ExprDelete(db, pTmp->pWhere);
114484    sqlite3ExprListDelete(db, pTmp->pExprList);
114485    sqlite3SelectDelete(db, pTmp->pSelect);
114486    sqlite3IdListDelete(db, pTmp->pIdList);
114487
114488    sqlite3DbFree(db, pTmp);
114489  }
114490}
114491
114492/*
114493** Given table pTab, return a list of all the triggers attached to
114494** the table. The list is connected by Trigger.pNext pointers.
114495**
114496** All of the triggers on pTab that are in the same database as pTab
114497** are already attached to pTab->pTrigger.  But there might be additional
114498** triggers on pTab in the TEMP schema.  This routine prepends all
114499** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
114500** and returns the combined list.
114501**
114502** To state it another way:  This routine returns a list of all triggers
114503** that fire off of pTab.  The list will include any TEMP triggers on
114504** pTab as well as the triggers lised in pTab->pTrigger.
114505*/
114506SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
114507  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
114508  Trigger *pList = 0;                  /* List of triggers to return */
114509
114510  if( pParse->disableTriggers ){
114511    return 0;
114512  }
114513
114514  if( pTmpSchema!=pTab->pSchema ){
114515    HashElem *p;
114516    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
114517    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
114518      Trigger *pTrig = (Trigger *)sqliteHashData(p);
114519      if( pTrig->pTabSchema==pTab->pSchema
114520       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
114521      ){
114522        pTrig->pNext = (pList ? pList : pTab->pTrigger);
114523        pList = pTrig;
114524      }
114525    }
114526  }
114527
114528  return (pList ? pList : pTab->pTrigger);
114529}
114530
114531/*
114532** This is called by the parser when it sees a CREATE TRIGGER statement
114533** up to the point of the BEGIN before the trigger actions.  A Trigger
114534** structure is generated based on the information available and stored
114535** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
114536** sqlite3FinishTrigger() function is called to complete the trigger
114537** construction process.
114538*/
114539SQLITE_PRIVATE void sqlite3BeginTrigger(
114540  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
114541  Token *pName1,      /* The name of the trigger */
114542  Token *pName2,      /* The name of the trigger */
114543  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
114544  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
114545  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
114546  SrcList *pTableName,/* The name of the table/view the trigger applies to */
114547  Expr *pWhen,        /* WHEN clause */
114548  int isTemp,         /* True if the TEMPORARY keyword is present */
114549  int noErr           /* Suppress errors if the trigger already exists */
114550){
114551  Trigger *pTrigger = 0;  /* The new trigger */
114552  Table *pTab;            /* Table that the trigger fires off of */
114553  char *zName = 0;        /* Name of the trigger */
114554  sqlite3 *db = pParse->db;  /* The database connection */
114555  int iDb;                /* The database to store the trigger in */
114556  Token *pName;           /* The unqualified db name */
114557  DbFixer sFix;           /* State vector for the DB fixer */
114558  int iTabDb;             /* Index of the database holding pTab */
114559
114560  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
114561  assert( pName2!=0 );
114562  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
114563  assert( op>0 && op<0xff );
114564  if( isTemp ){
114565    /* If TEMP was specified, then the trigger name may not be qualified. */
114566    if( pName2->n>0 ){
114567      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
114568      goto trigger_cleanup;
114569    }
114570    iDb = 1;
114571    pName = pName1;
114572  }else{
114573    /* Figure out the db that the trigger will be created in */
114574    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
114575    if( iDb<0 ){
114576      goto trigger_cleanup;
114577    }
114578  }
114579  if( !pTableName || db->mallocFailed ){
114580    goto trigger_cleanup;
114581  }
114582
114583  /* A long-standing parser bug is that this syntax was allowed:
114584  **
114585  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
114586  **                                                 ^^^^^^^^
114587  **
114588  ** To maintain backwards compatibility, ignore the database
114589  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
114590  */
114591  if( db->init.busy && iDb!=1 ){
114592    sqlite3DbFree(db, pTableName->a[0].zDatabase);
114593    pTableName->a[0].zDatabase = 0;
114594  }
114595
114596  /* If the trigger name was unqualified, and the table is a temp table,
114597  ** then set iDb to 1 to create the trigger in the temporary database.
114598  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
114599  ** exist, the error is caught by the block below.
114600  */
114601  pTab = sqlite3SrcListLookup(pParse, pTableName);
114602  if( db->init.busy==0 && pName2->n==0 && pTab
114603        && pTab->pSchema==db->aDb[1].pSchema ){
114604    iDb = 1;
114605  }
114606
114607  /* Ensure the table name matches database name and that the table exists */
114608  if( db->mallocFailed ) goto trigger_cleanup;
114609  assert( pTableName->nSrc==1 );
114610  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
114611  if( sqlite3FixSrcList(&sFix, pTableName) ){
114612    goto trigger_cleanup;
114613  }
114614  pTab = sqlite3SrcListLookup(pParse, pTableName);
114615  if( !pTab ){
114616    /* The table does not exist. */
114617    if( db->init.iDb==1 ){
114618      /* Ticket #3810.
114619      ** Normally, whenever a table is dropped, all associated triggers are
114620      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
114621      ** and the table is dropped by a different database connection, the
114622      ** trigger is not visible to the database connection that does the
114623      ** drop so the trigger cannot be dropped.  This results in an
114624      ** "orphaned trigger" - a trigger whose associated table is missing.
114625      */
114626      db->init.orphanTrigger = 1;
114627    }
114628    goto trigger_cleanup;
114629  }
114630  if( IsVirtual(pTab) ){
114631    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
114632    goto trigger_cleanup;
114633  }
114634
114635  /* Check that the trigger name is not reserved and that no trigger of the
114636  ** specified name exists */
114637  zName = sqlite3NameFromToken(db, pName);
114638  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
114639    goto trigger_cleanup;
114640  }
114641  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114642  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
114643    if( !noErr ){
114644      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
114645    }else{
114646      assert( !db->init.busy );
114647      sqlite3CodeVerifySchema(pParse, iDb);
114648    }
114649    goto trigger_cleanup;
114650  }
114651
114652  /* Do not create a trigger on a system table */
114653  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
114654    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
114655    goto trigger_cleanup;
114656  }
114657
114658  /* INSTEAD of triggers are only for views and views only support INSTEAD
114659  ** of triggers.
114660  */
114661  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
114662    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
114663        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
114664    goto trigger_cleanup;
114665  }
114666  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
114667    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
114668        " trigger on table: %S", pTableName, 0);
114669    goto trigger_cleanup;
114670  }
114671  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114672
114673#ifndef SQLITE_OMIT_AUTHORIZATION
114674  {
114675    int code = SQLITE_CREATE_TRIGGER;
114676    const char *zDb = db->aDb[iTabDb].zName;
114677    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
114678    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
114679    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
114680      goto trigger_cleanup;
114681    }
114682    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
114683      goto trigger_cleanup;
114684    }
114685  }
114686#endif
114687
114688  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
114689  ** cannot appear on views.  So we might as well translate every
114690  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
114691  ** elsewhere.
114692  */
114693  if (tr_tm == TK_INSTEAD){
114694    tr_tm = TK_BEFORE;
114695  }
114696
114697  /* Build the Trigger object */
114698  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
114699  if( pTrigger==0 ) goto trigger_cleanup;
114700  pTrigger->zName = zName;
114701  zName = 0;
114702  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
114703  pTrigger->pSchema = db->aDb[iDb].pSchema;
114704  pTrigger->pTabSchema = pTab->pSchema;
114705  pTrigger->op = (u8)op;
114706  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
114707  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
114708  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
114709  assert( pParse->pNewTrigger==0 );
114710  pParse->pNewTrigger = pTrigger;
114711
114712trigger_cleanup:
114713  sqlite3DbFree(db, zName);
114714  sqlite3SrcListDelete(db, pTableName);
114715  sqlite3IdListDelete(db, pColumns);
114716  sqlite3ExprDelete(db, pWhen);
114717  if( !pParse->pNewTrigger ){
114718    sqlite3DeleteTrigger(db, pTrigger);
114719  }else{
114720    assert( pParse->pNewTrigger==pTrigger );
114721  }
114722}
114723
114724/*
114725** This routine is called after all of the trigger actions have been parsed
114726** in order to complete the process of building the trigger.
114727*/
114728SQLITE_PRIVATE void sqlite3FinishTrigger(
114729  Parse *pParse,          /* Parser context */
114730  TriggerStep *pStepList, /* The triggered program */
114731  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
114732){
114733  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
114734  char *zName;                            /* Name of trigger */
114735  sqlite3 *db = pParse->db;               /* The database */
114736  DbFixer sFix;                           /* Fixer object */
114737  int iDb;                                /* Database containing the trigger */
114738  Token nameToken;                        /* Trigger name for error reporting */
114739
114740  pParse->pNewTrigger = 0;
114741  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
114742  zName = pTrig->zName;
114743  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
114744  pTrig->step_list = pStepList;
114745  while( pStepList ){
114746    pStepList->pTrig = pTrig;
114747    pStepList = pStepList->pNext;
114748  }
114749  nameToken.z = pTrig->zName;
114750  nameToken.n = sqlite3Strlen30(nameToken.z);
114751  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
114752  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
114753   || sqlite3FixExpr(&sFix, pTrig->pWhen)
114754  ){
114755    goto triggerfinish_cleanup;
114756  }
114757
114758  /* if we are not initializing,
114759  ** build the sqlite_master entry
114760  */
114761  if( !db->init.busy ){
114762    Vdbe *v;
114763    char *z;
114764
114765    /* Make an entry in the sqlite_master table */
114766    v = sqlite3GetVdbe(pParse);
114767    if( v==0 ) goto triggerfinish_cleanup;
114768    sqlite3BeginWriteOperation(pParse, 0, iDb);
114769    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
114770    sqlite3NestedParse(pParse,
114771       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
114772       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
114773       pTrig->table, z);
114774    sqlite3DbFree(db, z);
114775    sqlite3ChangeCookie(pParse, iDb);
114776    sqlite3VdbeAddParseSchemaOp(v, iDb,
114777        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
114778  }
114779
114780  if( db->init.busy ){
114781    Trigger *pLink = pTrig;
114782    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
114783    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114784    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
114785    if( pTrig ){
114786      db->mallocFailed = 1;
114787    }else if( pLink->pSchema==pLink->pTabSchema ){
114788      Table *pTab;
114789      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
114790      assert( pTab!=0 );
114791      pLink->pNext = pTab->pTrigger;
114792      pTab->pTrigger = pLink;
114793    }
114794  }
114795
114796triggerfinish_cleanup:
114797  sqlite3DeleteTrigger(db, pTrig);
114798  assert( !pParse->pNewTrigger );
114799  sqlite3DeleteTriggerStep(db, pStepList);
114800}
114801
114802/*
114803** Turn a SELECT statement (that the pSelect parameter points to) into
114804** a trigger step.  Return a pointer to a TriggerStep structure.
114805**
114806** The parser calls this routine when it finds a SELECT statement in
114807** body of a TRIGGER.
114808*/
114809SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
114810  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
114811  if( pTriggerStep==0 ) {
114812    sqlite3SelectDelete(db, pSelect);
114813    return 0;
114814  }
114815  pTriggerStep->op = TK_SELECT;
114816  pTriggerStep->pSelect = pSelect;
114817  pTriggerStep->orconf = OE_Default;
114818  return pTriggerStep;
114819}
114820
114821/*
114822** Allocate space to hold a new trigger step.  The allocated space
114823** holds both the TriggerStep object and the TriggerStep.target.z string.
114824**
114825** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
114826*/
114827static TriggerStep *triggerStepAllocate(
114828  sqlite3 *db,                /* Database connection */
114829  u8 op,                      /* Trigger opcode */
114830  Token *pName                /* The target name */
114831){
114832  TriggerStep *pTriggerStep;
114833
114834  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
114835  if( pTriggerStep ){
114836    char *z = (char*)&pTriggerStep[1];
114837    memcpy(z, pName->z, pName->n);
114838    sqlite3Dequote(z);
114839    pTriggerStep->zTarget = z;
114840    pTriggerStep->op = op;
114841  }
114842  return pTriggerStep;
114843}
114844
114845/*
114846** Build a trigger step out of an INSERT statement.  Return a pointer
114847** to the new trigger step.
114848**
114849** The parser calls this routine when it sees an INSERT inside the
114850** body of a trigger.
114851*/
114852SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
114853  sqlite3 *db,        /* The database connection */
114854  Token *pTableName,  /* Name of the table into which we insert */
114855  IdList *pColumn,    /* List of columns in pTableName to insert into */
114856  Select *pSelect,    /* A SELECT statement that supplies values */
114857  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
114858){
114859  TriggerStep *pTriggerStep;
114860
114861  assert(pSelect != 0 || db->mallocFailed);
114862
114863  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
114864  if( pTriggerStep ){
114865    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
114866    pTriggerStep->pIdList = pColumn;
114867    pTriggerStep->orconf = orconf;
114868  }else{
114869    sqlite3IdListDelete(db, pColumn);
114870  }
114871  sqlite3SelectDelete(db, pSelect);
114872
114873  return pTriggerStep;
114874}
114875
114876/*
114877** Construct a trigger step that implements an UPDATE statement and return
114878** a pointer to that trigger step.  The parser calls this routine when it
114879** sees an UPDATE statement inside the body of a CREATE TRIGGER.
114880*/
114881SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
114882  sqlite3 *db,         /* The database connection */
114883  Token *pTableName,   /* Name of the table to be updated */
114884  ExprList *pEList,    /* The SET clause: list of column and new values */
114885  Expr *pWhere,        /* The WHERE clause */
114886  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
114887){
114888  TriggerStep *pTriggerStep;
114889
114890  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
114891  if( pTriggerStep ){
114892    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
114893    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
114894    pTriggerStep->orconf = orconf;
114895  }
114896  sqlite3ExprListDelete(db, pEList);
114897  sqlite3ExprDelete(db, pWhere);
114898  return pTriggerStep;
114899}
114900
114901/*
114902** Construct a trigger step that implements a DELETE statement and return
114903** a pointer to that trigger step.  The parser calls this routine when it
114904** sees a DELETE statement inside the body of a CREATE TRIGGER.
114905*/
114906SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
114907  sqlite3 *db,            /* Database connection */
114908  Token *pTableName,      /* The table from which rows are deleted */
114909  Expr *pWhere            /* The WHERE clause */
114910){
114911  TriggerStep *pTriggerStep;
114912
114913  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
114914  if( pTriggerStep ){
114915    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
114916    pTriggerStep->orconf = OE_Default;
114917  }
114918  sqlite3ExprDelete(db, pWhere);
114919  return pTriggerStep;
114920}
114921
114922/*
114923** Recursively delete a Trigger structure
114924*/
114925SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
114926  if( pTrigger==0 ) return;
114927  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
114928  sqlite3DbFree(db, pTrigger->zName);
114929  sqlite3DbFree(db, pTrigger->table);
114930  sqlite3ExprDelete(db, pTrigger->pWhen);
114931  sqlite3IdListDelete(db, pTrigger->pColumns);
114932  sqlite3DbFree(db, pTrigger);
114933}
114934
114935/*
114936** This function is called to drop a trigger from the database schema.
114937**
114938** This may be called directly from the parser and therefore identifies
114939** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
114940** same job as this routine except it takes a pointer to the trigger
114941** instead of the trigger name.
114942**/
114943SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
114944  Trigger *pTrigger = 0;
114945  int i;
114946  const char *zDb;
114947  const char *zName;
114948  sqlite3 *db = pParse->db;
114949
114950  if( db->mallocFailed ) goto drop_trigger_cleanup;
114951  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
114952    goto drop_trigger_cleanup;
114953  }
114954
114955  assert( pName->nSrc==1 );
114956  zDb = pName->a[0].zDatabase;
114957  zName = pName->a[0].zName;
114958  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
114959  for(i=OMIT_TEMPDB; i<db->nDb; i++){
114960    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
114961    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
114962    assert( sqlite3SchemaMutexHeld(db, j, 0) );
114963    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
114964    if( pTrigger ) break;
114965  }
114966  if( !pTrigger ){
114967    if( !noErr ){
114968      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
114969    }else{
114970      sqlite3CodeVerifyNamedSchema(pParse, zDb);
114971    }
114972    pParse->checkSchema = 1;
114973    goto drop_trigger_cleanup;
114974  }
114975  sqlite3DropTriggerPtr(pParse, pTrigger);
114976
114977drop_trigger_cleanup:
114978  sqlite3SrcListDelete(db, pName);
114979}
114980
114981/*
114982** Return a pointer to the Table structure for the table that a trigger
114983** is set on.
114984*/
114985static Table *tableOfTrigger(Trigger *pTrigger){
114986  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
114987}
114988
114989
114990/*
114991** Drop a trigger given a pointer to that trigger.
114992*/
114993SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
114994  Table   *pTable;
114995  Vdbe *v;
114996  sqlite3 *db = pParse->db;
114997  int iDb;
114998
114999  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
115000  assert( iDb>=0 && iDb<db->nDb );
115001  pTable = tableOfTrigger(pTrigger);
115002  assert( pTable );
115003  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
115004#ifndef SQLITE_OMIT_AUTHORIZATION
115005  {
115006    int code = SQLITE_DROP_TRIGGER;
115007    const char *zDb = db->aDb[iDb].zName;
115008    const char *zTab = SCHEMA_TABLE(iDb);
115009    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
115010    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
115011      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
115012      return;
115013    }
115014  }
115015#endif
115016
115017  /* Generate code to destroy the database record of the trigger.
115018  */
115019  assert( pTable!=0 );
115020  if( (v = sqlite3GetVdbe(pParse))!=0 ){
115021    int base;
115022    static const int iLn = VDBE_OFFSET_LINENO(2);
115023    static const VdbeOpList dropTrigger[] = {
115024      { OP_Rewind,     0, ADDR(9),  0},
115025      { OP_String8,    0, 1,        0}, /* 1 */
115026      { OP_Column,     0, 1,        2},
115027      { OP_Ne,         2, ADDR(8),  1},
115028      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
115029      { OP_Column,     0, 0,        2},
115030      { OP_Ne,         2, ADDR(8),  1},
115031      { OP_Delete,     0, 0,        0},
115032      { OP_Next,       0, ADDR(1),  0}, /* 8 */
115033    };
115034
115035    sqlite3BeginWriteOperation(pParse, 0, iDb);
115036    sqlite3OpenMasterTable(pParse, iDb);
115037    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
115038    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
115039    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
115040    sqlite3ChangeCookie(pParse, iDb);
115041    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
115042    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
115043    if( pParse->nMem<3 ){
115044      pParse->nMem = 3;
115045    }
115046  }
115047}
115048
115049/*
115050** Remove a trigger from the hash tables of the sqlite* pointer.
115051*/
115052SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
115053  Trigger *pTrigger;
115054  Hash *pHash;
115055
115056  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115057  pHash = &(db->aDb[iDb].pSchema->trigHash);
115058  pTrigger = sqlite3HashInsert(pHash, zName, 0);
115059  if( ALWAYS(pTrigger) ){
115060    if( pTrigger->pSchema==pTrigger->pTabSchema ){
115061      Table *pTab = tableOfTrigger(pTrigger);
115062      Trigger **pp;
115063      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
115064      *pp = (*pp)->pNext;
115065    }
115066    sqlite3DeleteTrigger(db, pTrigger);
115067    db->flags |= SQLITE_InternChanges;
115068  }
115069}
115070
115071/*
115072** pEList is the SET clause of an UPDATE statement.  Each entry
115073** in pEList is of the format <id>=<expr>.  If any of the entries
115074** in pEList have an <id> which matches an identifier in pIdList,
115075** then return TRUE.  If pIdList==NULL, then it is considered a
115076** wildcard that matches anything.  Likewise if pEList==NULL then
115077** it matches anything so always return true.  Return false only
115078** if there is no match.
115079*/
115080static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
115081  int e;
115082  if( pIdList==0 || NEVER(pEList==0) ) return 1;
115083  for(e=0; e<pEList->nExpr; e++){
115084    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
115085  }
115086  return 0;
115087}
115088
115089/*
115090** Return a list of all triggers on table pTab if there exists at least
115091** one trigger that must be fired when an operation of type 'op' is
115092** performed on the table, and, if that operation is an UPDATE, if at
115093** least one of the columns in pChanges is being modified.
115094*/
115095SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
115096  Parse *pParse,          /* Parse context */
115097  Table *pTab,            /* The table the contains the triggers */
115098  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
115099  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
115100  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115101){
115102  int mask = 0;
115103  Trigger *pList = 0;
115104  Trigger *p;
115105
115106  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
115107    pList = sqlite3TriggerList(pParse, pTab);
115108  }
115109  assert( pList==0 || IsVirtual(pTab)==0 );
115110  for(p=pList; p; p=p->pNext){
115111    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
115112      mask |= p->tr_tm;
115113    }
115114  }
115115  if( pMask ){
115116    *pMask = mask;
115117  }
115118  return (mask ? pList : 0);
115119}
115120
115121/*
115122** Convert the pStep->zTarget string into a SrcList and return a pointer
115123** to that SrcList.
115124**
115125** This routine adds a specific database name, if needed, to the target when
115126** forming the SrcList.  This prevents a trigger in one database from
115127** referring to a target in another database.  An exception is when the
115128** trigger is in TEMP in which case it can refer to any other database it
115129** wants.
115130*/
115131static SrcList *targetSrcList(
115132  Parse *pParse,       /* The parsing context */
115133  TriggerStep *pStep   /* The trigger containing the target token */
115134){
115135  sqlite3 *db = pParse->db;
115136  int iDb;             /* Index of the database to use */
115137  SrcList *pSrc;       /* SrcList to be returned */
115138
115139  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
115140  if( pSrc ){
115141    assert( pSrc->nSrc>0 );
115142    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
115143    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
115144    if( iDb==0 || iDb>=2 ){
115145      assert( iDb<db->nDb );
115146      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
115147    }
115148  }
115149  return pSrc;
115150}
115151
115152/*
115153** Generate VDBE code for the statements inside the body of a single
115154** trigger.
115155*/
115156static int codeTriggerProgram(
115157  Parse *pParse,            /* The parser context */
115158  TriggerStep *pStepList,   /* List of statements inside the trigger body */
115159  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
115160){
115161  TriggerStep *pStep;
115162  Vdbe *v = pParse->pVdbe;
115163  sqlite3 *db = pParse->db;
115164
115165  assert( pParse->pTriggerTab && pParse->pToplevel );
115166  assert( pStepList );
115167  assert( v!=0 );
115168  for(pStep=pStepList; pStep; pStep=pStep->pNext){
115169    /* Figure out the ON CONFLICT policy that will be used for this step
115170    ** of the trigger program. If the statement that caused this trigger
115171    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
115172    ** the ON CONFLICT policy that was specified as part of the trigger
115173    ** step statement. Example:
115174    **
115175    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
115176    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
115177    **   END;
115178    **
115179    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
115180    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
115181    */
115182    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
115183    assert( pParse->okConstFactor==0 );
115184
115185    switch( pStep->op ){
115186      case TK_UPDATE: {
115187        sqlite3Update(pParse,
115188          targetSrcList(pParse, pStep),
115189          sqlite3ExprListDup(db, pStep->pExprList, 0),
115190          sqlite3ExprDup(db, pStep->pWhere, 0),
115191          pParse->eOrconf
115192        );
115193        break;
115194      }
115195      case TK_INSERT: {
115196        sqlite3Insert(pParse,
115197          targetSrcList(pParse, pStep),
115198          sqlite3SelectDup(db, pStep->pSelect, 0),
115199          sqlite3IdListDup(db, pStep->pIdList),
115200          pParse->eOrconf
115201        );
115202        break;
115203      }
115204      case TK_DELETE: {
115205        sqlite3DeleteFrom(pParse,
115206          targetSrcList(pParse, pStep),
115207          sqlite3ExprDup(db, pStep->pWhere, 0)
115208        );
115209        break;
115210      }
115211      default: assert( pStep->op==TK_SELECT ); {
115212        SelectDest sDest;
115213        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
115214        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
115215        sqlite3Select(pParse, pSelect, &sDest);
115216        sqlite3SelectDelete(db, pSelect);
115217        break;
115218      }
115219    }
115220    if( pStep->op!=TK_SELECT ){
115221      sqlite3VdbeAddOp0(v, OP_ResetCount);
115222    }
115223  }
115224
115225  return 0;
115226}
115227
115228#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
115229/*
115230** This function is used to add VdbeComment() annotations to a VDBE
115231** program. It is not used in production code, only for debugging.
115232*/
115233static const char *onErrorText(int onError){
115234  switch( onError ){
115235    case OE_Abort:    return "abort";
115236    case OE_Rollback: return "rollback";
115237    case OE_Fail:     return "fail";
115238    case OE_Replace:  return "replace";
115239    case OE_Ignore:   return "ignore";
115240    case OE_Default:  return "default";
115241  }
115242  return "n/a";
115243}
115244#endif
115245
115246/*
115247** Parse context structure pFrom has just been used to create a sub-vdbe
115248** (trigger program). If an error has occurred, transfer error information
115249** from pFrom to pTo.
115250*/
115251static void transferParseError(Parse *pTo, Parse *pFrom){
115252  assert( pFrom->zErrMsg==0 || pFrom->nErr );
115253  assert( pTo->zErrMsg==0 || pTo->nErr );
115254  if( pTo->nErr==0 ){
115255    pTo->zErrMsg = pFrom->zErrMsg;
115256    pTo->nErr = pFrom->nErr;
115257    pTo->rc = pFrom->rc;
115258  }else{
115259    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
115260  }
115261}
115262
115263/*
115264** Create and populate a new TriggerPrg object with a sub-program
115265** implementing trigger pTrigger with ON CONFLICT policy orconf.
115266*/
115267static TriggerPrg *codeRowTrigger(
115268  Parse *pParse,       /* Current parse context */
115269  Trigger *pTrigger,   /* Trigger to code */
115270  Table *pTab,         /* The table pTrigger is attached to */
115271  int orconf           /* ON CONFLICT policy to code trigger program with */
115272){
115273  Parse *pTop = sqlite3ParseToplevel(pParse);
115274  sqlite3 *db = pParse->db;   /* Database handle */
115275  TriggerPrg *pPrg;           /* Value to return */
115276  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
115277  Vdbe *v;                    /* Temporary VM */
115278  NameContext sNC;            /* Name context for sub-vdbe */
115279  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
115280  Parse *pSubParse;           /* Parse context for sub-vdbe */
115281  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
115282
115283  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
115284  assert( pTop->pVdbe );
115285
115286  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
115287  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
115288  ** list of the top-level Parse object sooner rather than later.  */
115289  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
115290  if( !pPrg ) return 0;
115291  pPrg->pNext = pTop->pTriggerPrg;
115292  pTop->pTriggerPrg = pPrg;
115293  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
115294  if( !pProgram ) return 0;
115295  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
115296  pPrg->pTrigger = pTrigger;
115297  pPrg->orconf = orconf;
115298  pPrg->aColmask[0] = 0xffffffff;
115299  pPrg->aColmask[1] = 0xffffffff;
115300
115301  /* Allocate and populate a new Parse context to use for coding the
115302  ** trigger sub-program.  */
115303  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
115304  if( !pSubParse ) return 0;
115305  memset(&sNC, 0, sizeof(sNC));
115306  sNC.pParse = pSubParse;
115307  pSubParse->db = db;
115308  pSubParse->pTriggerTab = pTab;
115309  pSubParse->pToplevel = pTop;
115310  pSubParse->zAuthContext = pTrigger->zName;
115311  pSubParse->eTriggerOp = pTrigger->op;
115312  pSubParse->nQueryLoop = pParse->nQueryLoop;
115313
115314  v = sqlite3GetVdbe(pSubParse);
115315  if( v ){
115316    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
115317      pTrigger->zName, onErrorText(orconf),
115318      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
115319        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
115320        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
115321        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
115322      pTab->zName
115323    ));
115324#ifndef SQLITE_OMIT_TRACE
115325    sqlite3VdbeChangeP4(v, -1,
115326      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
115327    );
115328#endif
115329
115330    /* If one was specified, code the WHEN clause. If it evaluates to false
115331    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
115332    ** OP_Halt inserted at the end of the program.  */
115333    if( pTrigger->pWhen ){
115334      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
115335      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
115336       && db->mallocFailed==0
115337      ){
115338        iEndTrigger = sqlite3VdbeMakeLabel(v);
115339        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
115340      }
115341      sqlite3ExprDelete(db, pWhen);
115342    }
115343
115344    /* Code the trigger program into the sub-vdbe. */
115345    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
115346
115347    /* Insert an OP_Halt at the end of the sub-program. */
115348    if( iEndTrigger ){
115349      sqlite3VdbeResolveLabel(v, iEndTrigger);
115350    }
115351    sqlite3VdbeAddOp0(v, OP_Halt);
115352    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
115353
115354    transferParseError(pParse, pSubParse);
115355    if( db->mallocFailed==0 ){
115356      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
115357    }
115358    pProgram->nMem = pSubParse->nMem;
115359    pProgram->nCsr = pSubParse->nTab;
115360    pProgram->nOnce = pSubParse->nOnce;
115361    pProgram->token = (void *)pTrigger;
115362    pPrg->aColmask[0] = pSubParse->oldmask;
115363    pPrg->aColmask[1] = pSubParse->newmask;
115364    sqlite3VdbeDelete(v);
115365  }
115366
115367  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
115368  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
115369  sqlite3ParserReset(pSubParse);
115370  sqlite3StackFree(db, pSubParse);
115371
115372  return pPrg;
115373}
115374
115375/*
115376** Return a pointer to a TriggerPrg object containing the sub-program for
115377** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
115378** TriggerPrg object exists, a new object is allocated and populated before
115379** being returned.
115380*/
115381static TriggerPrg *getRowTrigger(
115382  Parse *pParse,       /* Current parse context */
115383  Trigger *pTrigger,   /* Trigger to code */
115384  Table *pTab,         /* The table trigger pTrigger is attached to */
115385  int orconf           /* ON CONFLICT algorithm. */
115386){
115387  Parse *pRoot = sqlite3ParseToplevel(pParse);
115388  TriggerPrg *pPrg;
115389
115390  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
115391
115392  /* It may be that this trigger has already been coded (or is in the
115393  ** process of being coded). If this is the case, then an entry with
115394  ** a matching TriggerPrg.pTrigger field will be present somewhere
115395  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
115396  for(pPrg=pRoot->pTriggerPrg;
115397      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
115398      pPrg=pPrg->pNext
115399  );
115400
115401  /* If an existing TriggerPrg could not be located, create a new one. */
115402  if( !pPrg ){
115403    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
115404  }
115405
115406  return pPrg;
115407}
115408
115409/*
115410** Generate code for the trigger program associated with trigger p on
115411** table pTab. The reg, orconf and ignoreJump parameters passed to this
115412** function are the same as those described in the header function for
115413** sqlite3CodeRowTrigger()
115414*/
115415SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
115416  Parse *pParse,       /* Parse context */
115417  Trigger *p,          /* Trigger to code */
115418  Table *pTab,         /* The table to code triggers from */
115419  int reg,             /* Reg array containing OLD.* and NEW.* values */
115420  int orconf,          /* ON CONFLICT policy */
115421  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
115422){
115423  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
115424  TriggerPrg *pPrg;
115425  pPrg = getRowTrigger(pParse, p, pTab, orconf);
115426  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
115427
115428  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
115429  ** is a pointer to the sub-vdbe containing the trigger program.  */
115430  if( pPrg ){
115431    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
115432
115433    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
115434    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
115435    VdbeComment(
115436        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
115437
115438    /* Set the P5 operand of the OP_Program instruction to non-zero if
115439    ** recursive invocation of this trigger program is disallowed. Recursive
115440    ** invocation is disallowed if (a) the sub-program is really a trigger,
115441    ** not a foreign key action, and (b) the flag to enable recursive triggers
115442    ** is clear.  */
115443    sqlite3VdbeChangeP5(v, (u8)bRecursive);
115444  }
115445}
115446
115447/*
115448** This is called to code the required FOR EACH ROW triggers for an operation
115449** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
115450** is given by the op parameter. The tr_tm parameter determines whether the
115451** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
115452** parameter pChanges is passed the list of columns being modified.
115453**
115454** If there are no triggers that fire at the specified time for the specified
115455** operation on pTab, this function is a no-op.
115456**
115457** The reg argument is the address of the first in an array of registers
115458** that contain the values substituted for the new.* and old.* references
115459** in the trigger program. If N is the number of columns in table pTab
115460** (a copy of pTab->nCol), then registers are populated as follows:
115461**
115462**   Register       Contains
115463**   ------------------------------------------------------
115464**   reg+0          OLD.rowid
115465**   reg+1          OLD.* value of left-most column of pTab
115466**   ...            ...
115467**   reg+N          OLD.* value of right-most column of pTab
115468**   reg+N+1        NEW.rowid
115469**   reg+N+2        OLD.* value of left-most column of pTab
115470**   ...            ...
115471**   reg+N+N+1      NEW.* value of right-most column of pTab
115472**
115473** For ON DELETE triggers, the registers containing the NEW.* values will
115474** never be accessed by the trigger program, so they are not allocated or
115475** populated by the caller (there is no data to populate them with anyway).
115476** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
115477** are never accessed, and so are not allocated by the caller. So, for an
115478** ON INSERT trigger, the value passed to this function as parameter reg
115479** is not a readable register, although registers (reg+N) through
115480** (reg+N+N+1) are.
115481**
115482** Parameter orconf is the default conflict resolution algorithm for the
115483** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
115484** is the instruction that control should jump to if a trigger program
115485** raises an IGNORE exception.
115486*/
115487SQLITE_PRIVATE void sqlite3CodeRowTrigger(
115488  Parse *pParse,       /* Parse context */
115489  Trigger *pTrigger,   /* List of triggers on table pTab */
115490  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
115491  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
115492  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
115493  Table *pTab,         /* The table to code triggers from */
115494  int reg,             /* The first in an array of registers (see above) */
115495  int orconf,          /* ON CONFLICT policy */
115496  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
115497){
115498  Trigger *p;          /* Used to iterate through pTrigger list */
115499
115500  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
115501  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
115502  assert( (op==TK_UPDATE)==(pChanges!=0) );
115503
115504  for(p=pTrigger; p; p=p->pNext){
115505
115506    /* Sanity checking:  The schema for the trigger and for the table are
115507    ** always defined.  The trigger must be in the same schema as the table
115508    ** or else it must be a TEMP trigger. */
115509    assert( p->pSchema!=0 );
115510    assert( p->pTabSchema!=0 );
115511    assert( p->pSchema==p->pTabSchema
115512         || p->pSchema==pParse->db->aDb[1].pSchema );
115513
115514    /* Determine whether we should code this trigger */
115515    if( p->op==op
115516     && p->tr_tm==tr_tm
115517     && checkColumnOverlap(p->pColumns, pChanges)
115518    ){
115519      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
115520    }
115521  }
115522}
115523
115524/*
115525** Triggers may access values stored in the old.* or new.* pseudo-table.
115526** This function returns a 32-bit bitmask indicating which columns of the
115527** old.* or new.* tables actually are used by triggers. This information
115528** may be used by the caller, for example, to avoid having to load the entire
115529** old.* record into memory when executing an UPDATE or DELETE command.
115530**
115531** Bit 0 of the returned mask is set if the left-most column of the
115532** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
115533** the second leftmost column value is required, and so on. If there
115534** are more than 32 columns in the table, and at least one of the columns
115535** with an index greater than 32 may be accessed, 0xffffffff is returned.
115536**
115537** It is not possible to determine if the old.rowid or new.rowid column is
115538** accessed by triggers. The caller must always assume that it is.
115539**
115540** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
115541** applies to the old.* table. If 1, the new.* table.
115542**
115543** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
115544** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
115545** included in the returned mask if the TRIGGER_BEFORE bit is set in the
115546** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
115547** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
115548*/
115549SQLITE_PRIVATE u32 sqlite3TriggerColmask(
115550  Parse *pParse,       /* Parse context */
115551  Trigger *pTrigger,   /* List of triggers on table pTab */
115552  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
115553  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
115554  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115555  Table *pTab,         /* The table to code triggers from */
115556  int orconf           /* Default ON CONFLICT policy for trigger steps */
115557){
115558  const int op = pChanges ? TK_UPDATE : TK_DELETE;
115559  u32 mask = 0;
115560  Trigger *p;
115561
115562  assert( isNew==1 || isNew==0 );
115563  for(p=pTrigger; p; p=p->pNext){
115564    if( p->op==op && (tr_tm&p->tr_tm)
115565     && checkColumnOverlap(p->pColumns,pChanges)
115566    ){
115567      TriggerPrg *pPrg;
115568      pPrg = getRowTrigger(pParse, p, pTab, orconf);
115569      if( pPrg ){
115570        mask |= pPrg->aColmask[isNew];
115571      }
115572    }
115573  }
115574
115575  return mask;
115576}
115577
115578#endif /* !defined(SQLITE_OMIT_TRIGGER) */
115579
115580/************** End of trigger.c *********************************************/
115581/************** Begin file update.c ******************************************/
115582/*
115583** 2001 September 15
115584**
115585** The author disclaims copyright to this source code.  In place of
115586** a legal notice, here is a blessing:
115587**
115588**    May you do good and not evil.
115589**    May you find forgiveness for yourself and forgive others.
115590**    May you share freely, never taking more than you give.
115591**
115592*************************************************************************
115593** This file contains C code routines that are called by the parser
115594** to handle UPDATE statements.
115595*/
115596/* #include "sqliteInt.h" */
115597
115598#ifndef SQLITE_OMIT_VIRTUALTABLE
115599/* Forward declaration */
115600static void updateVirtualTable(
115601  Parse *pParse,       /* The parsing context */
115602  SrcList *pSrc,       /* The virtual table to be modified */
115603  Table *pTab,         /* The virtual table */
115604  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
115605  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
115606  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
115607  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
115608  int onError          /* ON CONFLICT strategy */
115609);
115610#endif /* SQLITE_OMIT_VIRTUALTABLE */
115611
115612/*
115613** The most recently coded instruction was an OP_Column to retrieve the
115614** i-th column of table pTab. This routine sets the P4 parameter of the
115615** OP_Column to the default value, if any.
115616**
115617** The default value of a column is specified by a DEFAULT clause in the
115618** column definition. This was either supplied by the user when the table
115619** was created, or added later to the table definition by an ALTER TABLE
115620** command. If the latter, then the row-records in the table btree on disk
115621** may not contain a value for the column and the default value, taken
115622** from the P4 parameter of the OP_Column instruction, is returned instead.
115623** If the former, then all row-records are guaranteed to include a value
115624** for the column and the P4 value is not required.
115625**
115626** Column definitions created by an ALTER TABLE command may only have
115627** literal default values specified: a number, null or a string. (If a more
115628** complicated default expression value was provided, it is evaluated
115629** when the ALTER TABLE is executed and one of the literal values written
115630** into the sqlite_master table.)
115631**
115632** Therefore, the P4 parameter is only required if the default value for
115633** the column is a literal number, string or null. The sqlite3ValueFromExpr()
115634** function is capable of transforming these types of expressions into
115635** sqlite3_value objects.
115636**
115637** If parameter iReg is not negative, code an OP_RealAffinity instruction
115638** on register iReg. This is used when an equivalent integer value is
115639** stored in place of an 8-byte floating point value in order to save
115640** space.
115641*/
115642SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
115643  assert( pTab!=0 );
115644  if( !pTab->pSelect ){
115645    sqlite3_value *pValue = 0;
115646    u8 enc = ENC(sqlite3VdbeDb(v));
115647    Column *pCol = &pTab->aCol[i];
115648    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
115649    assert( i<pTab->nCol );
115650    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
115651                         pCol->affinity, &pValue);
115652    if( pValue ){
115653      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
115654    }
115655#ifndef SQLITE_OMIT_FLOATING_POINT
115656    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
115657      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
115658    }
115659#endif
115660  }
115661}
115662
115663/*
115664** Process an UPDATE statement.
115665**
115666**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
115667**          \_______/ \________/     \______/       \________________/
115668*            onError   pTabList      pChanges             pWhere
115669*/
115670SQLITE_PRIVATE void sqlite3Update(
115671  Parse *pParse,         /* The parser context */
115672  SrcList *pTabList,     /* The table in which we should change things */
115673  ExprList *pChanges,    /* Things to be changed */
115674  Expr *pWhere,          /* The WHERE clause.  May be null */
115675  int onError            /* How to handle constraint errors */
115676){
115677  int i, j;              /* Loop counters */
115678  Table *pTab;           /* The table to be updated */
115679  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
115680  WhereInfo *pWInfo;     /* Information about the WHERE clause */
115681  Vdbe *v;               /* The virtual database engine */
115682  Index *pIdx;           /* For looping over indices */
115683  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
115684  int nIdx;              /* Number of indices that need updating */
115685  int iBaseCur;          /* Base cursor number */
115686  int iDataCur;          /* Cursor for the canonical data btree */
115687  int iIdxCur;           /* Cursor for the first index */
115688  sqlite3 *db;           /* The database structure */
115689  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
115690  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
115691                         ** an expression for the i-th column of the table.
115692                         ** aXRef[i]==-1 if the i-th column is not changed. */
115693  u8 *aToOpen;           /* 1 for tables and indices to be opened */
115694  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
115695  u8 chngRowid;          /* Rowid changed in a normal table */
115696  u8 chngKey;            /* Either chngPk or chngRowid */
115697  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
115698  AuthContext sContext;  /* The authorization context */
115699  NameContext sNC;       /* The name-context to resolve expressions in */
115700  int iDb;               /* Database containing the table being updated */
115701  int okOnePass;         /* True for one-pass algorithm without the FIFO */
115702  int hasFK;             /* True if foreign key processing is required */
115703  int labelBreak;        /* Jump here to break out of UPDATE loop */
115704  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
115705
115706#ifndef SQLITE_OMIT_TRIGGER
115707  int isView;            /* True when updating a view (INSTEAD OF trigger) */
115708  Trigger *pTrigger;     /* List of triggers on pTab, if required */
115709  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115710#endif
115711  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
115712  int iEph = 0;          /* Ephemeral table holding all primary key values */
115713  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
115714  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
115715
115716  /* Register Allocations */
115717  int regRowCount = 0;   /* A count of rows changed */
115718  int regOldRowid = 0;   /* The old rowid */
115719  int regNewRowid = 0;   /* The new rowid */
115720  int regNew = 0;        /* Content of the NEW.* table in triggers */
115721  int regOld = 0;        /* Content of OLD.* table in triggers */
115722  int regRowSet = 0;     /* Rowset of rows to be updated */
115723  int regKey = 0;        /* composite PRIMARY KEY value */
115724
115725  memset(&sContext, 0, sizeof(sContext));
115726  db = pParse->db;
115727  if( pParse->nErr || db->mallocFailed ){
115728    goto update_cleanup;
115729  }
115730  assert( pTabList->nSrc==1 );
115731
115732  /* Locate the table which we want to update.
115733  */
115734  pTab = sqlite3SrcListLookup(pParse, pTabList);
115735  if( pTab==0 ) goto update_cleanup;
115736  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
115737
115738  /* Figure out if we have any triggers and if the table being
115739  ** updated is a view.
115740  */
115741#ifndef SQLITE_OMIT_TRIGGER
115742  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
115743  isView = pTab->pSelect!=0;
115744  assert( pTrigger || tmask==0 );
115745#else
115746# define pTrigger 0
115747# define isView 0
115748# define tmask 0
115749#endif
115750#ifdef SQLITE_OMIT_VIEW
115751# undef isView
115752# define isView 0
115753#endif
115754
115755  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
115756    goto update_cleanup;
115757  }
115758  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
115759    goto update_cleanup;
115760  }
115761
115762  /* Allocate a cursors for the main database table and for all indices.
115763  ** The index cursors might not be used, but if they are used they
115764  ** need to occur right after the database cursor.  So go ahead and
115765  ** allocate enough space, just in case.
115766  */
115767  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
115768  iIdxCur = iDataCur+1;
115769  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
115770  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
115771    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
115772      iDataCur = pParse->nTab;
115773      pTabList->a[0].iCursor = iDataCur;
115774    }
115775    pParse->nTab++;
115776  }
115777
115778  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
115779  ** Initialize aXRef[] and aToOpen[] to their default values.
115780  */
115781  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
115782  if( aXRef==0 ) goto update_cleanup;
115783  aRegIdx = aXRef+pTab->nCol;
115784  aToOpen = (u8*)(aRegIdx+nIdx);
115785  memset(aToOpen, 1, nIdx+1);
115786  aToOpen[nIdx+1] = 0;
115787  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
115788
115789  /* Initialize the name-context */
115790  memset(&sNC, 0, sizeof(sNC));
115791  sNC.pParse = pParse;
115792  sNC.pSrcList = pTabList;
115793
115794  /* Resolve the column names in all the expressions of the
115795  ** of the UPDATE statement.  Also find the column index
115796  ** for each column to be updated in the pChanges array.  For each
115797  ** column to be updated, make sure we have authorization to change
115798  ** that column.
115799  */
115800  chngRowid = chngPk = 0;
115801  for(i=0; i<pChanges->nExpr; i++){
115802    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
115803      goto update_cleanup;
115804    }
115805    for(j=0; j<pTab->nCol; j++){
115806      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
115807        if( j==pTab->iPKey ){
115808          chngRowid = 1;
115809          pRowidExpr = pChanges->a[i].pExpr;
115810        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
115811          chngPk = 1;
115812        }
115813        aXRef[j] = i;
115814        break;
115815      }
115816    }
115817    if( j>=pTab->nCol ){
115818      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
115819        j = -1;
115820        chngRowid = 1;
115821        pRowidExpr = pChanges->a[i].pExpr;
115822      }else{
115823        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
115824        pParse->checkSchema = 1;
115825        goto update_cleanup;
115826      }
115827    }
115828#ifndef SQLITE_OMIT_AUTHORIZATION
115829    {
115830      int rc;
115831      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
115832                            j<0 ? "ROWID" : pTab->aCol[j].zName,
115833                            db->aDb[iDb].zName);
115834      if( rc==SQLITE_DENY ){
115835        goto update_cleanup;
115836      }else if( rc==SQLITE_IGNORE ){
115837        aXRef[j] = -1;
115838      }
115839    }
115840#endif
115841  }
115842  assert( (chngRowid & chngPk)==0 );
115843  assert( chngRowid==0 || chngRowid==1 );
115844  assert( chngPk==0 || chngPk==1 );
115845  chngKey = chngRowid + chngPk;
115846
115847  /* The SET expressions are not actually used inside the WHERE loop.
115848  ** So reset the colUsed mask
115849  */
115850  pTabList->a[0].colUsed = 0;
115851
115852  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
115853
115854  /* There is one entry in the aRegIdx[] array for each index on the table
115855  ** being updated.  Fill in aRegIdx[] with a register number that will hold
115856  ** the key for accessing each index.
115857  **
115858  ** FIXME:  Be smarter about omitting indexes that use expressions.
115859  */
115860  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115861    int reg;
115862    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
115863      reg = ++pParse->nMem;
115864    }else{
115865      reg = 0;
115866      for(i=0; i<pIdx->nKeyCol; i++){
115867        i16 iIdxCol = pIdx->aiColumn[i];
115868        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
115869          reg = ++pParse->nMem;
115870          break;
115871        }
115872      }
115873    }
115874    if( reg==0 ) aToOpen[j+1] = 0;
115875    aRegIdx[j] = reg;
115876  }
115877
115878  /* Begin generating code. */
115879  v = sqlite3GetVdbe(pParse);
115880  if( v==0 ) goto update_cleanup;
115881  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
115882  sqlite3BeginWriteOperation(pParse, 1, iDb);
115883
115884  /* Allocate required registers. */
115885  if( !IsVirtual(pTab) ){
115886    regRowSet = ++pParse->nMem;
115887    regOldRowid = regNewRowid = ++pParse->nMem;
115888    if( chngPk || pTrigger || hasFK ){
115889      regOld = pParse->nMem + 1;
115890      pParse->nMem += pTab->nCol;
115891    }
115892    if( chngKey || pTrigger || hasFK ){
115893      regNewRowid = ++pParse->nMem;
115894    }
115895    regNew = pParse->nMem + 1;
115896    pParse->nMem += pTab->nCol;
115897  }
115898
115899  /* Start the view context. */
115900  if( isView ){
115901    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
115902  }
115903
115904  /* If we are trying to update a view, realize that view into
115905  ** an ephemeral table.
115906  */
115907#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
115908  if( isView ){
115909    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
115910  }
115911#endif
115912
115913  /* Resolve the column names in all the expressions in the
115914  ** WHERE clause.
115915  */
115916  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
115917    goto update_cleanup;
115918  }
115919
115920#ifndef SQLITE_OMIT_VIRTUALTABLE
115921  /* Virtual tables must be handled separately */
115922  if( IsVirtual(pTab) ){
115923    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
115924                       pWhere, onError);
115925    goto update_cleanup;
115926  }
115927#endif
115928
115929  /* Begin the database scan
115930  */
115931  if( HasRowid(pTab) ){
115932    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
115933    pWInfo = sqlite3WhereBegin(
115934        pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
115935    );
115936    if( pWInfo==0 ) goto update_cleanup;
115937    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
115938
115939    /* Remember the rowid of every item to be updated.
115940    */
115941    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
115942    if( !okOnePass ){
115943      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
115944    }
115945
115946    /* End the database scan loop.
115947    */
115948    sqlite3WhereEnd(pWInfo);
115949  }else{
115950    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
115951    i16 nPk;         /* Number of components of the PRIMARY KEY */
115952    int addrOpen;    /* Address of the OpenEphemeral instruction */
115953
115954    assert( pPk!=0 );
115955    nPk = pPk->nKeyCol;
115956    iPk = pParse->nMem+1;
115957    pParse->nMem += nPk;
115958    regKey = ++pParse->nMem;
115959    iEph = pParse->nTab++;
115960    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
115961    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
115962    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
115963    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
115964                               WHERE_ONEPASS_DESIRED, iIdxCur);
115965    if( pWInfo==0 ) goto update_cleanup;
115966    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
115967    for(i=0; i<nPk; i++){
115968      assert( pPk->aiColumn[i]>=0 );
115969      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
115970                                      iPk+i);
115971    }
115972    if( okOnePass ){
115973      sqlite3VdbeChangeToNoop(v, addrOpen);
115974      nKey = nPk;
115975      regKey = iPk;
115976    }else{
115977      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
115978                        sqlite3IndexAffinityStr(db, pPk), nPk);
115979      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
115980    }
115981    sqlite3WhereEnd(pWInfo);
115982  }
115983
115984  /* Initialize the count of updated rows
115985  */
115986  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
115987    regRowCount = ++pParse->nMem;
115988    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
115989  }
115990
115991  labelBreak = sqlite3VdbeMakeLabel(v);
115992  if( !isView ){
115993    /*
115994    ** Open every index that needs updating.  Note that if any
115995    ** index could potentially invoke a REPLACE conflict resolution
115996    ** action, then we need to open all indices because we might need
115997    ** to be deleting some records.
115998    */
115999    if( onError==OE_Replace ){
116000      memset(aToOpen, 1, nIdx+1);
116001    }else{
116002      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
116003        if( pIdx->onError==OE_Replace ){
116004          memset(aToOpen, 1, nIdx+1);
116005          break;
116006        }
116007      }
116008    }
116009    if( okOnePass ){
116010      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
116011      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
116012    }
116013    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
116014                               0, 0);
116015  }
116016
116017  /* Top of the update loop */
116018  if( okOnePass ){
116019    if( aToOpen[iDataCur-iBaseCur] && !isView ){
116020      assert( pPk );
116021      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
116022      VdbeCoverageNeverTaken(v);
116023    }
116024    labelContinue = labelBreak;
116025    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
116026    VdbeCoverageIf(v, pPk==0);
116027    VdbeCoverageIf(v, pPk!=0);
116028  }else if( pPk ){
116029    labelContinue = sqlite3VdbeMakeLabel(v);
116030    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
116031    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
116032    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
116033    VdbeCoverage(v);
116034  }else{
116035    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
116036                             regOldRowid);
116037    VdbeCoverage(v);
116038    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
116039    VdbeCoverage(v);
116040  }
116041
116042  /* If the record number will change, set register regNewRowid to
116043  ** contain the new value. If the record number is not being modified,
116044  ** then regNewRowid is the same register as regOldRowid, which is
116045  ** already populated.  */
116046  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
116047  if( chngRowid ){
116048    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
116049    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
116050  }
116051
116052  /* Compute the old pre-UPDATE content of the row being changed, if that
116053  ** information is needed */
116054  if( chngPk || hasFK || pTrigger ){
116055    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
116056    oldmask |= sqlite3TriggerColmask(pParse,
116057        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
116058    );
116059    for(i=0; i<pTab->nCol; i++){
116060      if( oldmask==0xffffffff
116061       || (i<32 && (oldmask & MASKBIT32(i))!=0)
116062       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
116063      ){
116064        testcase(  oldmask!=0xffffffff && i==31 );
116065        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
116066      }else{
116067        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
116068      }
116069    }
116070    if( chngRowid==0 && pPk==0 ){
116071      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
116072    }
116073  }
116074
116075  /* Populate the array of registers beginning at regNew with the new
116076  ** row data. This array is used to check constants, create the new
116077  ** table and index records, and as the values for any new.* references
116078  ** made by triggers.
116079  **
116080  ** If there are one or more BEFORE triggers, then do not populate the
116081  ** registers associated with columns that are (a) not modified by
116082  ** this UPDATE statement and (b) not accessed by new.* references. The
116083  ** values for registers not modified by the UPDATE must be reloaded from
116084  ** the database after the BEFORE triggers are fired anyway (as the trigger
116085  ** may have modified them). So not loading those that are not going to
116086  ** be used eliminates some redundant opcodes.
116087  */
116088  newmask = sqlite3TriggerColmask(
116089      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
116090  );
116091  for(i=0; i<pTab->nCol; i++){
116092    if( i==pTab->iPKey ){
116093      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
116094    }else{
116095      j = aXRef[i];
116096      if( j>=0 ){
116097        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
116098      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
116099        /* This branch loads the value of a column that will not be changed
116100        ** into a register. This is done if there are no BEFORE triggers, or
116101        ** if there are one or more BEFORE triggers that use this value via
116102        ** a new.* reference in a trigger program.
116103        */
116104        testcase( i==31 );
116105        testcase( i==32 );
116106        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
116107      }else{
116108        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
116109      }
116110    }
116111  }
116112
116113  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
116114  ** verified. One could argue that this is wrong.
116115  */
116116  if( tmask&TRIGGER_BEFORE ){
116117    sqlite3TableAffinity(v, pTab, regNew);
116118    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
116119        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
116120
116121    /* The row-trigger may have deleted the row being updated. In this
116122    ** case, jump to the next row. No updates or AFTER triggers are
116123    ** required. This behavior - what happens when the row being updated
116124    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
116125    ** documentation.
116126    */
116127    if( pPk ){
116128      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
116129      VdbeCoverage(v);
116130    }else{
116131      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
116132      VdbeCoverage(v);
116133    }
116134
116135    /* If it did not delete it, the row-trigger may still have modified
116136    ** some of the columns of the row being updated. Load the values for
116137    ** all columns not modified by the update statement into their
116138    ** registers in case this has happened.
116139    */
116140    for(i=0; i<pTab->nCol; i++){
116141      if( aXRef[i]<0 && i!=pTab->iPKey ){
116142        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
116143      }
116144    }
116145  }
116146
116147  if( !isView ){
116148    int addr1 = 0;        /* Address of jump instruction */
116149    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
116150
116151    /* Do constraint checks. */
116152    assert( regOldRowid>0 );
116153    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
116154        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
116155
116156    /* Do FK constraint checks. */
116157    if( hasFK ){
116158      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
116159    }
116160
116161    /* Delete the index entries associated with the current record.  */
116162    if( bReplace || chngKey ){
116163      if( pPk ){
116164        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
116165      }else{
116166        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
116167      }
116168      VdbeCoverageNeverTaken(v);
116169    }
116170    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
116171
116172    /* If changing the record number, delete the old record.  */
116173    if( hasFK || chngKey || pPk!=0 ){
116174      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
116175    }
116176    if( bReplace || chngKey ){
116177      sqlite3VdbeJumpHere(v, addr1);
116178    }
116179
116180    if( hasFK ){
116181      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
116182    }
116183
116184    /* Insert the new index entries and the new record. */
116185    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
116186                             regNewRowid, aRegIdx, 1, 0, 0);
116187
116188    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
116189    ** handle rows (possibly in other tables) that refer via a foreign key
116190    ** to the row just updated. */
116191    if( hasFK ){
116192      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
116193    }
116194  }
116195
116196  /* Increment the row counter
116197  */
116198  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
116199    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
116200  }
116201
116202  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
116203      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
116204
116205  /* Repeat the above with the next record to be updated, until
116206  ** all record selected by the WHERE clause have been updated.
116207  */
116208  if( okOnePass ){
116209    /* Nothing to do at end-of-loop for a single-pass */
116210  }else if( pPk ){
116211    sqlite3VdbeResolveLabel(v, labelContinue);
116212    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
116213  }else{
116214    sqlite3VdbeGoto(v, labelContinue);
116215  }
116216  sqlite3VdbeResolveLabel(v, labelBreak);
116217
116218  /* Close all tables */
116219  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
116220    assert( aRegIdx );
116221    if( aToOpen[i+1] ){
116222      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
116223    }
116224  }
116225  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
116226
116227  /* Update the sqlite_sequence table by storing the content of the
116228  ** maximum rowid counter values recorded while inserting into
116229  ** autoincrement tables.
116230  */
116231  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
116232    sqlite3AutoincrementEnd(pParse);
116233  }
116234
116235  /*
116236  ** Return the number of rows that were changed. If this routine is
116237  ** generating code because of a call to sqlite3NestedParse(), do not
116238  ** invoke the callback function.
116239  */
116240  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
116241    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
116242    sqlite3VdbeSetNumCols(v, 1);
116243    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
116244  }
116245
116246update_cleanup:
116247  sqlite3AuthContextPop(&sContext);
116248  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
116249  sqlite3SrcListDelete(db, pTabList);
116250  sqlite3ExprListDelete(db, pChanges);
116251  sqlite3ExprDelete(db, pWhere);
116252  return;
116253}
116254/* Make sure "isView" and other macros defined above are undefined. Otherwise
116255** they may interfere with compilation of other functions in this file
116256** (or in another file, if this file becomes part of the amalgamation).  */
116257#ifdef isView
116258 #undef isView
116259#endif
116260#ifdef pTrigger
116261 #undef pTrigger
116262#endif
116263
116264#ifndef SQLITE_OMIT_VIRTUALTABLE
116265/*
116266** Generate code for an UPDATE of a virtual table.
116267**
116268** There are two possible strategies - the default and the special
116269** "onepass" strategy. Onepass is only used if the virtual table
116270** implementation indicates that pWhere may match at most one row.
116271**
116272** The default strategy is to create an ephemeral table that contains
116273** for each row to be changed:
116274**
116275**   (A)  The original rowid of that row.
116276**   (B)  The revised rowid for the row.
116277**   (C)  The content of every column in the row.
116278**
116279** Then loop through the contents of this ephemeral table executing a
116280** VUpdate for each row. When finished, drop the ephemeral table.
116281**
116282** The "onepass" strategy does not use an ephemeral table. Instead, it
116283** stores the same values (A, B and C above) in a register array and
116284** makes a single invocation of VUpdate.
116285*/
116286static void updateVirtualTable(
116287  Parse *pParse,       /* The parsing context */
116288  SrcList *pSrc,       /* The virtual table to be modified */
116289  Table *pTab,         /* The virtual table */
116290  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
116291  Expr *pRowid,        /* Expression used to recompute the rowid */
116292  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
116293  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
116294  int onError          /* ON CONFLICT strategy */
116295){
116296  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
116297  int ephemTab;             /* Table holding the result of the SELECT */
116298  int i;                    /* Loop counter */
116299  sqlite3 *db = pParse->db; /* Database connection */
116300  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
116301  WhereInfo *pWInfo;
116302  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
116303  int regArg;                     /* First register in VUpdate arg array */
116304  int regRec;                     /* Register in which to assemble record */
116305  int regRowid;                   /* Register for ephem table rowid */
116306  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
116307  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
116308  int bOnePass;                   /* True to use onepass strategy */
116309  int addr;                       /* Address of OP_OpenEphemeral */
116310
116311  /* Allocate nArg registers to martial the arguments to VUpdate. Then
116312  ** create and open the ephemeral table in which the records created from
116313  ** these arguments will be temporarily stored. */
116314  assert( v );
116315  ephemTab = pParse->nTab++;
116316  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
116317  regArg = pParse->nMem + 1;
116318  pParse->nMem += nArg;
116319  regRec = ++pParse->nMem;
116320  regRowid = ++pParse->nMem;
116321
116322  /* Start scanning the virtual table */
116323  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
116324  if( pWInfo==0 ) return;
116325
116326  /* Populate the argument registers. */
116327  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
116328  if( pRowid ){
116329    sqlite3ExprCode(pParse, pRowid, regArg+1);
116330  }else{
116331    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
116332  }
116333  for(i=0; i<pTab->nCol; i++){
116334    if( aXRef[i]>=0 ){
116335      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
116336    }else{
116337      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
116338    }
116339  }
116340
116341  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
116342
116343  if( bOnePass ){
116344    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
116345    ** above. Also, if this is a top-level parse (not a trigger), clear the
116346    ** multi-write flag so that the VM does not open a statement journal */
116347    sqlite3VdbeChangeToNoop(v, addr);
116348    if( sqlite3IsToplevel(pParse) ){
116349      pParse->isMultiWrite = 0;
116350    }
116351  }else{
116352    /* Create a record from the argument register contents and insert it into
116353    ** the ephemeral table. */
116354    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
116355    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
116356    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
116357  }
116358
116359
116360  if( bOnePass==0 ){
116361    /* End the virtual table scan */
116362    sqlite3WhereEnd(pWInfo);
116363
116364    /* Begin scannning through the ephemeral table. */
116365    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
116366
116367    /* Extract arguments from the current row of the ephemeral table and
116368    ** invoke the VUpdate method.  */
116369    for(i=0; i<nArg; i++){
116370      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
116371    }
116372  }
116373  sqlite3VtabMakeWritable(pParse, pTab);
116374  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
116375  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
116376  sqlite3MayAbort(pParse);
116377
116378  /* End of the ephemeral table scan. Or, if using the onepass strategy,
116379  ** jump to here if the scan visited zero rows. */
116380  if( bOnePass==0 ){
116381    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
116382    sqlite3VdbeJumpHere(v, addr);
116383    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
116384  }else{
116385    sqlite3WhereEnd(pWInfo);
116386  }
116387}
116388#endif /* SQLITE_OMIT_VIRTUALTABLE */
116389
116390/************** End of update.c **********************************************/
116391/************** Begin file vacuum.c ******************************************/
116392/*
116393** 2003 April 6
116394**
116395** The author disclaims copyright to this source code.  In place of
116396** a legal notice, here is a blessing:
116397**
116398**    May you do good and not evil.
116399**    May you find forgiveness for yourself and forgive others.
116400**    May you share freely, never taking more than you give.
116401**
116402*************************************************************************
116403** This file contains code used to implement the VACUUM command.
116404**
116405** Most of the code in this file may be omitted by defining the
116406** SQLITE_OMIT_VACUUM macro.
116407*/
116408/* #include "sqliteInt.h" */
116409/* #include "vdbeInt.h" */
116410
116411#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
116412/*
116413** Finalize a prepared statement.  If there was an error, store the
116414** text of the error message in *pzErrMsg.  Return the result code.
116415*/
116416static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
116417  int rc;
116418  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
116419  if( rc ){
116420    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
116421  }
116422  return rc;
116423}
116424
116425/*
116426** Execute zSql on database db. Return an error code.
116427*/
116428static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
116429  sqlite3_stmt *pStmt;
116430  VVA_ONLY( int rc; )
116431  if( !zSql ){
116432    return SQLITE_NOMEM;
116433  }
116434  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
116435    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
116436    return sqlite3_errcode(db);
116437  }
116438  VVA_ONLY( rc = ) sqlite3_step(pStmt);
116439  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
116440  return vacuumFinalize(db, pStmt, pzErrMsg);
116441}
116442
116443/*
116444** Execute zSql on database db. The statement returns exactly
116445** one column. Execute this as SQL on the same database.
116446*/
116447static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
116448  sqlite3_stmt *pStmt;
116449  int rc;
116450
116451  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
116452  if( rc!=SQLITE_OK ) return rc;
116453
116454  while( SQLITE_ROW==sqlite3_step(pStmt) ){
116455    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
116456    if( rc!=SQLITE_OK ){
116457      vacuumFinalize(db, pStmt, pzErrMsg);
116458      return rc;
116459    }
116460  }
116461
116462  return vacuumFinalize(db, pStmt, pzErrMsg);
116463}
116464
116465/*
116466** The VACUUM command is used to clean up the database,
116467** collapse free space, etc.  It is modelled after the VACUUM command
116468** in PostgreSQL.  The VACUUM command works as follows:
116469**
116470**   (1)  Create a new transient database file
116471**   (2)  Copy all content from the database being vacuumed into
116472**        the new transient database file
116473**   (3)  Copy content from the transient database back into the
116474**        original database.
116475**
116476** The transient database requires temporary disk space approximately
116477** equal to the size of the original database.  The copy operation of
116478** step (3) requires additional temporary disk space approximately equal
116479** to the size of the original database for the rollback journal.
116480** Hence, temporary disk space that is approximately 2x the size of the
116481** original database is required.  Every page of the database is written
116482** approximately 3 times:  Once for step (2) and twice for step (3).
116483** Two writes per page are required in step (3) because the original
116484** database content must be written into the rollback journal prior to
116485** overwriting the database with the vacuumed content.
116486**
116487** Only 1x temporary space and only 1x writes would be required if
116488** the copy of step (3) were replaced by deleting the original database
116489** and renaming the transient database as the original.  But that will
116490** not work if other processes are attached to the original database.
116491** And a power loss in between deleting the original and renaming the
116492** transient would cause the database file to appear to be deleted
116493** following reboot.
116494*/
116495SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
116496  Vdbe *v = sqlite3GetVdbe(pParse);
116497  if( v ){
116498    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
116499    sqlite3VdbeUsesBtree(v, 0);
116500  }
116501  return;
116502}
116503
116504/*
116505** This routine implements the OP_Vacuum opcode of the VDBE.
116506*/
116507SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
116508  int rc = SQLITE_OK;     /* Return code from service routines */
116509  Btree *pMain;           /* The database being vacuumed */
116510  Btree *pTemp;           /* The temporary database we vacuum into */
116511  char *zSql = 0;         /* SQL statements */
116512  int saved_flags;        /* Saved value of the db->flags */
116513  int saved_nChange;      /* Saved value of db->nChange */
116514  int saved_nTotalChange; /* Saved value of db->nTotalChange */
116515  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
116516  Db *pDb = 0;            /* Database to detach at end of vacuum */
116517  int isMemDb;            /* True if vacuuming a :memory: database */
116518  int nRes;               /* Bytes of reserved space at the end of each page */
116519  int nDb;                /* Number of attached databases */
116520
116521  if( !db->autoCommit ){
116522    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
116523    return SQLITE_ERROR;
116524  }
116525  if( db->nVdbeActive>1 ){
116526    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
116527    return SQLITE_ERROR;
116528  }
116529
116530  /* Save the current value of the database flags so that it can be
116531  ** restored before returning. Then set the writable-schema flag, and
116532  ** disable CHECK and foreign key constraints.  */
116533  saved_flags = db->flags;
116534  saved_nChange = db->nChange;
116535  saved_nTotalChange = db->nTotalChange;
116536  saved_xTrace = db->xTrace;
116537  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
116538  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
116539  db->xTrace = 0;
116540
116541  pMain = db->aDb[0].pBt;
116542  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
116543
116544  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
116545  ** can be set to 'off' for this file, as it is not recovered if a crash
116546  ** occurs anyway. The integrity of the database is maintained by a
116547  ** (possibly synchronous) transaction opened on the main database before
116548  ** sqlite3BtreeCopyFile() is called.
116549  **
116550  ** An optimisation would be to use a non-journaled pager.
116551  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
116552  ** that actually made the VACUUM run slower.  Very little journalling
116553  ** actually occurs when doing a vacuum since the vacuum_db is initially
116554  ** empty.  Only the journal header is written.  Apparently it takes more
116555  ** time to parse and run the PRAGMA to turn journalling off than it does
116556  ** to write the journal header file.
116557  */
116558  nDb = db->nDb;
116559  if( sqlite3TempInMemory(db) ){
116560    zSql = "ATTACH ':memory:' AS vacuum_db;";
116561  }else{
116562    zSql = "ATTACH '' AS vacuum_db;";
116563  }
116564  rc = execSql(db, pzErrMsg, zSql);
116565  if( db->nDb>nDb ){
116566    pDb = &db->aDb[db->nDb-1];
116567    assert( strcmp(pDb->zName,"vacuum_db")==0 );
116568  }
116569  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116570  pTemp = db->aDb[db->nDb-1].pBt;
116571
116572  /* The call to execSql() to attach the temp database has left the file
116573  ** locked (as there was more than one active statement when the transaction
116574  ** to read the schema was concluded. Unlock it here so that this doesn't
116575  ** cause problems for the call to BtreeSetPageSize() below.  */
116576  sqlite3BtreeCommit(pTemp);
116577
116578  nRes = sqlite3BtreeGetOptimalReserve(pMain);
116579
116580  /* A VACUUM cannot change the pagesize of an encrypted database. */
116581#ifdef SQLITE_HAS_CODEC
116582  if( db->nextPagesize ){
116583    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
116584    int nKey;
116585    char *zKey;
116586    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
116587    if( nKey ) db->nextPagesize = 0;
116588  }
116589#endif
116590
116591  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
116592  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116593
116594  /* Begin a transaction and take an exclusive lock on the main database
116595  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
116596  ** to ensure that we do not try to change the page-size on a WAL database.
116597  */
116598  rc = execSql(db, pzErrMsg, "BEGIN;");
116599  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116600  rc = sqlite3BtreeBeginTrans(pMain, 2);
116601  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116602
116603  /* Do not attempt to change the page size for a WAL database */
116604  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
116605                                               ==PAGER_JOURNALMODE_WAL ){
116606    db->nextPagesize = 0;
116607  }
116608
116609  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
116610   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
116611   || NEVER(db->mallocFailed)
116612  ){
116613    rc = SQLITE_NOMEM;
116614    goto end_of_vacuum;
116615  }
116616
116617#ifndef SQLITE_OMIT_AUTOVACUUM
116618  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
116619                                           sqlite3BtreeGetAutoVacuum(pMain));
116620#endif
116621
116622  /* Query the schema of the main database. Create a mirror schema
116623  ** in the temporary database.
116624  */
116625  rc = execExecSql(db, pzErrMsg,
116626      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
116627      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
116628      "   AND coalesce(rootpage,1)>0"
116629  );
116630  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116631  rc = execExecSql(db, pzErrMsg,
116632      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
116633      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
116634  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116635  rc = execExecSql(db, pzErrMsg,
116636      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
116637      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
116638  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116639
116640  /* Loop through the tables in the main database. For each, do
116641  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
116642  ** the contents to the temporary database.
116643  */
116644  assert( (db->flags & SQLITE_Vacuum)==0 );
116645  db->flags |= SQLITE_Vacuum;
116646  rc = execExecSql(db, pzErrMsg,
116647      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
116648      "|| ' SELECT * FROM main.' || quote(name) || ';'"
116649      "FROM main.sqlite_master "
116650      "WHERE type = 'table' AND name!='sqlite_sequence' "
116651      "  AND coalesce(rootpage,1)>0"
116652  );
116653  assert( (db->flags & SQLITE_Vacuum)!=0 );
116654  db->flags &= ~SQLITE_Vacuum;
116655  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116656
116657  /* Copy over the sequence table
116658  */
116659  rc = execExecSql(db, pzErrMsg,
116660      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
116661      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
116662  );
116663  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116664  rc = execExecSql(db, pzErrMsg,
116665      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
116666      "|| ' SELECT * FROM main.' || quote(name) || ';' "
116667      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
116668  );
116669  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116670
116671
116672  /* Copy the triggers, views, and virtual tables from the main database
116673  ** over to the temporary database.  None of these objects has any
116674  ** associated storage, so all we have to do is copy their entries
116675  ** from the SQLITE_MASTER table.
116676  */
116677  rc = execSql(db, pzErrMsg,
116678      "INSERT INTO vacuum_db.sqlite_master "
116679      "  SELECT type, name, tbl_name, rootpage, sql"
116680      "    FROM main.sqlite_master"
116681      "   WHERE type='view' OR type='trigger'"
116682      "      OR (type='table' AND rootpage=0)"
116683  );
116684  if( rc ) goto end_of_vacuum;
116685
116686  /* At this point, there is a write transaction open on both the
116687  ** vacuum database and the main database. Assuming no error occurs,
116688  ** both transactions are closed by this block - the main database
116689  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
116690  ** call to sqlite3BtreeCommit().
116691  */
116692  {
116693    u32 meta;
116694    int i;
116695
116696    /* This array determines which meta meta values are preserved in the
116697    ** vacuum.  Even entries are the meta value number and odd entries
116698    ** are an increment to apply to the meta value after the vacuum.
116699    ** The increment is used to increase the schema cookie so that other
116700    ** connections to the same database will know to reread the schema.
116701    */
116702    static const unsigned char aCopy[] = {
116703       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
116704       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
116705       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
116706       BTREE_USER_VERSION,       0,  /* Preserve the user version */
116707       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
116708    };
116709
116710    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
116711    assert( 1==sqlite3BtreeIsInTrans(pMain) );
116712
116713    /* Copy Btree meta values */
116714    for(i=0; i<ArraySize(aCopy); i+=2){
116715      /* GetMeta() and UpdateMeta() cannot fail in this context because
116716      ** we already have page 1 loaded into cache and marked dirty. */
116717      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
116718      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
116719      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
116720    }
116721
116722    rc = sqlite3BtreeCopyFile(pMain, pTemp);
116723    if( rc!=SQLITE_OK ) goto end_of_vacuum;
116724    rc = sqlite3BtreeCommit(pTemp);
116725    if( rc!=SQLITE_OK ) goto end_of_vacuum;
116726#ifndef SQLITE_OMIT_AUTOVACUUM
116727    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
116728#endif
116729  }
116730
116731  assert( rc==SQLITE_OK );
116732  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
116733
116734end_of_vacuum:
116735  /* Restore the original value of db->flags */
116736  db->flags = saved_flags;
116737  db->nChange = saved_nChange;
116738  db->nTotalChange = saved_nTotalChange;
116739  db->xTrace = saved_xTrace;
116740  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
116741
116742  /* Currently there is an SQL level transaction open on the vacuum
116743  ** database. No locks are held on any other files (since the main file
116744  ** was committed at the btree level). So it safe to end the transaction
116745  ** by manually setting the autoCommit flag to true and detaching the
116746  ** vacuum database. The vacuum_db journal file is deleted when the pager
116747  ** is closed by the DETACH.
116748  */
116749  db->autoCommit = 1;
116750
116751  if( pDb ){
116752    sqlite3BtreeClose(pDb->pBt);
116753    pDb->pBt = 0;
116754    pDb->pSchema = 0;
116755  }
116756
116757  /* This both clears the schemas and reduces the size of the db->aDb[]
116758  ** array. */
116759  sqlite3ResetAllSchemasOfConnection(db);
116760
116761  return rc;
116762}
116763
116764#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
116765
116766/************** End of vacuum.c **********************************************/
116767/************** Begin file vtab.c ********************************************/
116768/*
116769** 2006 June 10
116770**
116771** The author disclaims copyright to this source code.  In place of
116772** a legal notice, here is a blessing:
116773**
116774**    May you do good and not evil.
116775**    May you find forgiveness for yourself and forgive others.
116776**    May you share freely, never taking more than you give.
116777**
116778*************************************************************************
116779** This file contains code used to help implement virtual tables.
116780*/
116781#ifndef SQLITE_OMIT_VIRTUALTABLE
116782/* #include "sqliteInt.h" */
116783
116784/*
116785** Before a virtual table xCreate() or xConnect() method is invoked, the
116786** sqlite3.pVtabCtx member variable is set to point to an instance of
116787** this struct allocated on the stack. It is used by the implementation of
116788** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
116789** are invoked only from within xCreate and xConnect methods.
116790*/
116791struct VtabCtx {
116792  VTable *pVTable;    /* The virtual table being constructed */
116793  Table *pTab;        /* The Table object to which the virtual table belongs */
116794  VtabCtx *pPrior;    /* Parent context (if any) */
116795  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
116796};
116797
116798/*
116799** The actual function that does the work of creating a new module.
116800** This function implements the sqlite3_create_module() and
116801** sqlite3_create_module_v2() interfaces.
116802*/
116803static int createModule(
116804  sqlite3 *db,                    /* Database in which module is registered */
116805  const char *zName,              /* Name assigned to this module */
116806  const sqlite3_module *pModule,  /* The definition of the module */
116807  void *pAux,                     /* Context pointer for xCreate/xConnect */
116808  void (*xDestroy)(void *)        /* Module destructor function */
116809){
116810  int rc = SQLITE_OK;
116811  int nName;
116812
116813  sqlite3_mutex_enter(db->mutex);
116814  nName = sqlite3Strlen30(zName);
116815  if( sqlite3HashFind(&db->aModule, zName) ){
116816    rc = SQLITE_MISUSE_BKPT;
116817  }else{
116818    Module *pMod;
116819    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
116820    if( pMod ){
116821      Module *pDel;
116822      char *zCopy = (char *)(&pMod[1]);
116823      memcpy(zCopy, zName, nName+1);
116824      pMod->zName = zCopy;
116825      pMod->pModule = pModule;
116826      pMod->pAux = pAux;
116827      pMod->xDestroy = xDestroy;
116828      pMod->pEpoTab = 0;
116829      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
116830      assert( pDel==0 || pDel==pMod );
116831      if( pDel ){
116832        db->mallocFailed = 1;
116833        sqlite3DbFree(db, pDel);
116834      }
116835    }
116836  }
116837  rc = sqlite3ApiExit(db, rc);
116838  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
116839
116840  sqlite3_mutex_leave(db->mutex);
116841  return rc;
116842}
116843
116844
116845/*
116846** External API function used to create a new virtual-table module.
116847*/
116848SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
116849  sqlite3 *db,                    /* Database in which module is registered */
116850  const char *zName,              /* Name assigned to this module */
116851  const sqlite3_module *pModule,  /* The definition of the module */
116852  void *pAux                      /* Context pointer for xCreate/xConnect */
116853){
116854#ifdef SQLITE_ENABLE_API_ARMOR
116855  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
116856#endif
116857  return createModule(db, zName, pModule, pAux, 0);
116858}
116859
116860/*
116861** External API function used to create a new virtual-table module.
116862*/
116863SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
116864  sqlite3 *db,                    /* Database in which module is registered */
116865  const char *zName,              /* Name assigned to this module */
116866  const sqlite3_module *pModule,  /* The definition of the module */
116867  void *pAux,                     /* Context pointer for xCreate/xConnect */
116868  void (*xDestroy)(void *)        /* Module destructor function */
116869){
116870#ifdef SQLITE_ENABLE_API_ARMOR
116871  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
116872#endif
116873  return createModule(db, zName, pModule, pAux, xDestroy);
116874}
116875
116876/*
116877** Lock the virtual table so that it cannot be disconnected.
116878** Locks nest.  Every lock should have a corresponding unlock.
116879** If an unlock is omitted, resources leaks will occur.
116880**
116881** If a disconnect is attempted while a virtual table is locked,
116882** the disconnect is deferred until all locks have been removed.
116883*/
116884SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
116885  pVTab->nRef++;
116886}
116887
116888
116889/*
116890** pTab is a pointer to a Table structure representing a virtual-table.
116891** Return a pointer to the VTable object used by connection db to access
116892** this virtual-table, if one has been created, or NULL otherwise.
116893*/
116894SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
116895  VTable *pVtab;
116896  assert( IsVirtual(pTab) );
116897  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
116898  return pVtab;
116899}
116900
116901/*
116902** Decrement the ref-count on a virtual table object. When the ref-count
116903** reaches zero, call the xDisconnect() method to delete the object.
116904*/
116905SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
116906  sqlite3 *db = pVTab->db;
116907
116908  assert( db );
116909  assert( pVTab->nRef>0 );
116910  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
116911
116912  pVTab->nRef--;
116913  if( pVTab->nRef==0 ){
116914    sqlite3_vtab *p = pVTab->pVtab;
116915    if( p ){
116916      p->pModule->xDisconnect(p);
116917    }
116918    sqlite3DbFree(db, pVTab);
116919  }
116920}
116921
116922/*
116923** Table p is a virtual table. This function moves all elements in the
116924** p->pVTable list to the sqlite3.pDisconnect lists of their associated
116925** database connections to be disconnected at the next opportunity.
116926** Except, if argument db is not NULL, then the entry associated with
116927** connection db is left in the p->pVTable list.
116928*/
116929static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
116930  VTable *pRet = 0;
116931  VTable *pVTable = p->pVTable;
116932  p->pVTable = 0;
116933
116934  /* Assert that the mutex (if any) associated with the BtShared database
116935  ** that contains table p is held by the caller. See header comments
116936  ** above function sqlite3VtabUnlockList() for an explanation of why
116937  ** this makes it safe to access the sqlite3.pDisconnect list of any
116938  ** database connection that may have an entry in the p->pVTable list.
116939  */
116940  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
116941
116942  while( pVTable ){
116943    sqlite3 *db2 = pVTable->db;
116944    VTable *pNext = pVTable->pNext;
116945    assert( db2 );
116946    if( db2==db ){
116947      pRet = pVTable;
116948      p->pVTable = pRet;
116949      pRet->pNext = 0;
116950    }else{
116951      pVTable->pNext = db2->pDisconnect;
116952      db2->pDisconnect = pVTable;
116953    }
116954    pVTable = pNext;
116955  }
116956
116957  assert( !db || pRet );
116958  return pRet;
116959}
116960
116961/*
116962** Table *p is a virtual table. This function removes the VTable object
116963** for table *p associated with database connection db from the linked
116964** list in p->pVTab. It also decrements the VTable ref count. This is
116965** used when closing database connection db to free all of its VTable
116966** objects without disturbing the rest of the Schema object (which may
116967** be being used by other shared-cache connections).
116968*/
116969SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
116970  VTable **ppVTab;
116971
116972  assert( IsVirtual(p) );
116973  assert( sqlite3BtreeHoldsAllMutexes(db) );
116974  assert( sqlite3_mutex_held(db->mutex) );
116975
116976  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
116977    if( (*ppVTab)->db==db  ){
116978      VTable *pVTab = *ppVTab;
116979      *ppVTab = pVTab->pNext;
116980      sqlite3VtabUnlock(pVTab);
116981      break;
116982    }
116983  }
116984}
116985
116986
116987/*
116988** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
116989**
116990** This function may only be called when the mutexes associated with all
116991** shared b-tree databases opened using connection db are held by the
116992** caller. This is done to protect the sqlite3.pDisconnect list. The
116993** sqlite3.pDisconnect list is accessed only as follows:
116994**
116995**   1) By this function. In this case, all BtShared mutexes and the mutex
116996**      associated with the database handle itself must be held.
116997**
116998**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
116999**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
117000**      associated with the database the virtual table is stored in is held
117001**      or, if the virtual table is stored in a non-sharable database, then
117002**      the database handle mutex is held.
117003**
117004** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
117005** by multiple threads. It is thread-safe.
117006*/
117007SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
117008  VTable *p = db->pDisconnect;
117009  db->pDisconnect = 0;
117010
117011  assert( sqlite3BtreeHoldsAllMutexes(db) );
117012  assert( sqlite3_mutex_held(db->mutex) );
117013
117014  if( p ){
117015    sqlite3ExpirePreparedStatements(db);
117016    do {
117017      VTable *pNext = p->pNext;
117018      sqlite3VtabUnlock(p);
117019      p = pNext;
117020    }while( p );
117021  }
117022}
117023
117024/*
117025** Clear any and all virtual-table information from the Table record.
117026** This routine is called, for example, just before deleting the Table
117027** record.
117028**
117029** Since it is a virtual-table, the Table structure contains a pointer
117030** to the head of a linked list of VTable structures. Each VTable
117031** structure is associated with a single sqlite3* user of the schema.
117032** The reference count of the VTable structure associated with database
117033** connection db is decremented immediately (which may lead to the
117034** structure being xDisconnected and free). Any other VTable structures
117035** in the list are moved to the sqlite3.pDisconnect list of the associated
117036** database connection.
117037*/
117038SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
117039  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
117040  if( p->azModuleArg ){
117041    int i;
117042    for(i=0; i<p->nModuleArg; i++){
117043      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
117044    }
117045    sqlite3DbFree(db, p->azModuleArg);
117046  }
117047}
117048
117049/*
117050** Add a new module argument to pTable->azModuleArg[].
117051** The string is not copied - the pointer is stored.  The
117052** string will be freed automatically when the table is
117053** deleted.
117054*/
117055static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
117056  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
117057  char **azModuleArg;
117058  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
117059  if( azModuleArg==0 ){
117060    sqlite3DbFree(db, zArg);
117061  }else{
117062    int i = pTable->nModuleArg++;
117063    azModuleArg[i] = zArg;
117064    azModuleArg[i+1] = 0;
117065    pTable->azModuleArg = azModuleArg;
117066  }
117067}
117068
117069/*
117070** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
117071** statement.  The module name has been parsed, but the optional list
117072** of parameters that follow the module name are still pending.
117073*/
117074SQLITE_PRIVATE void sqlite3VtabBeginParse(
117075  Parse *pParse,        /* Parsing context */
117076  Token *pName1,        /* Name of new table, or database name */
117077  Token *pName2,        /* Name of new table or NULL */
117078  Token *pModuleName,   /* Name of the module for the virtual table */
117079  int ifNotExists       /* No error if the table already exists */
117080){
117081  int iDb;              /* The database the table is being created in */
117082  Table *pTable;        /* The new virtual table */
117083  sqlite3 *db;          /* Database connection */
117084
117085  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
117086  pTable = pParse->pNewTable;
117087  if( pTable==0 ) return;
117088  assert( 0==pTable->pIndex );
117089
117090  db = pParse->db;
117091  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
117092  assert( iDb>=0 );
117093
117094  pTable->tabFlags |= TF_Virtual;
117095  pTable->nModuleArg = 0;
117096  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
117097  addModuleArgument(db, pTable, 0);
117098  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
117099  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
117100       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
117101  );
117102  pParse->sNameToken.n = (int)(
117103      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
117104  );
117105
117106#ifndef SQLITE_OMIT_AUTHORIZATION
117107  /* Creating a virtual table invokes the authorization callback twice.
117108  ** The first invocation, to obtain permission to INSERT a row into the
117109  ** sqlite_master table, has already been made by sqlite3StartTable().
117110  ** The second call, to obtain permission to create the table, is made now.
117111  */
117112  if( pTable->azModuleArg ){
117113    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
117114            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
117115  }
117116#endif
117117}
117118
117119/*
117120** This routine takes the module argument that has been accumulating
117121** in pParse->zArg[] and appends it to the list of arguments on the
117122** virtual table currently under construction in pParse->pTable.
117123*/
117124static void addArgumentToVtab(Parse *pParse){
117125  if( pParse->sArg.z && pParse->pNewTable ){
117126    const char *z = (const char*)pParse->sArg.z;
117127    int n = pParse->sArg.n;
117128    sqlite3 *db = pParse->db;
117129    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
117130  }
117131}
117132
117133/*
117134** The parser calls this routine after the CREATE VIRTUAL TABLE statement
117135** has been completely parsed.
117136*/
117137SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
117138  Table *pTab = pParse->pNewTable;  /* The table being constructed */
117139  sqlite3 *db = pParse->db;         /* The database connection */
117140
117141  if( pTab==0 ) return;
117142  addArgumentToVtab(pParse);
117143  pParse->sArg.z = 0;
117144  if( pTab->nModuleArg<1 ) return;
117145
117146  /* If the CREATE VIRTUAL TABLE statement is being entered for the
117147  ** first time (in other words if the virtual table is actually being
117148  ** created now instead of just being read out of sqlite_master) then
117149  ** do additional initialization work and store the statement text
117150  ** in the sqlite_master table.
117151  */
117152  if( !db->init.busy ){
117153    char *zStmt;
117154    char *zWhere;
117155    int iDb;
117156    int iReg;
117157    Vdbe *v;
117158
117159    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
117160    if( pEnd ){
117161      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
117162    }
117163    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
117164
117165    /* A slot for the record has already been allocated in the
117166    ** SQLITE_MASTER table.  We just need to update that slot with all
117167    ** the information we've collected.
117168    **
117169    ** The VM register number pParse->regRowid holds the rowid of an
117170    ** entry in the sqlite_master table tht was created for this vtab
117171    ** by sqlite3StartTable().
117172    */
117173    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117174    sqlite3NestedParse(pParse,
117175      "UPDATE %Q.%s "
117176         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
117177       "WHERE rowid=#%d",
117178      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
117179      pTab->zName,
117180      pTab->zName,
117181      zStmt,
117182      pParse->regRowid
117183    );
117184    sqlite3DbFree(db, zStmt);
117185    v = sqlite3GetVdbe(pParse);
117186    sqlite3ChangeCookie(pParse, iDb);
117187
117188    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
117189    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
117190    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
117191
117192    iReg = ++pParse->nMem;
117193    sqlite3VdbeLoadString(v, iReg, pTab->zName);
117194    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
117195  }
117196
117197  /* If we are rereading the sqlite_master table create the in-memory
117198  ** record of the table. The xConnect() method is not called until
117199  ** the first time the virtual table is used in an SQL statement. This
117200  ** allows a schema that contains virtual tables to be loaded before
117201  ** the required virtual table implementations are registered.  */
117202  else {
117203    Table *pOld;
117204    Schema *pSchema = pTab->pSchema;
117205    const char *zName = pTab->zName;
117206    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
117207    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
117208    if( pOld ){
117209      db->mallocFailed = 1;
117210      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
117211      return;
117212    }
117213    pParse->pNewTable = 0;
117214  }
117215}
117216
117217/*
117218** The parser calls this routine when it sees the first token
117219** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
117220*/
117221SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
117222  addArgumentToVtab(pParse);
117223  pParse->sArg.z = 0;
117224  pParse->sArg.n = 0;
117225}
117226
117227/*
117228** The parser calls this routine for each token after the first token
117229** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
117230*/
117231SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
117232  Token *pArg = &pParse->sArg;
117233  if( pArg->z==0 ){
117234    pArg->z = p->z;
117235    pArg->n = p->n;
117236  }else{
117237    assert(pArg->z <= p->z);
117238    pArg->n = (int)(&p->z[p->n] - pArg->z);
117239  }
117240}
117241
117242/*
117243** Invoke a virtual table constructor (either xCreate or xConnect). The
117244** pointer to the function to invoke is passed as the fourth parameter
117245** to this procedure.
117246*/
117247static int vtabCallConstructor(
117248  sqlite3 *db,
117249  Table *pTab,
117250  Module *pMod,
117251  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
117252  char **pzErr
117253){
117254  VtabCtx sCtx;
117255  VTable *pVTable;
117256  int rc;
117257  const char *const*azArg = (const char *const*)pTab->azModuleArg;
117258  int nArg = pTab->nModuleArg;
117259  char *zErr = 0;
117260  char *zModuleName;
117261  int iDb;
117262  VtabCtx *pCtx;
117263
117264  /* Check that the virtual-table is not already being initialized */
117265  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
117266    if( pCtx->pTab==pTab ){
117267      *pzErr = sqlite3MPrintf(db,
117268          "vtable constructor called recursively: %s", pTab->zName
117269      );
117270      return SQLITE_LOCKED;
117271    }
117272  }
117273
117274  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
117275  if( !zModuleName ){
117276    return SQLITE_NOMEM;
117277  }
117278
117279  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
117280  if( !pVTable ){
117281    sqlite3DbFree(db, zModuleName);
117282    return SQLITE_NOMEM;
117283  }
117284  pVTable->db = db;
117285  pVTable->pMod = pMod;
117286
117287  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117288  pTab->azModuleArg[1] = db->aDb[iDb].zName;
117289
117290  /* Invoke the virtual table constructor */
117291  assert( &db->pVtabCtx );
117292  assert( xConstruct );
117293  sCtx.pTab = pTab;
117294  sCtx.pVTable = pVTable;
117295  sCtx.pPrior = db->pVtabCtx;
117296  sCtx.bDeclared = 0;
117297  db->pVtabCtx = &sCtx;
117298  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
117299  db->pVtabCtx = sCtx.pPrior;
117300  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
117301  assert( sCtx.pTab==pTab );
117302
117303  if( SQLITE_OK!=rc ){
117304    if( zErr==0 ){
117305      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
117306    }else {
117307      *pzErr = sqlite3MPrintf(db, "%s", zErr);
117308      sqlite3_free(zErr);
117309    }
117310    sqlite3DbFree(db, pVTable);
117311  }else if( ALWAYS(pVTable->pVtab) ){
117312    /* Justification of ALWAYS():  A correct vtab constructor must allocate
117313    ** the sqlite3_vtab object if successful.  */
117314    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
117315    pVTable->pVtab->pModule = pMod->pModule;
117316    pVTable->nRef = 1;
117317    if( sCtx.bDeclared==0 ){
117318      const char *zFormat = "vtable constructor did not declare schema: %s";
117319      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
117320      sqlite3VtabUnlock(pVTable);
117321      rc = SQLITE_ERROR;
117322    }else{
117323      int iCol;
117324      u8 oooHidden = 0;
117325      /* If everything went according to plan, link the new VTable structure
117326      ** into the linked list headed by pTab->pVTable. Then loop through the
117327      ** columns of the table to see if any of them contain the token "hidden".
117328      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
117329      ** the type string.  */
117330      pVTable->pNext = pTab->pVTable;
117331      pTab->pVTable = pVTable;
117332
117333      for(iCol=0; iCol<pTab->nCol; iCol++){
117334        char *zType = pTab->aCol[iCol].zType;
117335        int nType;
117336        int i = 0;
117337        if( !zType ){
117338          pTab->tabFlags |= oooHidden;
117339          continue;
117340        }
117341        nType = sqlite3Strlen30(zType);
117342        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
117343          for(i=0; i<nType; i++){
117344            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
117345             && (zType[i+7]=='\0' || zType[i+7]==' ')
117346            ){
117347              i++;
117348              break;
117349            }
117350          }
117351        }
117352        if( i<nType ){
117353          int j;
117354          int nDel = 6 + (zType[i+6] ? 1 : 0);
117355          for(j=i; (j+nDel)<=nType; j++){
117356            zType[j] = zType[j+nDel];
117357          }
117358          if( zType[i]=='\0' && i>0 ){
117359            assert(zType[i-1]==' ');
117360            zType[i-1] = '\0';
117361          }
117362          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
117363          oooHidden = TF_OOOHidden;
117364        }else{
117365          pTab->tabFlags |= oooHidden;
117366        }
117367      }
117368    }
117369  }
117370
117371  sqlite3DbFree(db, zModuleName);
117372  return rc;
117373}
117374
117375/*
117376** This function is invoked by the parser to call the xConnect() method
117377** of the virtual table pTab. If an error occurs, an error code is returned
117378** and an error left in pParse.
117379**
117380** This call is a no-op if table pTab is not a virtual table.
117381*/
117382SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
117383  sqlite3 *db = pParse->db;
117384  const char *zMod;
117385  Module *pMod;
117386  int rc;
117387
117388  assert( pTab );
117389  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
117390    return SQLITE_OK;
117391  }
117392
117393  /* Locate the required virtual table module */
117394  zMod = pTab->azModuleArg[0];
117395  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
117396
117397  if( !pMod ){
117398    const char *zModule = pTab->azModuleArg[0];
117399    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
117400    rc = SQLITE_ERROR;
117401  }else{
117402    char *zErr = 0;
117403    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
117404    if( rc!=SQLITE_OK ){
117405      sqlite3ErrorMsg(pParse, "%s", zErr);
117406    }
117407    sqlite3DbFree(db, zErr);
117408  }
117409
117410  return rc;
117411}
117412/*
117413** Grow the db->aVTrans[] array so that there is room for at least one
117414** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
117415*/
117416static int growVTrans(sqlite3 *db){
117417  const int ARRAY_INCR = 5;
117418
117419  /* Grow the sqlite3.aVTrans array if required */
117420  if( (db->nVTrans%ARRAY_INCR)==0 ){
117421    VTable **aVTrans;
117422    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
117423    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
117424    if( !aVTrans ){
117425      return SQLITE_NOMEM;
117426    }
117427    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
117428    db->aVTrans = aVTrans;
117429  }
117430
117431  return SQLITE_OK;
117432}
117433
117434/*
117435** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
117436** have already been reserved using growVTrans().
117437*/
117438static void addToVTrans(sqlite3 *db, VTable *pVTab){
117439  /* Add pVtab to the end of sqlite3.aVTrans */
117440  db->aVTrans[db->nVTrans++] = pVTab;
117441  sqlite3VtabLock(pVTab);
117442}
117443
117444/*
117445** This function is invoked by the vdbe to call the xCreate method
117446** of the virtual table named zTab in database iDb.
117447**
117448** If an error occurs, *pzErr is set to point an an English language
117449** description of the error and an SQLITE_XXX error code is returned.
117450** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
117451*/
117452SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
117453  int rc = SQLITE_OK;
117454  Table *pTab;
117455  Module *pMod;
117456  const char *zMod;
117457
117458  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
117459  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
117460
117461  /* Locate the required virtual table module */
117462  zMod = pTab->azModuleArg[0];
117463  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
117464
117465  /* If the module has been registered and includes a Create method,
117466  ** invoke it now. If the module has not been registered, return an
117467  ** error. Otherwise, do nothing.
117468  */
117469  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
117470    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
117471    rc = SQLITE_ERROR;
117472  }else{
117473    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
117474  }
117475
117476  /* Justification of ALWAYS():  The xConstructor method is required to
117477  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
117478  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
117479    rc = growVTrans(db);
117480    if( rc==SQLITE_OK ){
117481      addToVTrans(db, sqlite3GetVTable(db, pTab));
117482    }
117483  }
117484
117485  return rc;
117486}
117487
117488/*
117489** This function is used to set the schema of a virtual table.  It is only
117490** valid to call this function from within the xCreate() or xConnect() of a
117491** virtual table module.
117492*/
117493SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
117494  VtabCtx *pCtx;
117495  Parse *pParse;
117496  int rc = SQLITE_OK;
117497  Table *pTab;
117498  char *zErr = 0;
117499
117500#ifdef SQLITE_ENABLE_API_ARMOR
117501  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
117502    return SQLITE_MISUSE_BKPT;
117503  }
117504#endif
117505  sqlite3_mutex_enter(db->mutex);
117506  pCtx = db->pVtabCtx;
117507  if( !pCtx || pCtx->bDeclared ){
117508    sqlite3Error(db, SQLITE_MISUSE);
117509    sqlite3_mutex_leave(db->mutex);
117510    return SQLITE_MISUSE_BKPT;
117511  }
117512  pTab = pCtx->pTab;
117513  assert( (pTab->tabFlags & TF_Virtual)!=0 );
117514
117515  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
117516  if( pParse==0 ){
117517    rc = SQLITE_NOMEM;
117518  }else{
117519    pParse->declareVtab = 1;
117520    pParse->db = db;
117521    pParse->nQueryLoop = 1;
117522
117523    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
117524     && pParse->pNewTable
117525     && !db->mallocFailed
117526     && !pParse->pNewTable->pSelect
117527     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
117528    ){
117529      if( !pTab->aCol ){
117530        pTab->aCol = pParse->pNewTable->aCol;
117531        pTab->nCol = pParse->pNewTable->nCol;
117532        pParse->pNewTable->nCol = 0;
117533        pParse->pNewTable->aCol = 0;
117534      }
117535      pCtx->bDeclared = 1;
117536    }else{
117537      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
117538      sqlite3DbFree(db, zErr);
117539      rc = SQLITE_ERROR;
117540    }
117541    pParse->declareVtab = 0;
117542
117543    if( pParse->pVdbe ){
117544      sqlite3VdbeFinalize(pParse->pVdbe);
117545    }
117546    sqlite3DeleteTable(db, pParse->pNewTable);
117547    sqlite3ParserReset(pParse);
117548    sqlite3StackFree(db, pParse);
117549  }
117550
117551  assert( (rc&0xff)==rc );
117552  rc = sqlite3ApiExit(db, rc);
117553  sqlite3_mutex_leave(db->mutex);
117554  return rc;
117555}
117556
117557/*
117558** This function is invoked by the vdbe to call the xDestroy method
117559** of the virtual table named zTab in database iDb. This occurs
117560** when a DROP TABLE is mentioned.
117561**
117562** This call is a no-op if zTab is not a virtual table.
117563*/
117564SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
117565  int rc = SQLITE_OK;
117566  Table *pTab;
117567
117568  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
117569  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
117570    VTable *p;
117571    int (*xDestroy)(sqlite3_vtab *);
117572    for(p=pTab->pVTable; p; p=p->pNext){
117573      assert( p->pVtab );
117574      if( p->pVtab->nRef>0 ){
117575        return SQLITE_LOCKED;
117576      }
117577    }
117578    p = vtabDisconnectAll(db, pTab);
117579    xDestroy = p->pMod->pModule->xDestroy;
117580    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
117581    rc = xDestroy(p->pVtab);
117582    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
117583    if( rc==SQLITE_OK ){
117584      assert( pTab->pVTable==p && p->pNext==0 );
117585      p->pVtab = 0;
117586      pTab->pVTable = 0;
117587      sqlite3VtabUnlock(p);
117588    }
117589  }
117590
117591  return rc;
117592}
117593
117594/*
117595** This function invokes either the xRollback or xCommit method
117596** of each of the virtual tables in the sqlite3.aVTrans array. The method
117597** called is identified by the second argument, "offset", which is
117598** the offset of the method to call in the sqlite3_module structure.
117599**
117600** The array is cleared after invoking the callbacks.
117601*/
117602static void callFinaliser(sqlite3 *db, int offset){
117603  int i;
117604  if( db->aVTrans ){
117605    VTable **aVTrans = db->aVTrans;
117606    db->aVTrans = 0;
117607    for(i=0; i<db->nVTrans; i++){
117608      VTable *pVTab = aVTrans[i];
117609      sqlite3_vtab *p = pVTab->pVtab;
117610      if( p ){
117611        int (*x)(sqlite3_vtab *);
117612        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
117613        if( x ) x(p);
117614      }
117615      pVTab->iSavepoint = 0;
117616      sqlite3VtabUnlock(pVTab);
117617    }
117618    sqlite3DbFree(db, aVTrans);
117619    db->nVTrans = 0;
117620  }
117621}
117622
117623/*
117624** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
117625** array. Return the error code for the first error that occurs, or
117626** SQLITE_OK if all xSync operations are successful.
117627**
117628** If an error message is available, leave it in p->zErrMsg.
117629*/
117630SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
117631  int i;
117632  int rc = SQLITE_OK;
117633  VTable **aVTrans = db->aVTrans;
117634
117635  db->aVTrans = 0;
117636  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
117637    int (*x)(sqlite3_vtab *);
117638    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
117639    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
117640      rc = x(pVtab);
117641      sqlite3VtabImportErrmsg(p, pVtab);
117642    }
117643  }
117644  db->aVTrans = aVTrans;
117645  return rc;
117646}
117647
117648/*
117649** Invoke the xRollback method of all virtual tables in the
117650** sqlite3.aVTrans array. Then clear the array itself.
117651*/
117652SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
117653  callFinaliser(db, offsetof(sqlite3_module,xRollback));
117654  return SQLITE_OK;
117655}
117656
117657/*
117658** Invoke the xCommit method of all virtual tables in the
117659** sqlite3.aVTrans array. Then clear the array itself.
117660*/
117661SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
117662  callFinaliser(db, offsetof(sqlite3_module,xCommit));
117663  return SQLITE_OK;
117664}
117665
117666/*
117667** If the virtual table pVtab supports the transaction interface
117668** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
117669** not currently open, invoke the xBegin method now.
117670**
117671** If the xBegin call is successful, place the sqlite3_vtab pointer
117672** in the sqlite3.aVTrans array.
117673*/
117674SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
117675  int rc = SQLITE_OK;
117676  const sqlite3_module *pModule;
117677
117678  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
117679  ** than zero, then this function is being called from within a
117680  ** virtual module xSync() callback. It is illegal to write to
117681  ** virtual module tables in this case, so return SQLITE_LOCKED.
117682  */
117683  if( sqlite3VtabInSync(db) ){
117684    return SQLITE_LOCKED;
117685  }
117686  if( !pVTab ){
117687    return SQLITE_OK;
117688  }
117689  pModule = pVTab->pVtab->pModule;
117690
117691  if( pModule->xBegin ){
117692    int i;
117693
117694    /* If pVtab is already in the aVTrans array, return early */
117695    for(i=0; i<db->nVTrans; i++){
117696      if( db->aVTrans[i]==pVTab ){
117697        return SQLITE_OK;
117698      }
117699    }
117700
117701    /* Invoke the xBegin method. If successful, add the vtab to the
117702    ** sqlite3.aVTrans[] array. */
117703    rc = growVTrans(db);
117704    if( rc==SQLITE_OK ){
117705      rc = pModule->xBegin(pVTab->pVtab);
117706      if( rc==SQLITE_OK ){
117707        int iSvpt = db->nStatement + db->nSavepoint;
117708        addToVTrans(db, pVTab);
117709        if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
117710      }
117711    }
117712  }
117713  return rc;
117714}
117715
117716/*
117717** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
117718** virtual tables that currently have an open transaction. Pass iSavepoint
117719** as the second argument to the virtual table method invoked.
117720**
117721** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
117722** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
117723** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
117724** an open transaction is invoked.
117725**
117726** If any virtual table method returns an error code other than SQLITE_OK,
117727** processing is abandoned and the error returned to the caller of this
117728** function immediately. If all calls to virtual table methods are successful,
117729** SQLITE_OK is returned.
117730*/
117731SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
117732  int rc = SQLITE_OK;
117733
117734  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
117735  assert( iSavepoint>=-1 );
117736  if( db->aVTrans ){
117737    int i;
117738    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
117739      VTable *pVTab = db->aVTrans[i];
117740      const sqlite3_module *pMod = pVTab->pMod->pModule;
117741      if( pVTab->pVtab && pMod->iVersion>=2 ){
117742        int (*xMethod)(sqlite3_vtab *, int);
117743        switch( op ){
117744          case SAVEPOINT_BEGIN:
117745            xMethod = pMod->xSavepoint;
117746            pVTab->iSavepoint = iSavepoint+1;
117747            break;
117748          case SAVEPOINT_ROLLBACK:
117749            xMethod = pMod->xRollbackTo;
117750            break;
117751          default:
117752            xMethod = pMod->xRelease;
117753            break;
117754        }
117755        if( xMethod && pVTab->iSavepoint>iSavepoint ){
117756          rc = xMethod(pVTab->pVtab, iSavepoint);
117757        }
117758      }
117759    }
117760  }
117761  return rc;
117762}
117763
117764/*
117765** The first parameter (pDef) is a function implementation.  The
117766** second parameter (pExpr) is the first argument to this function.
117767** If pExpr is a column in a virtual table, then let the virtual
117768** table implementation have an opportunity to overload the function.
117769**
117770** This routine is used to allow virtual table implementations to
117771** overload MATCH, LIKE, GLOB, and REGEXP operators.
117772**
117773** Return either the pDef argument (indicating no change) or a
117774** new FuncDef structure that is marked as ephemeral using the
117775** SQLITE_FUNC_EPHEM flag.
117776*/
117777SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
117778  sqlite3 *db,    /* Database connection for reporting malloc problems */
117779  FuncDef *pDef,  /* Function to possibly overload */
117780  int nArg,       /* Number of arguments to the function */
117781  Expr *pExpr     /* First argument to the function */
117782){
117783  Table *pTab;
117784  sqlite3_vtab *pVtab;
117785  sqlite3_module *pMod;
117786  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
117787  void *pArg = 0;
117788  FuncDef *pNew;
117789  int rc = 0;
117790  char *zLowerName;
117791  unsigned char *z;
117792
117793
117794  /* Check to see the left operand is a column in a virtual table */
117795  if( NEVER(pExpr==0) ) return pDef;
117796  if( pExpr->op!=TK_COLUMN ) return pDef;
117797  pTab = pExpr->pTab;
117798  if( NEVER(pTab==0) ) return pDef;
117799  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
117800  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
117801  assert( pVtab!=0 );
117802  assert( pVtab->pModule!=0 );
117803  pMod = (sqlite3_module *)pVtab->pModule;
117804  if( pMod->xFindFunction==0 ) return pDef;
117805
117806  /* Call the xFindFunction method on the virtual table implementation
117807  ** to see if the implementation wants to overload this function
117808  */
117809  zLowerName = sqlite3DbStrDup(db, pDef->zName);
117810  if( zLowerName ){
117811    for(z=(unsigned char*)zLowerName; *z; z++){
117812      *z = sqlite3UpperToLower[*z];
117813    }
117814    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
117815    sqlite3DbFree(db, zLowerName);
117816  }
117817  if( rc==0 ){
117818    return pDef;
117819  }
117820
117821  /* Create a new ephemeral function definition for the overloaded
117822  ** function */
117823  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
117824                             + sqlite3Strlen30(pDef->zName) + 1);
117825  if( pNew==0 ){
117826    return pDef;
117827  }
117828  *pNew = *pDef;
117829  pNew->zName = (char *)&pNew[1];
117830  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
117831  pNew->xFunc = xFunc;
117832  pNew->pUserData = pArg;
117833  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
117834  return pNew;
117835}
117836
117837/*
117838** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
117839** array so that an OP_VBegin will get generated for it.  Add pTab to the
117840** array if it is missing.  If pTab is already in the array, this routine
117841** is a no-op.
117842*/
117843SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
117844  Parse *pToplevel = sqlite3ParseToplevel(pParse);
117845  int i, n;
117846  Table **apVtabLock;
117847
117848  assert( IsVirtual(pTab) );
117849  for(i=0; i<pToplevel->nVtabLock; i++){
117850    if( pTab==pToplevel->apVtabLock[i] ) return;
117851  }
117852  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
117853  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
117854  if( apVtabLock ){
117855    pToplevel->apVtabLock = apVtabLock;
117856    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
117857  }else{
117858    pToplevel->db->mallocFailed = 1;
117859  }
117860}
117861
117862/*
117863** Check to see if virtual tale module pMod can be have an eponymous
117864** virtual table instance.  If it can, create one if one does not already
117865** exist. Return non-zero if the eponymous virtual table instance exists
117866** when this routine returns, and return zero if it does not exist.
117867**
117868** An eponymous virtual table instance is one that is named after its
117869** module, and more importantly, does not require a CREATE VIRTUAL TABLE
117870** statement in order to come into existance.  Eponymous virtual table
117871** instances always exist.  They cannot be DROP-ed.
117872**
117873** Any virtual table module for which xConnect and xCreate are the same
117874** method can have an eponymous virtual table instance.
117875*/
117876SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
117877  const sqlite3_module *pModule = pMod->pModule;
117878  Table *pTab;
117879  char *zErr = 0;
117880  int nName;
117881  int rc;
117882  sqlite3 *db = pParse->db;
117883  if( pMod->pEpoTab ) return 1;
117884  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
117885  nName = sqlite3Strlen30(pMod->zName) + 1;
117886  pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
117887  if( pTab==0 ) return 0;
117888  pMod->pEpoTab = pTab;
117889  pTab->zName = (char*)&pTab[1];
117890  memcpy(pTab->zName, pMod->zName, nName);
117891  pTab->nRef = 1;
117892  pTab->pSchema = db->aDb[0].pSchema;
117893  pTab->tabFlags |= TF_Virtual;
117894  pTab->nModuleArg = 0;
117895  pTab->iPKey = -1;
117896  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
117897  addModuleArgument(db, pTab, 0);
117898  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
117899  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
117900  if( rc ){
117901    sqlite3ErrorMsg(pParse, "%s", zErr);
117902    sqlite3DbFree(db, zErr);
117903    sqlite3VtabEponymousTableClear(db, pMod);
117904    return 0;
117905  }
117906  return 1;
117907}
117908
117909/*
117910** Erase the eponymous virtual table instance associated with
117911** virtual table module pMod, if it exists.
117912*/
117913SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
117914  Table *pTab = pMod->pEpoTab;
117915  if( pTab!=0 ){
117916    sqlite3DeleteColumnNames(db, pTab);
117917    sqlite3VtabClear(db, pTab);
117918    sqlite3DbFree(db, pTab);
117919    pMod->pEpoTab = 0;
117920  }
117921}
117922
117923/*
117924** Return the ON CONFLICT resolution mode in effect for the virtual
117925** table update operation currently in progress.
117926**
117927** The results of this routine are undefined unless it is called from
117928** within an xUpdate method.
117929*/
117930SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
117931  static const unsigned char aMap[] = {
117932    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
117933  };
117934#ifdef SQLITE_ENABLE_API_ARMOR
117935  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
117936#endif
117937  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
117938  assert( OE_Ignore==4 && OE_Replace==5 );
117939  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
117940  return (int)aMap[db->vtabOnConflict-1];
117941}
117942
117943/*
117944** Call from within the xCreate() or xConnect() methods to provide
117945** the SQLite core with additional information about the behavior
117946** of the virtual table being implemented.
117947*/
117948SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
117949  va_list ap;
117950  int rc = SQLITE_OK;
117951
117952#ifdef SQLITE_ENABLE_API_ARMOR
117953  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
117954#endif
117955  sqlite3_mutex_enter(db->mutex);
117956  va_start(ap, op);
117957  switch( op ){
117958    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
117959      VtabCtx *p = db->pVtabCtx;
117960      if( !p ){
117961        rc = SQLITE_MISUSE_BKPT;
117962      }else{
117963        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
117964        p->pVTable->bConstraint = (u8)va_arg(ap, int);
117965      }
117966      break;
117967    }
117968    default:
117969      rc = SQLITE_MISUSE_BKPT;
117970      break;
117971  }
117972  va_end(ap);
117973
117974  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
117975  sqlite3_mutex_leave(db->mutex);
117976  return rc;
117977}
117978
117979#endif /* SQLITE_OMIT_VIRTUALTABLE */
117980
117981/************** End of vtab.c ************************************************/
117982/************** Begin file wherecode.c ***************************************/
117983/*
117984** 2015-06-06
117985**
117986** The author disclaims copyright to this source code.  In place of
117987** a legal notice, here is a blessing:
117988**
117989**    May you do good and not evil.
117990**    May you find forgiveness for yourself and forgive others.
117991**    May you share freely, never taking more than you give.
117992**
117993*************************************************************************
117994** This module contains C code that generates VDBE code used to process
117995** the WHERE clause of SQL statements.
117996**
117997** This file was split off from where.c on 2015-06-06 in order to reduce the
117998** size of where.c and make it easier to edit.  This file contains the routines
117999** that actually generate the bulk of the WHERE loop code.  The original where.c
118000** file retains the code that does query planning and analysis.
118001*/
118002/* #include "sqliteInt.h" */
118003/************** Include whereInt.h in the middle of wherecode.c **************/
118004/************** Begin file whereInt.h ****************************************/
118005/*
118006** 2013-11-12
118007**
118008** The author disclaims copyright to this source code.  In place of
118009** a legal notice, here is a blessing:
118010**
118011**    May you do good and not evil.
118012**    May you find forgiveness for yourself and forgive others.
118013**    May you share freely, never taking more than you give.
118014**
118015*************************************************************************
118016**
118017** This file contains structure and macro definitions for the query
118018** planner logic in "where.c".  These definitions are broken out into
118019** a separate source file for easier editing.
118020*/
118021
118022/*
118023** Trace output macros
118024*/
118025#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
118026/***/ int sqlite3WhereTrace;
118027#endif
118028#if defined(SQLITE_DEBUG) \
118029    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
118030# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
118031# define WHERETRACE_ENABLED 1
118032#else
118033# define WHERETRACE(K,X)
118034#endif
118035
118036/* Forward references
118037*/
118038typedef struct WhereClause WhereClause;
118039typedef struct WhereMaskSet WhereMaskSet;
118040typedef struct WhereOrInfo WhereOrInfo;
118041typedef struct WhereAndInfo WhereAndInfo;
118042typedef struct WhereLevel WhereLevel;
118043typedef struct WhereLoop WhereLoop;
118044typedef struct WherePath WherePath;
118045typedef struct WhereTerm WhereTerm;
118046typedef struct WhereLoopBuilder WhereLoopBuilder;
118047typedef struct WhereScan WhereScan;
118048typedef struct WhereOrCost WhereOrCost;
118049typedef struct WhereOrSet WhereOrSet;
118050
118051/*
118052** This object contains information needed to implement a single nested
118053** loop in WHERE clause.
118054**
118055** Contrast this object with WhereLoop.  This object describes the
118056** implementation of the loop.  WhereLoop describes the algorithm.
118057** This object contains a pointer to the WhereLoop algorithm as one of
118058** its elements.
118059**
118060** The WhereInfo object contains a single instance of this object for
118061** each term in the FROM clause (which is to say, for each of the
118062** nested loops as implemented).  The order of WhereLevel objects determines
118063** the loop nested order, with WhereInfo.a[0] being the outer loop and
118064** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
118065*/
118066struct WhereLevel {
118067  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
118068  int iTabCur;          /* The VDBE cursor used to access the table */
118069  int iIdxCur;          /* The VDBE cursor used to access pIdx */
118070  int addrBrk;          /* Jump here to break out of the loop */
118071  int addrNxt;          /* Jump here to start the next IN combination */
118072  int addrSkip;         /* Jump here for next iteration of skip-scan */
118073  int addrCont;         /* Jump here to continue with the next loop cycle */
118074  int addrFirst;        /* First instruction of interior of the loop */
118075  int addrBody;         /* Beginning of the body of this loop */
118076  int iLikeRepCntr;     /* LIKE range processing counter register */
118077  int addrLikeRep;      /* LIKE range processing address */
118078  u8 iFrom;             /* Which entry in the FROM clause */
118079  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
118080  int p1, p2;           /* Operands of the opcode used to ends the loop */
118081  union {               /* Information that depends on pWLoop->wsFlags */
118082    struct {
118083      int nIn;              /* Number of entries in aInLoop[] */
118084      struct InLoop {
118085        int iCur;              /* The VDBE cursor used by this IN operator */
118086        int addrInTop;         /* Top of the IN loop */
118087        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
118088      } *aInLoop;           /* Information about each nested IN operator */
118089    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
118090    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
118091  } u;
118092  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
118093  Bitmask notReady;          /* FROM entries not usable at this level */
118094#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118095  int addrVisit;        /* Address at which row is visited */
118096#endif
118097};
118098
118099/*
118100** Each instance of this object represents an algorithm for evaluating one
118101** term of a join.  Every term of the FROM clause will have at least
118102** one corresponding WhereLoop object (unless INDEXED BY constraints
118103** prevent a query solution - which is an error) and many terms of the
118104** FROM clause will have multiple WhereLoop objects, each describing a
118105** potential way of implementing that FROM-clause term, together with
118106** dependencies and cost estimates for using the chosen algorithm.
118107**
118108** Query planning consists of building up a collection of these WhereLoop
118109** objects, then computing a particular sequence of WhereLoop objects, with
118110** one WhereLoop object per FROM clause term, that satisfy all dependencies
118111** and that minimize the overall cost.
118112*/
118113struct WhereLoop {
118114  Bitmask prereq;       /* Bitmask of other loops that must run first */
118115  Bitmask maskSelf;     /* Bitmask identifying table iTab */
118116#ifdef SQLITE_DEBUG
118117  char cId;             /* Symbolic ID of this loop for debugging use */
118118#endif
118119  u8 iTab;              /* Position in FROM clause of table for this loop */
118120  u8 iSortIdx;          /* Sorting index number.  0==None */
118121  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
118122  LogEst rRun;          /* Cost of running each loop */
118123  LogEst nOut;          /* Estimated number of output rows */
118124  union {
118125    struct {               /* Information for internal btree tables */
118126      u16 nEq;               /* Number of equality constraints */
118127      Index *pIndex;         /* Index used, or NULL */
118128    } btree;
118129    struct {               /* Information for virtual tables */
118130      int idxNum;            /* Index number */
118131      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
118132      i8 isOrdered;          /* True if satisfies ORDER BY */
118133      u16 omitMask;          /* Terms that may be omitted */
118134      char *idxStr;          /* Index identifier string */
118135    } vtab;
118136  } u;
118137  u32 wsFlags;          /* WHERE_* flags describing the plan */
118138  u16 nLTerm;           /* Number of entries in aLTerm[] */
118139  u16 nSkip;            /* Number of NULL aLTerm[] entries */
118140  /**** whereLoopXfer() copies fields above ***********************/
118141# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
118142  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
118143  WhereTerm **aLTerm;   /* WhereTerms used */
118144  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
118145  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
118146};
118147
118148/* This object holds the prerequisites and the cost of running a
118149** subquery on one operand of an OR operator in the WHERE clause.
118150** See WhereOrSet for additional information
118151*/
118152struct WhereOrCost {
118153  Bitmask prereq;     /* Prerequisites */
118154  LogEst rRun;        /* Cost of running this subquery */
118155  LogEst nOut;        /* Number of outputs for this subquery */
118156};
118157
118158/* The WhereOrSet object holds a set of possible WhereOrCosts that
118159** correspond to the subquery(s) of OR-clause processing.  Only the
118160** best N_OR_COST elements are retained.
118161*/
118162#define N_OR_COST 3
118163struct WhereOrSet {
118164  u16 n;                      /* Number of valid a[] entries */
118165  WhereOrCost a[N_OR_COST];   /* Set of best costs */
118166};
118167
118168/*
118169** Each instance of this object holds a sequence of WhereLoop objects
118170** that implement some or all of a query plan.
118171**
118172** Think of each WhereLoop object as a node in a graph with arcs
118173** showing dependencies and costs for travelling between nodes.  (That is
118174** not a completely accurate description because WhereLoop costs are a
118175** vector, not a scalar, and because dependencies are many-to-one, not
118176** one-to-one as are graph nodes.  But it is a useful visualization aid.)
118177** Then a WherePath object is a path through the graph that visits some
118178** or all of the WhereLoop objects once.
118179**
118180** The "solver" works by creating the N best WherePath objects of length
118181** 1.  Then using those as a basis to compute the N best WherePath objects
118182** of length 2.  And so forth until the length of WherePaths equals the
118183** number of nodes in the FROM clause.  The best (lowest cost) WherePath
118184** at the end is the chosen query plan.
118185*/
118186struct WherePath {
118187  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
118188  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
118189  LogEst nRow;          /* Estimated number of rows generated by this path */
118190  LogEst rCost;         /* Total cost of this path */
118191  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
118192  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
118193  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
118194};
118195
118196/*
118197** The query generator uses an array of instances of this structure to
118198** help it analyze the subexpressions of the WHERE clause.  Each WHERE
118199** clause subexpression is separated from the others by AND operators,
118200** usually, or sometimes subexpressions separated by OR.
118201**
118202** All WhereTerms are collected into a single WhereClause structure.
118203** The following identity holds:
118204**
118205**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
118206**
118207** When a term is of the form:
118208**
118209**              X <op> <expr>
118210**
118211** where X is a column name and <op> is one of certain operators,
118212** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
118213** cursor number and column number for X.  WhereTerm.eOperator records
118214** the <op> using a bitmask encoding defined by WO_xxx below.  The
118215** use of a bitmask encoding for the operator allows us to search
118216** quickly for terms that match any of several different operators.
118217**
118218** A WhereTerm might also be two or more subterms connected by OR:
118219**
118220**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
118221**
118222** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
118223** and the WhereTerm.u.pOrInfo field points to auxiliary information that
118224** is collected about the OR clause.
118225**
118226** If a term in the WHERE clause does not match either of the two previous
118227** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
118228** to the original subexpression content and wtFlags is set up appropriately
118229** but no other fields in the WhereTerm object are meaningful.
118230**
118231** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
118232** but they do so indirectly.  A single WhereMaskSet structure translates
118233** cursor number into bits and the translated bit is stored in the prereq
118234** fields.  The translation is used in order to maximize the number of
118235** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
118236** spread out over the non-negative integers.  For example, the cursor
118237** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
118238** translates these sparse cursor numbers into consecutive integers
118239** beginning with 0 in order to make the best possible use of the available
118240** bits in the Bitmask.  So, in the example above, the cursor numbers
118241** would be mapped into integers 0 through 7.
118242**
118243** The number of terms in a join is limited by the number of bits
118244** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
118245** is only able to process joins with 64 or fewer tables.
118246*/
118247struct WhereTerm {
118248  Expr *pExpr;            /* Pointer to the subexpression that is this term */
118249  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
118250  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
118251  union {
118252    int leftColumn;         /* Column number of X in "X <op> <expr>" */
118253    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
118254    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
118255  } u;
118256  LogEst truthProb;       /* Probability of truth for this expression */
118257  u16 eOperator;          /* A WO_xx value describing <op> */
118258  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
118259  u8 nChild;              /* Number of children that must disable us */
118260  WhereClause *pWC;       /* The clause this term is part of */
118261  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
118262  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
118263};
118264
118265/*
118266** Allowed values of WhereTerm.wtFlags
118267*/
118268#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
118269#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
118270#define TERM_CODED      0x04   /* This term is already coded */
118271#define TERM_COPIED     0x08   /* Has a child */
118272#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
118273#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
118274#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
118275#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118276#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
118277#else
118278#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
118279#endif
118280#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
118281#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
118282#define TERM_LIKE       0x400  /* The original LIKE operator */
118283#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
118284
118285/*
118286** An instance of the WhereScan object is used as an iterator for locating
118287** terms in the WHERE clause that are useful to the query planner.
118288*/
118289struct WhereScan {
118290  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
118291  WhereClause *pWC;          /* WhereClause currently being scanned */
118292  char *zCollName;           /* Required collating sequence, if not NULL */
118293  Expr *pIdxExpr;            /* Search for this index expression */
118294  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
118295  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
118296  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
118297  u32 opMask;                /* Acceptable operators */
118298  int k;                     /* Resume scanning at this->pWC->a[this->k] */
118299  int aiCur[11];             /* Cursors in the equivalence class */
118300  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
118301};
118302
118303/*
118304** An instance of the following structure holds all information about a
118305** WHERE clause.  Mostly this is a container for one or more WhereTerms.
118306**
118307** Explanation of pOuter:  For a WHERE clause of the form
118308**
118309**           a AND ((b AND c) OR (d AND e)) AND f
118310**
118311** There are separate WhereClause objects for the whole clause and for
118312** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
118313** subclauses points to the WhereClause object for the whole clause.
118314*/
118315struct WhereClause {
118316  WhereInfo *pWInfo;       /* WHERE clause processing context */
118317  WhereClause *pOuter;     /* Outer conjunction */
118318  u8 op;                   /* Split operator.  TK_AND or TK_OR */
118319  int nTerm;               /* Number of terms */
118320  int nSlot;               /* Number of entries in a[] */
118321  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
118322#if defined(SQLITE_SMALL_STACK)
118323  WhereTerm aStatic[1];    /* Initial static space for a[] */
118324#else
118325  WhereTerm aStatic[8];    /* Initial static space for a[] */
118326#endif
118327};
118328
118329/*
118330** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
118331** a dynamically allocated instance of the following structure.
118332*/
118333struct WhereOrInfo {
118334  WhereClause wc;          /* Decomposition into subterms */
118335  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
118336};
118337
118338/*
118339** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
118340** a dynamically allocated instance of the following structure.
118341*/
118342struct WhereAndInfo {
118343  WhereClause wc;          /* The subexpression broken out */
118344};
118345
118346/*
118347** An instance of the following structure keeps track of a mapping
118348** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
118349**
118350** The VDBE cursor numbers are small integers contained in
118351** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
118352** clause, the cursor numbers might not begin with 0 and they might
118353** contain gaps in the numbering sequence.  But we want to make maximum
118354** use of the bits in our bitmasks.  This structure provides a mapping
118355** from the sparse cursor numbers into consecutive integers beginning
118356** with 0.
118357**
118358** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
118359** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
118360**
118361** For example, if the WHERE clause expression used these VDBE
118362** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
118363** would map those cursor numbers into bits 0 through 5.
118364**
118365** Note that the mapping is not necessarily ordered.  In the example
118366** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
118367** 57->5, 73->4.  Or one of 719 other combinations might be used. It
118368** does not really matter.  What is important is that sparse cursor
118369** numbers all get mapped into bit numbers that begin with 0 and contain
118370** no gaps.
118371*/
118372struct WhereMaskSet {
118373  int n;                        /* Number of assigned cursor values */
118374  int ix[BMS];                  /* Cursor assigned to each bit */
118375};
118376
118377/*
118378** Initialize a WhereMaskSet object
118379*/
118380#define initMaskSet(P)  (P)->n=0
118381
118382/*
118383** This object is a convenience wrapper holding all information needed
118384** to construct WhereLoop objects for a particular query.
118385*/
118386struct WhereLoopBuilder {
118387  WhereInfo *pWInfo;        /* Information about this WHERE */
118388  WhereClause *pWC;         /* WHERE clause terms */
118389  ExprList *pOrderBy;       /* ORDER BY clause */
118390  WhereLoop *pNew;          /* Template WhereLoop */
118391  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
118392#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118393  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
118394  int nRecValid;            /* Number of valid fields currently in pRec */
118395#endif
118396};
118397
118398/*
118399** The WHERE clause processing routine has two halves.  The
118400** first part does the start of the WHERE loop and the second
118401** half does the tail of the WHERE loop.  An instance of
118402** this structure is returned by the first half and passed
118403** into the second half to give some continuity.
118404**
118405** An instance of this object holds the complete state of the query
118406** planner.
118407*/
118408struct WhereInfo {
118409  Parse *pParse;            /* Parsing and code generating context */
118410  SrcList *pTabList;        /* List of tables in the join */
118411  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
118412  ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
118413  WhereLoop *pLoops;        /* List of all WhereLoop objects */
118414  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
118415  LogEst nRowOut;           /* Estimated number of output rows */
118416  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
118417  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
118418  u8 sorted;                /* True if really sorted (not just grouped) */
118419  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
118420  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
118421  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
118422  u8 nLevel;                /* Number of nested loop */
118423  int iTop;                 /* The very beginning of the WHERE loop */
118424  int iContinue;            /* Jump here to continue with next record */
118425  int iBreak;               /* Jump here to break out of the loop */
118426  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
118427  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
118428  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
118429  WhereClause sWC;          /* Decomposition of the WHERE clause */
118430  WhereLevel a[1];          /* Information about each nest loop in WHERE */
118431};
118432
118433/*
118434** Private interfaces - callable only by other where.c routines.
118435**
118436** where.c:
118437*/
118438SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
118439SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
118440  WhereClause *pWC,     /* The WHERE clause to be searched */
118441  int iCur,             /* Cursor number of LHS */
118442  int iColumn,          /* Column number of LHS */
118443  Bitmask notReady,     /* RHS must not overlap with this mask */
118444  u32 op,               /* Mask of WO_xx values describing operator */
118445  Index *pIdx           /* Must be compatible with this index, if not NULL */
118446);
118447
118448/* wherecode.c: */
118449#ifndef SQLITE_OMIT_EXPLAIN
118450SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
118451  Parse *pParse,                  /* Parse context */
118452  SrcList *pTabList,              /* Table list this loop refers to */
118453  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
118454  int iLevel,                     /* Value for "level" column of output */
118455  int iFrom,                      /* Value for "from" column of output */
118456  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
118457);
118458#else
118459# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
118460#endif /* SQLITE_OMIT_EXPLAIN */
118461#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118462SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
118463  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
118464  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
118465  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
118466  int addrExplain                 /* Address of OP_Explain (or 0) */
118467);
118468#else
118469# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
118470#endif
118471SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
118472  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
118473  int iLevel,          /* Which level of pWInfo->a[] should be coded */
118474  Bitmask notReady     /* Which tables are currently available */
118475);
118476
118477/* whereexpr.c: */
118478SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
118479SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
118480SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
118481SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
118482SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
118483SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
118484SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
118485
118486
118487
118488
118489
118490/*
118491** Bitmasks for the operators on WhereTerm objects.  These are all
118492** operators that are of interest to the query planner.  An
118493** OR-ed combination of these values can be used when searching for
118494** particular WhereTerms within a WhereClause.
118495*/
118496#define WO_IN     0x0001
118497#define WO_EQ     0x0002
118498#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
118499#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
118500#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
118501#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
118502#define WO_MATCH  0x0040
118503#define WO_IS     0x0080
118504#define WO_ISNULL 0x0100
118505#define WO_OR     0x0200       /* Two or more OR-connected terms */
118506#define WO_AND    0x0400       /* Two or more AND-connected terms */
118507#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
118508#define WO_NOOP   0x1000       /* This term does not restrict search space */
118509
118510#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
118511#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
118512
118513/*
118514** These are definitions of bits in the WhereLoop.wsFlags field.
118515** The particular combination of bits in each WhereLoop help to
118516** determine the algorithm that WhereLoop represents.
118517*/
118518#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
118519#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
118520#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
118521#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
118522#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
118523#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
118524#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
118525#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
118526#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
118527#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
118528#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
118529#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
118530#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
118531#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
118532#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
118533#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
118534#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
118535#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
118536#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
118537
118538/************** End of whereInt.h ********************************************/
118539/************** Continuing where we left off in wherecode.c ******************/
118540
118541#ifndef SQLITE_OMIT_EXPLAIN
118542/*
118543** This routine is a helper for explainIndexRange() below
118544**
118545** pStr holds the text of an expression that we are building up one term
118546** at a time.  This routine adds a new term to the end of the expression.
118547** Terms are separated by AND so add the "AND" text for second and subsequent
118548** terms only.
118549*/
118550static void explainAppendTerm(
118551  StrAccum *pStr,             /* The text expression being built */
118552  int iTerm,                  /* Index of this term.  First is zero */
118553  const char *zColumn,        /* Name of the column */
118554  const char *zOp             /* Name of the operator */
118555){
118556  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118557  sqlite3StrAccumAppendAll(pStr, zColumn);
118558  sqlite3StrAccumAppend(pStr, zOp, 1);
118559  sqlite3StrAccumAppend(pStr, "?", 1);
118560}
118561
118562/*
118563** Return the name of the i-th column of the pIdx index.
118564*/
118565static const char *explainIndexColumnName(Index *pIdx, int i){
118566  i = pIdx->aiColumn[i];
118567  if( i==XN_EXPR ) return "<expr>";
118568  if( i==XN_ROWID ) return "rowid";
118569  return pIdx->pTable->aCol[i].zName;
118570}
118571
118572/*
118573** Argument pLevel describes a strategy for scanning table pTab. This
118574** function appends text to pStr that describes the subset of table
118575** rows scanned by the strategy in the form of an SQL expression.
118576**
118577** For example, if the query:
118578**
118579**   SELECT * FROM t1 WHERE a=1 AND b>2;
118580**
118581** is run and there is an index on (a, b), then this function returns a
118582** string similar to:
118583**
118584**   "a=? AND b>?"
118585*/
118586static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
118587  Index *pIndex = pLoop->u.btree.pIndex;
118588  u16 nEq = pLoop->u.btree.nEq;
118589  u16 nSkip = pLoop->nSkip;
118590  int i, j;
118591
118592  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
118593  sqlite3StrAccumAppend(pStr, " (", 2);
118594  for(i=0; i<nEq; i++){
118595    const char *z = explainIndexColumnName(pIndex, i);
118596    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118597    sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z);
118598  }
118599
118600  j = i;
118601  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
118602    const char *z = explainIndexColumnName(pIndex, i);
118603    explainAppendTerm(pStr, i++, z, ">");
118604  }
118605  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
118606    const char *z = explainIndexColumnName(pIndex, j);
118607    explainAppendTerm(pStr, i, z, "<");
118608  }
118609  sqlite3StrAccumAppend(pStr, ")", 1);
118610}
118611
118612/*
118613** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
118614** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
118615** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
118616** is added to the output to describe the table scan strategy in pLevel.
118617**
118618** If an OP_Explain opcode is added to the VM, its address is returned.
118619** Otherwise, if no OP_Explain is coded, zero is returned.
118620*/
118621SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
118622  Parse *pParse,                  /* Parse context */
118623  SrcList *pTabList,              /* Table list this loop refers to */
118624  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
118625  int iLevel,                     /* Value for "level" column of output */
118626  int iFrom,                      /* Value for "from" column of output */
118627  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
118628){
118629  int ret = 0;
118630#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
118631  if( pParse->explain==2 )
118632#endif
118633  {
118634    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
118635    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
118636    sqlite3 *db = pParse->db;     /* Database handle */
118637    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
118638    int isSearch;                 /* True for a SEARCH. False for SCAN. */
118639    WhereLoop *pLoop;             /* The controlling WhereLoop object */
118640    u32 flags;                    /* Flags that describe this loop */
118641    char *zMsg;                   /* Text to add to EQP output */
118642    StrAccum str;                 /* EQP output string */
118643    char zBuf[100];               /* Initial space for EQP output string */
118644
118645    pLoop = pLevel->pWLoop;
118646    flags = pLoop->wsFlags;
118647    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
118648
118649    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
118650            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
118651            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
118652
118653    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
118654    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
118655    if( pItem->pSelect ){
118656      sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
118657    }else{
118658      sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
118659    }
118660
118661    if( pItem->zAlias ){
118662      sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
118663    }
118664    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
118665      const char *zFmt = 0;
118666      Index *pIdx;
118667
118668      assert( pLoop->u.btree.pIndex!=0 );
118669      pIdx = pLoop->u.btree.pIndex;
118670      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
118671      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
118672        if( isSearch ){
118673          zFmt = "PRIMARY KEY";
118674        }
118675      }else if( flags & WHERE_PARTIALIDX ){
118676        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
118677      }else if( flags & WHERE_AUTO_INDEX ){
118678        zFmt = "AUTOMATIC COVERING INDEX";
118679      }else if( flags & WHERE_IDX_ONLY ){
118680        zFmt = "COVERING INDEX %s";
118681      }else{
118682        zFmt = "INDEX %s";
118683      }
118684      if( zFmt ){
118685        sqlite3StrAccumAppend(&str, " USING ", 7);
118686        sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
118687        explainIndexRange(&str, pLoop);
118688      }
118689    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
118690      const char *zRangeOp;
118691      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
118692        zRangeOp = "=";
118693      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
118694        zRangeOp = ">? AND rowid<";
118695      }else if( flags&WHERE_BTM_LIMIT ){
118696        zRangeOp = ">";
118697      }else{
118698        assert( flags&WHERE_TOP_LIMIT);
118699        zRangeOp = "<";
118700      }
118701      sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
118702    }
118703#ifndef SQLITE_OMIT_VIRTUALTABLE
118704    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
118705      sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
118706                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
118707    }
118708#endif
118709#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
118710    if( pLoop->nOut>=10 ){
118711      sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
118712    }else{
118713      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
118714    }
118715#endif
118716    zMsg = sqlite3StrAccumFinish(&str);
118717    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
118718  }
118719  return ret;
118720}
118721#endif /* SQLITE_OMIT_EXPLAIN */
118722
118723#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118724/*
118725** Configure the VM passed as the first argument with an
118726** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
118727** implement level pLvl. Argument pSrclist is a pointer to the FROM
118728** clause that the scan reads data from.
118729**
118730** If argument addrExplain is not 0, it must be the address of an
118731** OP_Explain instruction that describes the same loop.
118732*/
118733SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
118734  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
118735  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
118736  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
118737  int addrExplain                 /* Address of OP_Explain (or 0) */
118738){
118739  const char *zObj = 0;
118740  WhereLoop *pLoop = pLvl->pWLoop;
118741  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
118742    zObj = pLoop->u.btree.pIndex->zName;
118743  }else{
118744    zObj = pSrclist->a[pLvl->iFrom].zName;
118745  }
118746  sqlite3VdbeScanStatus(
118747      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
118748  );
118749}
118750#endif
118751
118752
118753/*
118754** Disable a term in the WHERE clause.  Except, do not disable the term
118755** if it controls a LEFT OUTER JOIN and it did not originate in the ON
118756** or USING clause of that join.
118757**
118758** Consider the term t2.z='ok' in the following queries:
118759**
118760**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
118761**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
118762**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
118763**
118764** The t2.z='ok' is disabled in the in (2) because it originates
118765** in the ON clause.  The term is disabled in (3) because it is not part
118766** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
118767**
118768** Disabling a term causes that term to not be tested in the inner loop
118769** of the join.  Disabling is an optimization.  When terms are satisfied
118770** by indices, we disable them to prevent redundant tests in the inner
118771** loop.  We would get the correct results if nothing were ever disabled,
118772** but joins might run a little slower.  The trick is to disable as much
118773** as we can without disabling too much.  If we disabled in (1), we'd get
118774** the wrong answer.  See ticket #813.
118775**
118776** If all the children of a term are disabled, then that term is also
118777** automatically disabled.  In this way, terms get disabled if derived
118778** virtual terms are tested first.  For example:
118779**
118780**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
118781**      \___________/     \______/     \_____/
118782**         parent          child1       child2
118783**
118784** Only the parent term was in the original WHERE clause.  The child1
118785** and child2 terms were added by the LIKE optimization.  If both of
118786** the virtual child terms are valid, then testing of the parent can be
118787** skipped.
118788**
118789** Usually the parent term is marked as TERM_CODED.  But if the parent
118790** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
118791** The TERM_LIKECOND marking indicates that the term should be coded inside
118792** a conditional such that is only evaluated on the second pass of a
118793** LIKE-optimization loop, when scanning BLOBs instead of strings.
118794*/
118795static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
118796  int nLoop = 0;
118797  while( pTerm
118798      && (pTerm->wtFlags & TERM_CODED)==0
118799      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
118800      && (pLevel->notReady & pTerm->prereqAll)==0
118801  ){
118802    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
118803      pTerm->wtFlags |= TERM_LIKECOND;
118804    }else{
118805      pTerm->wtFlags |= TERM_CODED;
118806    }
118807    if( pTerm->iParent<0 ) break;
118808    pTerm = &pTerm->pWC->a[pTerm->iParent];
118809    pTerm->nChild--;
118810    if( pTerm->nChild!=0 ) break;
118811    nLoop++;
118812  }
118813}
118814
118815/*
118816** Code an OP_Affinity opcode to apply the column affinity string zAff
118817** to the n registers starting at base.
118818**
118819** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
118820** beginning and end of zAff are ignored.  If all entries in zAff are
118821** SQLITE_AFF_BLOB, then no code gets generated.
118822**
118823** This routine makes its own copy of zAff so that the caller is free
118824** to modify zAff after this routine returns.
118825*/
118826static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
118827  Vdbe *v = pParse->pVdbe;
118828  if( zAff==0 ){
118829    assert( pParse->db->mallocFailed );
118830    return;
118831  }
118832  assert( v!=0 );
118833
118834  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
118835  ** and end of the affinity string.
118836  */
118837  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
118838    n--;
118839    base++;
118840    zAff++;
118841  }
118842  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
118843    n--;
118844  }
118845
118846  /* Code the OP_Affinity opcode if there is anything left to do. */
118847  if( n>0 ){
118848    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
118849    sqlite3VdbeChangeP4(v, -1, zAff, n);
118850    sqlite3ExprCacheAffinityChange(pParse, base, n);
118851  }
118852}
118853
118854
118855/*
118856** Generate code for a single equality term of the WHERE clause.  An equality
118857** term can be either X=expr or X IN (...).   pTerm is the term to be
118858** coded.
118859**
118860** The current value for the constraint is left in register iReg.
118861**
118862** For a constraint of the form X=expr, the expression is evaluated and its
118863** result is left on the stack.  For constraints of the form X IN (...)
118864** this routine sets up a loop that will iterate over all values of X.
118865*/
118866static int codeEqualityTerm(
118867  Parse *pParse,      /* The parsing context */
118868  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
118869  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
118870  int iEq,            /* Index of the equality term within this level */
118871  int bRev,           /* True for reverse-order IN operations */
118872  int iTarget         /* Attempt to leave results in this register */
118873){
118874  Expr *pX = pTerm->pExpr;
118875  Vdbe *v = pParse->pVdbe;
118876  int iReg;                  /* Register holding results */
118877
118878  assert( iTarget>0 );
118879  if( pX->op==TK_EQ || pX->op==TK_IS ){
118880    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
118881  }else if( pX->op==TK_ISNULL ){
118882    iReg = iTarget;
118883    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
118884#ifndef SQLITE_OMIT_SUBQUERY
118885  }else{
118886    int eType;
118887    int iTab;
118888    struct InLoop *pIn;
118889    WhereLoop *pLoop = pLevel->pWLoop;
118890
118891    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
118892      && pLoop->u.btree.pIndex!=0
118893      && pLoop->u.btree.pIndex->aSortOrder[iEq]
118894    ){
118895      testcase( iEq==0 );
118896      testcase( bRev );
118897      bRev = !bRev;
118898    }
118899    assert( pX->op==TK_IN );
118900    iReg = iTarget;
118901    eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
118902    if( eType==IN_INDEX_INDEX_DESC ){
118903      testcase( bRev );
118904      bRev = !bRev;
118905    }
118906    iTab = pX->iTable;
118907    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
118908    VdbeCoverageIf(v, bRev);
118909    VdbeCoverageIf(v, !bRev);
118910    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
118911    pLoop->wsFlags |= WHERE_IN_ABLE;
118912    if( pLevel->u.in.nIn==0 ){
118913      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
118914    }
118915    pLevel->u.in.nIn++;
118916    pLevel->u.in.aInLoop =
118917       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
118918                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
118919    pIn = pLevel->u.in.aInLoop;
118920    if( pIn ){
118921      pIn += pLevel->u.in.nIn - 1;
118922      pIn->iCur = iTab;
118923      if( eType==IN_INDEX_ROWID ){
118924        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
118925      }else{
118926        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
118927      }
118928      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
118929      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
118930    }else{
118931      pLevel->u.in.nIn = 0;
118932    }
118933#endif
118934  }
118935  disableTerm(pLevel, pTerm);
118936  return iReg;
118937}
118938
118939/*
118940** Generate code that will evaluate all == and IN constraints for an
118941** index scan.
118942**
118943** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
118944** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
118945** The index has as many as three equality constraints, but in this
118946** example, the third "c" value is an inequality.  So only two
118947** constraints are coded.  This routine will generate code to evaluate
118948** a==5 and b IN (1,2,3).  The current values for a and b will be stored
118949** in consecutive registers and the index of the first register is returned.
118950**
118951** In the example above nEq==2.  But this subroutine works for any value
118952** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
118953** The only thing it does is allocate the pLevel->iMem memory cell and
118954** compute the affinity string.
118955**
118956** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
118957** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
118958** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
118959** occurs after the nEq quality constraints.
118960**
118961** This routine allocates a range of nEq+nExtraReg memory cells and returns
118962** the index of the first memory cell in that range. The code that
118963** calls this routine will use that memory range to store keys for
118964** start and termination conditions of the loop.
118965** key value of the loop.  If one or more IN operators appear, then
118966** this routine allocates an additional nEq memory cells for internal
118967** use.
118968**
118969** Before returning, *pzAff is set to point to a buffer containing a
118970** copy of the column affinity string of the index allocated using
118971** sqlite3DbMalloc(). Except, entries in the copy of the string associated
118972** with equality constraints that use BLOB or NONE affinity are set to
118973** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
118974**
118975**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
118976**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
118977**
118978** In the example above, the index on t1(a) has TEXT affinity. But since
118979** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
118980** no conversion should be attempted before using a t2.b value as part of
118981** a key to search the index. Hence the first byte in the returned affinity
118982** string in this example would be set to SQLITE_AFF_BLOB.
118983*/
118984static int codeAllEqualityTerms(
118985  Parse *pParse,        /* Parsing context */
118986  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
118987  int bRev,             /* Reverse the order of IN operators */
118988  int nExtraReg,        /* Number of extra registers to allocate */
118989  char **pzAff          /* OUT: Set to point to affinity string */
118990){
118991  u16 nEq;                      /* The number of == or IN constraints to code */
118992  u16 nSkip;                    /* Number of left-most columns to skip */
118993  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
118994  Index *pIdx;                  /* The index being used for this loop */
118995  WhereTerm *pTerm;             /* A single constraint term */
118996  WhereLoop *pLoop;             /* The WhereLoop object */
118997  int j;                        /* Loop counter */
118998  int regBase;                  /* Base register */
118999  int nReg;                     /* Number of registers to allocate */
119000  char *zAff;                   /* Affinity string to return */
119001
119002  /* This module is only called on query plans that use an index. */
119003  pLoop = pLevel->pWLoop;
119004  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
119005  nEq = pLoop->u.btree.nEq;
119006  nSkip = pLoop->nSkip;
119007  pIdx = pLoop->u.btree.pIndex;
119008  assert( pIdx!=0 );
119009
119010  /* Figure out how many memory cells we will need then allocate them.
119011  */
119012  regBase = pParse->nMem + 1;
119013  nReg = pLoop->u.btree.nEq + nExtraReg;
119014  pParse->nMem += nReg;
119015
119016  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
119017  if( !zAff ){
119018    pParse->db->mallocFailed = 1;
119019  }
119020
119021  if( nSkip ){
119022    int iIdxCur = pLevel->iIdxCur;
119023    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
119024    VdbeCoverageIf(v, bRev==0);
119025    VdbeCoverageIf(v, bRev!=0);
119026    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
119027    j = sqlite3VdbeAddOp0(v, OP_Goto);
119028    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
119029                            iIdxCur, 0, regBase, nSkip);
119030    VdbeCoverageIf(v, bRev==0);
119031    VdbeCoverageIf(v, bRev!=0);
119032    sqlite3VdbeJumpHere(v, j);
119033    for(j=0; j<nSkip; j++){
119034      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
119035      testcase( pIdx->aiColumn[j]==XN_EXPR );
119036      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
119037    }
119038  }
119039
119040  /* Evaluate the equality constraints
119041  */
119042  assert( zAff==0 || (int)strlen(zAff)>=nEq );
119043  for(j=nSkip; j<nEq; j++){
119044    int r1;
119045    pTerm = pLoop->aLTerm[j];
119046    assert( pTerm!=0 );
119047    /* The following testcase is true for indices with redundant columns.
119048    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
119049    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
119050    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119051    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
119052    if( r1!=regBase+j ){
119053      if( nReg==1 ){
119054        sqlite3ReleaseTempReg(pParse, regBase);
119055        regBase = r1;
119056      }else{
119057        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
119058      }
119059    }
119060    testcase( pTerm->eOperator & WO_ISNULL );
119061    testcase( pTerm->eOperator & WO_IN );
119062    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
119063      Expr *pRight = pTerm->pExpr->pRight;
119064      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
119065        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
119066        VdbeCoverage(v);
119067      }
119068      if( zAff ){
119069        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
119070          zAff[j] = SQLITE_AFF_BLOB;
119071        }
119072        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
119073          zAff[j] = SQLITE_AFF_BLOB;
119074        }
119075      }
119076    }
119077  }
119078  *pzAff = zAff;
119079  return regBase;
119080}
119081
119082/*
119083** If the most recently coded instruction is a constant range contraint
119084** that originated from the LIKE optimization, then change the P3 to be
119085** pLoop->iLikeRepCntr and set P5.
119086**
119087** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
119088** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
119089** scan loop run twice, once for strings and a second time for BLOBs.
119090** The OP_String opcodes on the second pass convert the upper and lower
119091** bound string contants to blobs.  This routine makes the necessary changes
119092** to the OP_String opcodes for that to happen.
119093*/
119094static void whereLikeOptimizationStringFixup(
119095  Vdbe *v,                /* prepared statement under construction */
119096  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
119097  WhereTerm *pTerm        /* The upper or lower bound just coded */
119098){
119099  if( pTerm->wtFlags & TERM_LIKEOPT ){
119100    VdbeOp *pOp;
119101    assert( pLevel->iLikeRepCntr>0 );
119102    pOp = sqlite3VdbeGetOp(v, -1);
119103    assert( pOp!=0 );
119104    assert( pOp->opcode==OP_String8
119105            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
119106    pOp->p3 = pLevel->iLikeRepCntr;
119107    pOp->p5 = 1;
119108  }
119109}
119110
119111
119112/*
119113** Generate code for the start of the iLevel-th loop in the WHERE clause
119114** implementation described by pWInfo.
119115*/
119116SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
119117  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
119118  int iLevel,          /* Which level of pWInfo->a[] should be coded */
119119  Bitmask notReady     /* Which tables are currently available */
119120){
119121  int j, k;            /* Loop counters */
119122  int iCur;            /* The VDBE cursor for the table */
119123  int addrNxt;         /* Where to jump to continue with the next IN case */
119124  int omitTable;       /* True if we use the index only */
119125  int bRev;            /* True if we need to scan in reverse order */
119126  WhereLevel *pLevel;  /* The where level to be coded */
119127  WhereLoop *pLoop;    /* The WhereLoop object being coded */
119128  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
119129  WhereTerm *pTerm;               /* A WHERE clause term */
119130  Parse *pParse;                  /* Parsing context */
119131  sqlite3 *db;                    /* Database connection */
119132  Vdbe *v;                        /* The prepared stmt under constructions */
119133  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
119134  int addrBrk;                    /* Jump here to break out of the loop */
119135  int addrCont;                   /* Jump here to continue with next cycle */
119136  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
119137  int iReleaseReg = 0;      /* Temp register to free before returning */
119138
119139  pParse = pWInfo->pParse;
119140  v = pParse->pVdbe;
119141  pWC = &pWInfo->sWC;
119142  db = pParse->db;
119143  pLevel = &pWInfo->a[iLevel];
119144  pLoop = pLevel->pWLoop;
119145  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
119146  iCur = pTabItem->iCursor;
119147  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
119148  bRev = (pWInfo->revMask>>iLevel)&1;
119149  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
119150           && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
119151  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
119152
119153  /* Create labels for the "break" and "continue" instructions
119154  ** for the current loop.  Jump to addrBrk to break out of a loop.
119155  ** Jump to cont to go immediately to the next iteration of the
119156  ** loop.
119157  **
119158  ** When there is an IN operator, we also have a "addrNxt" label that
119159  ** means to continue with the next IN value combination.  When
119160  ** there are no IN operators in the constraints, the "addrNxt" label
119161  ** is the same as "addrBrk".
119162  */
119163  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
119164  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
119165
119166  /* If this is the right table of a LEFT OUTER JOIN, allocate and
119167  ** initialize a memory cell that records if this table matches any
119168  ** row of the left table of the join.
119169  */
119170  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
119171    pLevel->iLeftJoin = ++pParse->nMem;
119172    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
119173    VdbeComment((v, "init LEFT JOIN no-match flag"));
119174  }
119175
119176  /* Special case of a FROM clause subquery implemented as a co-routine */
119177  if( pTabItem->fg.viaCoroutine ){
119178    int regYield = pTabItem->regReturn;
119179    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
119180    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
119181    VdbeCoverage(v);
119182    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
119183    pLevel->op = OP_Goto;
119184  }else
119185
119186#ifndef SQLITE_OMIT_VIRTUALTABLE
119187  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
119188    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
119189    **          to access the data.
119190    */
119191    int iReg;   /* P3 Value for OP_VFilter */
119192    int addrNotFound;
119193    int nConstraint = pLoop->nLTerm;
119194
119195    sqlite3ExprCachePush(pParse);
119196    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
119197    addrNotFound = pLevel->addrBrk;
119198    for(j=0; j<nConstraint; j++){
119199      int iTarget = iReg+j+2;
119200      pTerm = pLoop->aLTerm[j];
119201      if( pTerm==0 ) continue;
119202      if( pTerm->eOperator & WO_IN ){
119203        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
119204        addrNotFound = pLevel->addrNxt;
119205      }else{
119206        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
119207      }
119208    }
119209    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
119210    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
119211    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
119212                      pLoop->u.vtab.idxStr,
119213                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
119214    VdbeCoverage(v);
119215    pLoop->u.vtab.needFree = 0;
119216    for(j=0; j<nConstraint && j<16; j++){
119217      if( (pLoop->u.vtab.omitMask>>j)&1 ){
119218        disableTerm(pLevel, pLoop->aLTerm[j]);
119219      }
119220    }
119221    pLevel->p1 = iCur;
119222    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
119223    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119224    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
119225    sqlite3ExprCachePop(pParse);
119226  }else
119227#endif /* SQLITE_OMIT_VIRTUALTABLE */
119228
119229  if( (pLoop->wsFlags & WHERE_IPK)!=0
119230   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
119231  ){
119232    /* Case 2:  We can directly reference a single row using an
119233    **          equality comparison against the ROWID field.  Or
119234    **          we reference multiple rows using a "rowid IN (...)"
119235    **          construct.
119236    */
119237    assert( pLoop->u.btree.nEq==1 );
119238    pTerm = pLoop->aLTerm[0];
119239    assert( pTerm!=0 );
119240    assert( pTerm->pExpr!=0 );
119241    assert( omitTable==0 );
119242    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119243    iReleaseReg = ++pParse->nMem;
119244    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
119245    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
119246    addrNxt = pLevel->addrNxt;
119247    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
119248    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
119249    VdbeCoverage(v);
119250    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
119251    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119252    VdbeComment((v, "pk"));
119253    pLevel->op = OP_Noop;
119254  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
119255         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
119256  ){
119257    /* Case 3:  We have an inequality comparison against the ROWID field.
119258    */
119259    int testOp = OP_Noop;
119260    int start;
119261    int memEndValue = 0;
119262    WhereTerm *pStart, *pEnd;
119263
119264    assert( omitTable==0 );
119265    j = 0;
119266    pStart = pEnd = 0;
119267    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
119268    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
119269    assert( pStart!=0 || pEnd!=0 );
119270    if( bRev ){
119271      pTerm = pStart;
119272      pStart = pEnd;
119273      pEnd = pTerm;
119274    }
119275    if( pStart ){
119276      Expr *pX;             /* The expression that defines the start bound */
119277      int r1, rTemp;        /* Registers for holding the start boundary */
119278
119279      /* The following constant maps TK_xx codes into corresponding
119280      ** seek opcodes.  It depends on a particular ordering of TK_xx
119281      */
119282      const u8 aMoveOp[] = {
119283           /* TK_GT */  OP_SeekGT,
119284           /* TK_LE */  OP_SeekLE,
119285           /* TK_LT */  OP_SeekLT,
119286           /* TK_GE */  OP_SeekGE
119287      };
119288      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
119289      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
119290      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
119291
119292      assert( (pStart->wtFlags & TERM_VNULL)==0 );
119293      testcase( pStart->wtFlags & TERM_VIRTUAL );
119294      pX = pStart->pExpr;
119295      assert( pX!=0 );
119296      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
119297      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
119298      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
119299      VdbeComment((v, "pk"));
119300      VdbeCoverageIf(v, pX->op==TK_GT);
119301      VdbeCoverageIf(v, pX->op==TK_LE);
119302      VdbeCoverageIf(v, pX->op==TK_LT);
119303      VdbeCoverageIf(v, pX->op==TK_GE);
119304      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
119305      sqlite3ReleaseTempReg(pParse, rTemp);
119306      disableTerm(pLevel, pStart);
119307    }else{
119308      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
119309      VdbeCoverageIf(v, bRev==0);
119310      VdbeCoverageIf(v, bRev!=0);
119311    }
119312    if( pEnd ){
119313      Expr *pX;
119314      pX = pEnd->pExpr;
119315      assert( pX!=0 );
119316      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
119317      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
119318      testcase( pEnd->wtFlags & TERM_VIRTUAL );
119319      memEndValue = ++pParse->nMem;
119320      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
119321      if( pX->op==TK_LT || pX->op==TK_GT ){
119322        testOp = bRev ? OP_Le : OP_Ge;
119323      }else{
119324        testOp = bRev ? OP_Lt : OP_Gt;
119325      }
119326      disableTerm(pLevel, pEnd);
119327    }
119328    start = sqlite3VdbeCurrentAddr(v);
119329    pLevel->op = bRev ? OP_Prev : OP_Next;
119330    pLevel->p1 = iCur;
119331    pLevel->p2 = start;
119332    assert( pLevel->p5==0 );
119333    if( testOp!=OP_Noop ){
119334      iRowidReg = ++pParse->nMem;
119335      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
119336      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119337      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
119338      VdbeCoverageIf(v, testOp==OP_Le);
119339      VdbeCoverageIf(v, testOp==OP_Lt);
119340      VdbeCoverageIf(v, testOp==OP_Ge);
119341      VdbeCoverageIf(v, testOp==OP_Gt);
119342      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
119343    }
119344  }else if( pLoop->wsFlags & WHERE_INDEXED ){
119345    /* Case 4: A scan using an index.
119346    **
119347    **         The WHERE clause may contain zero or more equality
119348    **         terms ("==" or "IN" operators) that refer to the N
119349    **         left-most columns of the index. It may also contain
119350    **         inequality constraints (>, <, >= or <=) on the indexed
119351    **         column that immediately follows the N equalities. Only
119352    **         the right-most column can be an inequality - the rest must
119353    **         use the "==" and "IN" operators. For example, if the
119354    **         index is on (x,y,z), then the following clauses are all
119355    **         optimized:
119356    **
119357    **            x=5
119358    **            x=5 AND y=10
119359    **            x=5 AND y<10
119360    **            x=5 AND y>5 AND y<10
119361    **            x=5 AND y=5 AND z<=10
119362    **
119363    **         The z<10 term of the following cannot be used, only
119364    **         the x=5 term:
119365    **
119366    **            x=5 AND z<10
119367    **
119368    **         N may be zero if there are inequality constraints.
119369    **         If there are no inequality constraints, then N is at
119370    **         least one.
119371    **
119372    **         This case is also used when there are no WHERE clause
119373    **         constraints but an index is selected anyway, in order
119374    **         to force the output order to conform to an ORDER BY.
119375    */
119376    static const u8 aStartOp[] = {
119377      0,
119378      0,
119379      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
119380      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
119381      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
119382      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
119383      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
119384      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
119385    };
119386    static const u8 aEndOp[] = {
119387      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
119388      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
119389      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
119390      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
119391    };
119392    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
119393    int regBase;                 /* Base register holding constraint values */
119394    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
119395    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
119396    int startEq;                 /* True if range start uses ==, >= or <= */
119397    int endEq;                   /* True if range end uses ==, >= or <= */
119398    int start_constraints;       /* Start of range is constrained */
119399    int nConstraint;             /* Number of constraint terms */
119400    Index *pIdx;                 /* The index we will be using */
119401    int iIdxCur;                 /* The VDBE cursor for the index */
119402    int nExtraReg = 0;           /* Number of extra registers needed */
119403    int op;                      /* Instruction opcode */
119404    char *zStartAff;             /* Affinity for start of range constraint */
119405    char cEndAff = 0;            /* Affinity for end of range constraint */
119406    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
119407    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
119408
119409    pIdx = pLoop->u.btree.pIndex;
119410    iIdxCur = pLevel->iIdxCur;
119411    assert( nEq>=pLoop->nSkip );
119412
119413    /* If this loop satisfies a sort order (pOrderBy) request that
119414    ** was passed to this function to implement a "SELECT min(x) ..."
119415    ** query, then the caller will only allow the loop to run for
119416    ** a single iteration. This means that the first row returned
119417    ** should not have a NULL value stored in 'x'. If column 'x' is
119418    ** the first one after the nEq equality constraints in the index,
119419    ** this requires some special handling.
119420    */
119421    assert( pWInfo->pOrderBy==0
119422         || pWInfo->pOrderBy->nExpr==1
119423         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
119424    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
119425     && pWInfo->nOBSat>0
119426     && (pIdx->nKeyCol>nEq)
119427    ){
119428      assert( pLoop->nSkip==0 );
119429      bSeekPastNull = 1;
119430      nExtraReg = 1;
119431    }
119432
119433    /* Find any inequality constraint terms for the start and end
119434    ** of the range.
119435    */
119436    j = nEq;
119437    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
119438      pRangeStart = pLoop->aLTerm[j++];
119439      nExtraReg = 1;
119440      /* Like optimization range constraints always occur in pairs */
119441      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
119442              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
119443    }
119444    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
119445      pRangeEnd = pLoop->aLTerm[j++];
119446      nExtraReg = 1;
119447      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
119448        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
119449        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
119450        pLevel->iLikeRepCntr = ++pParse->nMem;
119451        testcase( bRev );
119452        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
119453        sqlite3VdbeAddOp2(v, OP_Integer,
119454                          bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
119455                          pLevel->iLikeRepCntr);
119456        VdbeComment((v, "LIKE loop counter"));
119457        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
119458      }
119459      if( pRangeStart==0
119460       && (j = pIdx->aiColumn[nEq])>=0
119461       && pIdx->pTable->aCol[j].notNull==0
119462      ){
119463        bSeekPastNull = 1;
119464      }
119465    }
119466    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
119467
119468    /* Generate code to evaluate all constraint terms using == or IN
119469    ** and store the values of those terms in an array of registers
119470    ** starting at regBase.
119471    */
119472    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
119473    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
119474    if( zStartAff ) cEndAff = zStartAff[nEq];
119475    addrNxt = pLevel->addrNxt;
119476
119477    /* If we are doing a reverse order scan on an ascending index, or
119478    ** a forward order scan on a descending index, interchange the
119479    ** start and end terms (pRangeStart and pRangeEnd).
119480    */
119481    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
119482     || (bRev && pIdx->nKeyCol==nEq)
119483    ){
119484      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
119485      SWAP(u8, bSeekPastNull, bStopAtNull);
119486    }
119487
119488    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
119489    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
119490    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
119491    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
119492    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
119493    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
119494    start_constraints = pRangeStart || nEq>0;
119495
119496    /* Seek the index cursor to the start of the range. */
119497    nConstraint = nEq;
119498    if( pRangeStart ){
119499      Expr *pRight = pRangeStart->pExpr->pRight;
119500      sqlite3ExprCode(pParse, pRight, regBase+nEq);
119501      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
119502      if( (pRangeStart->wtFlags & TERM_VNULL)==0
119503       && sqlite3ExprCanBeNull(pRight)
119504      ){
119505        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119506        VdbeCoverage(v);
119507      }
119508      if( zStartAff ){
119509        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
119510          /* Since the comparison is to be performed with no conversions
119511          ** applied to the operands, set the affinity to apply to pRight to
119512          ** SQLITE_AFF_BLOB.  */
119513          zStartAff[nEq] = SQLITE_AFF_BLOB;
119514        }
119515        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
119516          zStartAff[nEq] = SQLITE_AFF_BLOB;
119517        }
119518      }
119519      nConstraint++;
119520      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
119521    }else if( bSeekPastNull ){
119522      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119523      nConstraint++;
119524      startEq = 0;
119525      start_constraints = 1;
119526    }
119527    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
119528    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
119529    assert( op!=0 );
119530    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119531    VdbeCoverage(v);
119532    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
119533    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
119534    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
119535    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
119536    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
119537    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
119538
119539    /* Load the value for the inequality constraint at the end of the
119540    ** range (if any).
119541    */
119542    nConstraint = nEq;
119543    if( pRangeEnd ){
119544      Expr *pRight = pRangeEnd->pExpr->pRight;
119545      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
119546      sqlite3ExprCode(pParse, pRight, regBase+nEq);
119547      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
119548      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
119549       && sqlite3ExprCanBeNull(pRight)
119550      ){
119551        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119552        VdbeCoverage(v);
119553      }
119554      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
119555       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
119556      ){
119557        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
119558      }
119559      nConstraint++;
119560      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
119561    }else if( bStopAtNull ){
119562      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119563      endEq = 0;
119564      nConstraint++;
119565    }
119566    sqlite3DbFree(db, zStartAff);
119567
119568    /* Top of the loop body */
119569    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119570
119571    /* Check if the index cursor is past the end of the range. */
119572    if( nConstraint ){
119573      op = aEndOp[bRev*2 + endEq];
119574      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119575      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
119576      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
119577      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
119578      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
119579    }
119580
119581    /* Seek the table cursor, if required */
119582    disableTerm(pLevel, pRangeStart);
119583    disableTerm(pLevel, pRangeEnd);
119584    if( omitTable ){
119585      /* pIdx is a covering index.  No need to access the main table. */
119586    }else if( HasRowid(pIdx->pTable) ){
119587      iRowidReg = ++pParse->nMem;
119588      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
119589      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119590      if( pWInfo->eOnePass!=ONEPASS_OFF ){
119591        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
119592        VdbeCoverage(v);
119593      }else{
119594        sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
119595      }
119596    }else if( iCur!=iIdxCur ){
119597      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
119598      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
119599      for(j=0; j<pPk->nKeyCol; j++){
119600        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
119601        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
119602      }
119603      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
119604                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
119605    }
119606
119607    /* Record the instruction used to terminate the loop. Disable
119608    ** WHERE clause terms made redundant by the index range scan.
119609    */
119610    if( pLoop->wsFlags & WHERE_ONEROW ){
119611      pLevel->op = OP_Noop;
119612    }else if( bRev ){
119613      pLevel->op = OP_Prev;
119614    }else{
119615      pLevel->op = OP_Next;
119616    }
119617    pLevel->p1 = iIdxCur;
119618    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
119619    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
119620      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119621    }else{
119622      assert( pLevel->p5==0 );
119623    }
119624  }else
119625
119626#ifndef SQLITE_OMIT_OR_OPTIMIZATION
119627  if( pLoop->wsFlags & WHERE_MULTI_OR ){
119628    /* Case 5:  Two or more separately indexed terms connected by OR
119629    **
119630    ** Example:
119631    **
119632    **   CREATE TABLE t1(a,b,c,d);
119633    **   CREATE INDEX i1 ON t1(a);
119634    **   CREATE INDEX i2 ON t1(b);
119635    **   CREATE INDEX i3 ON t1(c);
119636    **
119637    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
119638    **
119639    ** In the example, there are three indexed terms connected by OR.
119640    ** The top of the loop looks like this:
119641    **
119642    **          Null       1                # Zero the rowset in reg 1
119643    **
119644    ** Then, for each indexed term, the following. The arguments to
119645    ** RowSetTest are such that the rowid of the current row is inserted
119646    ** into the RowSet. If it is already present, control skips the
119647    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
119648    **
119649    **        sqlite3WhereBegin(<term>)
119650    **          RowSetTest                  # Insert rowid into rowset
119651    **          Gosub      2 A
119652    **        sqlite3WhereEnd()
119653    **
119654    ** Following the above, code to terminate the loop. Label A, the target
119655    ** of the Gosub above, jumps to the instruction right after the Goto.
119656    **
119657    **          Null       1                # Zero the rowset in reg 1
119658    **          Goto       B                # The loop is finished.
119659    **
119660    **       A: <loop body>                 # Return data, whatever.
119661    **
119662    **          Return     2                # Jump back to the Gosub
119663    **
119664    **       B: <after the loop>
119665    **
119666    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
119667    ** use an ephemeral index instead of a RowSet to record the primary
119668    ** keys of the rows we have already seen.
119669    **
119670    */
119671    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
119672    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
119673    Index *pCov = 0;             /* Potential covering index (or NULL) */
119674    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
119675
119676    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
119677    int regRowset = 0;                        /* Register for RowSet object */
119678    int regRowid = 0;                         /* Register holding rowid */
119679    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
119680    int iRetInit;                             /* Address of regReturn init */
119681    int untestedTerms = 0;             /* Some terms not completely tested */
119682    int ii;                            /* Loop counter */
119683    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
119684    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
119685    Table *pTab = pTabItem->pTab;
119686
119687    pTerm = pLoop->aLTerm[0];
119688    assert( pTerm!=0 );
119689    assert( pTerm->eOperator & WO_OR );
119690    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
119691    pOrWc = &pTerm->u.pOrInfo->wc;
119692    pLevel->op = OP_Return;
119693    pLevel->p1 = regReturn;
119694
119695    /* Set up a new SrcList in pOrTab containing the table being scanned
119696    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
119697    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
119698    */
119699    if( pWInfo->nLevel>1 ){
119700      int nNotReady;                 /* The number of notReady tables */
119701      struct SrcList_item *origSrc;     /* Original list of tables */
119702      nNotReady = pWInfo->nLevel - iLevel - 1;
119703      pOrTab = sqlite3StackAllocRaw(db,
119704                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
119705      if( pOrTab==0 ) return notReady;
119706      pOrTab->nAlloc = (u8)(nNotReady + 1);
119707      pOrTab->nSrc = pOrTab->nAlloc;
119708      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
119709      origSrc = pWInfo->pTabList->a;
119710      for(k=1; k<=nNotReady; k++){
119711        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
119712      }
119713    }else{
119714      pOrTab = pWInfo->pTabList;
119715    }
119716
119717    /* Initialize the rowset register to contain NULL. An SQL NULL is
119718    ** equivalent to an empty rowset.  Or, create an ephemeral index
119719    ** capable of holding primary keys in the case of a WITHOUT ROWID.
119720    **
119721    ** Also initialize regReturn to contain the address of the instruction
119722    ** immediately following the OP_Return at the bottom of the loop. This
119723    ** is required in a few obscure LEFT JOIN cases where control jumps
119724    ** over the top of the loop into the body of it. In this case the
119725    ** correct response for the end-of-loop code (the OP_Return) is to
119726    ** fall through to the next instruction, just as an OP_Next does if
119727    ** called on an uninitialized cursor.
119728    */
119729    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119730      if( HasRowid(pTab) ){
119731        regRowset = ++pParse->nMem;
119732        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
119733      }else{
119734        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119735        regRowset = pParse->nTab++;
119736        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
119737        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
119738      }
119739      regRowid = ++pParse->nMem;
119740    }
119741    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
119742
119743    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
119744    ** Then for every term xN, evaluate as the subexpression: xN AND z
119745    ** That way, terms in y that are factored into the disjunction will
119746    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
119747    **
119748    ** Actually, each subexpression is converted to "xN AND w" where w is
119749    ** the "interesting" terms of z - terms that did not originate in the
119750    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
119751    ** indices.
119752    **
119753    ** This optimization also only applies if the (x1 OR x2 OR ...) term
119754    ** is not contained in the ON clause of a LEFT JOIN.
119755    ** See ticket http://www.sqlite.org/src/info/f2369304e4
119756    */
119757    if( pWC->nTerm>1 ){
119758      int iTerm;
119759      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
119760        Expr *pExpr = pWC->a[iTerm].pExpr;
119761        if( &pWC->a[iTerm] == pTerm ) continue;
119762        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
119763        if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
119764        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
119765        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
119766        pExpr = sqlite3ExprDup(db, pExpr, 0);
119767        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
119768      }
119769      if( pAndExpr ){
119770        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
119771      }
119772    }
119773
119774    /* Run a separate WHERE clause for each term of the OR clause.  After
119775    ** eliminating duplicates from other WHERE clauses, the action for each
119776    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
119777    */
119778    wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
119779                | WHERE_FORCE_TABLE
119780                | WHERE_ONETABLE_ONLY
119781                | WHERE_NO_AUTOINDEX;
119782    for(ii=0; ii<pOrWc->nTerm; ii++){
119783      WhereTerm *pOrTerm = &pOrWc->a[ii];
119784      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
119785        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
119786        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
119787        int jmp1 = 0;                   /* Address of jump operation */
119788        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
119789          pAndExpr->pLeft = pOrExpr;
119790          pOrExpr = pAndExpr;
119791        }
119792        /* Loop through table entries that match term pOrTerm. */
119793        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
119794        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
119795                                      wctrlFlags, iCovCur);
119796        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
119797        if( pSubWInfo ){
119798          WhereLoop *pSubLoop;
119799          int addrExplain = sqlite3WhereExplainOneScan(
119800              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
119801          );
119802          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
119803
119804          /* This is the sub-WHERE clause body.  First skip over
119805          ** duplicate rows from prior sub-WHERE clauses, and record the
119806          ** rowid (or PRIMARY KEY) for the current row so that the same
119807          ** row will be skipped in subsequent sub-WHERE clauses.
119808          */
119809          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119810            int r;
119811            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
119812            if( HasRowid(pTab) ){
119813              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
119814              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
119815                                           r,iSet);
119816              VdbeCoverage(v);
119817            }else{
119818              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119819              int nPk = pPk->nKeyCol;
119820              int iPk;
119821
119822              /* Read the PK into an array of temp registers. */
119823              r = sqlite3GetTempRange(pParse, nPk);
119824              for(iPk=0; iPk<nPk; iPk++){
119825                int iCol = pPk->aiColumn[iPk];
119826                int rx;
119827                rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
119828                if( rx!=r+iPk ){
119829                  sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
119830                }
119831              }
119832
119833              /* Check if the temp table already contains this key. If so,
119834              ** the row has already been included in the result set and
119835              ** can be ignored (by jumping past the Gosub below). Otherwise,
119836              ** insert the key into the temp table and proceed with processing
119837              ** the row.
119838              **
119839              ** Use some of the same optimizations as OP_RowSetTest: If iSet
119840              ** is zero, assume that the key cannot already be present in
119841              ** the temp table. And if iSet is -1, assume that there is no
119842              ** need to insert the key into the temp table, as it will never
119843              ** be tested for.  */
119844              if( iSet ){
119845                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
119846                VdbeCoverage(v);
119847              }
119848              if( iSet>=0 ){
119849                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
119850                sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
119851                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
119852              }
119853
119854              /* Release the array of temp registers */
119855              sqlite3ReleaseTempRange(pParse, r, nPk);
119856            }
119857          }
119858
119859          /* Invoke the main loop body as a subroutine */
119860          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
119861
119862          /* Jump here (skipping the main loop body subroutine) if the
119863          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
119864          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
119865
119866          /* The pSubWInfo->untestedTerms flag means that this OR term
119867          ** contained one or more AND term from a notReady table.  The
119868          ** terms from the notReady table could not be tested and will
119869          ** need to be tested later.
119870          */
119871          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
119872
119873          /* If all of the OR-connected terms are optimized using the same
119874          ** index, and the index is opened using the same cursor number
119875          ** by each call to sqlite3WhereBegin() made by this loop, it may
119876          ** be possible to use that index as a covering index.
119877          **
119878          ** If the call to sqlite3WhereBegin() above resulted in a scan that
119879          ** uses an index, and this is either the first OR-connected term
119880          ** processed or the index is the same as that used by all previous
119881          ** terms, set pCov to the candidate covering index. Otherwise, set
119882          ** pCov to NULL to indicate that no candidate covering index will
119883          ** be available.
119884          */
119885          pSubLoop = pSubWInfo->a[0].pWLoop;
119886          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
119887          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
119888           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
119889           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
119890          ){
119891            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
119892            pCov = pSubLoop->u.btree.pIndex;
119893            wctrlFlags |= WHERE_REOPEN_IDX;
119894          }else{
119895            pCov = 0;
119896          }
119897
119898          /* Finish the loop through table entries that match term pOrTerm. */
119899          sqlite3WhereEnd(pSubWInfo);
119900        }
119901      }
119902    }
119903    pLevel->u.pCovidx = pCov;
119904    if( pCov ) pLevel->iIdxCur = iCovCur;
119905    if( pAndExpr ){
119906      pAndExpr->pLeft = 0;
119907      sqlite3ExprDelete(db, pAndExpr);
119908    }
119909    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
119910    sqlite3VdbeGoto(v, pLevel->addrBrk);
119911    sqlite3VdbeResolveLabel(v, iLoopBody);
119912
119913    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
119914    if( !untestedTerms ) disableTerm(pLevel, pTerm);
119915  }else
119916#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
119917
119918  {
119919    /* Case 6:  There is no usable index.  We must do a complete
119920    **          scan of the entire table.
119921    */
119922    static const u8 aStep[] = { OP_Next, OP_Prev };
119923    static const u8 aStart[] = { OP_Rewind, OP_Last };
119924    assert( bRev==0 || bRev==1 );
119925    if( pTabItem->fg.isRecursive ){
119926      /* Tables marked isRecursive have only a single row that is stored in
119927      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
119928      pLevel->op = OP_Noop;
119929    }else{
119930      pLevel->op = aStep[bRev];
119931      pLevel->p1 = iCur;
119932      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
119933      VdbeCoverageIf(v, bRev==0);
119934      VdbeCoverageIf(v, bRev!=0);
119935      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119936    }
119937  }
119938
119939#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
119940  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
119941#endif
119942
119943  /* Insert code to test every subexpression that can be completely
119944  ** computed using the current set of tables.
119945  */
119946  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
119947    Expr *pE;
119948    int skipLikeAddr = 0;
119949    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119950    testcase( pTerm->wtFlags & TERM_CODED );
119951    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119952    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
119953      testcase( pWInfo->untestedTerms==0
119954               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
119955      pWInfo->untestedTerms = 1;
119956      continue;
119957    }
119958    pE = pTerm->pExpr;
119959    assert( pE!=0 );
119960    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
119961      continue;
119962    }
119963    if( pTerm->wtFlags & TERM_LIKECOND ){
119964      assert( pLevel->iLikeRepCntr>0 );
119965      skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
119966      VdbeCoverage(v);
119967    }
119968    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
119969    if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
119970    pTerm->wtFlags |= TERM_CODED;
119971  }
119972
119973  /* Insert code to test for implied constraints based on transitivity
119974  ** of the "==" operator.
119975  **
119976  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
119977  ** and we are coding the t1 loop and the t2 loop has not yet coded,
119978  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
119979  ** the implied "t1.a=123" constraint.
119980  */
119981  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
119982    Expr *pE, *pEAlt;
119983    WhereTerm *pAlt;
119984    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119985    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
119986    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
119987    if( pTerm->leftCursor!=iCur ) continue;
119988    if( pLevel->iLeftJoin ) continue;
119989    pE = pTerm->pExpr;
119990    assert( !ExprHasProperty(pE, EP_FromJoin) );
119991    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
119992    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
119993                    WO_EQ|WO_IN|WO_IS, 0);
119994    if( pAlt==0 ) continue;
119995    if( pAlt->wtFlags & (TERM_CODED) ) continue;
119996    testcase( pAlt->eOperator & WO_EQ );
119997    testcase( pAlt->eOperator & WO_IS );
119998    testcase( pAlt->eOperator & WO_IN );
119999    VdbeModuleComment((v, "begin transitive constraint"));
120000    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
120001    if( pEAlt ){
120002      *pEAlt = *pAlt->pExpr;
120003      pEAlt->pLeft = pE->pLeft;
120004      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
120005      sqlite3StackFree(db, pEAlt);
120006    }
120007  }
120008
120009  /* For a LEFT OUTER JOIN, generate code that will record the fact that
120010  ** at least one row of the right table has matched the left table.
120011  */
120012  if( pLevel->iLeftJoin ){
120013    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
120014    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
120015    VdbeComment((v, "record LEFT JOIN hit"));
120016    sqlite3ExprCacheClear(pParse);
120017    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
120018      testcase( pTerm->wtFlags & TERM_VIRTUAL );
120019      testcase( pTerm->wtFlags & TERM_CODED );
120020      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120021      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
120022        assert( pWInfo->untestedTerms );
120023        continue;
120024      }
120025      assert( pTerm->pExpr );
120026      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
120027      pTerm->wtFlags |= TERM_CODED;
120028    }
120029  }
120030
120031  return pLevel->notReady;
120032}
120033
120034/************** End of wherecode.c *******************************************/
120035/************** Begin file whereexpr.c ***************************************/
120036/*
120037** 2015-06-08
120038**
120039** The author disclaims copyright to this source code.  In place of
120040** a legal notice, here is a blessing:
120041**
120042**    May you do good and not evil.
120043**    May you find forgiveness for yourself and forgive others.
120044**    May you share freely, never taking more than you give.
120045**
120046*************************************************************************
120047** This module contains C code that generates VDBE code used to process
120048** the WHERE clause of SQL statements.
120049**
120050** This file was originally part of where.c but was split out to improve
120051** readability and editabiliity.  This file contains utility routines for
120052** analyzing Expr objects in the WHERE clause.
120053*/
120054/* #include "sqliteInt.h" */
120055/* #include "whereInt.h" */
120056
120057/* Forward declarations */
120058static void exprAnalyze(SrcList*, WhereClause*, int);
120059
120060/*
120061** Deallocate all memory associated with a WhereOrInfo object.
120062*/
120063static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
120064  sqlite3WhereClauseClear(&p->wc);
120065  sqlite3DbFree(db, p);
120066}
120067
120068/*
120069** Deallocate all memory associated with a WhereAndInfo object.
120070*/
120071static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
120072  sqlite3WhereClauseClear(&p->wc);
120073  sqlite3DbFree(db, p);
120074}
120075
120076/*
120077** Add a single new WhereTerm entry to the WhereClause object pWC.
120078** The new WhereTerm object is constructed from Expr p and with wtFlags.
120079** The index in pWC->a[] of the new WhereTerm is returned on success.
120080** 0 is returned if the new WhereTerm could not be added due to a memory
120081** allocation error.  The memory allocation failure will be recorded in
120082** the db->mallocFailed flag so that higher-level functions can detect it.
120083**
120084** This routine will increase the size of the pWC->a[] array as necessary.
120085**
120086** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
120087** for freeing the expression p is assumed by the WhereClause object pWC.
120088** This is true even if this routine fails to allocate a new WhereTerm.
120089**
120090** WARNING:  This routine might reallocate the space used to store
120091** WhereTerms.  All pointers to WhereTerms should be invalidated after
120092** calling this routine.  Such pointers may be reinitialized by referencing
120093** the pWC->a[] array.
120094*/
120095static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
120096  WhereTerm *pTerm;
120097  int idx;
120098  testcase( wtFlags & TERM_VIRTUAL );
120099  if( pWC->nTerm>=pWC->nSlot ){
120100    WhereTerm *pOld = pWC->a;
120101    sqlite3 *db = pWC->pWInfo->pParse->db;
120102    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
120103    if( pWC->a==0 ){
120104      if( wtFlags & TERM_DYNAMIC ){
120105        sqlite3ExprDelete(db, p);
120106      }
120107      pWC->a = pOld;
120108      return 0;
120109    }
120110    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
120111    if( pOld!=pWC->aStatic ){
120112      sqlite3DbFree(db, pOld);
120113    }
120114    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
120115    memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
120116  }
120117  pTerm = &pWC->a[idx = pWC->nTerm++];
120118  if( p && ExprHasProperty(p, EP_Unlikely) ){
120119    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
120120  }else{
120121    pTerm->truthProb = 1;
120122  }
120123  pTerm->pExpr = sqlite3ExprSkipCollate(p);
120124  pTerm->wtFlags = wtFlags;
120125  pTerm->pWC = pWC;
120126  pTerm->iParent = -1;
120127  return idx;
120128}
120129
120130/*
120131** Return TRUE if the given operator is one of the operators that is
120132** allowed for an indexable WHERE clause term.  The allowed operators are
120133** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
120134*/
120135static int allowedOp(int op){
120136  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
120137  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
120138  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
120139  assert( TK_GE==TK_EQ+4 );
120140  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
120141}
120142
120143/*
120144** Commute a comparison operator.  Expressions of the form "X op Y"
120145** are converted into "Y op X".
120146**
120147** If left/right precedence rules come into play when determining the
120148** collating sequence, then COLLATE operators are adjusted to ensure
120149** that the collating sequence does not change.  For example:
120150** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
120151** the left hand side of a comparison overrides any collation sequence
120152** attached to the right. For the same reason the EP_Collate flag
120153** is not commuted.
120154*/
120155static void exprCommute(Parse *pParse, Expr *pExpr){
120156  u16 expRight = (pExpr->pRight->flags & EP_Collate);
120157  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
120158  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
120159  if( expRight==expLeft ){
120160    /* Either X and Y both have COLLATE operator or neither do */
120161    if( expRight ){
120162      /* Both X and Y have COLLATE operators.  Make sure X is always
120163      ** used by clearing the EP_Collate flag from Y. */
120164      pExpr->pRight->flags &= ~EP_Collate;
120165    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
120166      /* Neither X nor Y have COLLATE operators, but X has a non-default
120167      ** collating sequence.  So add the EP_Collate marker on X to cause
120168      ** it to be searched first. */
120169      pExpr->pLeft->flags |= EP_Collate;
120170    }
120171  }
120172  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
120173  if( pExpr->op>=TK_GT ){
120174    assert( TK_LT==TK_GT+2 );
120175    assert( TK_GE==TK_LE+2 );
120176    assert( TK_GT>TK_EQ );
120177    assert( TK_GT<TK_LE );
120178    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
120179    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
120180  }
120181}
120182
120183/*
120184** Translate from TK_xx operator to WO_xx bitmask.
120185*/
120186static u16 operatorMask(int op){
120187  u16 c;
120188  assert( allowedOp(op) );
120189  if( op==TK_IN ){
120190    c = WO_IN;
120191  }else if( op==TK_ISNULL ){
120192    c = WO_ISNULL;
120193  }else if( op==TK_IS ){
120194    c = WO_IS;
120195  }else{
120196    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
120197    c = (u16)(WO_EQ<<(op-TK_EQ));
120198  }
120199  assert( op!=TK_ISNULL || c==WO_ISNULL );
120200  assert( op!=TK_IN || c==WO_IN );
120201  assert( op!=TK_EQ || c==WO_EQ );
120202  assert( op!=TK_LT || c==WO_LT );
120203  assert( op!=TK_LE || c==WO_LE );
120204  assert( op!=TK_GT || c==WO_GT );
120205  assert( op!=TK_GE || c==WO_GE );
120206  assert( op!=TK_IS || c==WO_IS );
120207  return c;
120208}
120209
120210
120211#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
120212/*
120213** Check to see if the given expression is a LIKE or GLOB operator that
120214** can be optimized using inequality constraints.  Return TRUE if it is
120215** so and false if not.
120216**
120217** In order for the operator to be optimizible, the RHS must be a string
120218** literal that does not begin with a wildcard.  The LHS must be a column
120219** that may only be NULL, a string, or a BLOB, never a number. (This means
120220** that virtual tables cannot participate in the LIKE optimization.)  The
120221** collating sequence for the column on the LHS must be appropriate for
120222** the operator.
120223*/
120224static int isLikeOrGlob(
120225  Parse *pParse,    /* Parsing and code generating context */
120226  Expr *pExpr,      /* Test this expression */
120227  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
120228  int *pisComplete, /* True if the only wildcard is % in the last character */
120229  int *pnoCase      /* True if uppercase is equivalent to lowercase */
120230){
120231  const char *z = 0;         /* String on RHS of LIKE operator */
120232  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
120233  ExprList *pList;           /* List of operands to the LIKE operator */
120234  int c;                     /* One character in z[] */
120235  int cnt;                   /* Number of non-wildcard prefix characters */
120236  char wc[3];                /* Wildcard characters */
120237  sqlite3 *db = pParse->db;  /* Database connection */
120238  sqlite3_value *pVal = 0;
120239  int op;                    /* Opcode of pRight */
120240
120241  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
120242    return 0;
120243  }
120244#ifdef SQLITE_EBCDIC
120245  if( *pnoCase ) return 0;
120246#endif
120247  pList = pExpr->x.pList;
120248  pLeft = pList->a[1].pExpr;
120249  if( pLeft->op!=TK_COLUMN
120250   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
120251   || IsVirtual(pLeft->pTab)  /* Value might be numeric */
120252  ){
120253    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
120254    ** be the name of an indexed column with TEXT affinity. */
120255    return 0;
120256  }
120257  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
120258
120259  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
120260  op = pRight->op;
120261  if( op==TK_VARIABLE ){
120262    Vdbe *pReprepare = pParse->pReprepare;
120263    int iCol = pRight->iColumn;
120264    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
120265    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
120266      z = (char *)sqlite3_value_text(pVal);
120267    }
120268    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
120269    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
120270  }else if( op==TK_STRING ){
120271    z = pRight->u.zToken;
120272  }
120273  if( z ){
120274    cnt = 0;
120275    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
120276      cnt++;
120277    }
120278    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
120279      Expr *pPrefix;
120280      *pisComplete = c==wc[0] && z[cnt+1]==0;
120281      pPrefix = sqlite3Expr(db, TK_STRING, z);
120282      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
120283      *ppPrefix = pPrefix;
120284      if( op==TK_VARIABLE ){
120285        Vdbe *v = pParse->pVdbe;
120286        sqlite3VdbeSetVarmask(v, pRight->iColumn);
120287        if( *pisComplete && pRight->u.zToken[1] ){
120288          /* If the rhs of the LIKE expression is a variable, and the current
120289          ** value of the variable means there is no need to invoke the LIKE
120290          ** function, then no OP_Variable will be added to the program.
120291          ** This causes problems for the sqlite3_bind_parameter_name()
120292          ** API. To work around them, add a dummy OP_Variable here.
120293          */
120294          int r1 = sqlite3GetTempReg(pParse);
120295          sqlite3ExprCodeTarget(pParse, pRight, r1);
120296          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
120297          sqlite3ReleaseTempReg(pParse, r1);
120298        }
120299      }
120300    }else{
120301      z = 0;
120302    }
120303  }
120304
120305  sqlite3ValueFree(pVal);
120306  return (z!=0);
120307}
120308#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
120309
120310
120311#ifndef SQLITE_OMIT_VIRTUALTABLE
120312/*
120313** Check to see if the given expression is of the form
120314**
120315**         column MATCH expr
120316**
120317** If it is then return TRUE.  If not, return FALSE.
120318*/
120319static int isMatchOfColumn(
120320  Expr *pExpr      /* Test this expression */
120321){
120322  ExprList *pList;
120323
120324  if( pExpr->op!=TK_FUNCTION ){
120325    return 0;
120326  }
120327  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
120328    return 0;
120329  }
120330  pList = pExpr->x.pList;
120331  if( pList->nExpr!=2 ){
120332    return 0;
120333  }
120334  if( pList->a[1].pExpr->op != TK_COLUMN ){
120335    return 0;
120336  }
120337  return 1;
120338}
120339#endif /* SQLITE_OMIT_VIRTUALTABLE */
120340
120341/*
120342** If the pBase expression originated in the ON or USING clause of
120343** a join, then transfer the appropriate markings over to derived.
120344*/
120345static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
120346  if( pDerived ){
120347    pDerived->flags |= pBase->flags & EP_FromJoin;
120348    pDerived->iRightJoinTable = pBase->iRightJoinTable;
120349  }
120350}
120351
120352/*
120353** Mark term iChild as being a child of term iParent
120354*/
120355static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
120356  pWC->a[iChild].iParent = iParent;
120357  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
120358  pWC->a[iParent].nChild++;
120359}
120360
120361/*
120362** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
120363** a conjunction, then return just pTerm when N==0.  If N is exceeds
120364** the number of available subterms, return NULL.
120365*/
120366static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
120367  if( pTerm->eOperator!=WO_AND ){
120368    return N==0 ? pTerm : 0;
120369  }
120370  if( N<pTerm->u.pAndInfo->wc.nTerm ){
120371    return &pTerm->u.pAndInfo->wc.a[N];
120372  }
120373  return 0;
120374}
120375
120376/*
120377** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
120378** two subterms are in disjunction - they are OR-ed together.
120379**
120380** If these two terms are both of the form:  "A op B" with the same
120381** A and B values but different operators and if the operators are
120382** compatible (if one is = and the other is <, for example) then
120383** add a new virtual AND term to pWC that is the combination of the
120384** two.
120385**
120386** Some examples:
120387**
120388**    x<y OR x=y    -->     x<=y
120389**    x=y OR x=y    -->     x=y
120390**    x<=y OR x<y   -->     x<=y
120391**
120392** The following is NOT generated:
120393**
120394**    x<y OR x>y    -->     x!=y
120395*/
120396static void whereCombineDisjuncts(
120397  SrcList *pSrc,         /* the FROM clause */
120398  WhereClause *pWC,      /* The complete WHERE clause */
120399  WhereTerm *pOne,       /* First disjunct */
120400  WhereTerm *pTwo        /* Second disjunct */
120401){
120402  u16 eOp = pOne->eOperator | pTwo->eOperator;
120403  sqlite3 *db;           /* Database connection (for malloc) */
120404  Expr *pNew;            /* New virtual expression */
120405  int op;                /* Operator for the combined expression */
120406  int idxNew;            /* Index in pWC of the next virtual term */
120407
120408  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
120409  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
120410  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
120411   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
120412  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
120413  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
120414  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
120415  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
120416  /* If we reach this point, it means the two subterms can be combined */
120417  if( (eOp & (eOp-1))!=0 ){
120418    if( eOp & (WO_LT|WO_LE) ){
120419      eOp = WO_LE;
120420    }else{
120421      assert( eOp & (WO_GT|WO_GE) );
120422      eOp = WO_GE;
120423    }
120424  }
120425  db = pWC->pWInfo->pParse->db;
120426  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
120427  if( pNew==0 ) return;
120428  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
120429  pNew->op = op;
120430  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
120431  exprAnalyze(pSrc, pWC, idxNew);
120432}
120433
120434#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
120435/*
120436** Analyze a term that consists of two or more OR-connected
120437** subterms.  So in:
120438**
120439**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
120440**                          ^^^^^^^^^^^^^^^^^^^^
120441**
120442** This routine analyzes terms such as the middle term in the above example.
120443** A WhereOrTerm object is computed and attached to the term under
120444** analysis, regardless of the outcome of the analysis.  Hence:
120445**
120446**     WhereTerm.wtFlags   |=  TERM_ORINFO
120447**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
120448**
120449** The term being analyzed must have two or more of OR-connected subterms.
120450** A single subterm might be a set of AND-connected sub-subterms.
120451** Examples of terms under analysis:
120452**
120453**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
120454**     (B)     x=expr1 OR expr2=x OR x=expr3
120455**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
120456**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
120457**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
120458**     (F)     x>A OR (x=A AND y>=B)
120459**
120460** CASE 1:
120461**
120462** If all subterms are of the form T.C=expr for some single column of C and
120463** a single table T (as shown in example B above) then create a new virtual
120464** term that is an equivalent IN expression.  In other words, if the term
120465** being analyzed is:
120466**
120467**      x = expr1  OR  expr2 = x  OR  x = expr3
120468**
120469** then create a new virtual term like this:
120470**
120471**      x IN (expr1,expr2,expr3)
120472**
120473** CASE 2:
120474**
120475** If there are exactly two disjuncts and one side has x>A and the other side
120476** has x=A (for the same x and A) then add a new virtual conjunct term to the
120477** WHERE clause of the form "x>=A".  Example:
120478**
120479**      x>A OR (x=A AND y>B)    adds:    x>=A
120480**
120481** The added conjunct can sometimes be helpful in query planning.
120482**
120483** CASE 3:
120484**
120485** If all subterms are indexable by a single table T, then set
120486**
120487**     WhereTerm.eOperator              =  WO_OR
120488**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
120489**
120490** A subterm is "indexable" if it is of the form
120491** "T.C <op> <expr>" where C is any column of table T and
120492** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
120493** A subterm is also indexable if it is an AND of two or more
120494** subsubterms at least one of which is indexable.  Indexable AND
120495** subterms have their eOperator set to WO_AND and they have
120496** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
120497**
120498** From another point of view, "indexable" means that the subterm could
120499** potentially be used with an index if an appropriate index exists.
120500** This analysis does not consider whether or not the index exists; that
120501** is decided elsewhere.  This analysis only looks at whether subterms
120502** appropriate for indexing exist.
120503**
120504** All examples A through E above satisfy case 3.  But if a term
120505** also satisfies case 1 (such as B) we know that the optimizer will
120506** always prefer case 1, so in that case we pretend that case 3 is not
120507** satisfied.
120508**
120509** It might be the case that multiple tables are indexable.  For example,
120510** (E) above is indexable on tables P, Q, and R.
120511**
120512** Terms that satisfy case 3 are candidates for lookup by using
120513** separate indices to find rowids for each subterm and composing
120514** the union of all rowids using a RowSet object.  This is similar
120515** to "bitmap indices" in other database engines.
120516**
120517** OTHERWISE:
120518**
120519** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
120520** zero.  This term is not useful for search.
120521*/
120522static void exprAnalyzeOrTerm(
120523  SrcList *pSrc,            /* the FROM clause */
120524  WhereClause *pWC,         /* the complete WHERE clause */
120525  int idxTerm               /* Index of the OR-term to be analyzed */
120526){
120527  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
120528  Parse *pParse = pWInfo->pParse;         /* Parser context */
120529  sqlite3 *db = pParse->db;               /* Database connection */
120530  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
120531  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
120532  int i;                                  /* Loop counters */
120533  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
120534  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
120535  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
120536  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
120537  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
120538
120539  /*
120540  ** Break the OR clause into its separate subterms.  The subterms are
120541  ** stored in a WhereClause structure containing within the WhereOrInfo
120542  ** object that is attached to the original OR clause term.
120543  */
120544  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
120545  assert( pExpr->op==TK_OR );
120546  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
120547  if( pOrInfo==0 ) return;
120548  pTerm->wtFlags |= TERM_ORINFO;
120549  pOrWc = &pOrInfo->wc;
120550  sqlite3WhereClauseInit(pOrWc, pWInfo);
120551  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
120552  sqlite3WhereExprAnalyze(pSrc, pOrWc);
120553  if( db->mallocFailed ) return;
120554  assert( pOrWc->nTerm>=2 );
120555
120556  /*
120557  ** Compute the set of tables that might satisfy cases 1 or 3.
120558  */
120559  indexable = ~(Bitmask)0;
120560  chngToIN = ~(Bitmask)0;
120561  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
120562    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
120563      WhereAndInfo *pAndInfo;
120564      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
120565      chngToIN = 0;
120566      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
120567      if( pAndInfo ){
120568        WhereClause *pAndWC;
120569        WhereTerm *pAndTerm;
120570        int j;
120571        Bitmask b = 0;
120572        pOrTerm->u.pAndInfo = pAndInfo;
120573        pOrTerm->wtFlags |= TERM_ANDINFO;
120574        pOrTerm->eOperator = WO_AND;
120575        pAndWC = &pAndInfo->wc;
120576        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
120577        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
120578        sqlite3WhereExprAnalyze(pSrc, pAndWC);
120579        pAndWC->pOuter = pWC;
120580        testcase( db->mallocFailed );
120581        if( !db->mallocFailed ){
120582          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
120583            assert( pAndTerm->pExpr );
120584            if( allowedOp(pAndTerm->pExpr->op) ){
120585              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
120586            }
120587          }
120588        }
120589        indexable &= b;
120590      }
120591    }else if( pOrTerm->wtFlags & TERM_COPIED ){
120592      /* Skip this term for now.  We revisit it when we process the
120593      ** corresponding TERM_VIRTUAL term */
120594    }else{
120595      Bitmask b;
120596      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
120597      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
120598        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
120599        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
120600      }
120601      indexable &= b;
120602      if( (pOrTerm->eOperator & WO_EQ)==0 ){
120603        chngToIN = 0;
120604      }else{
120605        chngToIN &= b;
120606      }
120607    }
120608  }
120609
120610  /*
120611  ** Record the set of tables that satisfy case 3.  The set might be
120612  ** empty.
120613  */
120614  pOrInfo->indexable = indexable;
120615  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
120616
120617  /* For a two-way OR, attempt to implementation case 2.
120618  */
120619  if( indexable && pOrWc->nTerm==2 ){
120620    int iOne = 0;
120621    WhereTerm *pOne;
120622    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
120623      int iTwo = 0;
120624      WhereTerm *pTwo;
120625      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
120626        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
120627      }
120628    }
120629  }
120630
120631  /*
120632  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
120633  ** we have to do some additional checking to see if case 1 really
120634  ** is satisfied.
120635  **
120636  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
120637  ** that there is no possibility of transforming the OR clause into an
120638  ** IN operator because one or more terms in the OR clause contain
120639  ** something other than == on a column in the single table.  The 1-bit
120640  ** case means that every term of the OR clause is of the form
120641  ** "table.column=expr" for some single table.  The one bit that is set
120642  ** will correspond to the common table.  We still need to check to make
120643  ** sure the same column is used on all terms.  The 2-bit case is when
120644  ** the all terms are of the form "table1.column=table2.column".  It
120645  ** might be possible to form an IN operator with either table1.column
120646  ** or table2.column as the LHS if either is common to every term of
120647  ** the OR clause.
120648  **
120649  ** Note that terms of the form "table.column1=table.column2" (the
120650  ** same table on both sizes of the ==) cannot be optimized.
120651  */
120652  if( chngToIN ){
120653    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
120654    int iColumn = -1;         /* Column index on lhs of IN operator */
120655    int iCursor = -1;         /* Table cursor common to all terms */
120656    int j = 0;                /* Loop counter */
120657
120658    /* Search for a table and column that appears on one side or the
120659    ** other of the == operator in every subterm.  That table and column
120660    ** will be recorded in iCursor and iColumn.  There might not be any
120661    ** such table and column.  Set okToChngToIN if an appropriate table
120662    ** and column is found but leave okToChngToIN false if not found.
120663    */
120664    for(j=0; j<2 && !okToChngToIN; j++){
120665      pOrTerm = pOrWc->a;
120666      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
120667        assert( pOrTerm->eOperator & WO_EQ );
120668        pOrTerm->wtFlags &= ~TERM_OR_OK;
120669        if( pOrTerm->leftCursor==iCursor ){
120670          /* This is the 2-bit case and we are on the second iteration and
120671          ** current term is from the first iteration.  So skip this term. */
120672          assert( j==1 );
120673          continue;
120674        }
120675        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
120676                                            pOrTerm->leftCursor))==0 ){
120677          /* This term must be of the form t1.a==t2.b where t2 is in the
120678          ** chngToIN set but t1 is not.  This term will be either preceded
120679          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
120680          ** and use its inversion. */
120681          testcase( pOrTerm->wtFlags & TERM_COPIED );
120682          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
120683          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
120684          continue;
120685        }
120686        iColumn = pOrTerm->u.leftColumn;
120687        iCursor = pOrTerm->leftCursor;
120688        break;
120689      }
120690      if( i<0 ){
120691        /* No candidate table+column was found.  This can only occur
120692        ** on the second iteration */
120693        assert( j==1 );
120694        assert( IsPowerOfTwo(chngToIN) );
120695        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
120696        break;
120697      }
120698      testcase( j==1 );
120699
120700      /* We have found a candidate table and column.  Check to see if that
120701      ** table and column is common to every term in the OR clause */
120702      okToChngToIN = 1;
120703      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
120704        assert( pOrTerm->eOperator & WO_EQ );
120705        if( pOrTerm->leftCursor!=iCursor ){
120706          pOrTerm->wtFlags &= ~TERM_OR_OK;
120707        }else if( pOrTerm->u.leftColumn!=iColumn ){
120708          okToChngToIN = 0;
120709        }else{
120710          int affLeft, affRight;
120711          /* If the right-hand side is also a column, then the affinities
120712          ** of both right and left sides must be such that no type
120713          ** conversions are required on the right.  (Ticket #2249)
120714          */
120715          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
120716          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
120717          if( affRight!=0 && affRight!=affLeft ){
120718            okToChngToIN = 0;
120719          }else{
120720            pOrTerm->wtFlags |= TERM_OR_OK;
120721          }
120722        }
120723      }
120724    }
120725
120726    /* At this point, okToChngToIN is true if original pTerm satisfies
120727    ** case 1.  In that case, construct a new virtual term that is
120728    ** pTerm converted into an IN operator.
120729    */
120730    if( okToChngToIN ){
120731      Expr *pDup;            /* A transient duplicate expression */
120732      ExprList *pList = 0;   /* The RHS of the IN operator */
120733      Expr *pLeft = 0;       /* The LHS of the IN operator */
120734      Expr *pNew;            /* The complete IN operator */
120735
120736      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
120737        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
120738        assert( pOrTerm->eOperator & WO_EQ );
120739        assert( pOrTerm->leftCursor==iCursor );
120740        assert( pOrTerm->u.leftColumn==iColumn );
120741        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
120742        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
120743        pLeft = pOrTerm->pExpr->pLeft;
120744      }
120745      assert( pLeft!=0 );
120746      pDup = sqlite3ExprDup(db, pLeft, 0);
120747      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
120748      if( pNew ){
120749        int idxNew;
120750        transferJoinMarkings(pNew, pExpr);
120751        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
120752        pNew->x.pList = pList;
120753        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
120754        testcase( idxNew==0 );
120755        exprAnalyze(pSrc, pWC, idxNew);
120756        pTerm = &pWC->a[idxTerm];
120757        markTermAsChild(pWC, idxNew, idxTerm);
120758      }else{
120759        sqlite3ExprListDelete(db, pList);
120760      }
120761      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
120762    }
120763  }
120764}
120765#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
120766
120767/*
120768** We already know that pExpr is a binary operator where both operands are
120769** column references.  This routine checks to see if pExpr is an equivalence
120770** relation:
120771**   1.  The SQLITE_Transitive optimization must be enabled
120772**   2.  Must be either an == or an IS operator
120773**   3.  Not originating in the ON clause of an OUTER JOIN
120774**   4.  The affinities of A and B must be compatible
120775**   5a. Both operands use the same collating sequence OR
120776**   5b. The overall collating sequence is BINARY
120777** If this routine returns TRUE, that means that the RHS can be substituted
120778** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
120779** This is an optimization.  No harm comes from returning 0.  But if 1 is
120780** returned when it should not be, then incorrect answers might result.
120781*/
120782static int termIsEquivalence(Parse *pParse, Expr *pExpr){
120783  char aff1, aff2;
120784  CollSeq *pColl;
120785  const char *zColl1, *zColl2;
120786  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
120787  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
120788  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
120789  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
120790  aff2 = sqlite3ExprAffinity(pExpr->pRight);
120791  if( aff1!=aff2
120792   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
120793  ){
120794    return 0;
120795  }
120796  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
120797  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
120798  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
120799  /* Since pLeft and pRight are both a column references, their collating
120800  ** sequence should always be defined. */
120801  zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
120802  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
120803  zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
120804  return sqlite3StrICmp(zColl1, zColl2)==0;
120805}
120806
120807/*
120808** Recursively walk the expressions of a SELECT statement and generate
120809** a bitmask indicating which tables are used in that expression
120810** tree.
120811*/
120812static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
120813  Bitmask mask = 0;
120814  while( pS ){
120815    SrcList *pSrc = pS->pSrc;
120816    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
120817    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
120818    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
120819    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
120820    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
120821    if( ALWAYS(pSrc!=0) ){
120822      int i;
120823      for(i=0; i<pSrc->nSrc; i++){
120824        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
120825        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
120826      }
120827    }
120828    pS = pS->pPrior;
120829  }
120830  return mask;
120831}
120832
120833/*
120834** Expression pExpr is one operand of a comparison operator that might
120835** be useful for indexing.  This routine checks to see if pExpr appears
120836** in any index.  Return TRUE (1) if pExpr is an indexed term and return
120837** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
120838** number of the table that is indexed and *piColumn to the column number
120839** of the column that is indexed, or -2 if an expression is being indexed.
120840**
120841** If pExpr is a TK_COLUMN column reference, then this routine always returns
120842** true even if that particular column is not indexed, because the column
120843** might be added to an automatic index later.
120844*/
120845static int exprMightBeIndexed(
120846  SrcList *pFrom,        /* The FROM clause */
120847  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
120848  Expr *pExpr,           /* An operand of a comparison operator */
120849  int *piCur,            /* Write the referenced table cursor number here */
120850  int *piColumn          /* Write the referenced table column number here */
120851){
120852  Index *pIdx;
120853  int i;
120854  int iCur;
120855  if( pExpr->op==TK_COLUMN ){
120856    *piCur = pExpr->iTable;
120857    *piColumn = pExpr->iColumn;
120858    return 1;
120859  }
120860  if( mPrereq==0 ) return 0;                 /* No table references */
120861  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
120862  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
120863  iCur = pFrom->a[i].iCursor;
120864  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120865    if( pIdx->aColExpr==0 ) continue;
120866    for(i=0; i<pIdx->nKeyCol; i++){
120867      if( pIdx->aiColumn[i]!=(-2) ) continue;
120868      if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
120869        *piCur = iCur;
120870        *piColumn = -2;
120871        return 1;
120872      }
120873    }
120874  }
120875  return 0;
120876}
120877
120878/*
120879** The input to this routine is an WhereTerm structure with only the
120880** "pExpr" field filled in.  The job of this routine is to analyze the
120881** subexpression and populate all the other fields of the WhereTerm
120882** structure.
120883**
120884** If the expression is of the form "<expr> <op> X" it gets commuted
120885** to the standard form of "X <op> <expr>".
120886**
120887** If the expression is of the form "X <op> Y" where both X and Y are
120888** columns, then the original expression is unchanged and a new virtual
120889** term of the form "Y <op> X" is added to the WHERE clause and
120890** analyzed separately.  The original term is marked with TERM_COPIED
120891** and the new term is marked with TERM_DYNAMIC (because it's pExpr
120892** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
120893** is a commuted copy of a prior term.)  The original term has nChild=1
120894** and the copy has idxParent set to the index of the original term.
120895*/
120896static void exprAnalyze(
120897  SrcList *pSrc,            /* the FROM clause */
120898  WhereClause *pWC,         /* the WHERE clause */
120899  int idxTerm               /* Index of the term to be analyzed */
120900){
120901  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
120902  WhereTerm *pTerm;                /* The term to be analyzed */
120903  WhereMaskSet *pMaskSet;          /* Set of table index masks */
120904  Expr *pExpr;                     /* The expression to be analyzed */
120905  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
120906  Bitmask prereqAll;               /* Prerequesites of pExpr */
120907  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
120908  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
120909  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
120910  int noCase = 0;                  /* uppercase equivalent to lowercase */
120911  int op;                          /* Top-level operator.  pExpr->op */
120912  Parse *pParse = pWInfo->pParse;  /* Parsing context */
120913  sqlite3 *db = pParse->db;        /* Database connection */
120914
120915  if( db->mallocFailed ){
120916    return;
120917  }
120918  pTerm = &pWC->a[idxTerm];
120919  pMaskSet = &pWInfo->sMaskSet;
120920  pExpr = pTerm->pExpr;
120921  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
120922  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
120923  op = pExpr->op;
120924  if( op==TK_IN ){
120925    assert( pExpr->pRight==0 );
120926    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120927      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
120928    }else{
120929      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
120930    }
120931  }else if( op==TK_ISNULL ){
120932    pTerm->prereqRight = 0;
120933  }else{
120934    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
120935  }
120936  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
120937  if( ExprHasProperty(pExpr, EP_FromJoin) ){
120938    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
120939    prereqAll |= x;
120940    extraRight = x-1;  /* ON clause terms may not be used with an index
120941                       ** on left table of a LEFT JOIN.  Ticket #3015 */
120942  }
120943  pTerm->prereqAll = prereqAll;
120944  pTerm->leftCursor = -1;
120945  pTerm->iParent = -1;
120946  pTerm->eOperator = 0;
120947  if( allowedOp(op) ){
120948    int iCur, iColumn;
120949    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
120950    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
120951    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
120952    if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
120953      pTerm->leftCursor = iCur;
120954      pTerm->u.leftColumn = iColumn;
120955      pTerm->eOperator = operatorMask(op) & opMask;
120956    }
120957    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
120958    if( pRight
120959     && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
120960    ){
120961      WhereTerm *pNew;
120962      Expr *pDup;
120963      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
120964      if( pTerm->leftCursor>=0 ){
120965        int idxNew;
120966        pDup = sqlite3ExprDup(db, pExpr, 0);
120967        if( db->mallocFailed ){
120968          sqlite3ExprDelete(db, pDup);
120969          return;
120970        }
120971        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
120972        if( idxNew==0 ) return;
120973        pNew = &pWC->a[idxNew];
120974        markTermAsChild(pWC, idxNew, idxTerm);
120975        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
120976        pTerm = &pWC->a[idxTerm];
120977        pTerm->wtFlags |= TERM_COPIED;
120978
120979        if( termIsEquivalence(pParse, pDup) ){
120980          pTerm->eOperator |= WO_EQUIV;
120981          eExtraOp = WO_EQUIV;
120982        }
120983      }else{
120984        pDup = pExpr;
120985        pNew = pTerm;
120986      }
120987      exprCommute(pParse, pDup);
120988      pNew->leftCursor = iCur;
120989      pNew->u.leftColumn = iColumn;
120990      testcase( (prereqLeft | extraRight) != prereqLeft );
120991      pNew->prereqRight = prereqLeft | extraRight;
120992      pNew->prereqAll = prereqAll;
120993      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
120994    }
120995  }
120996
120997#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
120998  /* If a term is the BETWEEN operator, create two new virtual terms
120999  ** that define the range that the BETWEEN implements.  For example:
121000  **
121001  **      a BETWEEN b AND c
121002  **
121003  ** is converted into:
121004  **
121005  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
121006  **
121007  ** The two new terms are added onto the end of the WhereClause object.
121008  ** The new terms are "dynamic" and are children of the original BETWEEN
121009  ** term.  That means that if the BETWEEN term is coded, the children are
121010  ** skipped.  Or, if the children are satisfied by an index, the original
121011  ** BETWEEN term is skipped.
121012  */
121013  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
121014    ExprList *pList = pExpr->x.pList;
121015    int i;
121016    static const u8 ops[] = {TK_GE, TK_LE};
121017    assert( pList!=0 );
121018    assert( pList->nExpr==2 );
121019    for(i=0; i<2; i++){
121020      Expr *pNewExpr;
121021      int idxNew;
121022      pNewExpr = sqlite3PExpr(pParse, ops[i],
121023                             sqlite3ExprDup(db, pExpr->pLeft, 0),
121024                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
121025      transferJoinMarkings(pNewExpr, pExpr);
121026      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
121027      testcase( idxNew==0 );
121028      exprAnalyze(pSrc, pWC, idxNew);
121029      pTerm = &pWC->a[idxTerm];
121030      markTermAsChild(pWC, idxNew, idxTerm);
121031    }
121032  }
121033#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
121034
121035#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
121036  /* Analyze a term that is composed of two or more subterms connected by
121037  ** an OR operator.
121038  */
121039  else if( pExpr->op==TK_OR ){
121040    assert( pWC->op==TK_AND );
121041    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
121042    pTerm = &pWC->a[idxTerm];
121043  }
121044#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
121045
121046#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
121047  /* Add constraints to reduce the search space on a LIKE or GLOB
121048  ** operator.
121049  **
121050  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
121051  **
121052  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
121053  **
121054  ** The last character of the prefix "abc" is incremented to form the
121055  ** termination condition "abd".  If case is not significant (the default
121056  ** for LIKE) then the lower-bound is made all uppercase and the upper-
121057  ** bound is made all lowercase so that the bounds also work when comparing
121058  ** BLOBs.
121059  */
121060  if( pWC->op==TK_AND
121061   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
121062  ){
121063    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
121064    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
121065    Expr *pNewExpr1;
121066    Expr *pNewExpr2;
121067    int idxNew1;
121068    int idxNew2;
121069    const char *zCollSeqName;     /* Name of collating sequence */
121070    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
121071
121072    pLeft = pExpr->x.pList->a[1].pExpr;
121073    pStr2 = sqlite3ExprDup(db, pStr1, 0);
121074
121075    /* Convert the lower bound to upper-case and the upper bound to
121076    ** lower-case (upper-case is less than lower-case in ASCII) so that
121077    ** the range constraints also work for BLOBs
121078    */
121079    if( noCase && !pParse->db->mallocFailed ){
121080      int i;
121081      char c;
121082      pTerm->wtFlags |= TERM_LIKE;
121083      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
121084        pStr1->u.zToken[i] = sqlite3Toupper(c);
121085        pStr2->u.zToken[i] = sqlite3Tolower(c);
121086      }
121087    }
121088
121089    if( !db->mallocFailed ){
121090      u8 c, *pC;       /* Last character before the first wildcard */
121091      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
121092      c = *pC;
121093      if( noCase ){
121094        /* The point is to increment the last character before the first
121095        ** wildcard.  But if we increment '@', that will push it into the
121096        ** alphabetic range where case conversions will mess up the
121097        ** inequality.  To avoid this, make sure to also run the full
121098        ** LIKE on all candidate expressions by clearing the isComplete flag
121099        */
121100        if( c=='A'-1 ) isComplete = 0;
121101        c = sqlite3UpperToLower[c];
121102      }
121103      *pC = c + 1;
121104    }
121105    zCollSeqName = noCase ? "NOCASE" : "BINARY";
121106    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
121107    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
121108           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
121109           pStr1, 0);
121110    transferJoinMarkings(pNewExpr1, pExpr);
121111    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
121112    testcase( idxNew1==0 );
121113    exprAnalyze(pSrc, pWC, idxNew1);
121114    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
121115    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
121116           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
121117           pStr2, 0);
121118    transferJoinMarkings(pNewExpr2, pExpr);
121119    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
121120    testcase( idxNew2==0 );
121121    exprAnalyze(pSrc, pWC, idxNew2);
121122    pTerm = &pWC->a[idxTerm];
121123    if( isComplete ){
121124      markTermAsChild(pWC, idxNew1, idxTerm);
121125      markTermAsChild(pWC, idxNew2, idxTerm);
121126    }
121127  }
121128#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
121129
121130#ifndef SQLITE_OMIT_VIRTUALTABLE
121131  /* Add a WO_MATCH auxiliary term to the constraint set if the
121132  ** current expression is of the form:  column MATCH expr.
121133  ** This information is used by the xBestIndex methods of
121134  ** virtual tables.  The native query optimizer does not attempt
121135  ** to do anything with MATCH functions.
121136  */
121137  if( isMatchOfColumn(pExpr) ){
121138    int idxNew;
121139    Expr *pRight, *pLeft;
121140    WhereTerm *pNewTerm;
121141    Bitmask prereqColumn, prereqExpr;
121142
121143    pRight = pExpr->x.pList->a[0].pExpr;
121144    pLeft = pExpr->x.pList->a[1].pExpr;
121145    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
121146    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
121147    if( (prereqExpr & prereqColumn)==0 ){
121148      Expr *pNewExpr;
121149      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
121150                              0, sqlite3ExprDup(db, pRight, 0), 0);
121151      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
121152      testcase( idxNew==0 );
121153      pNewTerm = &pWC->a[idxNew];
121154      pNewTerm->prereqRight = prereqExpr;
121155      pNewTerm->leftCursor = pLeft->iTable;
121156      pNewTerm->u.leftColumn = pLeft->iColumn;
121157      pNewTerm->eOperator = WO_MATCH;
121158      markTermAsChild(pWC, idxNew, idxTerm);
121159      pTerm = &pWC->a[idxTerm];
121160      pTerm->wtFlags |= TERM_COPIED;
121161      pNewTerm->prereqAll = pTerm->prereqAll;
121162    }
121163  }
121164#endif /* SQLITE_OMIT_VIRTUALTABLE */
121165
121166#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
121167  /* When sqlite_stat3 histogram data is available an operator of the
121168  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
121169  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
121170  ** virtual term of that form.
121171  **
121172  ** Note that the virtual term must be tagged with TERM_VNULL.
121173  */
121174  if( pExpr->op==TK_NOTNULL
121175   && pExpr->pLeft->op==TK_COLUMN
121176   && pExpr->pLeft->iColumn>=0
121177   && OptimizationEnabled(db, SQLITE_Stat34)
121178  ){
121179    Expr *pNewExpr;
121180    Expr *pLeft = pExpr->pLeft;
121181    int idxNew;
121182    WhereTerm *pNewTerm;
121183
121184    pNewExpr = sqlite3PExpr(pParse, TK_GT,
121185                            sqlite3ExprDup(db, pLeft, 0),
121186                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
121187
121188    idxNew = whereClauseInsert(pWC, pNewExpr,
121189                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
121190    if( idxNew ){
121191      pNewTerm = &pWC->a[idxNew];
121192      pNewTerm->prereqRight = 0;
121193      pNewTerm->leftCursor = pLeft->iTable;
121194      pNewTerm->u.leftColumn = pLeft->iColumn;
121195      pNewTerm->eOperator = WO_GT;
121196      markTermAsChild(pWC, idxNew, idxTerm);
121197      pTerm = &pWC->a[idxTerm];
121198      pTerm->wtFlags |= TERM_COPIED;
121199      pNewTerm->prereqAll = pTerm->prereqAll;
121200    }
121201  }
121202#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
121203
121204  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
121205  ** an index for tables to the left of the join.
121206  */
121207  pTerm->prereqRight |= extraRight;
121208}
121209
121210/***************************************************************************
121211** Routines with file scope above.  Interface to the rest of the where.c
121212** subsystem follows.
121213***************************************************************************/
121214
121215/*
121216** This routine identifies subexpressions in the WHERE clause where
121217** each subexpression is separated by the AND operator or some other
121218** operator specified in the op parameter.  The WhereClause structure
121219** is filled with pointers to subexpressions.  For example:
121220**
121221**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
121222**           \________/     \_______________/     \________________/
121223**            slot[0]            slot[1]               slot[2]
121224**
121225** The original WHERE clause in pExpr is unaltered.  All this routine
121226** does is make slot[] entries point to substructure within pExpr.
121227**
121228** In the previous sentence and in the diagram, "slot[]" refers to
121229** the WhereClause.a[] array.  The slot[] array grows as needed to contain
121230** all terms of the WHERE clause.
121231*/
121232SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
121233  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
121234  pWC->op = op;
121235  if( pE2==0 ) return;
121236  if( pE2->op!=op ){
121237    whereClauseInsert(pWC, pExpr, 0);
121238  }else{
121239    sqlite3WhereSplit(pWC, pE2->pLeft, op);
121240    sqlite3WhereSplit(pWC, pE2->pRight, op);
121241  }
121242}
121243
121244/*
121245** Initialize a preallocated WhereClause structure.
121246*/
121247SQLITE_PRIVATE void sqlite3WhereClauseInit(
121248  WhereClause *pWC,        /* The WhereClause to be initialized */
121249  WhereInfo *pWInfo        /* The WHERE processing context */
121250){
121251  pWC->pWInfo = pWInfo;
121252  pWC->pOuter = 0;
121253  pWC->nTerm = 0;
121254  pWC->nSlot = ArraySize(pWC->aStatic);
121255  pWC->a = pWC->aStatic;
121256}
121257
121258/*
121259** Deallocate a WhereClause structure.  The WhereClause structure
121260** itself is not freed.  This routine is the inverse of sqlite3WhereClauseInit().
121261*/
121262SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
121263  int i;
121264  WhereTerm *a;
121265  sqlite3 *db = pWC->pWInfo->pParse->db;
121266  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
121267    if( a->wtFlags & TERM_DYNAMIC ){
121268      sqlite3ExprDelete(db, a->pExpr);
121269    }
121270    if( a->wtFlags & TERM_ORINFO ){
121271      whereOrInfoDelete(db, a->u.pOrInfo);
121272    }else if( a->wtFlags & TERM_ANDINFO ){
121273      whereAndInfoDelete(db, a->u.pAndInfo);
121274    }
121275  }
121276  if( pWC->a!=pWC->aStatic ){
121277    sqlite3DbFree(db, pWC->a);
121278  }
121279}
121280
121281
121282/*
121283** These routines walk (recursively) an expression tree and generate
121284** a bitmask indicating which tables are used in that expression
121285** tree.
121286*/
121287SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
121288  Bitmask mask = 0;
121289  if( p==0 ) return 0;
121290  if( p->op==TK_COLUMN ){
121291    mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
121292    return mask;
121293  }
121294  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
121295  mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
121296  if( ExprHasProperty(p, EP_xIsSelect) ){
121297    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
121298  }else{
121299    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
121300  }
121301  return mask;
121302}
121303SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
121304  int i;
121305  Bitmask mask = 0;
121306  if( pList ){
121307    for(i=0; i<pList->nExpr; i++){
121308      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
121309    }
121310  }
121311  return mask;
121312}
121313
121314
121315/*
121316** Call exprAnalyze on all terms in a WHERE clause.
121317**
121318** Note that exprAnalyze() might add new virtual terms onto the
121319** end of the WHERE clause.  We do not want to analyze these new
121320** virtual terms, so start analyzing at the end and work forward
121321** so that the added virtual terms are never processed.
121322*/
121323SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
121324  SrcList *pTabList,       /* the FROM clause */
121325  WhereClause *pWC         /* the WHERE clause to be analyzed */
121326){
121327  int i;
121328  for(i=pWC->nTerm-1; i>=0; i--){
121329    exprAnalyze(pTabList, pWC, i);
121330  }
121331}
121332
121333/*
121334** For table-valued-functions, transform the function arguments into
121335** new WHERE clause terms.
121336**
121337** Each function argument translates into an equality constraint against
121338** a HIDDEN column in the table.
121339*/
121340SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
121341  Parse *pParse,                    /* Parsing context */
121342  struct SrcList_item *pItem,       /* The FROM clause term to process */
121343  WhereClause *pWC                  /* Xfer function arguments to here */
121344){
121345  Table *pTab;
121346  int j, k;
121347  ExprList *pArgs;
121348  Expr *pColRef;
121349  Expr *pTerm;
121350  if( pItem->fg.isTabFunc==0 ) return;
121351  pTab = pItem->pTab;
121352  assert( pTab!=0 );
121353  pArgs = pItem->u1.pFuncArg;
121354  assert( pArgs!=0 );
121355  for(j=k=0; j<pArgs->nExpr; j++){
121356    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){ k++; }
121357    if( k>=pTab->nCol ){
121358      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
121359                      pTab->zName, j);
121360      return;
121361    }
121362    pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
121363    if( pColRef==0 ) return;
121364    pColRef->iTable = pItem->iCursor;
121365    pColRef->iColumn = k++;
121366    pColRef->pTab = pTab;
121367    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
121368                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
121369    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
121370  }
121371}
121372
121373/************** End of whereexpr.c *******************************************/
121374/************** Begin file where.c *******************************************/
121375/*
121376** 2001 September 15
121377**
121378** The author disclaims copyright to this source code.  In place of
121379** a legal notice, here is a blessing:
121380**
121381**    May you do good and not evil.
121382**    May you find forgiveness for yourself and forgive others.
121383**    May you share freely, never taking more than you give.
121384**
121385*************************************************************************
121386** This module contains C code that generates VDBE code used to process
121387** the WHERE clause of SQL statements.  This module is responsible for
121388** generating the code that loops through a table looking for applicable
121389** rows.  Indices are selected and used to speed the search when doing
121390** so is applicable.  Because this module is responsible for selecting
121391** indices, you might also think of this module as the "query optimizer".
121392*/
121393/* #include "sqliteInt.h" */
121394/* #include "whereInt.h" */
121395
121396/* Forward declaration of methods */
121397static int whereLoopResize(sqlite3*, WhereLoop*, int);
121398
121399/* Test variable that can be set to enable WHERE tracing */
121400#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
121401/***/ int sqlite3WhereTrace = 0;
121402#endif
121403
121404
121405/*
121406** Return the estimated number of output rows from a WHERE clause
121407*/
121408SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
121409  return sqlite3LogEstToInt(pWInfo->nRowOut);
121410}
121411
121412/*
121413** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
121414** WHERE clause returns outputs for DISTINCT processing.
121415*/
121416SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
121417  return pWInfo->eDistinct;
121418}
121419
121420/*
121421** Return TRUE if the WHERE clause returns rows in ORDER BY order.
121422** Return FALSE if the output needs to be sorted.
121423*/
121424SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
121425  return pWInfo->nOBSat;
121426}
121427
121428/*
121429** Return the VDBE address or label to jump to in order to continue
121430** immediately with the next row of a WHERE clause.
121431*/
121432SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
121433  assert( pWInfo->iContinue!=0 );
121434  return pWInfo->iContinue;
121435}
121436
121437/*
121438** Return the VDBE address or label to jump to in order to break
121439** out of a WHERE loop.
121440*/
121441SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
121442  return pWInfo->iBreak;
121443}
121444
121445/*
121446** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
121447** operate directly on the rowis returned by a WHERE clause.  Return
121448** ONEPASS_SINGLE (1) if the statement can operation directly because only
121449** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
121450** optimization can be used on multiple
121451**
121452** If the ONEPASS optimization is used (if this routine returns true)
121453** then also write the indices of open cursors used by ONEPASS
121454** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
121455** table and iaCur[1] gets the cursor used by an auxiliary index.
121456** Either value may be -1, indicating that cursor is not used.
121457** Any cursors returned will have been opened for writing.
121458**
121459** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
121460** unable to use the ONEPASS optimization.
121461*/
121462SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
121463  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
121464#ifdef WHERETRACE_ENABLED
121465  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
121466    sqlite3DebugPrintf("%s cursors: %d %d\n",
121467         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
121468         aiCur[0], aiCur[1]);
121469  }
121470#endif
121471  return pWInfo->eOnePass;
121472}
121473
121474/*
121475** Move the content of pSrc into pDest
121476*/
121477static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
121478  pDest->n = pSrc->n;
121479  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
121480}
121481
121482/*
121483** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
121484**
121485** The new entry might overwrite an existing entry, or it might be
121486** appended, or it might be discarded.  Do whatever is the right thing
121487** so that pSet keeps the N_OR_COST best entries seen so far.
121488*/
121489static int whereOrInsert(
121490  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
121491  Bitmask prereq,        /* Prerequisites of the new entry */
121492  LogEst rRun,           /* Run-cost of the new entry */
121493  LogEst nOut            /* Number of outputs for the new entry */
121494){
121495  u16 i;
121496  WhereOrCost *p;
121497  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
121498    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
121499      goto whereOrInsert_done;
121500    }
121501    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
121502      return 0;
121503    }
121504  }
121505  if( pSet->n<N_OR_COST ){
121506    p = &pSet->a[pSet->n++];
121507    p->nOut = nOut;
121508  }else{
121509    p = pSet->a;
121510    for(i=1; i<pSet->n; i++){
121511      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
121512    }
121513    if( p->rRun<=rRun ) return 0;
121514  }
121515whereOrInsert_done:
121516  p->prereq = prereq;
121517  p->rRun = rRun;
121518  if( p->nOut>nOut ) p->nOut = nOut;
121519  return 1;
121520}
121521
121522/*
121523** Return the bitmask for the given cursor number.  Return 0 if
121524** iCursor is not in the set.
121525*/
121526SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
121527  int i;
121528  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
121529  for(i=0; i<pMaskSet->n; i++){
121530    if( pMaskSet->ix[i]==iCursor ){
121531      return MASKBIT(i);
121532    }
121533  }
121534  return 0;
121535}
121536
121537/*
121538** Create a new mask for cursor iCursor.
121539**
121540** There is one cursor per table in the FROM clause.  The number of
121541** tables in the FROM clause is limited by a test early in the
121542** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
121543** array will never overflow.
121544*/
121545static void createMask(WhereMaskSet *pMaskSet, int iCursor){
121546  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
121547  pMaskSet->ix[pMaskSet->n++] = iCursor;
121548}
121549
121550/*
121551** Advance to the next WhereTerm that matches according to the criteria
121552** established when the pScan object was initialized by whereScanInit().
121553** Return NULL if there are no more matching WhereTerms.
121554*/
121555static WhereTerm *whereScanNext(WhereScan *pScan){
121556  int iCur;            /* The cursor on the LHS of the term */
121557  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
121558  Expr *pX;            /* An expression being tested */
121559  WhereClause *pWC;    /* Shorthand for pScan->pWC */
121560  WhereTerm *pTerm;    /* The term being tested */
121561  int k = pScan->k;    /* Where to start scanning */
121562
121563  while( pScan->iEquiv<=pScan->nEquiv ){
121564    iCur = pScan->aiCur[pScan->iEquiv-1];
121565    iColumn = pScan->aiColumn[pScan->iEquiv-1];
121566    if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
121567    while( (pWC = pScan->pWC)!=0 ){
121568      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
121569        if( pTerm->leftCursor==iCur
121570         && pTerm->u.leftColumn==iColumn
121571         && (iColumn!=XN_EXPR
121572             || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
121573         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
121574        ){
121575          if( (pTerm->eOperator & WO_EQUIV)!=0
121576           && pScan->nEquiv<ArraySize(pScan->aiCur)
121577           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
121578          ){
121579            int j;
121580            for(j=0; j<pScan->nEquiv; j++){
121581              if( pScan->aiCur[j]==pX->iTable
121582               && pScan->aiColumn[j]==pX->iColumn ){
121583                  break;
121584              }
121585            }
121586            if( j==pScan->nEquiv ){
121587              pScan->aiCur[j] = pX->iTable;
121588              pScan->aiColumn[j] = pX->iColumn;
121589              pScan->nEquiv++;
121590            }
121591          }
121592          if( (pTerm->eOperator & pScan->opMask)!=0 ){
121593            /* Verify the affinity and collating sequence match */
121594            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
121595              CollSeq *pColl;
121596              Parse *pParse = pWC->pWInfo->pParse;
121597              pX = pTerm->pExpr;
121598              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
121599                continue;
121600              }
121601              assert(pX->pLeft);
121602              pColl = sqlite3BinaryCompareCollSeq(pParse,
121603                                                  pX->pLeft, pX->pRight);
121604              if( pColl==0 ) pColl = pParse->db->pDfltColl;
121605              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
121606                continue;
121607              }
121608            }
121609            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
121610             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
121611             && pX->iTable==pScan->aiCur[0]
121612             && pX->iColumn==pScan->aiColumn[0]
121613            ){
121614              testcase( pTerm->eOperator & WO_IS );
121615              continue;
121616            }
121617            pScan->k = k+1;
121618            return pTerm;
121619          }
121620        }
121621      }
121622      pScan->pWC = pScan->pWC->pOuter;
121623      k = 0;
121624    }
121625    pScan->pWC = pScan->pOrigWC;
121626    k = 0;
121627    pScan->iEquiv++;
121628  }
121629  return 0;
121630}
121631
121632/*
121633** Initialize a WHERE clause scanner object.  Return a pointer to the
121634** first match.  Return NULL if there are no matches.
121635**
121636** The scanner will be searching the WHERE clause pWC.  It will look
121637** for terms of the form "X <op> <expr>" where X is column iColumn of table
121638** iCur.  The <op> must be one of the operators described by opMask.
121639**
121640** If the search is for X and the WHERE clause contains terms of the
121641** form X=Y then this routine might also return terms of the form
121642** "Y <op> <expr>".  The number of levels of transitivity is limited,
121643** but is enough to handle most commonly occurring SQL statements.
121644**
121645** If X is not the INTEGER PRIMARY KEY then X must be compatible with
121646** index pIdx.
121647*/
121648static WhereTerm *whereScanInit(
121649  WhereScan *pScan,       /* The WhereScan object being initialized */
121650  WhereClause *pWC,       /* The WHERE clause to be scanned */
121651  int iCur,               /* Cursor to scan for */
121652  int iColumn,            /* Column to scan for */
121653  u32 opMask,             /* Operator(s) to scan for */
121654  Index *pIdx             /* Must be compatible with this index */
121655){
121656  int j = 0;
121657
121658  /* memset(pScan, 0, sizeof(*pScan)); */
121659  pScan->pOrigWC = pWC;
121660  pScan->pWC = pWC;
121661  pScan->pIdxExpr = 0;
121662  if( pIdx ){
121663    j = iColumn;
121664    iColumn = pIdx->aiColumn[j];
121665    if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
121666  }
121667  if( pIdx && iColumn>=0 ){
121668    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
121669    pScan->zCollName = pIdx->azColl[j];
121670  }else{
121671    pScan->idxaff = 0;
121672    pScan->zCollName = 0;
121673  }
121674  pScan->opMask = opMask;
121675  pScan->k = 0;
121676  pScan->aiCur[0] = iCur;
121677  pScan->aiColumn[0] = iColumn;
121678  pScan->nEquiv = 1;
121679  pScan->iEquiv = 1;
121680  return whereScanNext(pScan);
121681}
121682
121683/*
121684** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
121685** where X is a reference to the iColumn of table iCur and <op> is one of
121686** the WO_xx operator codes specified by the op parameter.
121687** Return a pointer to the term.  Return 0 if not found.
121688**
121689** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
121690** rather than the iColumn-th column of table iCur.
121691**
121692** The term returned might by Y=<expr> if there is another constraint in
121693** the WHERE clause that specifies that X=Y.  Any such constraints will be
121694** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
121695** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
121696** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
121697** other equivalent values.  Hence a search for X will return <expr> if X=A1
121698** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
121699**
121700** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
121701** then try for the one with no dependencies on <expr> - in other words where
121702** <expr> is a constant expression of some kind.  Only return entries of
121703** the form "X <op> Y" where Y is a column in another table if no terms of
121704** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
121705** exist, try to return a term that does not use WO_EQUIV.
121706*/
121707SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
121708  WhereClause *pWC,     /* The WHERE clause to be searched */
121709  int iCur,             /* Cursor number of LHS */
121710  int iColumn,          /* Column number of LHS */
121711  Bitmask notReady,     /* RHS must not overlap with this mask */
121712  u32 op,               /* Mask of WO_xx values describing operator */
121713  Index *pIdx           /* Must be compatible with this index, if not NULL */
121714){
121715  WhereTerm *pResult = 0;
121716  WhereTerm *p;
121717  WhereScan scan;
121718
121719  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
121720  op &= WO_EQ|WO_IS;
121721  while( p ){
121722    if( (p->prereqRight & notReady)==0 ){
121723      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
121724        testcase( p->eOperator & WO_IS );
121725        return p;
121726      }
121727      if( pResult==0 ) pResult = p;
121728    }
121729    p = whereScanNext(&scan);
121730  }
121731  return pResult;
121732}
121733
121734/*
121735** This function searches pList for an entry that matches the iCol-th column
121736** of index pIdx.
121737**
121738** If such an expression is found, its index in pList->a[] is returned. If
121739** no expression is found, -1 is returned.
121740*/
121741static int findIndexCol(
121742  Parse *pParse,                  /* Parse context */
121743  ExprList *pList,                /* Expression list to search */
121744  int iBase,                      /* Cursor for table associated with pIdx */
121745  Index *pIdx,                    /* Index to match column of */
121746  int iCol                        /* Column of index to match */
121747){
121748  int i;
121749  const char *zColl = pIdx->azColl[iCol];
121750
121751  for(i=0; i<pList->nExpr; i++){
121752    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
121753    if( p->op==TK_COLUMN
121754     && p->iColumn==pIdx->aiColumn[iCol]
121755     && p->iTable==iBase
121756    ){
121757      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
121758      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
121759        return i;
121760      }
121761    }
121762  }
121763
121764  return -1;
121765}
121766
121767/*
121768** Return TRUE if the iCol-th column of index pIdx is NOT NULL
121769*/
121770static int indexColumnNotNull(Index *pIdx, int iCol){
121771  int j;
121772  assert( pIdx!=0 );
121773  assert( iCol>=0 && iCol<pIdx->nColumn );
121774  j = pIdx->aiColumn[iCol];
121775  if( j>=0 ){
121776    return pIdx->pTable->aCol[j].notNull;
121777  }else if( j==(-1) ){
121778    return 1;
121779  }else{
121780    assert( j==(-2) );
121781    return 0;  /* Assume an indexed expression can always yield a NULL */
121782
121783  }
121784}
121785
121786/*
121787** Return true if the DISTINCT expression-list passed as the third argument
121788** is redundant.
121789**
121790** A DISTINCT list is redundant if any subset of the columns in the
121791** DISTINCT list are collectively unique and individually non-null.
121792*/
121793static int isDistinctRedundant(
121794  Parse *pParse,            /* Parsing context */
121795  SrcList *pTabList,        /* The FROM clause */
121796  WhereClause *pWC,         /* The WHERE clause */
121797  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
121798){
121799  Table *pTab;
121800  Index *pIdx;
121801  int i;
121802  int iBase;
121803
121804  /* If there is more than one table or sub-select in the FROM clause of
121805  ** this query, then it will not be possible to show that the DISTINCT
121806  ** clause is redundant. */
121807  if( pTabList->nSrc!=1 ) return 0;
121808  iBase = pTabList->a[0].iCursor;
121809  pTab = pTabList->a[0].pTab;
121810
121811  /* If any of the expressions is an IPK column on table iBase, then return
121812  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
121813  ** current SELECT is a correlated sub-query.
121814  */
121815  for(i=0; i<pDistinct->nExpr; i++){
121816    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
121817    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
121818  }
121819
121820  /* Loop through all indices on the table, checking each to see if it makes
121821  ** the DISTINCT qualifier redundant. It does so if:
121822  **
121823  **   1. The index is itself UNIQUE, and
121824  **
121825  **   2. All of the columns in the index are either part of the pDistinct
121826  **      list, or else the WHERE clause contains a term of the form "col=X",
121827  **      where X is a constant value. The collation sequences of the
121828  **      comparison and select-list expressions must match those of the index.
121829  **
121830  **   3. All of those index columns for which the WHERE clause does not
121831  **      contain a "col=X" term are subject to a NOT NULL constraint.
121832  */
121833  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121834    if( !IsUniqueIndex(pIdx) ) continue;
121835    for(i=0; i<pIdx->nKeyCol; i++){
121836      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
121837        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
121838        if( indexColumnNotNull(pIdx, i)==0 ) break;
121839      }
121840    }
121841    if( i==pIdx->nKeyCol ){
121842      /* This index implies that the DISTINCT qualifier is redundant. */
121843      return 1;
121844    }
121845  }
121846
121847  return 0;
121848}
121849
121850
121851/*
121852** Estimate the logarithm of the input value to base 2.
121853*/
121854static LogEst estLog(LogEst N){
121855  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
121856}
121857
121858/*
121859** Convert OP_Column opcodes to OP_Copy in previously generated code.
121860**
121861** This routine runs over generated VDBE code and translates OP_Column
121862** opcodes into OP_Copy when the table is being accessed via co-routine
121863** instead of via table lookup.
121864**
121865** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
121866** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
121867** then each OP_Rowid is transformed into an instruction to increment the
121868** value stored in its output register.
121869*/
121870static void translateColumnToCopy(
121871  Vdbe *v,            /* The VDBE containing code to translate */
121872  int iStart,         /* Translate from this opcode to the end */
121873  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
121874  int iRegister,      /* The first column is in this register */
121875  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
121876){
121877  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
121878  int iEnd = sqlite3VdbeCurrentAddr(v);
121879  for(; iStart<iEnd; iStart++, pOp++){
121880    if( pOp->p1!=iTabCur ) continue;
121881    if( pOp->opcode==OP_Column ){
121882      pOp->opcode = OP_Copy;
121883      pOp->p1 = pOp->p2 + iRegister;
121884      pOp->p2 = pOp->p3;
121885      pOp->p3 = 0;
121886    }else if( pOp->opcode==OP_Rowid ){
121887      if( bIncrRowid ){
121888        /* Increment the value stored in the P2 operand of the OP_Rowid. */
121889        pOp->opcode = OP_AddImm;
121890        pOp->p1 = pOp->p2;
121891        pOp->p2 = 1;
121892      }else{
121893        pOp->opcode = OP_Null;
121894        pOp->p1 = 0;
121895        pOp->p3 = 0;
121896      }
121897    }
121898  }
121899}
121900
121901/*
121902** Two routines for printing the content of an sqlite3_index_info
121903** structure.  Used for testing and debugging only.  If neither
121904** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
121905** are no-ops.
121906*/
121907#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
121908static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
121909  int i;
121910  if( !sqlite3WhereTrace ) return;
121911  for(i=0; i<p->nConstraint; i++){
121912    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
121913       i,
121914       p->aConstraint[i].iColumn,
121915       p->aConstraint[i].iTermOffset,
121916       p->aConstraint[i].op,
121917       p->aConstraint[i].usable);
121918  }
121919  for(i=0; i<p->nOrderBy; i++){
121920    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
121921       i,
121922       p->aOrderBy[i].iColumn,
121923       p->aOrderBy[i].desc);
121924  }
121925}
121926static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
121927  int i;
121928  if( !sqlite3WhereTrace ) return;
121929  for(i=0; i<p->nConstraint; i++){
121930    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
121931       i,
121932       p->aConstraintUsage[i].argvIndex,
121933       p->aConstraintUsage[i].omit);
121934  }
121935  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
121936  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
121937  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
121938  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
121939  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
121940}
121941#else
121942#define TRACE_IDX_INPUTS(A)
121943#define TRACE_IDX_OUTPUTS(A)
121944#endif
121945
121946#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
121947/*
121948** Return TRUE if the WHERE clause term pTerm is of a form where it
121949** could be used with an index to access pSrc, assuming an appropriate
121950** index existed.
121951*/
121952static int termCanDriveIndex(
121953  WhereTerm *pTerm,              /* WHERE clause term to check */
121954  struct SrcList_item *pSrc,     /* Table we are trying to access */
121955  Bitmask notReady               /* Tables in outer loops of the join */
121956){
121957  char aff;
121958  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
121959  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
121960  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
121961  if( pTerm->u.leftColumn<0 ) return 0;
121962  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
121963  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
121964  testcase( pTerm->pExpr->op==TK_IS );
121965  return 1;
121966}
121967#endif
121968
121969
121970#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
121971/*
121972** Generate code to construct the Index object for an automatic index
121973** and to set up the WhereLevel object pLevel so that the code generator
121974** makes use of the automatic index.
121975*/
121976static void constructAutomaticIndex(
121977  Parse *pParse,              /* The parsing context */
121978  WhereClause *pWC,           /* The WHERE clause */
121979  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
121980  Bitmask notReady,           /* Mask of cursors that are not available */
121981  WhereLevel *pLevel          /* Write new index here */
121982){
121983  int nKeyCol;                /* Number of columns in the constructed index */
121984  WhereTerm *pTerm;           /* A single term of the WHERE clause */
121985  WhereTerm *pWCEnd;          /* End of pWC->a[] */
121986  Index *pIdx;                /* Object describing the transient index */
121987  Vdbe *v;                    /* Prepared statement under construction */
121988  int addrInit;               /* Address of the initialization bypass jump */
121989  Table *pTable;              /* The table being indexed */
121990  int addrTop;                /* Top of the index fill loop */
121991  int regRecord;              /* Register holding an index record */
121992  int n;                      /* Column counter */
121993  int i;                      /* Loop counter */
121994  int mxBitCol;               /* Maximum column in pSrc->colUsed */
121995  CollSeq *pColl;             /* Collating sequence to on a column */
121996  WhereLoop *pLoop;           /* The Loop object */
121997  char *zNotUsed;             /* Extra space on the end of pIdx */
121998  Bitmask idxCols;            /* Bitmap of columns used for indexing */
121999  Bitmask extraCols;          /* Bitmap of additional columns */
122000  u8 sentWarning = 0;         /* True if a warnning has been issued */
122001  Expr *pPartial = 0;         /* Partial Index Expression */
122002  int iContinue = 0;          /* Jump here to skip excluded rows */
122003  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
122004  int addrCounter;            /* Address where integer counter is initialized */
122005  int regBase;                /* Array of registers where record is assembled */
122006
122007  /* Generate code to skip over the creation and initialization of the
122008  ** transient index on 2nd and subsequent iterations of the loop. */
122009  v = pParse->pVdbe;
122010  assert( v!=0 );
122011  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
122012
122013  /* Count the number of columns that will be added to the index
122014  ** and used to match WHERE clause constraints */
122015  nKeyCol = 0;
122016  pTable = pSrc->pTab;
122017  pWCEnd = &pWC->a[pWC->nTerm];
122018  pLoop = pLevel->pWLoop;
122019  idxCols = 0;
122020  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
122021    Expr *pExpr = pTerm->pExpr;
122022    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
122023         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
122024         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
122025    if( pLoop->prereq==0
122026     && (pTerm->wtFlags & TERM_VIRTUAL)==0
122027     && !ExprHasProperty(pExpr, EP_FromJoin)
122028     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
122029      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
122030                                sqlite3ExprDup(pParse->db, pExpr, 0));
122031    }
122032    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
122033      int iCol = pTerm->u.leftColumn;
122034      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
122035      testcase( iCol==BMS );
122036      testcase( iCol==BMS-1 );
122037      if( !sentWarning ){
122038        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
122039            "automatic index on %s(%s)", pTable->zName,
122040            pTable->aCol[iCol].zName);
122041        sentWarning = 1;
122042      }
122043      if( (idxCols & cMask)==0 ){
122044        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
122045          goto end_auto_index_create;
122046        }
122047        pLoop->aLTerm[nKeyCol++] = pTerm;
122048        idxCols |= cMask;
122049      }
122050    }
122051  }
122052  assert( nKeyCol>0 );
122053  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
122054  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
122055                     | WHERE_AUTO_INDEX;
122056
122057  /* Count the number of additional columns needed to create a
122058  ** covering index.  A "covering index" is an index that contains all
122059  ** columns that are needed by the query.  With a covering index, the
122060  ** original table never needs to be accessed.  Automatic indices must
122061  ** be a covering index because the index will not be updated if the
122062  ** original table changes and the index and table cannot both be used
122063  ** if they go out of sync.
122064  */
122065  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
122066  mxBitCol = MIN(BMS-1,pTable->nCol);
122067  testcase( pTable->nCol==BMS-1 );
122068  testcase( pTable->nCol==BMS-2 );
122069  for(i=0; i<mxBitCol; i++){
122070    if( extraCols & MASKBIT(i) ) nKeyCol++;
122071  }
122072  if( pSrc->colUsed & MASKBIT(BMS-1) ){
122073    nKeyCol += pTable->nCol - BMS + 1;
122074  }
122075
122076  /* Construct the Index object to describe this index */
122077  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
122078  if( pIdx==0 ) goto end_auto_index_create;
122079  pLoop->u.btree.pIndex = pIdx;
122080  pIdx->zName = "auto-index";
122081  pIdx->pTable = pTable;
122082  n = 0;
122083  idxCols = 0;
122084  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
122085    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
122086      int iCol = pTerm->u.leftColumn;
122087      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
122088      testcase( iCol==BMS-1 );
122089      testcase( iCol==BMS );
122090      if( (idxCols & cMask)==0 ){
122091        Expr *pX = pTerm->pExpr;
122092        idxCols |= cMask;
122093        pIdx->aiColumn[n] = pTerm->u.leftColumn;
122094        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
122095        pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
122096        n++;
122097      }
122098    }
122099  }
122100  assert( (u32)n==pLoop->u.btree.nEq );
122101
122102  /* Add additional columns needed to make the automatic index into
122103  ** a covering index */
122104  for(i=0; i<mxBitCol; i++){
122105    if( extraCols & MASKBIT(i) ){
122106      pIdx->aiColumn[n] = i;
122107      pIdx->azColl[n] = "BINARY";
122108      n++;
122109    }
122110  }
122111  if( pSrc->colUsed & MASKBIT(BMS-1) ){
122112    for(i=BMS-1; i<pTable->nCol; i++){
122113      pIdx->aiColumn[n] = i;
122114      pIdx->azColl[n] = "BINARY";
122115      n++;
122116    }
122117  }
122118  assert( n==nKeyCol );
122119  pIdx->aiColumn[n] = XN_ROWID;
122120  pIdx->azColl[n] = "BINARY";
122121
122122  /* Create the automatic index */
122123  assert( pLevel->iIdxCur>=0 );
122124  pLevel->iIdxCur = pParse->nTab++;
122125  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
122126  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
122127  VdbeComment((v, "for %s", pTable->zName));
122128
122129  /* Fill the automatic index with content */
122130  sqlite3ExprCachePush(pParse);
122131  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
122132  if( pTabItem->fg.viaCoroutine ){
122133    int regYield = pTabItem->regReturn;
122134    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
122135    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
122136    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
122137    VdbeCoverage(v);
122138    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
122139  }else{
122140    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
122141  }
122142  if( pPartial ){
122143    iContinue = sqlite3VdbeMakeLabel(v);
122144    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
122145    pLoop->wsFlags |= WHERE_PARTIALIDX;
122146  }
122147  regRecord = sqlite3GetTempReg(pParse);
122148  regBase = sqlite3GenerateIndexKey(
122149      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
122150  );
122151  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
122152  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
122153  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
122154  if( pTabItem->fg.viaCoroutine ){
122155    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
122156    translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
122157    sqlite3VdbeGoto(v, addrTop);
122158    pTabItem->fg.viaCoroutine = 0;
122159  }else{
122160    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
122161  }
122162  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
122163  sqlite3VdbeJumpHere(v, addrTop);
122164  sqlite3ReleaseTempReg(pParse, regRecord);
122165  sqlite3ExprCachePop(pParse);
122166
122167  /* Jump here when skipping the initialization */
122168  sqlite3VdbeJumpHere(v, addrInit);
122169
122170end_auto_index_create:
122171  sqlite3ExprDelete(pParse->db, pPartial);
122172}
122173#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
122174
122175#ifndef SQLITE_OMIT_VIRTUALTABLE
122176/*
122177** Allocate and populate an sqlite3_index_info structure. It is the
122178** responsibility of the caller to eventually release the structure
122179** by passing the pointer returned by this function to sqlite3_free().
122180*/
122181static sqlite3_index_info *allocateIndexInfo(
122182  Parse *pParse,
122183  WhereClause *pWC,
122184  Bitmask mUnusable,              /* Ignore terms with these prereqs */
122185  struct SrcList_item *pSrc,
122186  ExprList *pOrderBy
122187){
122188  int i, j;
122189  int nTerm;
122190  struct sqlite3_index_constraint *pIdxCons;
122191  struct sqlite3_index_orderby *pIdxOrderBy;
122192  struct sqlite3_index_constraint_usage *pUsage;
122193  WhereTerm *pTerm;
122194  int nOrderBy;
122195  sqlite3_index_info *pIdxInfo;
122196
122197  /* Count the number of possible WHERE clause constraints referring
122198  ** to this virtual table */
122199  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
122200    if( pTerm->leftCursor != pSrc->iCursor ) continue;
122201    if( pTerm->prereqRight & mUnusable ) continue;
122202    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
122203    testcase( pTerm->eOperator & WO_IN );
122204    testcase( pTerm->eOperator & WO_ISNULL );
122205    testcase( pTerm->eOperator & WO_IS );
122206    testcase( pTerm->eOperator & WO_ALL );
122207    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
122208    if( pTerm->wtFlags & TERM_VNULL ) continue;
122209    assert( pTerm->u.leftColumn>=(-1) );
122210    nTerm++;
122211  }
122212
122213  /* If the ORDER BY clause contains only columns in the current
122214  ** virtual table then allocate space for the aOrderBy part of
122215  ** the sqlite3_index_info structure.
122216  */
122217  nOrderBy = 0;
122218  if( pOrderBy ){
122219    int n = pOrderBy->nExpr;
122220    for(i=0; i<n; i++){
122221      Expr *pExpr = pOrderBy->a[i].pExpr;
122222      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
122223    }
122224    if( i==n){
122225      nOrderBy = n;
122226    }
122227  }
122228
122229  /* Allocate the sqlite3_index_info structure
122230  */
122231  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
122232                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
122233                           + sizeof(*pIdxOrderBy)*nOrderBy );
122234  if( pIdxInfo==0 ){
122235    sqlite3ErrorMsg(pParse, "out of memory");
122236    return 0;
122237  }
122238
122239  /* Initialize the structure.  The sqlite3_index_info structure contains
122240  ** many fields that are declared "const" to prevent xBestIndex from
122241  ** changing them.  We have to do some funky casting in order to
122242  ** initialize those fields.
122243  */
122244  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
122245  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
122246  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
122247  *(int*)&pIdxInfo->nConstraint = nTerm;
122248  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
122249  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
122250  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
122251  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
122252                                                                   pUsage;
122253
122254  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
122255    u8 op;
122256    if( pTerm->leftCursor != pSrc->iCursor ) continue;
122257    if( pTerm->prereqRight & mUnusable ) continue;
122258    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
122259    testcase( pTerm->eOperator & WO_IN );
122260    testcase( pTerm->eOperator & WO_IS );
122261    testcase( pTerm->eOperator & WO_ISNULL );
122262    testcase( pTerm->eOperator & WO_ALL );
122263    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
122264    if( pTerm->wtFlags & TERM_VNULL ) continue;
122265    assert( pTerm->u.leftColumn>=(-1) );
122266    pIdxCons[j].iColumn = pTerm->u.leftColumn;
122267    pIdxCons[j].iTermOffset = i;
122268    op = (u8)pTerm->eOperator & WO_ALL;
122269    if( op==WO_IN ) op = WO_EQ;
122270    pIdxCons[j].op = op;
122271    /* The direct assignment in the previous line is possible only because
122272    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
122273    ** following asserts verify this fact. */
122274    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
122275    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
122276    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
122277    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
122278    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
122279    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
122280    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
122281    j++;
122282  }
122283  for(i=0; i<nOrderBy; i++){
122284    Expr *pExpr = pOrderBy->a[i].pExpr;
122285    pIdxOrderBy[i].iColumn = pExpr->iColumn;
122286    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
122287  }
122288
122289  return pIdxInfo;
122290}
122291
122292/*
122293** The table object reference passed as the second argument to this function
122294** must represent a virtual table. This function invokes the xBestIndex()
122295** method of the virtual table with the sqlite3_index_info object that
122296** comes in as the 3rd argument to this function.
122297**
122298** If an error occurs, pParse is populated with an error message and a
122299** non-zero value is returned. Otherwise, 0 is returned and the output
122300** part of the sqlite3_index_info structure is left populated.
122301**
122302** Whether or not an error is returned, it is the responsibility of the
122303** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
122304** that this is required.
122305*/
122306static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
122307  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
122308  int i;
122309  int rc;
122310
122311  TRACE_IDX_INPUTS(p);
122312  rc = pVtab->pModule->xBestIndex(pVtab, p);
122313  TRACE_IDX_OUTPUTS(p);
122314
122315  if( rc!=SQLITE_OK ){
122316    if( rc==SQLITE_NOMEM ){
122317      pParse->db->mallocFailed = 1;
122318    }else if( !pVtab->zErrMsg ){
122319      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
122320    }else{
122321      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
122322    }
122323  }
122324  sqlite3_free(pVtab->zErrMsg);
122325  pVtab->zErrMsg = 0;
122326
122327  for(i=0; i<p->nConstraint; i++){
122328    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
122329      sqlite3ErrorMsg(pParse,
122330          "table %s: xBestIndex returned an invalid plan", pTab->zName);
122331    }
122332  }
122333
122334  return pParse->nErr;
122335}
122336#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
122337
122338#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122339/*
122340** Estimate the location of a particular key among all keys in an
122341** index.  Store the results in aStat as follows:
122342**
122343**    aStat[0]      Est. number of rows less than pRec
122344**    aStat[1]      Est. number of rows equal to pRec
122345**
122346** Return the index of the sample that is the smallest sample that
122347** is greater than or equal to pRec. Note that this index is not an index
122348** into the aSample[] array - it is an index into a virtual set of samples
122349** based on the contents of aSample[] and the number of fields in record
122350** pRec.
122351*/
122352static int whereKeyStats(
122353  Parse *pParse,              /* Database connection */
122354  Index *pIdx,                /* Index to consider domain of */
122355  UnpackedRecord *pRec,       /* Vector of values to consider */
122356  int roundUp,                /* Round up if true.  Round down if false */
122357  tRowcnt *aStat              /* OUT: stats written here */
122358){
122359  IndexSample *aSample = pIdx->aSample;
122360  int iCol;                   /* Index of required stats in anEq[] etc. */
122361  int i;                      /* Index of first sample >= pRec */
122362  int iSample;                /* Smallest sample larger than or equal to pRec */
122363  int iMin = 0;               /* Smallest sample not yet tested */
122364  int iTest;                  /* Next sample to test */
122365  int res;                    /* Result of comparison operation */
122366  int nField;                 /* Number of fields in pRec */
122367  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
122368
122369#ifndef SQLITE_DEBUG
122370  UNUSED_PARAMETER( pParse );
122371#endif
122372  assert( pRec!=0 );
122373  assert( pIdx->nSample>0 );
122374  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
122375
122376  /* Do a binary search to find the first sample greater than or equal
122377  ** to pRec. If pRec contains a single field, the set of samples to search
122378  ** is simply the aSample[] array. If the samples in aSample[] contain more
122379  ** than one fields, all fields following the first are ignored.
122380  **
122381  ** If pRec contains N fields, where N is more than one, then as well as the
122382  ** samples in aSample[] (truncated to N fields), the search also has to
122383  ** consider prefixes of those samples. For example, if the set of samples
122384  ** in aSample is:
122385  **
122386  **     aSample[0] = (a, 5)
122387  **     aSample[1] = (a, 10)
122388  **     aSample[2] = (b, 5)
122389  **     aSample[3] = (c, 100)
122390  **     aSample[4] = (c, 105)
122391  **
122392  ** Then the search space should ideally be the samples above and the
122393  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
122394  ** the code actually searches this set:
122395  **
122396  **     0: (a)
122397  **     1: (a, 5)
122398  **     2: (a, 10)
122399  **     3: (a, 10)
122400  **     4: (b)
122401  **     5: (b, 5)
122402  **     6: (c)
122403  **     7: (c, 100)
122404  **     8: (c, 105)
122405  **     9: (c, 105)
122406  **
122407  ** For each sample in the aSample[] array, N samples are present in the
122408  ** effective sample array. In the above, samples 0 and 1 are based on
122409  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
122410  **
122411  ** Often, sample i of each block of N effective samples has (i+1) fields.
122412  ** Except, each sample may be extended to ensure that it is greater than or
122413  ** equal to the previous sample in the array. For example, in the above,
122414  ** sample 2 is the first sample of a block of N samples, so at first it
122415  ** appears that it should be 1 field in size. However, that would make it
122416  ** smaller than sample 1, so the binary search would not work. As a result,
122417  ** it is extended to two fields. The duplicates that this creates do not
122418  ** cause any problems.
122419  */
122420  nField = pRec->nField;
122421  iCol = 0;
122422  iSample = pIdx->nSample * nField;
122423  do{
122424    int iSamp;                    /* Index in aSample[] of test sample */
122425    int n;                        /* Number of fields in test sample */
122426
122427    iTest = (iMin+iSample)/2;
122428    iSamp = iTest / nField;
122429    if( iSamp>0 ){
122430      /* The proposed effective sample is a prefix of sample aSample[iSamp].
122431      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
122432      ** fields that is greater than the previous effective sample.  */
122433      for(n=(iTest % nField) + 1; n<nField; n++){
122434        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
122435      }
122436    }else{
122437      n = iTest + 1;
122438    }
122439
122440    pRec->nField = n;
122441    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
122442    if( res<0 ){
122443      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
122444      iMin = iTest+1;
122445    }else if( res==0 && n<nField ){
122446      iLower = aSample[iSamp].anLt[n-1];
122447      iMin = iTest+1;
122448      res = -1;
122449    }else{
122450      iSample = iTest;
122451      iCol = n-1;
122452    }
122453  }while( res && iMin<iSample );
122454  i = iSample / nField;
122455
122456#ifdef SQLITE_DEBUG
122457  /* The following assert statements check that the binary search code
122458  ** above found the right answer. This block serves no purpose other
122459  ** than to invoke the asserts.  */
122460  if( pParse->db->mallocFailed==0 ){
122461    if( res==0 ){
122462      /* If (res==0) is true, then pRec must be equal to sample i. */
122463      assert( i<pIdx->nSample );
122464      assert( iCol==nField-1 );
122465      pRec->nField = nField;
122466      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
122467           || pParse->db->mallocFailed
122468      );
122469    }else{
122470      /* Unless i==pIdx->nSample, indicating that pRec is larger than
122471      ** all samples in the aSample[] array, pRec must be smaller than the
122472      ** (iCol+1) field prefix of sample i.  */
122473      assert( i<=pIdx->nSample && i>=0 );
122474      pRec->nField = iCol+1;
122475      assert( i==pIdx->nSample
122476           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
122477           || pParse->db->mallocFailed );
122478
122479      /* if i==0 and iCol==0, then record pRec is smaller than all samples
122480      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
122481      ** be greater than or equal to the (iCol) field prefix of sample i.
122482      ** If (i>0), then pRec must also be greater than sample (i-1).  */
122483      if( iCol>0 ){
122484        pRec->nField = iCol;
122485        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
122486             || pParse->db->mallocFailed );
122487      }
122488      if( i>0 ){
122489        pRec->nField = nField;
122490        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
122491             || pParse->db->mallocFailed );
122492      }
122493    }
122494  }
122495#endif /* ifdef SQLITE_DEBUG */
122496
122497  if( res==0 ){
122498    /* Record pRec is equal to sample i */
122499    assert( iCol==nField-1 );
122500    aStat[0] = aSample[i].anLt[iCol];
122501    aStat[1] = aSample[i].anEq[iCol];
122502  }else{
122503    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
122504    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
122505    ** is larger than all samples in the array. */
122506    tRowcnt iUpper, iGap;
122507    if( i>=pIdx->nSample ){
122508      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
122509    }else{
122510      iUpper = aSample[i].anLt[iCol];
122511    }
122512
122513    if( iLower>=iUpper ){
122514      iGap = 0;
122515    }else{
122516      iGap = iUpper - iLower;
122517    }
122518    if( roundUp ){
122519      iGap = (iGap*2)/3;
122520    }else{
122521      iGap = iGap/3;
122522    }
122523    aStat[0] = iLower + iGap;
122524    aStat[1] = pIdx->aAvgEq[iCol];
122525  }
122526
122527  /* Restore the pRec->nField value before returning.  */
122528  pRec->nField = nField;
122529  return i;
122530}
122531#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122532
122533/*
122534** If it is not NULL, pTerm is a term that provides an upper or lower
122535** bound on a range scan. Without considering pTerm, it is estimated
122536** that the scan will visit nNew rows. This function returns the number
122537** estimated to be visited after taking pTerm into account.
122538**
122539** If the user explicitly specified a likelihood() value for this term,
122540** then the return value is the likelihood multiplied by the number of
122541** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
122542** has a likelihood of 0.50, and any other term a likelihood of 0.25.
122543*/
122544static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
122545  LogEst nRet = nNew;
122546  if( pTerm ){
122547    if( pTerm->truthProb<=0 ){
122548      nRet += pTerm->truthProb;
122549    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
122550      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
122551    }
122552  }
122553  return nRet;
122554}
122555
122556
122557#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122558/*
122559** Return the affinity for a single column of an index.
122560*/
122561static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
122562  assert( iCol>=0 && iCol<pIdx->nColumn );
122563  if( !pIdx->zColAff ){
122564    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
122565  }
122566  return pIdx->zColAff[iCol];
122567}
122568#endif
122569
122570
122571#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122572/*
122573** This function is called to estimate the number of rows visited by a
122574** range-scan on a skip-scan index. For example:
122575**
122576**   CREATE INDEX i1 ON t1(a, b, c);
122577**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
122578**
122579** Value pLoop->nOut is currently set to the estimated number of rows
122580** visited for scanning (a=? AND b=?). This function reduces that estimate
122581** by some factor to account for the (c BETWEEN ? AND ?) expression based
122582** on the stat4 data for the index. this scan will be peformed multiple
122583** times (once for each (a,b) combination that matches a=?) is dealt with
122584** by the caller.
122585**
122586** It does this by scanning through all stat4 samples, comparing values
122587** extracted from pLower and pUpper with the corresponding column in each
122588** sample. If L and U are the number of samples found to be less than or
122589** equal to the values extracted from pLower and pUpper respectively, and
122590** N is the total number of samples, the pLoop->nOut value is adjusted
122591** as follows:
122592**
122593**   nOut = nOut * ( min(U - L, 1) / N )
122594**
122595** If pLower is NULL, or a value cannot be extracted from the term, L is
122596** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
122597** U is set to N.
122598**
122599** Normally, this function sets *pbDone to 1 before returning. However,
122600** if no value can be extracted from either pLower or pUpper (and so the
122601** estimate of the number of rows delivered remains unchanged), *pbDone
122602** is left as is.
122603**
122604** If an error occurs, an SQLite error code is returned. Otherwise,
122605** SQLITE_OK.
122606*/
122607static int whereRangeSkipScanEst(
122608  Parse *pParse,       /* Parsing & code generating context */
122609  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
122610  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
122611  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
122612  int *pbDone          /* Set to true if at least one expr. value extracted */
122613){
122614  Index *p = pLoop->u.btree.pIndex;
122615  int nEq = pLoop->u.btree.nEq;
122616  sqlite3 *db = pParse->db;
122617  int nLower = -1;
122618  int nUpper = p->nSample+1;
122619  int rc = SQLITE_OK;
122620  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
122621  CollSeq *pColl;
122622
122623  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
122624  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
122625  sqlite3_value *pVal = 0;        /* Value extracted from record */
122626
122627  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
122628  if( pLower ){
122629    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
122630    nLower = 0;
122631  }
122632  if( pUpper && rc==SQLITE_OK ){
122633    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
122634    nUpper = p2 ? 0 : p->nSample;
122635  }
122636
122637  if( p1 || p2 ){
122638    int i;
122639    int nDiff;
122640    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
122641      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
122642      if( rc==SQLITE_OK && p1 ){
122643        int res = sqlite3MemCompare(p1, pVal, pColl);
122644        if( res>=0 ) nLower++;
122645      }
122646      if( rc==SQLITE_OK && p2 ){
122647        int res = sqlite3MemCompare(p2, pVal, pColl);
122648        if( res>=0 ) nUpper++;
122649      }
122650    }
122651    nDiff = (nUpper - nLower);
122652    if( nDiff<=0 ) nDiff = 1;
122653
122654    /* If there is both an upper and lower bound specified, and the
122655    ** comparisons indicate that they are close together, use the fallback
122656    ** method (assume that the scan visits 1/64 of the rows) for estimating
122657    ** the number of rows visited. Otherwise, estimate the number of rows
122658    ** using the method described in the header comment for this function. */
122659    if( nDiff!=1 || pUpper==0 || pLower==0 ){
122660      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
122661      pLoop->nOut -= nAdjust;
122662      *pbDone = 1;
122663      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
122664                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
122665    }
122666
122667  }else{
122668    assert( *pbDone==0 );
122669  }
122670
122671  sqlite3ValueFree(p1);
122672  sqlite3ValueFree(p2);
122673  sqlite3ValueFree(pVal);
122674
122675  return rc;
122676}
122677#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122678
122679/*
122680** This function is used to estimate the number of rows that will be visited
122681** by scanning an index for a range of values. The range may have an upper
122682** bound, a lower bound, or both. The WHERE clause terms that set the upper
122683** and lower bounds are represented by pLower and pUpper respectively. For
122684** example, assuming that index p is on t1(a):
122685**
122686**   ... FROM t1 WHERE a > ? AND a < ? ...
122687**                    |_____|   |_____|
122688**                       |         |
122689**                     pLower    pUpper
122690**
122691** If either of the upper or lower bound is not present, then NULL is passed in
122692** place of the corresponding WhereTerm.
122693**
122694** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
122695** column subject to the range constraint. Or, equivalently, the number of
122696** equality constraints optimized by the proposed index scan. For example,
122697** assuming index p is on t1(a, b), and the SQL query is:
122698**
122699**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
122700**
122701** then nEq is set to 1 (as the range restricted column, b, is the second
122702** left-most column of the index). Or, if the query is:
122703**
122704**   ... FROM t1 WHERE a > ? AND a < ? ...
122705**
122706** then nEq is set to 0.
122707**
122708** When this function is called, *pnOut is set to the sqlite3LogEst() of the
122709** number of rows that the index scan is expected to visit without
122710** considering the range constraints. If nEq is 0, then *pnOut is the number of
122711** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
122712** to account for the range constraints pLower and pUpper.
122713**
122714** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
122715** used, a single range inequality reduces the search space by a factor of 4.
122716** and a pair of constraints (x>? AND x<?) reduces the expected number of
122717** rows visited by a factor of 64.
122718*/
122719static int whereRangeScanEst(
122720  Parse *pParse,       /* Parsing & code generating context */
122721  WhereLoopBuilder *pBuilder,
122722  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
122723  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
122724  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
122725){
122726  int rc = SQLITE_OK;
122727  int nOut = pLoop->nOut;
122728  LogEst nNew;
122729
122730#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122731  Index *p = pLoop->u.btree.pIndex;
122732  int nEq = pLoop->u.btree.nEq;
122733
122734  if( p->nSample>0 && nEq<p->nSampleCol ){
122735    if( nEq==pBuilder->nRecValid ){
122736      UnpackedRecord *pRec = pBuilder->pRec;
122737      tRowcnt a[2];
122738      u8 aff;
122739
122740      /* Variable iLower will be set to the estimate of the number of rows in
122741      ** the index that are less than the lower bound of the range query. The
122742      ** lower bound being the concatenation of $P and $L, where $P is the
122743      ** key-prefix formed by the nEq values matched against the nEq left-most
122744      ** columns of the index, and $L is the value in pLower.
122745      **
122746      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
122747      ** is not a simple variable or literal value), the lower bound of the
122748      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
122749      ** if $L is available, whereKeyStats() is called for both ($P) and
122750      ** ($P:$L) and the larger of the two returned values is used.
122751      **
122752      ** Similarly, iUpper is to be set to the estimate of the number of rows
122753      ** less than the upper bound of the range query. Where the upper bound
122754      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
122755      ** of iUpper are requested of whereKeyStats() and the smaller used.
122756      **
122757      ** The number of rows between the two bounds is then just iUpper-iLower.
122758      */
122759      tRowcnt iLower;     /* Rows less than the lower bound */
122760      tRowcnt iUpper;     /* Rows less than the upper bound */
122761      int iLwrIdx = -2;   /* aSample[] for the lower bound */
122762      int iUprIdx = -1;   /* aSample[] for the upper bound */
122763
122764      if( pRec ){
122765        testcase( pRec->nField!=pBuilder->nRecValid );
122766        pRec->nField = pBuilder->nRecValid;
122767      }
122768      aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
122769      assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
122770      /* Determine iLower and iUpper using ($P) only. */
122771      if( nEq==0 ){
122772        iLower = 0;
122773        iUpper = p->nRowEst0;
122774      }else{
122775        /* Note: this call could be optimized away - since the same values must
122776        ** have been requested when testing key $P in whereEqualScanEst().  */
122777        whereKeyStats(pParse, p, pRec, 0, a);
122778        iLower = a[0];
122779        iUpper = a[0] + a[1];
122780      }
122781
122782      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
122783      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
122784      assert( p->aSortOrder!=0 );
122785      if( p->aSortOrder[nEq] ){
122786        /* The roles of pLower and pUpper are swapped for a DESC index */
122787        SWAP(WhereTerm*, pLower, pUpper);
122788      }
122789
122790      /* If possible, improve on the iLower estimate using ($P:$L). */
122791      if( pLower ){
122792        int bOk;                    /* True if value is extracted from pExpr */
122793        Expr *pExpr = pLower->pExpr->pRight;
122794        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
122795        if( rc==SQLITE_OK && bOk ){
122796          tRowcnt iNew;
122797          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
122798          iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
122799          if( iNew>iLower ) iLower = iNew;
122800          nOut--;
122801          pLower = 0;
122802        }
122803      }
122804
122805      /* If possible, improve on the iUpper estimate using ($P:$U). */
122806      if( pUpper ){
122807        int bOk;                    /* True if value is extracted from pExpr */
122808        Expr *pExpr = pUpper->pExpr->pRight;
122809        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
122810        if( rc==SQLITE_OK && bOk ){
122811          tRowcnt iNew;
122812          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
122813          iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
122814          if( iNew<iUpper ) iUpper = iNew;
122815          nOut--;
122816          pUpper = 0;
122817        }
122818      }
122819
122820      pBuilder->pRec = pRec;
122821      if( rc==SQLITE_OK ){
122822        if( iUpper>iLower ){
122823          nNew = sqlite3LogEst(iUpper - iLower);
122824          /* TUNING:  If both iUpper and iLower are derived from the same
122825          ** sample, then assume they are 4x more selective.  This brings
122826          ** the estimated selectivity more in line with what it would be
122827          ** if estimated without the use of STAT3/4 tables. */
122828          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
122829        }else{
122830          nNew = 10;        assert( 10==sqlite3LogEst(2) );
122831        }
122832        if( nNew<nOut ){
122833          nOut = nNew;
122834        }
122835        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
122836                           (u32)iLower, (u32)iUpper, nOut));
122837      }
122838    }else{
122839      int bDone = 0;
122840      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
122841      if( bDone ) return rc;
122842    }
122843  }
122844#else
122845  UNUSED_PARAMETER(pParse);
122846  UNUSED_PARAMETER(pBuilder);
122847  assert( pLower || pUpper );
122848#endif
122849  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
122850  nNew = whereRangeAdjust(pLower, nOut);
122851  nNew = whereRangeAdjust(pUpper, nNew);
122852
122853  /* TUNING: If there is both an upper and lower limit and neither limit
122854  ** has an application-defined likelihood(), assume the range is
122855  ** reduced by an additional 75%. This means that, by default, an open-ended
122856  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
122857  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
122858  ** match 1/64 of the index. */
122859  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
122860    nNew -= 20;
122861  }
122862
122863  nOut -= (pLower!=0) + (pUpper!=0);
122864  if( nNew<10 ) nNew = 10;
122865  if( nNew<nOut ) nOut = nNew;
122866#if defined(WHERETRACE_ENABLED)
122867  if( pLoop->nOut>nOut ){
122868    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
122869                    pLoop->nOut, nOut));
122870  }
122871#endif
122872  pLoop->nOut = (LogEst)nOut;
122873  return rc;
122874}
122875
122876#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122877/*
122878** Estimate the number of rows that will be returned based on
122879** an equality constraint x=VALUE and where that VALUE occurs in
122880** the histogram data.  This only works when x is the left-most
122881** column of an index and sqlite_stat3 histogram data is available
122882** for that index.  When pExpr==NULL that means the constraint is
122883** "x IS NULL" instead of "x=VALUE".
122884**
122885** Write the estimated row count into *pnRow and return SQLITE_OK.
122886** If unable to make an estimate, leave *pnRow unchanged and return
122887** non-zero.
122888**
122889** This routine can fail if it is unable to load a collating sequence
122890** required for string comparison, or if unable to allocate memory
122891** for a UTF conversion required for comparison.  The error is stored
122892** in the pParse structure.
122893*/
122894static int whereEqualScanEst(
122895  Parse *pParse,       /* Parsing & code generating context */
122896  WhereLoopBuilder *pBuilder,
122897  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
122898  tRowcnt *pnRow       /* Write the revised row estimate here */
122899){
122900  Index *p = pBuilder->pNew->u.btree.pIndex;
122901  int nEq = pBuilder->pNew->u.btree.nEq;
122902  UnpackedRecord *pRec = pBuilder->pRec;
122903  u8 aff;                   /* Column affinity */
122904  int rc;                   /* Subfunction return code */
122905  tRowcnt a[2];             /* Statistics */
122906  int bOk;
122907
122908  assert( nEq>=1 );
122909  assert( nEq<=p->nColumn );
122910  assert( p->aSample!=0 );
122911  assert( p->nSample>0 );
122912  assert( pBuilder->nRecValid<nEq );
122913
122914  /* If values are not available for all fields of the index to the left
122915  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
122916  if( pBuilder->nRecValid<(nEq-1) ){
122917    return SQLITE_NOTFOUND;
122918  }
122919
122920  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
122921  ** below would return the same value.  */
122922  if( nEq>=p->nColumn ){
122923    *pnRow = 1;
122924    return SQLITE_OK;
122925  }
122926
122927  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
122928  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
122929  pBuilder->pRec = pRec;
122930  if( rc!=SQLITE_OK ) return rc;
122931  if( bOk==0 ) return SQLITE_NOTFOUND;
122932  pBuilder->nRecValid = nEq;
122933
122934  whereKeyStats(pParse, p, pRec, 0, a);
122935  WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
122936  *pnRow = a[1];
122937
122938  return rc;
122939}
122940#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122941
122942#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122943/*
122944** Estimate the number of rows that will be returned based on
122945** an IN constraint where the right-hand side of the IN operator
122946** is a list of values.  Example:
122947**
122948**        WHERE x IN (1,2,3,4)
122949**
122950** Write the estimated row count into *pnRow and return SQLITE_OK.
122951** If unable to make an estimate, leave *pnRow unchanged and return
122952** non-zero.
122953**
122954** This routine can fail if it is unable to load a collating sequence
122955** required for string comparison, or if unable to allocate memory
122956** for a UTF conversion required for comparison.  The error is stored
122957** in the pParse structure.
122958*/
122959static int whereInScanEst(
122960  Parse *pParse,       /* Parsing & code generating context */
122961  WhereLoopBuilder *pBuilder,
122962  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
122963  tRowcnt *pnRow       /* Write the revised row estimate here */
122964){
122965  Index *p = pBuilder->pNew->u.btree.pIndex;
122966  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
122967  int nRecValid = pBuilder->nRecValid;
122968  int rc = SQLITE_OK;     /* Subfunction return code */
122969  tRowcnt nEst;           /* Number of rows for a single term */
122970  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
122971  int i;                  /* Loop counter */
122972
122973  assert( p->aSample!=0 );
122974  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
122975    nEst = nRow0;
122976    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
122977    nRowEst += nEst;
122978    pBuilder->nRecValid = nRecValid;
122979  }
122980
122981  if( rc==SQLITE_OK ){
122982    if( nRowEst > nRow0 ) nRowEst = nRow0;
122983    *pnRow = nRowEst;
122984    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
122985  }
122986  assert( pBuilder->nRecValid==nRecValid );
122987  return rc;
122988}
122989#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122990
122991
122992#ifdef WHERETRACE_ENABLED
122993/*
122994** Print the content of a WhereTerm object
122995*/
122996static void whereTermPrint(WhereTerm *pTerm, int iTerm){
122997  if( pTerm==0 ){
122998    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
122999  }else{
123000    char zType[4];
123001    memcpy(zType, "...", 4);
123002    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
123003    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
123004    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
123005    sqlite3DebugPrintf(
123006       "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
123007       iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
123008       pTerm->eOperator, pTerm->wtFlags);
123009    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
123010  }
123011}
123012#endif
123013
123014#ifdef WHERETRACE_ENABLED
123015/*
123016** Print a WhereLoop object for debugging purposes
123017*/
123018static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
123019  WhereInfo *pWInfo = pWC->pWInfo;
123020  int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
123021  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
123022  Table *pTab = pItem->pTab;
123023  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
123024                     p->iTab, nb, p->maskSelf, nb, p->prereq);
123025  sqlite3DebugPrintf(" %12s",
123026                     pItem->zAlias ? pItem->zAlias : pTab->zName);
123027  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
123028    const char *zName;
123029    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
123030      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
123031        int i = sqlite3Strlen30(zName) - 1;
123032        while( zName[i]!='_' ) i--;
123033        zName += i;
123034      }
123035      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
123036    }else{
123037      sqlite3DebugPrintf("%20s","");
123038    }
123039  }else{
123040    char *z;
123041    if( p->u.vtab.idxStr ){
123042      z = sqlite3_mprintf("(%d,\"%s\",%x)",
123043                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
123044    }else{
123045      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
123046    }
123047    sqlite3DebugPrintf(" %-19s", z);
123048    sqlite3_free(z);
123049  }
123050  if( p->wsFlags & WHERE_SKIPSCAN ){
123051    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
123052  }else{
123053    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
123054  }
123055  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
123056  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
123057    int i;
123058    for(i=0; i<p->nLTerm; i++){
123059      whereTermPrint(p->aLTerm[i], i);
123060    }
123061  }
123062}
123063#endif
123064
123065/*
123066** Convert bulk memory into a valid WhereLoop that can be passed
123067** to whereLoopClear harmlessly.
123068*/
123069static void whereLoopInit(WhereLoop *p){
123070  p->aLTerm = p->aLTermSpace;
123071  p->nLTerm = 0;
123072  p->nLSlot = ArraySize(p->aLTermSpace);
123073  p->wsFlags = 0;
123074}
123075
123076/*
123077** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
123078*/
123079static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
123080  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
123081    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
123082      sqlite3_free(p->u.vtab.idxStr);
123083      p->u.vtab.needFree = 0;
123084      p->u.vtab.idxStr = 0;
123085    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
123086      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
123087      sqlite3DbFree(db, p->u.btree.pIndex);
123088      p->u.btree.pIndex = 0;
123089    }
123090  }
123091}
123092
123093/*
123094** Deallocate internal memory used by a WhereLoop object
123095*/
123096static void whereLoopClear(sqlite3 *db, WhereLoop *p){
123097  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
123098  whereLoopClearUnion(db, p);
123099  whereLoopInit(p);
123100}
123101
123102/*
123103** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
123104*/
123105static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
123106  WhereTerm **paNew;
123107  if( p->nLSlot>=n ) return SQLITE_OK;
123108  n = (n+7)&~7;
123109  paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
123110  if( paNew==0 ) return SQLITE_NOMEM;
123111  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
123112  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
123113  p->aLTerm = paNew;
123114  p->nLSlot = n;
123115  return SQLITE_OK;
123116}
123117
123118/*
123119** Transfer content from the second pLoop into the first.
123120*/
123121static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
123122  whereLoopClearUnion(db, pTo);
123123  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
123124    memset(&pTo->u, 0, sizeof(pTo->u));
123125    return SQLITE_NOMEM;
123126  }
123127  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
123128  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
123129  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
123130    pFrom->u.vtab.needFree = 0;
123131  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
123132    pFrom->u.btree.pIndex = 0;
123133  }
123134  return SQLITE_OK;
123135}
123136
123137/*
123138** Delete a WhereLoop object
123139*/
123140static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
123141  whereLoopClear(db, p);
123142  sqlite3DbFree(db, p);
123143}
123144
123145/*
123146** Free a WhereInfo structure
123147*/
123148static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
123149  if( ALWAYS(pWInfo) ){
123150    int i;
123151    for(i=0; i<pWInfo->nLevel; i++){
123152      WhereLevel *pLevel = &pWInfo->a[i];
123153      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
123154        sqlite3DbFree(db, pLevel->u.in.aInLoop);
123155      }
123156    }
123157    sqlite3WhereClauseClear(&pWInfo->sWC);
123158    while( pWInfo->pLoops ){
123159      WhereLoop *p = pWInfo->pLoops;
123160      pWInfo->pLoops = p->pNextLoop;
123161      whereLoopDelete(db, p);
123162    }
123163    sqlite3DbFree(db, pWInfo);
123164  }
123165}
123166
123167/*
123168** Return TRUE if all of the following are true:
123169**
123170**   (1)  X has the same or lower cost that Y
123171**   (2)  X is a proper subset of Y
123172**   (3)  X skips at least as many columns as Y
123173**
123174** By "proper subset" we mean that X uses fewer WHERE clause terms
123175** than Y and that every WHERE clause term used by X is also used
123176** by Y.
123177**
123178** If X is a proper subset of Y then Y is a better choice and ought
123179** to have a lower cost.  This routine returns TRUE when that cost
123180** relationship is inverted and needs to be adjusted.  The third rule
123181** was added because if X uses skip-scan less than Y it still might
123182** deserve a lower cost even if it is a proper subset of Y.
123183*/
123184static int whereLoopCheaperProperSubset(
123185  const WhereLoop *pX,       /* First WhereLoop to compare */
123186  const WhereLoop *pY        /* Compare against this WhereLoop */
123187){
123188  int i, j;
123189  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
123190    return 0; /* X is not a subset of Y */
123191  }
123192  if( pY->nSkip > pX->nSkip ) return 0;
123193  if( pX->rRun >= pY->rRun ){
123194    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
123195    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
123196  }
123197  for(i=pX->nLTerm-1; i>=0; i--){
123198    if( pX->aLTerm[i]==0 ) continue;
123199    for(j=pY->nLTerm-1; j>=0; j--){
123200      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
123201    }
123202    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
123203  }
123204  return 1;  /* All conditions meet */
123205}
123206
123207/*
123208** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
123209** that:
123210**
123211**   (1) pTemplate costs less than any other WhereLoops that are a proper
123212**       subset of pTemplate
123213**
123214**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
123215**       is a proper subset.
123216**
123217** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
123218** WHERE clause terms than Y and that every WHERE clause term used by X is
123219** also used by Y.
123220*/
123221static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
123222  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
123223  for(; p; p=p->pNextLoop){
123224    if( p->iTab!=pTemplate->iTab ) continue;
123225    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
123226    if( whereLoopCheaperProperSubset(p, pTemplate) ){
123227      /* Adjust pTemplate cost downward so that it is cheaper than its
123228      ** subset p. */
123229      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
123230                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
123231      pTemplate->rRun = p->rRun;
123232      pTemplate->nOut = p->nOut - 1;
123233    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
123234      /* Adjust pTemplate cost upward so that it is costlier than p since
123235      ** pTemplate is a proper subset of p */
123236      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
123237                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
123238      pTemplate->rRun = p->rRun;
123239      pTemplate->nOut = p->nOut + 1;
123240    }
123241  }
123242}
123243
123244/*
123245** Search the list of WhereLoops in *ppPrev looking for one that can be
123246** supplanted by pTemplate.
123247**
123248** Return NULL if the WhereLoop list contains an entry that can supplant
123249** pTemplate, in other words if pTemplate does not belong on the list.
123250**
123251** If pX is a WhereLoop that pTemplate can supplant, then return the
123252** link that points to pX.
123253**
123254** If pTemplate cannot supplant any existing element of the list but needs
123255** to be added to the list, then return a pointer to the tail of the list.
123256*/
123257static WhereLoop **whereLoopFindLesser(
123258  WhereLoop **ppPrev,
123259  const WhereLoop *pTemplate
123260){
123261  WhereLoop *p;
123262  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
123263    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
123264      /* If either the iTab or iSortIdx values for two WhereLoop are different
123265      ** then those WhereLoops need to be considered separately.  Neither is
123266      ** a candidate to replace the other. */
123267      continue;
123268    }
123269    /* In the current implementation, the rSetup value is either zero
123270    ** or the cost of building an automatic index (NlogN) and the NlogN
123271    ** is the same for compatible WhereLoops. */
123272    assert( p->rSetup==0 || pTemplate->rSetup==0
123273                 || p->rSetup==pTemplate->rSetup );
123274
123275    /* whereLoopAddBtree() always generates and inserts the automatic index
123276    ** case first.  Hence compatible candidate WhereLoops never have a larger
123277    ** rSetup. Call this SETUP-INVARIANT */
123278    assert( p->rSetup>=pTemplate->rSetup );
123279
123280    /* Any loop using an appliation-defined index (or PRIMARY KEY or
123281    ** UNIQUE constraint) with one or more == constraints is better
123282    ** than an automatic index. Unless it is a skip-scan. */
123283    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
123284     && (pTemplate->nSkip)==0
123285     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
123286     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
123287     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
123288    ){
123289      break;
123290    }
123291
123292    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
123293    ** discarded.  WhereLoop p is better if:
123294    **   (1)  p has no more dependencies than pTemplate, and
123295    **   (2)  p has an equal or lower cost than pTemplate
123296    */
123297    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
123298     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
123299     && p->rRun<=pTemplate->rRun                      /* (2b) */
123300     && p->nOut<=pTemplate->nOut                      /* (2c) */
123301    ){
123302      return 0;  /* Discard pTemplate */
123303    }
123304
123305    /* If pTemplate is always better than p, then cause p to be overwritten
123306    ** with pTemplate.  pTemplate is better than p if:
123307    **   (1)  pTemplate has no more dependences than p, and
123308    **   (2)  pTemplate has an equal or lower cost than p.
123309    */
123310    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
123311     && p->rRun>=pTemplate->rRun                             /* (2a) */
123312     && p->nOut>=pTemplate->nOut                             /* (2b) */
123313    ){
123314      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
123315      break;   /* Cause p to be overwritten by pTemplate */
123316    }
123317  }
123318  return ppPrev;
123319}
123320
123321/*
123322** Insert or replace a WhereLoop entry using the template supplied.
123323**
123324** An existing WhereLoop entry might be overwritten if the new template
123325** is better and has fewer dependencies.  Or the template will be ignored
123326** and no insert will occur if an existing WhereLoop is faster and has
123327** fewer dependencies than the template.  Otherwise a new WhereLoop is
123328** added based on the template.
123329**
123330** If pBuilder->pOrSet is not NULL then we care about only the
123331** prerequisites and rRun and nOut costs of the N best loops.  That
123332** information is gathered in the pBuilder->pOrSet object.  This special
123333** processing mode is used only for OR clause processing.
123334**
123335** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
123336** still might overwrite similar loops with the new template if the
123337** new template is better.  Loops may be overwritten if the following
123338** conditions are met:
123339**
123340**    (1)  They have the same iTab.
123341**    (2)  They have the same iSortIdx.
123342**    (3)  The template has same or fewer dependencies than the current loop
123343**    (4)  The template has the same or lower cost than the current loop
123344*/
123345static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
123346  WhereLoop **ppPrev, *p;
123347  WhereInfo *pWInfo = pBuilder->pWInfo;
123348  sqlite3 *db = pWInfo->pParse->db;
123349
123350  /* If pBuilder->pOrSet is defined, then only keep track of the costs
123351  ** and prereqs.
123352  */
123353  if( pBuilder->pOrSet!=0 ){
123354    if( pTemplate->nLTerm ){
123355#if WHERETRACE_ENABLED
123356      u16 n = pBuilder->pOrSet->n;
123357      int x =
123358#endif
123359      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
123360                                    pTemplate->nOut);
123361#if WHERETRACE_ENABLED /* 0x8 */
123362      if( sqlite3WhereTrace & 0x8 ){
123363        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
123364        whereLoopPrint(pTemplate, pBuilder->pWC);
123365      }
123366#endif
123367    }
123368    return SQLITE_OK;
123369  }
123370
123371  /* Look for an existing WhereLoop to replace with pTemplate
123372  */
123373  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
123374  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
123375
123376  if( ppPrev==0 ){
123377    /* There already exists a WhereLoop on the list that is better
123378    ** than pTemplate, so just ignore pTemplate */
123379#if WHERETRACE_ENABLED /* 0x8 */
123380    if( sqlite3WhereTrace & 0x8 ){
123381      sqlite3DebugPrintf("   skip: ");
123382      whereLoopPrint(pTemplate, pBuilder->pWC);
123383    }
123384#endif
123385    return SQLITE_OK;
123386  }else{
123387    p = *ppPrev;
123388  }
123389
123390  /* If we reach this point it means that either p[] should be overwritten
123391  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
123392  ** WhereLoop and insert it.
123393  */
123394#if WHERETRACE_ENABLED /* 0x8 */
123395  if( sqlite3WhereTrace & 0x8 ){
123396    if( p!=0 ){
123397      sqlite3DebugPrintf("replace: ");
123398      whereLoopPrint(p, pBuilder->pWC);
123399    }
123400    sqlite3DebugPrintf("    add: ");
123401    whereLoopPrint(pTemplate, pBuilder->pWC);
123402  }
123403#endif
123404  if( p==0 ){
123405    /* Allocate a new WhereLoop to add to the end of the list */
123406    *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
123407    if( p==0 ) return SQLITE_NOMEM;
123408    whereLoopInit(p);
123409    p->pNextLoop = 0;
123410  }else{
123411    /* We will be overwriting WhereLoop p[].  But before we do, first
123412    ** go through the rest of the list and delete any other entries besides
123413    ** p[] that are also supplated by pTemplate */
123414    WhereLoop **ppTail = &p->pNextLoop;
123415    WhereLoop *pToDel;
123416    while( *ppTail ){
123417      ppTail = whereLoopFindLesser(ppTail, pTemplate);
123418      if( ppTail==0 ) break;
123419      pToDel = *ppTail;
123420      if( pToDel==0 ) break;
123421      *ppTail = pToDel->pNextLoop;
123422#if WHERETRACE_ENABLED /* 0x8 */
123423      if( sqlite3WhereTrace & 0x8 ){
123424        sqlite3DebugPrintf(" delete: ");
123425        whereLoopPrint(pToDel, pBuilder->pWC);
123426      }
123427#endif
123428      whereLoopDelete(db, pToDel);
123429    }
123430  }
123431  whereLoopXfer(db, p, pTemplate);
123432  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
123433    Index *pIndex = p->u.btree.pIndex;
123434    if( pIndex && pIndex->tnum==0 ){
123435      p->u.btree.pIndex = 0;
123436    }
123437  }
123438  return SQLITE_OK;
123439}
123440
123441/*
123442** Adjust the WhereLoop.nOut value downward to account for terms of the
123443** WHERE clause that reference the loop but which are not used by an
123444** index.
123445*
123446** For every WHERE clause term that is not used by the index
123447** and which has a truth probability assigned by one of the likelihood(),
123448** likely(), or unlikely() SQL functions, reduce the estimated number
123449** of output rows by the probability specified.
123450**
123451** TUNING:  For every WHERE clause term that is not used by the index
123452** and which does not have an assigned truth probability, heuristics
123453** described below are used to try to estimate the truth probability.
123454** TODO --> Perhaps this is something that could be improved by better
123455** table statistics.
123456**
123457** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
123458** value corresponds to -1 in LogEst notation, so this means decrement
123459** the WhereLoop.nOut field for every such WHERE clause term.
123460**
123461** Heuristic 2:  If there exists one or more WHERE clause terms of the
123462** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
123463** final output row estimate is no greater than 1/4 of the total number
123464** of rows in the table.  In other words, assume that x==EXPR will filter
123465** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
123466** "x" column is boolean or else -1 or 0 or 1 is a common default value
123467** on the "x" column and so in that case only cap the output row estimate
123468** at 1/2 instead of 1/4.
123469*/
123470static void whereLoopOutputAdjust(
123471  WhereClause *pWC,      /* The WHERE clause */
123472  WhereLoop *pLoop,      /* The loop to adjust downward */
123473  LogEst nRow            /* Number of rows in the entire table */
123474){
123475  WhereTerm *pTerm, *pX;
123476  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
123477  int i, j, k;
123478  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
123479
123480  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
123481  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
123482    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
123483    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
123484    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
123485    for(j=pLoop->nLTerm-1; j>=0; j--){
123486      pX = pLoop->aLTerm[j];
123487      if( pX==0 ) continue;
123488      if( pX==pTerm ) break;
123489      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
123490    }
123491    if( j<0 ){
123492      if( pTerm->truthProb<=0 ){
123493        /* If a truth probability is specified using the likelihood() hints,
123494        ** then use the probability provided by the application. */
123495        pLoop->nOut += pTerm->truthProb;
123496      }else{
123497        /* In the absence of explicit truth probabilities, use heuristics to
123498        ** guess a reasonable truth probability. */
123499        pLoop->nOut--;
123500        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
123501          Expr *pRight = pTerm->pExpr->pRight;
123502          testcase( pTerm->pExpr->op==TK_IS );
123503          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
123504            k = 10;
123505          }else{
123506            k = 20;
123507          }
123508          if( iReduce<k ) iReduce = k;
123509        }
123510      }
123511    }
123512  }
123513  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
123514}
123515
123516/*
123517** Adjust the cost C by the costMult facter T.  This only occurs if
123518** compiled with -DSQLITE_ENABLE_COSTMULT
123519*/
123520#ifdef SQLITE_ENABLE_COSTMULT
123521# define ApplyCostMultiplier(C,T)  C += T
123522#else
123523# define ApplyCostMultiplier(C,T)
123524#endif
123525
123526/*
123527** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
123528** index pIndex. Try to match one more.
123529**
123530** When this function is called, pBuilder->pNew->nOut contains the
123531** number of rows expected to be visited by filtering using the nEq
123532** terms only. If it is modified, this value is restored before this
123533** function returns.
123534**
123535** If pProbe->tnum==0, that means pIndex is a fake index used for the
123536** INTEGER PRIMARY KEY.
123537*/
123538static int whereLoopAddBtreeIndex(
123539  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
123540  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
123541  Index *pProbe,                  /* An index on pSrc */
123542  LogEst nInMul                   /* log(Number of iterations due to IN) */
123543){
123544  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
123545  Parse *pParse = pWInfo->pParse;        /* Parsing context */
123546  sqlite3 *db = pParse->db;       /* Database connection malloc context */
123547  WhereLoop *pNew;                /* Template WhereLoop under construction */
123548  WhereTerm *pTerm;               /* A WhereTerm under consideration */
123549  int opMask;                     /* Valid operators for constraints */
123550  WhereScan scan;                 /* Iterator for WHERE terms */
123551  Bitmask saved_prereq;           /* Original value of pNew->prereq */
123552  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
123553  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
123554  u16 saved_nSkip;                /* Original value of pNew->nSkip */
123555  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
123556  LogEst saved_nOut;              /* Original value of pNew->nOut */
123557  int rc = SQLITE_OK;             /* Return code */
123558  LogEst rSize;                   /* Number of rows in the table */
123559  LogEst rLogSize;                /* Logarithm of table size */
123560  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
123561
123562  pNew = pBuilder->pNew;
123563  if( db->mallocFailed ) return SQLITE_NOMEM;
123564
123565  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
123566  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
123567  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
123568    opMask = WO_LT|WO_LE;
123569  }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
123570    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
123571  }else{
123572    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
123573  }
123574  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
123575
123576  assert( pNew->u.btree.nEq<pProbe->nColumn );
123577
123578  saved_nEq = pNew->u.btree.nEq;
123579  saved_nSkip = pNew->nSkip;
123580  saved_nLTerm = pNew->nLTerm;
123581  saved_wsFlags = pNew->wsFlags;
123582  saved_prereq = pNew->prereq;
123583  saved_nOut = pNew->nOut;
123584  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
123585                        opMask, pProbe);
123586  pNew->rSetup = 0;
123587  rSize = pProbe->aiRowLogEst[0];
123588  rLogSize = estLog(rSize);
123589  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
123590    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
123591    LogEst rCostIdx;
123592    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
123593    int nIn = 0;
123594#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123595    int nRecValid = pBuilder->nRecValid;
123596#endif
123597    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
123598     && indexColumnNotNull(pProbe, saved_nEq)
123599    ){
123600      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
123601    }
123602    if( pTerm->prereqRight & pNew->maskSelf ) continue;
123603
123604    /* Do not allow the upper bound of a LIKE optimization range constraint
123605    ** to mix with a lower range bound from some other source */
123606    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
123607
123608    pNew->wsFlags = saved_wsFlags;
123609    pNew->u.btree.nEq = saved_nEq;
123610    pNew->nLTerm = saved_nLTerm;
123611    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
123612    pNew->aLTerm[pNew->nLTerm++] = pTerm;
123613    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
123614
123615    assert( nInMul==0
123616        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
123617        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
123618        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
123619    );
123620
123621    if( eOp & WO_IN ){
123622      Expr *pExpr = pTerm->pExpr;
123623      pNew->wsFlags |= WHERE_COLUMN_IN;
123624      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
123625        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
123626        nIn = 46;  assert( 46==sqlite3LogEst(25) );
123627      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
123628        /* "x IN (value, value, ...)" */
123629        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
123630      }
123631      assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
123632                        ** changes "x IN (?)" into "x=?". */
123633
123634    }else if( eOp & (WO_EQ|WO_IS) ){
123635      int iCol = pProbe->aiColumn[saved_nEq];
123636      pNew->wsFlags |= WHERE_COLUMN_EQ;
123637      assert( saved_nEq==pNew->u.btree.nEq );
123638      if( iCol==XN_ROWID
123639       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
123640      ){
123641        if( iCol>=0 && pProbe->uniqNotNull==0 ){
123642          pNew->wsFlags |= WHERE_UNQ_WANTED;
123643        }else{
123644          pNew->wsFlags |= WHERE_ONEROW;
123645        }
123646      }
123647    }else if( eOp & WO_ISNULL ){
123648      pNew->wsFlags |= WHERE_COLUMN_NULL;
123649    }else if( eOp & (WO_GT|WO_GE) ){
123650      testcase( eOp & WO_GT );
123651      testcase( eOp & WO_GE );
123652      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
123653      pBtm = pTerm;
123654      pTop = 0;
123655      if( pTerm->wtFlags & TERM_LIKEOPT ){
123656        /* Range contraints that come from the LIKE optimization are
123657        ** always used in pairs. */
123658        pTop = &pTerm[1];
123659        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
123660        assert( pTop->wtFlags & TERM_LIKEOPT );
123661        assert( pTop->eOperator==WO_LT );
123662        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
123663        pNew->aLTerm[pNew->nLTerm++] = pTop;
123664        pNew->wsFlags |= WHERE_TOP_LIMIT;
123665      }
123666    }else{
123667      assert( eOp & (WO_LT|WO_LE) );
123668      testcase( eOp & WO_LT );
123669      testcase( eOp & WO_LE );
123670      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
123671      pTop = pTerm;
123672      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
123673                     pNew->aLTerm[pNew->nLTerm-2] : 0;
123674    }
123675
123676    /* At this point pNew->nOut is set to the number of rows expected to
123677    ** be visited by the index scan before considering term pTerm, or the
123678    ** values of nIn and nInMul. In other words, assuming that all
123679    ** "x IN(...)" terms are replaced with "x = ?". This block updates
123680    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
123681    assert( pNew->nOut==saved_nOut );
123682    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
123683      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
123684      ** data, using some other estimate.  */
123685      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
123686    }else{
123687      int nEq = ++pNew->u.btree.nEq;
123688      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
123689
123690      assert( pNew->nOut==saved_nOut );
123691      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
123692        assert( (eOp & WO_IN) || nIn==0 );
123693        testcase( eOp & WO_IN );
123694        pNew->nOut += pTerm->truthProb;
123695        pNew->nOut -= nIn;
123696      }else{
123697#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123698        tRowcnt nOut = 0;
123699        if( nInMul==0
123700         && pProbe->nSample
123701         && pNew->u.btree.nEq<=pProbe->nSampleCol
123702         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
123703        ){
123704          Expr *pExpr = pTerm->pExpr;
123705          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
123706            testcase( eOp & WO_EQ );
123707            testcase( eOp & WO_IS );
123708            testcase( eOp & WO_ISNULL );
123709            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
123710          }else{
123711            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
123712          }
123713          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
123714          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
123715          if( nOut ){
123716            pNew->nOut = sqlite3LogEst(nOut);
123717            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
123718            pNew->nOut -= nIn;
123719          }
123720        }
123721        if( nOut==0 )
123722#endif
123723        {
123724          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
123725          if( eOp & WO_ISNULL ){
123726            /* TUNING: If there is no likelihood() value, assume that a
123727            ** "col IS NULL" expression matches twice as many rows
123728            ** as (col=?). */
123729            pNew->nOut += 10;
123730          }
123731        }
123732      }
123733    }
123734
123735    /* Set rCostIdx to the cost of visiting selected rows in index. Add
123736    ** it to pNew->rRun, which is currently set to the cost of the index
123737    ** seek only. Then, if this is a non-covering index, add the cost of
123738    ** visiting the rows in the main table.  */
123739    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
123740    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
123741    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
123742      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
123743    }
123744    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
123745
123746    nOutUnadjusted = pNew->nOut;
123747    pNew->rRun += nInMul + nIn;
123748    pNew->nOut += nInMul + nIn;
123749    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
123750    rc = whereLoopInsert(pBuilder, pNew);
123751
123752    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
123753      pNew->nOut = saved_nOut;
123754    }else{
123755      pNew->nOut = nOutUnadjusted;
123756    }
123757
123758    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
123759     && pNew->u.btree.nEq<pProbe->nColumn
123760    ){
123761      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
123762    }
123763    pNew->nOut = saved_nOut;
123764#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123765    pBuilder->nRecValid = nRecValid;
123766#endif
123767  }
123768  pNew->prereq = saved_prereq;
123769  pNew->u.btree.nEq = saved_nEq;
123770  pNew->nSkip = saved_nSkip;
123771  pNew->wsFlags = saved_wsFlags;
123772  pNew->nOut = saved_nOut;
123773  pNew->nLTerm = saved_nLTerm;
123774
123775  /* Consider using a skip-scan if there are no WHERE clause constraints
123776  ** available for the left-most terms of the index, and if the average
123777  ** number of repeats in the left-most terms is at least 18.
123778  **
123779  ** The magic number 18 is selected on the basis that scanning 17 rows
123780  ** is almost always quicker than an index seek (even though if the index
123781  ** contains fewer than 2^17 rows we assume otherwise in other parts of
123782  ** the code). And, even if it is not, it should not be too much slower.
123783  ** On the other hand, the extra seeks could end up being significantly
123784  ** more expensive.  */
123785  assert( 42==sqlite3LogEst(18) );
123786  if( saved_nEq==saved_nSkip
123787   && saved_nEq+1<pProbe->nKeyCol
123788   && pProbe->noSkipScan==0
123789   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
123790   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
123791  ){
123792    LogEst nIter;
123793    pNew->u.btree.nEq++;
123794    pNew->nSkip++;
123795    pNew->aLTerm[pNew->nLTerm++] = 0;
123796    pNew->wsFlags |= WHERE_SKIPSCAN;
123797    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
123798    pNew->nOut -= nIter;
123799    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
123800    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
123801    nIter += 5;
123802    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
123803    pNew->nOut = saved_nOut;
123804    pNew->u.btree.nEq = saved_nEq;
123805    pNew->nSkip = saved_nSkip;
123806    pNew->wsFlags = saved_wsFlags;
123807  }
123808
123809  return rc;
123810}
123811
123812/*
123813** Return True if it is possible that pIndex might be useful in
123814** implementing the ORDER BY clause in pBuilder.
123815**
123816** Return False if pBuilder does not contain an ORDER BY clause or
123817** if there is no way for pIndex to be useful in implementing that
123818** ORDER BY clause.
123819*/
123820static int indexMightHelpWithOrderBy(
123821  WhereLoopBuilder *pBuilder,
123822  Index *pIndex,
123823  int iCursor
123824){
123825  ExprList *pOB;
123826  ExprList *aColExpr;
123827  int ii, jj;
123828
123829  if( pIndex->bUnordered ) return 0;
123830  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
123831  for(ii=0; ii<pOB->nExpr; ii++){
123832    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
123833    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
123834      if( pExpr->iColumn<0 ) return 1;
123835      for(jj=0; jj<pIndex->nKeyCol; jj++){
123836        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
123837      }
123838    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
123839      for(jj=0; jj<pIndex->nKeyCol; jj++){
123840        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
123841        if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
123842          return 1;
123843        }
123844      }
123845    }
123846  }
123847  return 0;
123848}
123849
123850/*
123851** Return a bitmask where 1s indicate that the corresponding column of
123852** the table is used by an index.  Only the first 63 columns are considered.
123853*/
123854static Bitmask columnsInIndex(Index *pIdx){
123855  Bitmask m = 0;
123856  int j;
123857  for(j=pIdx->nColumn-1; j>=0; j--){
123858    int x = pIdx->aiColumn[j];
123859    if( x>=0 ){
123860      testcase( x==BMS-1 );
123861      testcase( x==BMS-2 );
123862      if( x<BMS-1 ) m |= MASKBIT(x);
123863    }
123864  }
123865  return m;
123866}
123867
123868/* Check to see if a partial index with pPartIndexWhere can be used
123869** in the current query.  Return true if it can be and false if not.
123870*/
123871static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
123872  int i;
123873  WhereTerm *pTerm;
123874  while( pWhere->op==TK_AND ){
123875    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
123876    pWhere = pWhere->pRight;
123877  }
123878  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
123879    Expr *pExpr = pTerm->pExpr;
123880    if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
123881     && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
123882    ){
123883      return 1;
123884    }
123885  }
123886  return 0;
123887}
123888
123889/*
123890** Add all WhereLoop objects for a single table of the join where the table
123891** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
123892** a b-tree table, not a virtual table.
123893**
123894** The costs (WhereLoop.rRun) of the b-tree loops added by this function
123895** are calculated as follows:
123896**
123897** For a full scan, assuming the table (or index) contains nRow rows:
123898**
123899**     cost = nRow * 3.0                    // full-table scan
123900**     cost = nRow * K                      // scan of covering index
123901**     cost = nRow * (K+3.0)                // scan of non-covering index
123902**
123903** where K is a value between 1.1 and 3.0 set based on the relative
123904** estimated average size of the index and table records.
123905**
123906** For an index scan, where nVisit is the number of index rows visited
123907** by the scan, and nSeek is the number of seek operations required on
123908** the index b-tree:
123909**
123910**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
123911**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
123912**
123913** Normally, nSeek is 1. nSeek values greater than 1 come about if the
123914** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
123915** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
123916**
123917** The estimated values (nRow, nVisit, nSeek) often contain a large amount
123918** of uncertainty.  For this reason, scoring is designed to pick plans that
123919** "do the least harm" if the estimates are inaccurate.  For example, a
123920** log(nRow) factor is omitted from a non-covering index scan in order to
123921** bias the scoring in favor of using an index, since the worst-case
123922** performance of using an index is far better than the worst-case performance
123923** of a full table scan.
123924*/
123925static int whereLoopAddBtree(
123926  WhereLoopBuilder *pBuilder, /* WHERE clause information */
123927  Bitmask mExtra              /* Extra prerequesites for using this table */
123928){
123929  WhereInfo *pWInfo;          /* WHERE analysis context */
123930  Index *pProbe;              /* An index we are evaluating */
123931  Index sPk;                  /* A fake index object for the primary key */
123932  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
123933  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
123934  SrcList *pTabList;          /* The FROM clause */
123935  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
123936  WhereLoop *pNew;            /* Template WhereLoop object */
123937  int rc = SQLITE_OK;         /* Return code */
123938  int iSortIdx = 1;           /* Index number */
123939  int b;                      /* A boolean value */
123940  LogEst rSize;               /* number of rows in the table */
123941  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
123942  WhereClause *pWC;           /* The parsed WHERE clause */
123943  Table *pTab;                /* Table being queried */
123944
123945  pNew = pBuilder->pNew;
123946  pWInfo = pBuilder->pWInfo;
123947  pTabList = pWInfo->pTabList;
123948  pSrc = pTabList->a + pNew->iTab;
123949  pTab = pSrc->pTab;
123950  pWC = pBuilder->pWC;
123951  assert( !IsVirtual(pSrc->pTab) );
123952
123953  if( pSrc->pIBIndex ){
123954    /* An INDEXED BY clause specifies a particular index to use */
123955    pProbe = pSrc->pIBIndex;
123956  }else if( !HasRowid(pTab) ){
123957    pProbe = pTab->pIndex;
123958  }else{
123959    /* There is no INDEXED BY clause.  Create a fake Index object in local
123960    ** variable sPk to represent the rowid primary key index.  Make this
123961    ** fake index the first in a chain of Index objects with all of the real
123962    ** indices to follow */
123963    Index *pFirst;                  /* First of real indices on the table */
123964    memset(&sPk, 0, sizeof(Index));
123965    sPk.nKeyCol = 1;
123966    sPk.nColumn = 1;
123967    sPk.aiColumn = &aiColumnPk;
123968    sPk.aiRowLogEst = aiRowEstPk;
123969    sPk.onError = OE_Replace;
123970    sPk.pTable = pTab;
123971    sPk.szIdxRow = pTab->szTabRow;
123972    aiRowEstPk[0] = pTab->nRowLogEst;
123973    aiRowEstPk[1] = 0;
123974    pFirst = pSrc->pTab->pIndex;
123975    if( pSrc->fg.notIndexed==0 ){
123976      /* The real indices of the table are only considered if the
123977      ** NOT INDEXED qualifier is omitted from the FROM clause */
123978      sPk.pNext = pFirst;
123979    }
123980    pProbe = &sPk;
123981  }
123982  rSize = pTab->nRowLogEst;
123983  rLogSize = estLog(rSize);
123984
123985#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
123986  /* Automatic indexes */
123987  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
123988   && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
123989   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
123990   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
123991   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
123992   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
123993   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
123994   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
123995  ){
123996    /* Generate auto-index WhereLoops */
123997    WhereTerm *pTerm;
123998    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
123999    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
124000      if( pTerm->prereqRight & pNew->maskSelf ) continue;
124001      if( termCanDriveIndex(pTerm, pSrc, 0) ){
124002        pNew->u.btree.nEq = 1;
124003        pNew->nSkip = 0;
124004        pNew->u.btree.pIndex = 0;
124005        pNew->nLTerm = 1;
124006        pNew->aLTerm[0] = pTerm;
124007        /* TUNING: One-time cost for computing the automatic index is
124008        ** estimated to be X*N*log2(N) where N is the number of rows in
124009        ** the table being indexed and where X is 7 (LogEst=28) for normal
124010        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
124011        ** of X is smaller for views and subqueries so that the query planner
124012        ** will be more aggressive about generating automatic indexes for
124013        ** those objects, since there is no opportunity to add schema
124014        ** indexes on subqueries and views. */
124015        pNew->rSetup = rLogSize + rSize + 4;
124016        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
124017          pNew->rSetup += 24;
124018        }
124019        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
124020        /* TUNING: Each index lookup yields 20 rows in the table.  This
124021        ** is more than the usual guess of 10 rows, since we have no way
124022        ** of knowing how selective the index will ultimately be.  It would
124023        ** not be unreasonable to make this value much larger. */
124024        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
124025        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
124026        pNew->wsFlags = WHERE_AUTO_INDEX;
124027        pNew->prereq = mExtra | pTerm->prereqRight;
124028        rc = whereLoopInsert(pBuilder, pNew);
124029      }
124030    }
124031  }
124032#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
124033
124034  /* Loop over all indices
124035  */
124036  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
124037    if( pProbe->pPartIdxWhere!=0
124038     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
124039      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
124040      continue;  /* Partial index inappropriate for this query */
124041    }
124042    rSize = pProbe->aiRowLogEst[0];
124043    pNew->u.btree.nEq = 0;
124044    pNew->nSkip = 0;
124045    pNew->nLTerm = 0;
124046    pNew->iSortIdx = 0;
124047    pNew->rSetup = 0;
124048    pNew->prereq = mExtra;
124049    pNew->nOut = rSize;
124050    pNew->u.btree.pIndex = pProbe;
124051    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
124052    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
124053    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
124054    if( pProbe->tnum<=0 ){
124055      /* Integer primary key index */
124056      pNew->wsFlags = WHERE_IPK;
124057
124058      /* Full table scan */
124059      pNew->iSortIdx = b ? iSortIdx : 0;
124060      /* TUNING: Cost of full table scan is (N*3.0). */
124061      pNew->rRun = rSize + 16;
124062      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
124063      whereLoopOutputAdjust(pWC, pNew, rSize);
124064      rc = whereLoopInsert(pBuilder, pNew);
124065      pNew->nOut = rSize;
124066      if( rc ) break;
124067    }else{
124068      Bitmask m;
124069      if( pProbe->isCovering ){
124070        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
124071        m = 0;
124072      }else{
124073        m = pSrc->colUsed & ~columnsInIndex(pProbe);
124074        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
124075      }
124076
124077      /* Full scan via index */
124078      if( b
124079       || !HasRowid(pTab)
124080       || ( m==0
124081         && pProbe->bUnordered==0
124082         && (pProbe->szIdxRow<pTab->szTabRow)
124083         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
124084         && sqlite3GlobalConfig.bUseCis
124085         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
124086          )
124087      ){
124088        pNew->iSortIdx = b ? iSortIdx : 0;
124089
124090        /* The cost of visiting the index rows is N*K, where K is
124091        ** between 1.1 and 3.0, depending on the relative sizes of the
124092        ** index and table rows. If this is a non-covering index scan,
124093        ** also add the cost of visiting table rows (N*3.0).  */
124094        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
124095        if( m!=0 ){
124096          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
124097        }
124098        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
124099        whereLoopOutputAdjust(pWC, pNew, rSize);
124100        rc = whereLoopInsert(pBuilder, pNew);
124101        pNew->nOut = rSize;
124102        if( rc ) break;
124103      }
124104    }
124105
124106    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
124107#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124108    sqlite3Stat4ProbeFree(pBuilder->pRec);
124109    pBuilder->nRecValid = 0;
124110    pBuilder->pRec = 0;
124111#endif
124112
124113    /* If there was an INDEXED BY clause, then only that one index is
124114    ** considered. */
124115    if( pSrc->pIBIndex ) break;
124116  }
124117  return rc;
124118}
124119
124120#ifndef SQLITE_OMIT_VIRTUALTABLE
124121/*
124122** Add all WhereLoop objects for a table of the join identified by
124123** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
124124**
124125** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
124126** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
124127** entries that occur before the virtual table in the FROM clause and are
124128** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
124129** mUnusable mask contains all FROM clause entries that occur after the
124130** virtual table and are separated from it by at least one LEFT or
124131** CROSS JOIN.
124132**
124133** For example, if the query were:
124134**
124135**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
124136**
124137** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
124138**
124139** All the tables in mExtra must be scanned before the current virtual
124140** table. So any terms for which all prerequisites are satisfied by
124141** mExtra may be specified as "usable" in all calls to xBestIndex.
124142** Conversely, all tables in mUnusable must be scanned after the current
124143** virtual table, so any terms for which the prerequisites overlap with
124144** mUnusable should always be configured as "not-usable" for xBestIndex.
124145*/
124146static int whereLoopAddVirtual(
124147  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
124148  Bitmask mExtra,              /* Tables that must be scanned before this one */
124149  Bitmask mUnusable            /* Tables that must be scanned after this one */
124150){
124151  WhereInfo *pWInfo;           /* WHERE analysis context */
124152  Parse *pParse;               /* The parsing context */
124153  WhereClause *pWC;            /* The WHERE clause */
124154  struct SrcList_item *pSrc;   /* The FROM clause term to search */
124155  Table *pTab;
124156  sqlite3 *db;
124157  sqlite3_index_info *pIdxInfo;
124158  struct sqlite3_index_constraint *pIdxCons;
124159  struct sqlite3_index_constraint_usage *pUsage;
124160  WhereTerm *pTerm;
124161  int i, j;
124162  int iTerm, mxTerm;
124163  int nConstraint;
124164  int seenIn = 0;              /* True if an IN operator is seen */
124165  int seenVar = 0;             /* True if a non-constant constraint is seen */
124166  int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
124167  WhereLoop *pNew;
124168  int rc = SQLITE_OK;
124169
124170  assert( (mExtra & mUnusable)==0 );
124171  pWInfo = pBuilder->pWInfo;
124172  pParse = pWInfo->pParse;
124173  db = pParse->db;
124174  pWC = pBuilder->pWC;
124175  pNew = pBuilder->pNew;
124176  pSrc = &pWInfo->pTabList->a[pNew->iTab];
124177  pTab = pSrc->pTab;
124178  assert( IsVirtual(pTab) );
124179  pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
124180  if( pIdxInfo==0 ) return SQLITE_NOMEM;
124181  pNew->prereq = 0;
124182  pNew->rSetup = 0;
124183  pNew->wsFlags = WHERE_VIRTUALTABLE;
124184  pNew->nLTerm = 0;
124185  pNew->u.vtab.needFree = 0;
124186  pUsage = pIdxInfo->aConstraintUsage;
124187  nConstraint = pIdxInfo->nConstraint;
124188  if( whereLoopResize(db, pNew, nConstraint) ){
124189    sqlite3DbFree(db, pIdxInfo);
124190    return SQLITE_NOMEM;
124191  }
124192
124193  for(iPhase=0; iPhase<=3; iPhase++){
124194    if( !seenIn && (iPhase&1)!=0 ){
124195      iPhase++;
124196      if( iPhase>3 ) break;
124197    }
124198    if( !seenVar && iPhase>1 ) break;
124199    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
124200    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
124201      j = pIdxCons->iTermOffset;
124202      pTerm = &pWC->a[j];
124203      switch( iPhase ){
124204        case 0:    /* Constants without IN operator */
124205          pIdxCons->usable = 0;
124206          if( (pTerm->eOperator & WO_IN)!=0 ){
124207            seenIn = 1;
124208          }
124209          if( (pTerm->prereqRight & ~mExtra)!=0 ){
124210            seenVar = 1;
124211          }else if( (pTerm->eOperator & WO_IN)==0 ){
124212            pIdxCons->usable = 1;
124213          }
124214          break;
124215        case 1:    /* Constants with IN operators */
124216          assert( seenIn );
124217          pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
124218          break;
124219        case 2:    /* Variables without IN */
124220          assert( seenVar );
124221          pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
124222          break;
124223        default:   /* Variables with IN */
124224          assert( seenVar && seenIn );
124225          pIdxCons->usable = 1;
124226          break;
124227      }
124228    }
124229    memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
124230    if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
124231    pIdxInfo->idxStr = 0;
124232    pIdxInfo->idxNum = 0;
124233    pIdxInfo->needToFreeIdxStr = 0;
124234    pIdxInfo->orderByConsumed = 0;
124235    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
124236    pIdxInfo->estimatedRows = 25;
124237    pIdxInfo->idxFlags = 0;
124238    rc = vtabBestIndex(pParse, pTab, pIdxInfo);
124239    if( rc ) goto whereLoopAddVtab_exit;
124240    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
124241    pNew->prereq = mExtra;
124242    mxTerm = -1;
124243    assert( pNew->nLSlot>=nConstraint );
124244    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
124245    pNew->u.vtab.omitMask = 0;
124246    for(i=0; i<nConstraint; i++, pIdxCons++){
124247      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
124248        j = pIdxCons->iTermOffset;
124249        if( iTerm>=nConstraint
124250         || j<0
124251         || j>=pWC->nTerm
124252         || pNew->aLTerm[iTerm]!=0
124253        ){
124254          rc = SQLITE_ERROR;
124255          sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
124256          goto whereLoopAddVtab_exit;
124257        }
124258        testcase( iTerm==nConstraint-1 );
124259        testcase( j==0 );
124260        testcase( j==pWC->nTerm-1 );
124261        pTerm = &pWC->a[j];
124262        pNew->prereq |= pTerm->prereqRight;
124263        assert( iTerm<pNew->nLSlot );
124264        pNew->aLTerm[iTerm] = pTerm;
124265        if( iTerm>mxTerm ) mxTerm = iTerm;
124266        testcase( iTerm==15 );
124267        testcase( iTerm==16 );
124268        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
124269        if( (pTerm->eOperator & WO_IN)!=0 ){
124270          if( pUsage[i].omit==0 ){
124271            /* Do not attempt to use an IN constraint if the virtual table
124272            ** says that the equivalent EQ constraint cannot be safely omitted.
124273            ** If we do attempt to use such a constraint, some rows might be
124274            ** repeated in the output. */
124275            break;
124276          }
124277          /* A virtual table that is constrained by an IN clause may not
124278          ** consume the ORDER BY clause because (1) the order of IN terms
124279          ** is not necessarily related to the order of output terms and
124280          ** (2) Multiple outputs from a single IN value will not merge
124281          ** together.  */
124282          pIdxInfo->orderByConsumed = 0;
124283          pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
124284        }
124285      }
124286    }
124287    if( i>=nConstraint ){
124288      pNew->nLTerm = mxTerm+1;
124289      assert( pNew->nLTerm<=pNew->nLSlot );
124290      pNew->u.vtab.idxNum = pIdxInfo->idxNum;
124291      pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
124292      pIdxInfo->needToFreeIdxStr = 0;
124293      pNew->u.vtab.idxStr = pIdxInfo->idxStr;
124294      pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
124295                                      pIdxInfo->nOrderBy : 0);
124296      pNew->rSetup = 0;
124297      pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
124298      pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
124299
124300      /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
124301      ** that the scan will visit at most one row. Clear it otherwise. */
124302      if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
124303        pNew->wsFlags |= WHERE_ONEROW;
124304      }else{
124305        pNew->wsFlags &= ~WHERE_ONEROW;
124306      }
124307      whereLoopInsert(pBuilder, pNew);
124308      if( pNew->u.vtab.needFree ){
124309        sqlite3_free(pNew->u.vtab.idxStr);
124310        pNew->u.vtab.needFree = 0;
124311      }
124312    }
124313  }
124314
124315whereLoopAddVtab_exit:
124316  if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
124317  sqlite3DbFree(db, pIdxInfo);
124318  return rc;
124319}
124320#endif /* SQLITE_OMIT_VIRTUALTABLE */
124321
124322/*
124323** Add WhereLoop entries to handle OR terms.  This works for either
124324** btrees or virtual tables.
124325*/
124326static int whereLoopAddOr(
124327  WhereLoopBuilder *pBuilder,
124328  Bitmask mExtra,
124329  Bitmask mUnusable
124330){
124331  WhereInfo *pWInfo = pBuilder->pWInfo;
124332  WhereClause *pWC;
124333  WhereLoop *pNew;
124334  WhereTerm *pTerm, *pWCEnd;
124335  int rc = SQLITE_OK;
124336  int iCur;
124337  WhereClause tempWC;
124338  WhereLoopBuilder sSubBuild;
124339  WhereOrSet sSum, sCur;
124340  struct SrcList_item *pItem;
124341
124342  pWC = pBuilder->pWC;
124343  pWCEnd = pWC->a + pWC->nTerm;
124344  pNew = pBuilder->pNew;
124345  memset(&sSum, 0, sizeof(sSum));
124346  pItem = pWInfo->pTabList->a + pNew->iTab;
124347  iCur = pItem->iCursor;
124348
124349  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
124350    if( (pTerm->eOperator & WO_OR)!=0
124351     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
124352    ){
124353      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
124354      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
124355      WhereTerm *pOrTerm;
124356      int once = 1;
124357      int i, j;
124358
124359      sSubBuild = *pBuilder;
124360      sSubBuild.pOrderBy = 0;
124361      sSubBuild.pOrSet = &sCur;
124362
124363      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
124364      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
124365        if( (pOrTerm->eOperator & WO_AND)!=0 ){
124366          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
124367        }else if( pOrTerm->leftCursor==iCur ){
124368          tempWC.pWInfo = pWC->pWInfo;
124369          tempWC.pOuter = pWC;
124370          tempWC.op = TK_AND;
124371          tempWC.nTerm = 1;
124372          tempWC.a = pOrTerm;
124373          sSubBuild.pWC = &tempWC;
124374        }else{
124375          continue;
124376        }
124377        sCur.n = 0;
124378#ifdef WHERETRACE_ENABLED
124379        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
124380                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
124381        if( sqlite3WhereTrace & 0x400 ){
124382          for(i=0; i<sSubBuild.pWC->nTerm; i++){
124383            whereTermPrint(&sSubBuild.pWC->a[i], i);
124384          }
124385        }
124386#endif
124387#ifndef SQLITE_OMIT_VIRTUALTABLE
124388        if( IsVirtual(pItem->pTab) ){
124389          rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
124390        }else
124391#endif
124392        {
124393          rc = whereLoopAddBtree(&sSubBuild, mExtra);
124394        }
124395        if( rc==SQLITE_OK ){
124396          rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
124397        }
124398        assert( rc==SQLITE_OK || sCur.n==0 );
124399        if( sCur.n==0 ){
124400          sSum.n = 0;
124401          break;
124402        }else if( once ){
124403          whereOrMove(&sSum, &sCur);
124404          once = 0;
124405        }else{
124406          WhereOrSet sPrev;
124407          whereOrMove(&sPrev, &sSum);
124408          sSum.n = 0;
124409          for(i=0; i<sPrev.n; i++){
124410            for(j=0; j<sCur.n; j++){
124411              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
124412                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
124413                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
124414            }
124415          }
124416        }
124417      }
124418      pNew->nLTerm = 1;
124419      pNew->aLTerm[0] = pTerm;
124420      pNew->wsFlags = WHERE_MULTI_OR;
124421      pNew->rSetup = 0;
124422      pNew->iSortIdx = 0;
124423      memset(&pNew->u, 0, sizeof(pNew->u));
124424      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
124425        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
124426        ** of all sub-scans required by the OR-scan. However, due to rounding
124427        ** errors, it may be that the cost of the OR-scan is equal to its
124428        ** most expensive sub-scan. Add the smallest possible penalty
124429        ** (equivalent to multiplying the cost by 1.07) to ensure that
124430        ** this does not happen. Otherwise, for WHERE clauses such as the
124431        ** following where there is an index on "y":
124432        **
124433        **     WHERE likelihood(x=?, 0.99) OR y=?
124434        **
124435        ** the planner may elect to "OR" together a full-table scan and an
124436        ** index lookup. And other similarly odd results.  */
124437        pNew->rRun = sSum.a[i].rRun + 1;
124438        pNew->nOut = sSum.a[i].nOut;
124439        pNew->prereq = sSum.a[i].prereq;
124440        rc = whereLoopInsert(pBuilder, pNew);
124441      }
124442      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
124443    }
124444  }
124445  return rc;
124446}
124447
124448/*
124449** Add all WhereLoop objects for all tables
124450*/
124451static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
124452  WhereInfo *pWInfo = pBuilder->pWInfo;
124453  Bitmask mExtra = 0;
124454  Bitmask mPrior = 0;
124455  int iTab;
124456  SrcList *pTabList = pWInfo->pTabList;
124457  struct SrcList_item *pItem;
124458  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
124459  sqlite3 *db = pWInfo->pParse->db;
124460  int rc = SQLITE_OK;
124461  WhereLoop *pNew;
124462  u8 priorJointype = 0;
124463
124464  /* Loop over the tables in the join, from left to right */
124465  pNew = pBuilder->pNew;
124466  whereLoopInit(pNew);
124467  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
124468    Bitmask mUnusable = 0;
124469    pNew->iTab = iTab;
124470    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
124471    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
124472      /* This condition is true when pItem is the FROM clause term on the
124473      ** right-hand-side of a LEFT or CROSS JOIN.  */
124474      mExtra = mPrior;
124475    }
124476    priorJointype = pItem->fg.jointype;
124477    if( IsVirtual(pItem->pTab) ){
124478      struct SrcList_item *p;
124479      for(p=&pItem[1]; p<pEnd; p++){
124480        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
124481          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
124482        }
124483      }
124484      rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
124485    }else{
124486      rc = whereLoopAddBtree(pBuilder, mExtra);
124487    }
124488    if( rc==SQLITE_OK ){
124489      rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
124490    }
124491    mPrior |= pNew->maskSelf;
124492    if( rc || db->mallocFailed ) break;
124493  }
124494
124495  whereLoopClear(db, pNew);
124496  return rc;
124497}
124498
124499/*
124500** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
124501** parameters) to see if it outputs rows in the requested ORDER BY
124502** (or GROUP BY) without requiring a separate sort operation.  Return N:
124503**
124504**   N>0:   N terms of the ORDER BY clause are satisfied
124505**   N==0:  No terms of the ORDER BY clause are satisfied
124506**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
124507**
124508** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
124509** strict.  With GROUP BY and DISTINCT the only requirement is that
124510** equivalent rows appear immediately adjacent to one another.  GROUP BY
124511** and DISTINCT do not require rows to appear in any particular order as long
124512** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
124513** the pOrderBy terms can be matched in any order.  With ORDER BY, the
124514** pOrderBy terms must be matched in strict left-to-right order.
124515*/
124516static i8 wherePathSatisfiesOrderBy(
124517  WhereInfo *pWInfo,    /* The WHERE clause */
124518  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
124519  WherePath *pPath,     /* The WherePath to check */
124520  u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
124521  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
124522  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
124523  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
124524){
124525  u8 revSet;            /* True if rev is known */
124526  u8 rev;               /* Composite sort order */
124527  u8 revIdx;            /* Index sort order */
124528  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
124529  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
124530  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
124531  u16 nKeyCol;          /* Number of key columns in pIndex */
124532  u16 nColumn;          /* Total number of ordered columns in the index */
124533  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
124534  int iLoop;            /* Index of WhereLoop in pPath being processed */
124535  int i, j;             /* Loop counters */
124536  int iCur;             /* Cursor number for current WhereLoop */
124537  int iColumn;          /* A column number within table iCur */
124538  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
124539  WhereTerm *pTerm;     /* A single term of the WHERE clause */
124540  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
124541  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
124542  Index *pIndex;        /* The index associated with pLoop */
124543  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
124544  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
124545  Bitmask obDone;       /* Mask of all ORDER BY terms */
124546  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
124547  Bitmask ready;              /* Mask of inner loops */
124548
124549  /*
124550  ** We say the WhereLoop is "one-row" if it generates no more than one
124551  ** row of output.  A WhereLoop is one-row if all of the following are true:
124552  **  (a) All index columns match with WHERE_COLUMN_EQ.
124553  **  (b) The index is unique
124554  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
124555  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
124556  **
124557  ** We say the WhereLoop is "order-distinct" if the set of columns from
124558  ** that WhereLoop that are in the ORDER BY clause are different for every
124559  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
124560  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
124561  ** is not order-distinct. To be order-distinct is not quite the same as being
124562  ** UNIQUE since a UNIQUE column or index can have multiple rows that
124563  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
124564  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
124565  **
124566  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
124567  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
124568  ** automatically order-distinct.
124569  */
124570
124571  assert( pOrderBy!=0 );
124572  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
124573
124574  nOrderBy = pOrderBy->nExpr;
124575  testcase( nOrderBy==BMS-1 );
124576  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
124577  isOrderDistinct = 1;
124578  obDone = MASKBIT(nOrderBy)-1;
124579  orderDistinctMask = 0;
124580  ready = 0;
124581  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
124582    if( iLoop>0 ) ready |= pLoop->maskSelf;
124583    pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
124584    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
124585      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
124586      break;
124587    }
124588    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
124589
124590    /* Mark off any ORDER BY term X that is a column in the table of
124591    ** the current loop for which there is term in the WHERE
124592    ** clause of the form X IS NULL or X=? that reference only outer
124593    ** loops.
124594    */
124595    for(i=0; i<nOrderBy; i++){
124596      if( MASKBIT(i) & obSat ) continue;
124597      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
124598      if( pOBExpr->op!=TK_COLUMN ) continue;
124599      if( pOBExpr->iTable!=iCur ) continue;
124600      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
124601                       ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
124602      if( pTerm==0 ) continue;
124603      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
124604        const char *z1, *z2;
124605        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
124606        if( !pColl ) pColl = db->pDfltColl;
124607        z1 = pColl->zName;
124608        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
124609        if( !pColl ) pColl = db->pDfltColl;
124610        z2 = pColl->zName;
124611        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
124612        testcase( pTerm->pExpr->op==TK_IS );
124613      }
124614      obSat |= MASKBIT(i);
124615    }
124616
124617    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
124618      if( pLoop->wsFlags & WHERE_IPK ){
124619        pIndex = 0;
124620        nKeyCol = 0;
124621        nColumn = 1;
124622      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
124623        return 0;
124624      }else{
124625        nKeyCol = pIndex->nKeyCol;
124626        nColumn = pIndex->nColumn;
124627        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
124628        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
124629                          || !HasRowid(pIndex->pTable));
124630        isOrderDistinct = IsUniqueIndex(pIndex);
124631      }
124632
124633      /* Loop through all columns of the index and deal with the ones
124634      ** that are not constrained by == or IN.
124635      */
124636      rev = revSet = 0;
124637      distinctColumns = 0;
124638      for(j=0; j<nColumn; j++){
124639        u8 bOnce;   /* True to run the ORDER BY search loop */
124640
124641        /* Skip over == and IS NULL terms */
124642        if( j<pLoop->u.btree.nEq
124643         && pLoop->nSkip==0
124644         && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
124645        ){
124646          if( i & WO_ISNULL ){
124647            testcase( isOrderDistinct );
124648            isOrderDistinct = 0;
124649          }
124650          continue;
124651        }
124652
124653        /* Get the column number in the table (iColumn) and sort order
124654        ** (revIdx) for the j-th column of the index.
124655        */
124656        if( pIndex ){
124657          iColumn = pIndex->aiColumn[j];
124658          revIdx = pIndex->aSortOrder[j];
124659          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
124660        }else{
124661          iColumn = XN_ROWID;
124662          revIdx = 0;
124663        }
124664
124665        /* An unconstrained column that might be NULL means that this
124666        ** WhereLoop is not well-ordered
124667        */
124668        if( isOrderDistinct
124669         && iColumn>=0
124670         && j>=pLoop->u.btree.nEq
124671         && pIndex->pTable->aCol[iColumn].notNull==0
124672        ){
124673          isOrderDistinct = 0;
124674        }
124675
124676        /* Find the ORDER BY term that corresponds to the j-th column
124677        ** of the index and mark that ORDER BY term off
124678        */
124679        bOnce = 1;
124680        isMatch = 0;
124681        for(i=0; bOnce && i<nOrderBy; i++){
124682          if( MASKBIT(i) & obSat ) continue;
124683          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
124684          testcase( wctrlFlags & WHERE_GROUPBY );
124685          testcase( wctrlFlags & WHERE_DISTINCTBY );
124686          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
124687          if( iColumn>=(-1) ){
124688            if( pOBExpr->op!=TK_COLUMN ) continue;
124689            if( pOBExpr->iTable!=iCur ) continue;
124690            if( pOBExpr->iColumn!=iColumn ) continue;
124691          }else{
124692            if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
124693              continue;
124694            }
124695          }
124696          if( iColumn>=0 ){
124697            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
124698            if( !pColl ) pColl = db->pDfltColl;
124699            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
124700          }
124701          isMatch = 1;
124702          break;
124703        }
124704        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
124705          /* Make sure the sort order is compatible in an ORDER BY clause.
124706          ** Sort order is irrelevant for a GROUP BY clause. */
124707          if( revSet ){
124708            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
124709          }else{
124710            rev = revIdx ^ pOrderBy->a[i].sortOrder;
124711            if( rev ) *pRevMask |= MASKBIT(iLoop);
124712            revSet = 1;
124713          }
124714        }
124715        if( isMatch ){
124716          if( iColumn<0 ){
124717            testcase( distinctColumns==0 );
124718            distinctColumns = 1;
124719          }
124720          obSat |= MASKBIT(i);
124721        }else{
124722          /* No match found */
124723          if( j==0 || j<nKeyCol ){
124724            testcase( isOrderDistinct!=0 );
124725            isOrderDistinct = 0;
124726          }
124727          break;
124728        }
124729      } /* end Loop over all index columns */
124730      if( distinctColumns ){
124731        testcase( isOrderDistinct==0 );
124732        isOrderDistinct = 1;
124733      }
124734    } /* end-if not one-row */
124735
124736    /* Mark off any other ORDER BY terms that reference pLoop */
124737    if( isOrderDistinct ){
124738      orderDistinctMask |= pLoop->maskSelf;
124739      for(i=0; i<nOrderBy; i++){
124740        Expr *p;
124741        Bitmask mTerm;
124742        if( MASKBIT(i) & obSat ) continue;
124743        p = pOrderBy->a[i].pExpr;
124744        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
124745        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
124746        if( (mTerm&~orderDistinctMask)==0 ){
124747          obSat |= MASKBIT(i);
124748        }
124749      }
124750    }
124751  } /* End the loop over all WhereLoops from outer-most down to inner-most */
124752  if( obSat==obDone ) return (i8)nOrderBy;
124753  if( !isOrderDistinct ){
124754    for(i=nOrderBy-1; i>0; i--){
124755      Bitmask m = MASKBIT(i) - 1;
124756      if( (obSat&m)==m ) return i;
124757    }
124758    return 0;
124759  }
124760  return -1;
124761}
124762
124763
124764/*
124765** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
124766** the planner assumes that the specified pOrderBy list is actually a GROUP
124767** BY clause - and so any order that groups rows as required satisfies the
124768** request.
124769**
124770** Normally, in this case it is not possible for the caller to determine
124771** whether or not the rows are really being delivered in sorted order, or
124772** just in some other order that provides the required grouping. However,
124773** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
124774** this function may be called on the returned WhereInfo object. It returns
124775** true if the rows really will be sorted in the specified order, or false
124776** otherwise.
124777**
124778** For example, assuming:
124779**
124780**   CREATE INDEX i1 ON t1(x, Y);
124781**
124782** then
124783**
124784**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
124785**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
124786*/
124787SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
124788  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
124789  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
124790  return pWInfo->sorted;
124791}
124792
124793#ifdef WHERETRACE_ENABLED
124794/* For debugging use only: */
124795static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
124796  static char zName[65];
124797  int i;
124798  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
124799  if( pLast ) zName[i++] = pLast->cId;
124800  zName[i] = 0;
124801  return zName;
124802}
124803#endif
124804
124805/*
124806** Return the cost of sorting nRow rows, assuming that the keys have
124807** nOrderby columns and that the first nSorted columns are already in
124808** order.
124809*/
124810static LogEst whereSortingCost(
124811  WhereInfo *pWInfo,
124812  LogEst nRow,
124813  int nOrderBy,
124814  int nSorted
124815){
124816  /* TUNING: Estimated cost of a full external sort, where N is
124817  ** the number of rows to sort is:
124818  **
124819  **   cost = (3.0 * N * log(N)).
124820  **
124821  ** Or, if the order-by clause has X terms but only the last Y
124822  ** terms are out of order, then block-sorting will reduce the
124823  ** sorting cost to:
124824  **
124825  **   cost = (3.0 * N * log(N)) * (Y/X)
124826  **
124827  ** The (Y/X) term is implemented using stack variable rScale
124828  ** below.  */
124829  LogEst rScale, rSortCost;
124830  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
124831  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
124832  rSortCost = nRow + estLog(nRow) + rScale + 16;
124833
124834  /* TUNING: The cost of implementing DISTINCT using a B-TREE is
124835  ** similar but with a larger constant of proportionality.
124836  ** Multiply by an additional factor of 3.0.  */
124837  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
124838    rSortCost += 16;
124839  }
124840
124841  return rSortCost;
124842}
124843
124844/*
124845** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
124846** attempts to find the lowest cost path that visits each WhereLoop
124847** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
124848**
124849** Assume that the total number of output rows that will need to be sorted
124850** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
124851** costs if nRowEst==0.
124852**
124853** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
124854** error occurs.
124855*/
124856static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
124857  int mxChoice;             /* Maximum number of simultaneous paths tracked */
124858  int nLoop;                /* Number of terms in the join */
124859  Parse *pParse;            /* Parsing context */
124860  sqlite3 *db;              /* The database connection */
124861  int iLoop;                /* Loop counter over the terms of the join */
124862  int ii, jj;               /* Loop counters */
124863  int mxI = 0;              /* Index of next entry to replace */
124864  int nOrderBy;             /* Number of ORDER BY clause terms */
124865  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
124866  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
124867  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
124868  WherePath *aFrom;         /* All nFrom paths at the previous level */
124869  WherePath *aTo;           /* The nTo best paths at the current level */
124870  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
124871  WherePath *pTo;           /* An element of aTo[] that we are working on */
124872  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
124873  WhereLoop **pX;           /* Used to divy up the pSpace memory */
124874  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
124875  char *pSpace;             /* Temporary memory used by this routine */
124876  int nSpace;               /* Bytes of space allocated at pSpace */
124877
124878  pParse = pWInfo->pParse;
124879  db = pParse->db;
124880  nLoop = pWInfo->nLevel;
124881  /* TUNING: For simple queries, only the best path is tracked.
124882  ** For 2-way joins, the 5 best paths are followed.
124883  ** For joins of 3 or more tables, track the 10 best paths */
124884  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
124885  assert( nLoop<=pWInfo->pTabList->nSrc );
124886  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
124887
124888  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
124889  ** case the purpose of this call is to estimate the number of rows returned
124890  ** by the overall query. Once this estimate has been obtained, the caller
124891  ** will invoke this function a second time, passing the estimate as the
124892  ** nRowEst parameter.  */
124893  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
124894    nOrderBy = 0;
124895  }else{
124896    nOrderBy = pWInfo->pOrderBy->nExpr;
124897  }
124898
124899  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
124900  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
124901  nSpace += sizeof(LogEst) * nOrderBy;
124902  pSpace = sqlite3DbMallocRaw(db, nSpace);
124903  if( pSpace==0 ) return SQLITE_NOMEM;
124904  aTo = (WherePath*)pSpace;
124905  aFrom = aTo+mxChoice;
124906  memset(aFrom, 0, sizeof(aFrom[0]));
124907  pX = (WhereLoop**)(aFrom+mxChoice);
124908  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
124909    pFrom->aLoop = pX;
124910  }
124911  if( nOrderBy ){
124912    /* If there is an ORDER BY clause and it is not being ignored, set up
124913    ** space for the aSortCost[] array. Each element of the aSortCost array
124914    ** is either zero - meaning it has not yet been initialized - or the
124915    ** cost of sorting nRowEst rows of data where the first X terms of
124916    ** the ORDER BY clause are already in order, where X is the array
124917    ** index.  */
124918    aSortCost = (LogEst*)pX;
124919    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
124920  }
124921  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
124922  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
124923
124924  /* Seed the search with a single WherePath containing zero WhereLoops.
124925  **
124926  ** TUNING: Do not let the number of iterations go above 28.  If the cost
124927  ** of computing an automatic index is not paid back within the first 28
124928  ** rows, then do not use the automatic index. */
124929  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
124930  nFrom = 1;
124931  assert( aFrom[0].isOrdered==0 );
124932  if( nOrderBy ){
124933    /* If nLoop is zero, then there are no FROM terms in the query. Since
124934    ** in this case the query may return a maximum of one row, the results
124935    ** are already in the requested order. Set isOrdered to nOrderBy to
124936    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
124937    ** -1, indicating that the result set may or may not be ordered,
124938    ** depending on the loops added to the current plan.  */
124939    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
124940  }
124941
124942  /* Compute successively longer WherePaths using the previous generation
124943  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
124944  ** best paths at each generation */
124945  for(iLoop=0; iLoop<nLoop; iLoop++){
124946    nTo = 0;
124947    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
124948      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
124949        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
124950        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
124951        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
124952        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
124953        Bitmask maskNew;                  /* Mask of src visited by (..) */
124954        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
124955
124956        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
124957        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
124958        /* At this point, pWLoop is a candidate to be the next loop.
124959        ** Compute its cost */
124960        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
124961        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
124962        nOut = pFrom->nRow + pWLoop->nOut;
124963        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
124964        if( isOrdered<0 ){
124965          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
124966                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
124967                       iLoop, pWLoop, &revMask);
124968        }else{
124969          revMask = pFrom->revLoop;
124970        }
124971        if( isOrdered>=0 && isOrdered<nOrderBy ){
124972          if( aSortCost[isOrdered]==0 ){
124973            aSortCost[isOrdered] = whereSortingCost(
124974                pWInfo, nRowEst, nOrderBy, isOrdered
124975            );
124976          }
124977          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
124978
124979          WHERETRACE(0x002,
124980              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
124981               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
124982               rUnsorted, rCost));
124983        }else{
124984          rCost = rUnsorted;
124985        }
124986
124987        /* Check to see if pWLoop should be added to the set of
124988        ** mxChoice best-so-far paths.
124989        **
124990        ** First look for an existing path among best-so-far paths
124991        ** that covers the same set of loops and has the same isOrdered
124992        ** setting as the current path candidate.
124993        **
124994        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
124995        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
124996        ** of legal values for isOrdered, -1..64.
124997        */
124998        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
124999          if( pTo->maskLoop==maskNew
125000           && ((pTo->isOrdered^isOrdered)&0x80)==0
125001          ){
125002            testcase( jj==nTo-1 );
125003            break;
125004          }
125005        }
125006        if( jj>=nTo ){
125007          /* None of the existing best-so-far paths match the candidate. */
125008          if( nTo>=mxChoice
125009           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
125010          ){
125011            /* The current candidate is no better than any of the mxChoice
125012            ** paths currently in the best-so-far buffer.  So discard
125013            ** this candidate as not viable. */
125014#ifdef WHERETRACE_ENABLED /* 0x4 */
125015            if( sqlite3WhereTrace&0x4 ){
125016              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
125017                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125018                  isOrdered>=0 ? isOrdered+'0' : '?');
125019            }
125020#endif
125021            continue;
125022          }
125023          /* If we reach this points it means that the new candidate path
125024          ** needs to be added to the set of best-so-far paths. */
125025          if( nTo<mxChoice ){
125026            /* Increase the size of the aTo set by one */
125027            jj = nTo++;
125028          }else{
125029            /* New path replaces the prior worst to keep count below mxChoice */
125030            jj = mxI;
125031          }
125032          pTo = &aTo[jj];
125033#ifdef WHERETRACE_ENABLED /* 0x4 */
125034          if( sqlite3WhereTrace&0x4 ){
125035            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
125036                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125037                isOrdered>=0 ? isOrdered+'0' : '?');
125038          }
125039#endif
125040        }else{
125041          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
125042          ** same set of loops and has the sam isOrdered setting as the
125043          ** candidate path.  Check to see if the candidate should replace
125044          ** pTo or if the candidate should be skipped */
125045          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
125046#ifdef WHERETRACE_ENABLED /* 0x4 */
125047            if( sqlite3WhereTrace&0x4 ){
125048              sqlite3DebugPrintf(
125049                  "Skip   %s cost=%-3d,%3d order=%c",
125050                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125051                  isOrdered>=0 ? isOrdered+'0' : '?');
125052              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
125053                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125054                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
125055            }
125056#endif
125057            /* Discard the candidate path from further consideration */
125058            testcase( pTo->rCost==rCost );
125059            continue;
125060          }
125061          testcase( pTo->rCost==rCost+1 );
125062          /* Control reaches here if the candidate path is better than the
125063          ** pTo path.  Replace pTo with the candidate. */
125064#ifdef WHERETRACE_ENABLED /* 0x4 */
125065          if( sqlite3WhereTrace&0x4 ){
125066            sqlite3DebugPrintf(
125067                "Update %s cost=%-3d,%3d order=%c",
125068                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125069                isOrdered>=0 ? isOrdered+'0' : '?');
125070            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
125071                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125072                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
125073          }
125074#endif
125075        }
125076        /* pWLoop is a winner.  Add it to the set of best so far */
125077        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
125078        pTo->revLoop = revMask;
125079        pTo->nRow = nOut;
125080        pTo->rCost = rCost;
125081        pTo->rUnsorted = rUnsorted;
125082        pTo->isOrdered = isOrdered;
125083        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
125084        pTo->aLoop[iLoop] = pWLoop;
125085        if( nTo>=mxChoice ){
125086          mxI = 0;
125087          mxCost = aTo[0].rCost;
125088          mxUnsorted = aTo[0].nRow;
125089          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
125090            if( pTo->rCost>mxCost
125091             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
125092            ){
125093              mxCost = pTo->rCost;
125094              mxUnsorted = pTo->rUnsorted;
125095              mxI = jj;
125096            }
125097          }
125098        }
125099      }
125100    }
125101
125102#ifdef WHERETRACE_ENABLED  /* >=2 */
125103    if( sqlite3WhereTrace & 0x02 ){
125104      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
125105      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
125106        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
125107           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125108           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
125109        if( pTo->isOrdered>0 ){
125110          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
125111        }else{
125112          sqlite3DebugPrintf("\n");
125113        }
125114      }
125115    }
125116#endif
125117
125118    /* Swap the roles of aFrom and aTo for the next generation */
125119    pFrom = aTo;
125120    aTo = aFrom;
125121    aFrom = pFrom;
125122    nFrom = nTo;
125123  }
125124
125125  if( nFrom==0 ){
125126    sqlite3ErrorMsg(pParse, "no query solution");
125127    sqlite3DbFree(db, pSpace);
125128    return SQLITE_ERROR;
125129  }
125130
125131  /* Find the lowest cost path.  pFrom will be left pointing to that path */
125132  pFrom = aFrom;
125133  for(ii=1; ii<nFrom; ii++){
125134    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
125135  }
125136  assert( pWInfo->nLevel==nLoop );
125137  /* Load the lowest cost path into pWInfo */
125138  for(iLoop=0; iLoop<nLoop; iLoop++){
125139    WhereLevel *pLevel = pWInfo->a + iLoop;
125140    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
125141    pLevel->iFrom = pWLoop->iTab;
125142    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
125143  }
125144  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
125145   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
125146   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
125147   && nRowEst
125148  ){
125149    Bitmask notUsed;
125150    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
125151                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
125152    if( rc==pWInfo->pResultSet->nExpr ){
125153      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
125154    }
125155  }
125156  if( pWInfo->pOrderBy ){
125157    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
125158      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
125159        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
125160      }
125161    }else{
125162      pWInfo->nOBSat = pFrom->isOrdered;
125163      if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
125164      pWInfo->revMask = pFrom->revLoop;
125165    }
125166    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
125167        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
125168    ){
125169      Bitmask revMask = 0;
125170      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
125171          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
125172      );
125173      assert( pWInfo->sorted==0 );
125174      if( nOrder==pWInfo->pOrderBy->nExpr ){
125175        pWInfo->sorted = 1;
125176        pWInfo->revMask = revMask;
125177      }
125178    }
125179  }
125180
125181
125182  pWInfo->nRowOut = pFrom->nRow;
125183
125184  /* Free temporary memory and return success */
125185  sqlite3DbFree(db, pSpace);
125186  return SQLITE_OK;
125187}
125188
125189/*
125190** Most queries use only a single table (they are not joins) and have
125191** simple == constraints against indexed fields.  This routine attempts
125192** to plan those simple cases using much less ceremony than the
125193** general-purpose query planner, and thereby yield faster sqlite3_prepare()
125194** times for the common case.
125195**
125196** Return non-zero on success, if this query can be handled by this
125197** no-frills query planner.  Return zero if this query needs the
125198** general-purpose query planner.
125199*/
125200static int whereShortCut(WhereLoopBuilder *pBuilder){
125201  WhereInfo *pWInfo;
125202  struct SrcList_item *pItem;
125203  WhereClause *pWC;
125204  WhereTerm *pTerm;
125205  WhereLoop *pLoop;
125206  int iCur;
125207  int j;
125208  Table *pTab;
125209  Index *pIdx;
125210
125211  pWInfo = pBuilder->pWInfo;
125212  if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
125213  assert( pWInfo->pTabList->nSrc>=1 );
125214  pItem = pWInfo->pTabList->a;
125215  pTab = pItem->pTab;
125216  if( IsVirtual(pTab) ) return 0;
125217  if( pItem->fg.isIndexedBy ) return 0;
125218  iCur = pItem->iCursor;
125219  pWC = &pWInfo->sWC;
125220  pLoop = pBuilder->pNew;
125221  pLoop->wsFlags = 0;
125222  pLoop->nSkip = 0;
125223  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
125224  if( pTerm ){
125225    testcase( pTerm->eOperator & WO_IS );
125226    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
125227    pLoop->aLTerm[0] = pTerm;
125228    pLoop->nLTerm = 1;
125229    pLoop->u.btree.nEq = 1;
125230    /* TUNING: Cost of a rowid lookup is 10 */
125231    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
125232  }else{
125233    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
125234      int opMask;
125235      assert( pLoop->aLTermSpace==pLoop->aLTerm );
125236      if( !IsUniqueIndex(pIdx)
125237       || pIdx->pPartIdxWhere!=0
125238       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
125239      ) continue;
125240      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
125241      for(j=0; j<pIdx->nKeyCol; j++){
125242        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
125243        if( pTerm==0 ) break;
125244        testcase( pTerm->eOperator & WO_IS );
125245        pLoop->aLTerm[j] = pTerm;
125246      }
125247      if( j!=pIdx->nKeyCol ) continue;
125248      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
125249      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
125250        pLoop->wsFlags |= WHERE_IDX_ONLY;
125251      }
125252      pLoop->nLTerm = j;
125253      pLoop->u.btree.nEq = j;
125254      pLoop->u.btree.pIndex = pIdx;
125255      /* TUNING: Cost of a unique index lookup is 15 */
125256      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
125257      break;
125258    }
125259  }
125260  if( pLoop->wsFlags ){
125261    pLoop->nOut = (LogEst)1;
125262    pWInfo->a[0].pWLoop = pLoop;
125263    pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
125264    pWInfo->a[0].iTabCur = iCur;
125265    pWInfo->nRowOut = 1;
125266    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
125267    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
125268      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125269    }
125270#ifdef SQLITE_DEBUG
125271    pLoop->cId = '0';
125272#endif
125273    return 1;
125274  }
125275  return 0;
125276}
125277
125278/*
125279** Generate the beginning of the loop used for WHERE clause processing.
125280** The return value is a pointer to an opaque structure that contains
125281** information needed to terminate the loop.  Later, the calling routine
125282** should invoke sqlite3WhereEnd() with the return value of this function
125283** in order to complete the WHERE clause processing.
125284**
125285** If an error occurs, this routine returns NULL.
125286**
125287** The basic idea is to do a nested loop, one loop for each table in
125288** the FROM clause of a select.  (INSERT and UPDATE statements are the
125289** same as a SELECT with only a single table in the FROM clause.)  For
125290** example, if the SQL is this:
125291**
125292**       SELECT * FROM t1, t2, t3 WHERE ...;
125293**
125294** Then the code generated is conceptually like the following:
125295**
125296**      foreach row1 in t1 do       \    Code generated
125297**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
125298**          foreach row3 in t3 do   /
125299**            ...
125300**          end                     \    Code generated
125301**        end                        |-- by sqlite3WhereEnd()
125302**      end                         /
125303**
125304** Note that the loops might not be nested in the order in which they
125305** appear in the FROM clause if a different order is better able to make
125306** use of indices.  Note also that when the IN operator appears in
125307** the WHERE clause, it might result in additional nested loops for
125308** scanning through all values on the right-hand side of the IN.
125309**
125310** There are Btree cursors associated with each table.  t1 uses cursor
125311** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
125312** And so forth.  This routine generates code to open those VDBE cursors
125313** and sqlite3WhereEnd() generates the code to close them.
125314**
125315** The code that sqlite3WhereBegin() generates leaves the cursors named
125316** in pTabList pointing at their appropriate entries.  The [...] code
125317** can use OP_Column and OP_Rowid opcodes on these cursors to extract
125318** data from the various tables of the loop.
125319**
125320** If the WHERE clause is empty, the foreach loops must each scan their
125321** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
125322** the tables have indices and there are terms in the WHERE clause that
125323** refer to those indices, a complete table scan can be avoided and the
125324** code will run much faster.  Most of the work of this routine is checking
125325** to see if there are indices that can be used to speed up the loop.
125326**
125327** Terms of the WHERE clause are also used to limit which rows actually
125328** make it to the "..." in the middle of the loop.  After each "foreach",
125329** terms of the WHERE clause that use only terms in that loop and outer
125330** loops are evaluated and if false a jump is made around all subsequent
125331** inner loops (or around the "..." if the test occurs within the inner-
125332** most loop)
125333**
125334** OUTER JOINS
125335**
125336** An outer join of tables t1 and t2 is conceptally coded as follows:
125337**
125338**    foreach row1 in t1 do
125339**      flag = 0
125340**      foreach row2 in t2 do
125341**        start:
125342**          ...
125343**          flag = 1
125344**      end
125345**      if flag==0 then
125346**        move the row2 cursor to a null row
125347**        goto start
125348**      fi
125349**    end
125350**
125351** ORDER BY CLAUSE PROCESSING
125352**
125353** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
125354** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
125355** if there is one.  If there is no ORDER BY clause or if this routine
125356** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
125357**
125358** The iIdxCur parameter is the cursor number of an index.  If
125359** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
125360** to use for OR clause processing.  The WHERE clause should use this
125361** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
125362** the first cursor in an array of cursors for all indices.  iIdxCur should
125363** be used to compute the appropriate cursor depending on which index is
125364** used.
125365*/
125366SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
125367  Parse *pParse,        /* The parser context */
125368  SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
125369  Expr *pWhere,         /* The WHERE clause */
125370  ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
125371  ExprList *pResultSet, /* Result set of the query */
125372  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
125373  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
125374){
125375  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
125376  int nTabList;              /* Number of elements in pTabList */
125377  WhereInfo *pWInfo;         /* Will become the return value of this function */
125378  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
125379  Bitmask notReady;          /* Cursors that are not yet positioned */
125380  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
125381  WhereMaskSet *pMaskSet;    /* The expression mask set */
125382  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
125383  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
125384  int ii;                    /* Loop counter */
125385  sqlite3 *db;               /* Database connection */
125386  int rc;                    /* Return code */
125387
125388  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
125389        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
125390     && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
125391  ));
125392
125393  /* Variable initialization */
125394  db = pParse->db;
125395  memset(&sWLB, 0, sizeof(sWLB));
125396
125397  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
125398  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
125399  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
125400  sWLB.pOrderBy = pOrderBy;
125401
125402  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
125403  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
125404  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
125405    wctrlFlags &= ~WHERE_WANT_DISTINCT;
125406  }
125407
125408  /* The number of tables in the FROM clause is limited by the number of
125409  ** bits in a Bitmask
125410  */
125411  testcase( pTabList->nSrc==BMS );
125412  if( pTabList->nSrc>BMS ){
125413    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
125414    return 0;
125415  }
125416
125417  /* This function normally generates a nested loop for all tables in
125418  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
125419  ** only generate code for the first table in pTabList and assume that
125420  ** any cursors associated with subsequent tables are uninitialized.
125421  */
125422  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
125423
125424  /* Allocate and initialize the WhereInfo structure that will become the
125425  ** return value. A single allocation is used to store the WhereInfo
125426  ** struct, the contents of WhereInfo.a[], the WhereClause structure
125427  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
125428  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
125429  ** some architectures. Hence the ROUND8() below.
125430  */
125431  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
125432  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
125433  if( db->mallocFailed ){
125434    sqlite3DbFree(db, pWInfo);
125435    pWInfo = 0;
125436    goto whereBeginError;
125437  }
125438  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
125439  pWInfo->nLevel = nTabList;
125440  pWInfo->pParse = pParse;
125441  pWInfo->pTabList = pTabList;
125442  pWInfo->pOrderBy = pOrderBy;
125443  pWInfo->pResultSet = pResultSet;
125444  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
125445  pWInfo->wctrlFlags = wctrlFlags;
125446  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
125447  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
125448  pMaskSet = &pWInfo->sMaskSet;
125449  sWLB.pWInfo = pWInfo;
125450  sWLB.pWC = &pWInfo->sWC;
125451  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
125452  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
125453  whereLoopInit(sWLB.pNew);
125454#ifdef SQLITE_DEBUG
125455  sWLB.pNew->cId = '*';
125456#endif
125457
125458  /* Split the WHERE clause into separate subexpressions where each
125459  ** subexpression is separated by an AND operator.
125460  */
125461  initMaskSet(pMaskSet);
125462  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
125463  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
125464
125465  /* Special case: a WHERE clause that is constant.  Evaluate the
125466  ** expression and either jump over all of the code or fall thru.
125467  */
125468  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
125469    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
125470      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
125471                         SQLITE_JUMPIFNULL);
125472      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
125473    }
125474  }
125475
125476  /* Special case: No FROM clause
125477  */
125478  if( nTabList==0 ){
125479    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
125480    if( wctrlFlags & WHERE_WANT_DISTINCT ){
125481      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125482    }
125483  }
125484
125485  /* Assign a bit from the bitmask to every term in the FROM clause.
125486  **
125487  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
125488  **
125489  ** The rule of the previous sentence ensures thta if X is the bitmask for
125490  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
125491  ** Knowing the bitmask for all tables to the left of a left join is
125492  ** important.  Ticket #3015.
125493  **
125494  ** Note that bitmasks are created for all pTabList->nSrc tables in
125495  ** pTabList, not just the first nTabList tables.  nTabList is normally
125496  ** equal to pTabList->nSrc but might be shortened to 1 if the
125497  ** WHERE_ONETABLE_ONLY flag is set.
125498  */
125499  for(ii=0; ii<pTabList->nSrc; ii++){
125500    createMask(pMaskSet, pTabList->a[ii].iCursor);
125501    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
125502  }
125503#ifdef SQLITE_DEBUG
125504  for(ii=0; ii<pTabList->nSrc; ii++){
125505    Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
125506    assert( m==MASKBIT(ii) );
125507  }
125508#endif
125509
125510  /* Analyze all of the subexpressions. */
125511  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
125512  if( db->mallocFailed ) goto whereBeginError;
125513
125514  if( wctrlFlags & WHERE_WANT_DISTINCT ){
125515    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
125516      /* The DISTINCT marking is pointless.  Ignore it. */
125517      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125518    }else if( pOrderBy==0 ){
125519      /* Try to ORDER BY the result set to make distinct processing easier */
125520      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
125521      pWInfo->pOrderBy = pResultSet;
125522    }
125523  }
125524
125525  /* Construct the WhereLoop objects */
125526  WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
125527             wctrlFlags));
125528#if defined(WHERETRACE_ENABLED)
125529  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
125530    int i;
125531    for(i=0; i<sWLB.pWC->nTerm; i++){
125532      whereTermPrint(&sWLB.pWC->a[i], i);
125533    }
125534  }
125535#endif
125536
125537  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
125538    rc = whereLoopAddAll(&sWLB);
125539    if( rc ) goto whereBeginError;
125540
125541#ifdef WHERETRACE_ENABLED
125542    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
125543      WhereLoop *p;
125544      int i;
125545      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
125546                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
125547      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
125548        p->cId = zLabel[i%sizeof(zLabel)];
125549        whereLoopPrint(p, sWLB.pWC);
125550      }
125551    }
125552#endif
125553
125554    wherePathSolver(pWInfo, 0);
125555    if( db->mallocFailed ) goto whereBeginError;
125556    if( pWInfo->pOrderBy ){
125557       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
125558       if( db->mallocFailed ) goto whereBeginError;
125559    }
125560  }
125561  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
125562     pWInfo->revMask = (Bitmask)(-1);
125563  }
125564  if( pParse->nErr || NEVER(db->mallocFailed) ){
125565    goto whereBeginError;
125566  }
125567#ifdef WHERETRACE_ENABLED
125568  if( sqlite3WhereTrace ){
125569    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
125570    if( pWInfo->nOBSat>0 ){
125571      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
125572    }
125573    switch( pWInfo->eDistinct ){
125574      case WHERE_DISTINCT_UNIQUE: {
125575        sqlite3DebugPrintf("  DISTINCT=unique");
125576        break;
125577      }
125578      case WHERE_DISTINCT_ORDERED: {
125579        sqlite3DebugPrintf("  DISTINCT=ordered");
125580        break;
125581      }
125582      case WHERE_DISTINCT_UNORDERED: {
125583        sqlite3DebugPrintf("  DISTINCT=unordered");
125584        break;
125585      }
125586    }
125587    sqlite3DebugPrintf("\n");
125588    for(ii=0; ii<pWInfo->nLevel; ii++){
125589      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
125590    }
125591  }
125592#endif
125593  /* Attempt to omit tables from the join that do not effect the result */
125594  if( pWInfo->nLevel>=2
125595   && pResultSet!=0
125596   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
125597  ){
125598    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
125599    if( sWLB.pOrderBy ){
125600      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
125601    }
125602    while( pWInfo->nLevel>=2 ){
125603      WhereTerm *pTerm, *pEnd;
125604      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
125605      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
125606      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
125607       && (pLoop->wsFlags & WHERE_ONEROW)==0
125608      ){
125609        break;
125610      }
125611      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
125612      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
125613      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
125614        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
125615         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
125616        ){
125617          break;
125618        }
125619      }
125620      if( pTerm<pEnd ) break;
125621      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
125622      pWInfo->nLevel--;
125623      nTabList--;
125624    }
125625  }
125626  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
125627  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
125628
125629  /* If the caller is an UPDATE or DELETE statement that is requesting
125630  ** to use a one-pass algorithm, determine if this is appropriate.
125631  ** The one-pass algorithm only works if the WHERE clause constrains
125632  ** the statement to update or delete a single row.
125633  */
125634  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
125635  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
125636    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
125637    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
125638    if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
125639       && 0==(wsFlags & WHERE_VIRTUALTABLE)
125640    )){
125641      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
125642      if( HasRowid(pTabList->a[0].pTab) ){
125643        pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
125644      }
125645    }
125646  }
125647
125648  /* Open all tables in the pTabList and any indices selected for
125649  ** searching those tables.
125650  */
125651  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
125652    Table *pTab;     /* Table to open */
125653    int iDb;         /* Index of database containing table/index */
125654    struct SrcList_item *pTabItem;
125655
125656    pTabItem = &pTabList->a[pLevel->iFrom];
125657    pTab = pTabItem->pTab;
125658    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
125659    pLoop = pLevel->pWLoop;
125660    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
125661      /* Do nothing */
125662    }else
125663#ifndef SQLITE_OMIT_VIRTUALTABLE
125664    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
125665      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
125666      int iCur = pTabItem->iCursor;
125667      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
125668    }else if( IsVirtual(pTab) ){
125669      /* noop */
125670    }else
125671#endif
125672    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
125673         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
125674      int op = OP_OpenRead;
125675      if( pWInfo->eOnePass!=ONEPASS_OFF ){
125676        op = OP_OpenWrite;
125677        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
125678      };
125679      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
125680      assert( pTabItem->iCursor==pLevel->iTabCur );
125681      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
125682      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
125683      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
125684        Bitmask b = pTabItem->colUsed;
125685        int n = 0;
125686        for(; b; b=b>>1, n++){}
125687        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
125688                            SQLITE_INT_TO_PTR(n), P4_INT32);
125689        assert( n<=pTab->nCol );
125690      }
125691#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
125692      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
125693                            (const u8*)&pTabItem->colUsed, P4_INT64);
125694#endif
125695    }else{
125696      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
125697    }
125698    if( pLoop->wsFlags & WHERE_INDEXED ){
125699      Index *pIx = pLoop->u.btree.pIndex;
125700      int iIndexCur;
125701      int op = OP_OpenRead;
125702      /* iIdxCur is always set if to a positive value if ONEPASS is possible */
125703      assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
125704      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
125705       && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
125706      ){
125707        /* This is one term of an OR-optimization using the PRIMARY KEY of a
125708        ** WITHOUT ROWID table.  No need for a separate index */
125709        iIndexCur = pLevel->iTabCur;
125710        op = 0;
125711      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
125712        Index *pJ = pTabItem->pTab->pIndex;
125713        iIndexCur = iIdxCur;
125714        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
125715        while( ALWAYS(pJ) && pJ!=pIx ){
125716          iIndexCur++;
125717          pJ = pJ->pNext;
125718        }
125719        op = OP_OpenWrite;
125720        pWInfo->aiCurOnePass[1] = iIndexCur;
125721      }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
125722        iIndexCur = iIdxCur;
125723        if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
125724      }else{
125725        iIndexCur = pParse->nTab++;
125726      }
125727      pLevel->iIdxCur = iIndexCur;
125728      assert( pIx->pSchema==pTab->pSchema );
125729      assert( iIndexCur>=0 );
125730      if( op ){
125731        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
125732        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
125733        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
125734         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
125735         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
125736        ){
125737          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
125738        }
125739        VdbeComment((v, "%s", pIx->zName));
125740#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
125741        {
125742          u64 colUsed = 0;
125743          int ii, jj;
125744          for(ii=0; ii<pIx->nColumn; ii++){
125745            jj = pIx->aiColumn[ii];
125746            if( jj<0 ) continue;
125747            if( jj>63 ) jj = 63;
125748            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
125749            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
125750          }
125751          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
125752                                (u8*)&colUsed, P4_INT64);
125753        }
125754#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
125755      }
125756    }
125757    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
125758  }
125759  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
125760  if( db->mallocFailed ) goto whereBeginError;
125761
125762  /* Generate the code to do the search.  Each iteration of the for
125763  ** loop below generates code for a single nested loop of the VM
125764  ** program.
125765  */
125766  notReady = ~(Bitmask)0;
125767  for(ii=0; ii<nTabList; ii++){
125768    int addrExplain;
125769    int wsFlags;
125770    pLevel = &pWInfo->a[ii];
125771    wsFlags = pLevel->pWLoop->wsFlags;
125772#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
125773    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
125774      constructAutomaticIndex(pParse, &pWInfo->sWC,
125775                &pTabList->a[pLevel->iFrom], notReady, pLevel);
125776      if( db->mallocFailed ) goto whereBeginError;
125777    }
125778#endif
125779    addrExplain = sqlite3WhereExplainOneScan(
125780        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
125781    );
125782    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
125783    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
125784    pWInfo->iContinue = pLevel->addrCont;
125785    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
125786      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
125787    }
125788  }
125789
125790  /* Done. */
125791  VdbeModuleComment((v, "Begin WHERE-core"));
125792  return pWInfo;
125793
125794  /* Jump here if malloc fails */
125795whereBeginError:
125796  if( pWInfo ){
125797    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
125798    whereInfoFree(db, pWInfo);
125799  }
125800  return 0;
125801}
125802
125803/*
125804** Generate the end of the WHERE loop.  See comments on
125805** sqlite3WhereBegin() for additional information.
125806*/
125807SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
125808  Parse *pParse = pWInfo->pParse;
125809  Vdbe *v = pParse->pVdbe;
125810  int i;
125811  WhereLevel *pLevel;
125812  WhereLoop *pLoop;
125813  SrcList *pTabList = pWInfo->pTabList;
125814  sqlite3 *db = pParse->db;
125815
125816  /* Generate loop termination code.
125817  */
125818  VdbeModuleComment((v, "End WHERE-core"));
125819  sqlite3ExprCacheClear(pParse);
125820  for(i=pWInfo->nLevel-1; i>=0; i--){
125821    int addr;
125822    pLevel = &pWInfo->a[i];
125823    pLoop = pLevel->pWLoop;
125824    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
125825    if( pLevel->op!=OP_Noop ){
125826      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
125827      sqlite3VdbeChangeP5(v, pLevel->p5);
125828      VdbeCoverage(v);
125829      VdbeCoverageIf(v, pLevel->op==OP_Next);
125830      VdbeCoverageIf(v, pLevel->op==OP_Prev);
125831      VdbeCoverageIf(v, pLevel->op==OP_VNext);
125832    }
125833    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
125834      struct InLoop *pIn;
125835      int j;
125836      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
125837      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
125838        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
125839        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
125840        VdbeCoverage(v);
125841        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
125842        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
125843        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
125844      }
125845    }
125846    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
125847    if( pLevel->addrSkip ){
125848      sqlite3VdbeGoto(v, pLevel->addrSkip);
125849      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
125850      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
125851      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
125852    }
125853    if( pLevel->addrLikeRep ){
125854      int op;
125855      if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
125856        op = OP_DecrJumpZero;
125857      }else{
125858        op = OP_JumpZeroIncr;
125859      }
125860      sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
125861      VdbeCoverage(v);
125862    }
125863    if( pLevel->iLeftJoin ){
125864      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
125865      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
125866           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
125867      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
125868        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
125869      }
125870      if( pLoop->wsFlags & WHERE_INDEXED ){
125871        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
125872      }
125873      if( pLevel->op==OP_Return ){
125874        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
125875      }else{
125876        sqlite3VdbeGoto(v, pLevel->addrFirst);
125877      }
125878      sqlite3VdbeJumpHere(v, addr);
125879    }
125880    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
125881                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
125882  }
125883
125884  /* The "break" point is here, just past the end of the outer loop.
125885  ** Set it.
125886  */
125887  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
125888
125889  assert( pWInfo->nLevel<=pTabList->nSrc );
125890  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
125891    int k, last;
125892    VdbeOp *pOp;
125893    Index *pIdx = 0;
125894    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
125895    Table *pTab = pTabItem->pTab;
125896    assert( pTab!=0 );
125897    pLoop = pLevel->pWLoop;
125898
125899    /* For a co-routine, change all OP_Column references to the table of
125900    ** the co-routine into OP_Copy of result contained in a register.
125901    ** OP_Rowid becomes OP_Null.
125902    */
125903    if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
125904      translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
125905                            pTabItem->regResult, 0);
125906      continue;
125907    }
125908
125909    /* Close all of the cursors that were opened by sqlite3WhereBegin.
125910    ** Except, do not close cursors that will be reused by the OR optimization
125911    ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
125912    ** created for the ONEPASS optimization.
125913    */
125914    if( (pTab->tabFlags & TF_Ephemeral)==0
125915     && pTab->pSelect==0
125916     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
125917    ){
125918      int ws = pLoop->wsFlags;
125919      if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
125920        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
125921      }
125922      if( (ws & WHERE_INDEXED)!=0
125923       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
125924       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
125925      ){
125926        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
125927      }
125928    }
125929
125930    /* If this scan uses an index, make VDBE code substitutions to read data
125931    ** from the index instead of from the table where possible.  In some cases
125932    ** this optimization prevents the table from ever being read, which can
125933    ** yield a significant performance boost.
125934    **
125935    ** Calls to the code generator in between sqlite3WhereBegin and
125936    ** sqlite3WhereEnd will have created code that references the table
125937    ** directly.  This loop scans all that code looking for opcodes
125938    ** that reference the table and converts them into opcodes that
125939    ** reference the index.
125940    */
125941    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
125942      pIdx = pLoop->u.btree.pIndex;
125943    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
125944      pIdx = pLevel->u.pCovidx;
125945    }
125946    if( pIdx
125947     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
125948     && !db->mallocFailed
125949    ){
125950      last = sqlite3VdbeCurrentAddr(v);
125951      k = pLevel->addrBody;
125952      pOp = sqlite3VdbeGetOp(v, k);
125953      for(; k<last; k++, pOp++){
125954        if( pOp->p1!=pLevel->iTabCur ) continue;
125955        if( pOp->opcode==OP_Column ){
125956          int x = pOp->p2;
125957          assert( pIdx->pTable==pTab );
125958          if( !HasRowid(pTab) ){
125959            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125960            x = pPk->aiColumn[x];
125961            assert( x>=0 );
125962          }
125963          x = sqlite3ColumnOfIndex(pIdx, x);
125964          if( x>=0 ){
125965            pOp->p2 = x;
125966            pOp->p1 = pLevel->iIdxCur;
125967          }
125968          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
125969        }else if( pOp->opcode==OP_Rowid ){
125970          pOp->p1 = pLevel->iIdxCur;
125971          pOp->opcode = OP_IdxRowid;
125972        }
125973      }
125974    }
125975  }
125976
125977  /* Final cleanup
125978  */
125979  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
125980  whereInfoFree(db, pWInfo);
125981  return;
125982}
125983
125984/************** End of where.c ***********************************************/
125985/************** Begin file parse.c *******************************************/
125986/* Driver template for the LEMON parser generator.
125987** The author disclaims copyright to this source code.
125988**
125989** This version of "lempar.c" is modified, slightly, for use by SQLite.
125990** The only modifications are the addition of a couple of NEVER()
125991** macros to disable tests that are needed in the case of a general
125992** LALR(1) grammar but which are always false in the
125993** specific grammar used by SQLite.
125994*/
125995/* First off, code is included that follows the "include" declaration
125996** in the input grammar file. */
125997/* #include <stdio.h> */
125998
125999/* #include "sqliteInt.h" */
126000
126001/*
126002** Disable all error recovery processing in the parser push-down
126003** automaton.
126004*/
126005#define YYNOERRORRECOVERY 1
126006
126007/*
126008** Make yytestcase() the same as testcase()
126009*/
126010#define yytestcase(X) testcase(X)
126011
126012/*
126013** An instance of this structure holds information about the
126014** LIMIT clause of a SELECT statement.
126015*/
126016struct LimitVal {
126017  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
126018  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
126019};
126020
126021/*
126022** An instance of this structure is used to store the LIKE,
126023** GLOB, NOT LIKE, and NOT GLOB operators.
126024*/
126025struct LikeOp {
126026  Token eOperator;  /* "like" or "glob" or "regexp" */
126027  int bNot;         /* True if the NOT keyword is present */
126028};
126029
126030/*
126031** An instance of the following structure describes the event of a
126032** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
126033** TK_DELETE, or TK_INSTEAD.  If the event is of the form
126034**
126035**      UPDATE ON (a,b,c)
126036**
126037** Then the "b" IdList records the list "a,b,c".
126038*/
126039struct TrigEvent { int a; IdList * b; };
126040
126041/*
126042** An instance of this structure holds the ATTACH key and the key type.
126043*/
126044struct AttachKey { int type;  Token key; };
126045
126046
126047  /*
126048  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
126049  ** all elements in the list.  And make sure list length does not exceed
126050  ** SQLITE_LIMIT_COMPOUND_SELECT.
126051  */
126052  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
126053    if( p->pPrior ){
126054      Select *pNext = 0, *pLoop;
126055      int mxSelect, cnt = 0;
126056      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
126057        pLoop->pNext = pNext;
126058        pLoop->selFlags |= SF_Compound;
126059      }
126060      if( (p->selFlags & SF_MultiValue)==0 &&
126061        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
126062        cnt>mxSelect
126063      ){
126064        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
126065      }
126066    }
126067  }
126068
126069  /* This is a utility routine used to set the ExprSpan.zStart and
126070  ** ExprSpan.zEnd values of pOut so that the span covers the complete
126071  ** range of text beginning with pStart and going to the end of pEnd.
126072  */
126073  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
126074    pOut->zStart = pStart->z;
126075    pOut->zEnd = &pEnd->z[pEnd->n];
126076  }
126077
126078  /* Construct a new Expr object from a single identifier.  Use the
126079  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
126080  ** that created the expression.
126081  */
126082  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
126083    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
126084    pOut->zStart = pValue->z;
126085    pOut->zEnd = &pValue->z[pValue->n];
126086  }
126087
126088  /* This routine constructs a binary expression node out of two ExprSpan
126089  ** objects and uses the result to populate a new ExprSpan object.
126090  */
126091  static void spanBinaryExpr(
126092    ExprSpan *pOut,     /* Write the result here */
126093    Parse *pParse,      /* The parsing context.  Errors accumulate here */
126094    int op,             /* The binary operation */
126095    ExprSpan *pLeft,    /* The left operand */
126096    ExprSpan *pRight    /* The right operand */
126097  ){
126098    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
126099    pOut->zStart = pLeft->zStart;
126100    pOut->zEnd = pRight->zEnd;
126101  }
126102
126103  /* Construct an expression node for a unary postfix operator
126104  */
126105  static void spanUnaryPostfix(
126106    ExprSpan *pOut,        /* Write the new expression node here */
126107    Parse *pParse,         /* Parsing context to record errors */
126108    int op,                /* The operator */
126109    ExprSpan *pOperand,    /* The operand */
126110    Token *pPostOp         /* The operand token for setting the span */
126111  ){
126112    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
126113    pOut->zStart = pOperand->zStart;
126114    pOut->zEnd = &pPostOp->z[pPostOp->n];
126115  }
126116
126117  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
126118  ** unary TK_ISNULL or TK_NOTNULL expression. */
126119  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
126120    sqlite3 *db = pParse->db;
126121    if( pY && pA && pY->op==TK_NULL ){
126122      pA->op = (u8)op;
126123      sqlite3ExprDelete(db, pA->pRight);
126124      pA->pRight = 0;
126125    }
126126  }
126127
126128  /* Construct an expression node for a unary prefix operator
126129  */
126130  static void spanUnaryPrefix(
126131    ExprSpan *pOut,        /* Write the new expression node here */
126132    Parse *pParse,         /* Parsing context to record errors */
126133    int op,                /* The operator */
126134    ExprSpan *pOperand,    /* The operand */
126135    Token *pPreOp         /* The operand token for setting the span */
126136  ){
126137    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
126138    pOut->zStart = pPreOp->z;
126139    pOut->zEnd = pOperand->zEnd;
126140  }
126141
126142  /* Add a single new term to an ExprList that is used to store a
126143  ** list of identifiers.  Report an error if the ID list contains
126144  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
126145  ** error while parsing a legacy schema.
126146  */
126147  static ExprList *parserAddExprIdListTerm(
126148    Parse *pParse,
126149    ExprList *pPrior,
126150    Token *pIdToken,
126151    int hasCollate,
126152    int sortOrder
126153  ){
126154    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
126155    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
126156        && pParse->db->init.busy==0
126157    ){
126158      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
126159                         pIdToken->n, pIdToken->z);
126160    }
126161    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
126162    return p;
126163  }
126164/* Next is all token values, in a form suitable for use by makeheaders.
126165** This section will be null unless lemon is run with the -m switch.
126166*/
126167/*
126168** These constants (all generated automatically by the parser generator)
126169** specify the various kinds of tokens (terminals) that the parser
126170** understands.
126171**
126172** Each symbol here is a terminal symbol in the grammar.
126173*/
126174/* Make sure the INTERFACE macro is defined.
126175*/
126176#ifndef INTERFACE
126177# define INTERFACE 1
126178#endif
126179/* The next thing included is series of defines which control
126180** various aspects of the generated parser.
126181**    YYCODETYPE         is the data type used for storing terminal
126182**                       and nonterminal numbers.  "unsigned char" is
126183**                       used if there are fewer than 250 terminals
126184**                       and nonterminals.  "int" is used otherwise.
126185**    YYNOCODE           is a number of type YYCODETYPE which corresponds
126186**                       to no legal terminal or nonterminal number.  This
126187**                       number is used to fill in empty slots of the hash
126188**                       table.
126189**    YYFALLBACK         If defined, this indicates that one or more tokens
126190**                       have fall-back values which should be used if the
126191**                       original value of the token will not parse.
126192**    YYACTIONTYPE       is the data type used for storing terminal
126193**                       and nonterminal numbers.  "unsigned char" is
126194**                       used if there are fewer than 250 rules and
126195**                       states combined.  "int" is used otherwise.
126196**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
126197**                       directly to the parser from the tokenizer.
126198**    YYMINORTYPE        is the data type used for all minor tokens.
126199**                       This is typically a union of many types, one of
126200**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
126201**                       for base tokens is called "yy0".
126202**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
126203**                       zero the stack is dynamically sized using realloc()
126204**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
126205**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
126206**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
126207**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
126208**    YYERRORSYMBOL      is the code number of the error symbol.  If not
126209**                       defined, then do no error processing.
126210**    YYNSTATE           the combined number of states.
126211**    YYNRULE            the number of rules in the grammar
126212**    YY_MAX_SHIFT       Maximum value for shift actions
126213**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
126214**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
126215**    YY_MIN_REDUCE      Maximum value for reduce actions
126216**    YY_ERROR_ACTION    The yy_action[] code for syntax error
126217**    YY_ACCEPT_ACTION   The yy_action[] code for accept
126218**    YY_NO_ACTION       The yy_action[] code for no-op
126219*/
126220#define YYCODETYPE unsigned char
126221#define YYNOCODE 254
126222#define YYACTIONTYPE unsigned short int
126223#define YYWILDCARD 70
126224#define sqlite3ParserTOKENTYPE Token
126225typedef union {
126226  int yyinit;
126227  sqlite3ParserTOKENTYPE yy0;
126228  Select* yy3;
126229  ExprList* yy14;
126230  With* yy59;
126231  SrcList* yy65;
126232  struct LikeOp yy96;
126233  Expr* yy132;
126234  u8 yy186;
126235  int yy328;
126236  ExprSpan yy346;
126237  struct TrigEvent yy378;
126238  u16 yy381;
126239  IdList* yy408;
126240  struct {int value; int mask;} yy429;
126241  TriggerStep* yy473;
126242  struct LimitVal yy476;
126243} YYMINORTYPE;
126244#ifndef YYSTACKDEPTH
126245#define YYSTACKDEPTH 100
126246#endif
126247#define sqlite3ParserARG_SDECL Parse *pParse;
126248#define sqlite3ParserARG_PDECL ,Parse *pParse
126249#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
126250#define sqlite3ParserARG_STORE yypParser->pParse = pParse
126251#define YYFALLBACK 1
126252#define YYNSTATE             436
126253#define YYNRULE              328
126254#define YY_MAX_SHIFT         435
126255#define YY_MIN_SHIFTREDUCE   649
126256#define YY_MAX_SHIFTREDUCE   976
126257#define YY_MIN_REDUCE        977
126258#define YY_MAX_REDUCE        1304
126259#define YY_ERROR_ACTION      1305
126260#define YY_ACCEPT_ACTION     1306
126261#define YY_NO_ACTION         1307
126262
126263/* The yyzerominor constant is used to initialize instances of
126264** YYMINORTYPE objects to zero. */
126265static const YYMINORTYPE yyzerominor = { 0 };
126266
126267/* Define the yytestcase() macro to be a no-op if is not already defined
126268** otherwise.
126269**
126270** Applications can choose to define yytestcase() in the %include section
126271** to a macro that can assist in verifying code coverage.  For production
126272** code the yytestcase() macro should be turned off.  But it is useful
126273** for testing.
126274*/
126275#ifndef yytestcase
126276# define yytestcase(X)
126277#endif
126278
126279
126280/* Next are the tables used to determine what action to take based on the
126281** current state and lookahead token.  These tables are used to implement
126282** functions that take a state number and lookahead value and return an
126283** action integer.
126284**
126285** Suppose the action integer is N.  Then the action is determined as
126286** follows
126287**
126288**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
126289**                                      token onto the stack and goto state N.
126290**
126291**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
126292**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
126293**
126294**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
126295**     and YY_MAX_REDUCE
126296
126297**   N == YY_ERROR_ACTION               A syntax error has occurred.
126298**
126299**   N == YY_ACCEPT_ACTION              The parser accepts its input.
126300**
126301**   N == YY_NO_ACTION                  No such action.  Denotes unused
126302**                                      slots in the yy_action[] table.
126303**
126304** The action table is constructed as a single large table named yy_action[].
126305** Given state S and lookahead X, the action is computed as
126306**
126307**      yy_action[ yy_shift_ofst[S] + X ]
126308**
126309** If the index value yy_shift_ofst[S]+X is out of range or if the value
126310** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
126311** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
126312** and that yy_default[S] should be used instead.
126313**
126314** The formula above is for computing the action when the lookahead is
126315** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
126316** a reduce action) then the yy_reduce_ofst[] array is used in place of
126317** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
126318** YY_SHIFT_USE_DFLT.
126319**
126320** The following are the tables generated in this section:
126321**
126322**  yy_action[]        A single table containing all actions.
126323**  yy_lookahead[]     A table containing the lookahead for each entry in
126324**                     yy_action.  Used to detect hash collisions.
126325**  yy_shift_ofst[]    For each state, the offset into yy_action for
126326**                     shifting terminals.
126327**  yy_reduce_ofst[]   For each state, the offset into yy_action for
126328**                     shifting non-terminals after a reduce.
126329**  yy_default[]       Default action for each state.
126330*/
126331#define YY_ACTTAB_COUNT (1501)
126332static const YYACTIONTYPE yy_action[] = {
126333 /*     0 */   311, 1306,  145,  651,    2,  192,  652,  338,  780,   92,
126334 /*    10 */    92,   92,   92,   85,   90,   90,   90,   90,   89,   89,
126335 /*    20 */    88,   88,   88,   87,  335,   88,   88,   88,   87,  335,
126336 /*    30 */   327,  856,  856,   92,   92,   92,   92,  776,   90,   90,
126337 /*    40 */    90,   90,   89,   89,   88,   88,   88,   87,  335,   86,
126338 /*    50 */    83,  166,   93,   94,   84,  868,  871,  860,  860,   91,
126339 /*    60 */    91,   92,   92,   92,   92,  335,   90,   90,   90,   90,
126340 /*    70 */    89,   89,   88,   88,   88,   87,  335,  311,  780,   90,
126341 /*    80 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  335,
126342 /*    90 */   123,  808,  689,  689,  689,  689,  112,  230,  430,  257,
126343 /*   100 */   809,  698,  430,   86,   83,  166,  324,   55,  856,  856,
126344 /*   110 */   201,  158,  276,  387,  271,  386,  188,  689,  689,  828,
126345 /*   120 */   833,   49,  944,  269,  833,   49,  123,   87,  335,   93,
126346 /*   130 */    94,   84,  868,  871,  860,  860,   91,   91,   92,   92,
126347 /*   140 */    92,   92,  342,   90,   90,   90,   90,   89,   89,   88,
126348 /*   150 */    88,   88,   87,  335,  311,  328,  333,  332,  701,  408,
126349 /*   160 */   394,   69,  690,  691,  690,  691,  715,  910,  251,  354,
126350 /*   170 */   250,  698,  704,  430,  908,  430,  909,   89,   89,   88,
126351 /*   180 */    88,   88,   87,  335,  391,  856,  856,  690,  691,  183,
126352 /*   190 */    95,  340,  384,  381,  380,  833,   31,  833,   49,  912,
126353 /*   200 */   912,  333,  332,  379,  123,  311,   93,   94,   84,  868,
126354 /*   210 */   871,  860,  860,   91,   91,   92,   92,   92,   92,  114,
126355 /*   220 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
126356 /*   230 */   335,  430,  408,  399,  435,  657,  856,  856,  346,   57,
126357 /*   240 */   232,  828,  109,   20,  912,  912,  231,  393,  937,  760,
126358 /*   250 */    97,  751,  752,  833,   49,  708,  708,   93,   94,   84,
126359 /*   260 */   868,  871,  860,  860,   91,   91,   92,   92,   92,   92,
126360 /*   270 */   707,   90,   90,   90,   90,   89,   89,   88,   88,   88,
126361 /*   280 */    87,  335,  311,  114,   22,  706,  688,   58,  408,  390,
126362 /*   290 */   251,  349,  240,  749,  752,  689,  689,  847,  685,  115,
126363 /*   300 */    21,  231,  393,  689,  689,  697,  183,  355,  430,  384,
126364 /*   310 */   381,  380,  192,  856,  856,  780,  123,  160,  159,  223,
126365 /*   320 */   379,  738,   25,  315,  362,  841,  143,  689,  689,  835,
126366 /*   330 */   833,   48,  339,  937,   93,   94,   84,  868,  871,  860,
126367 /*   340 */   860,   91,   91,   92,   92,   92,   92,  914,   90,   90,
126368 /*   350 */    90,   90,   89,   89,   88,   88,   88,   87,  335,  311,
126369 /*   360 */   840,  840,  840,  266,  430,  690,  691,  778,  114, 1300,
126370 /*   370 */  1300,  430,    1,  690,  691,  697,  688,  689,  689,  689,
126371 /*   380 */   689,  689,  689,  287,  298,  780,  833,   10,  686,  115,
126372 /*   390 */   856,  856,  355,  833,   10,  828,  366,  690,  691,  363,
126373 /*   400 */   321,   76,  123,   74,   23,  737,  807,  323,  356,  353,
126374 /*   410 */   847,   93,   94,   84,  868,  871,  860,  860,   91,   91,
126375 /*   420 */    92,   92,   92,   92,  940,   90,   90,   90,   90,   89,
126376 /*   430 */    89,   88,   88,   88,   87,  335,  311,  806,  841,  429,
126377 /*   440 */   713,  941,  835,  430,  251,  354,  250,  690,  691,  690,
126378 /*   450 */   691,  690,  691,   86,   83,  166,   24,  942,  151,  753,
126379 /*   460 */   285,  907,  403,  907,  164,  833,   10,  856,  856,  965,
126380 /*   470 */   306,  754,  679,  840,  840,  840,  795,  216,  794,  222,
126381 /*   480 */   906,  344,  906,  904,   86,   83,  166,  286,   93,   94,
126382 /*   490 */    84,  868,  871,  860,  860,   91,   91,   92,   92,   92,
126383 /*   500 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
126384 /*   510 */    88,   87,  335,  311,  430,  724,  352,  705,  427,  699,
126385 /*   520 */   700,  376,  210,  833,   49,  793,  397,  857,  857,  940,
126386 /*   530 */   213,  762,  727,  334,  699,  700,  833,   10,   86,   83,
126387 /*   540 */   166,  345,  396,  902,  856,  856,  941,  385,  833,    9,
126388 /*   550 */   406,  869,  872,  187,  890,  728,  347,  398,  404,  977,
126389 /*   560 */   652,  338,  942,  954,  413,   93,   94,   84,  868,  871,
126390 /*   570 */   860,  860,   91,   91,   92,   92,   92,   92,  861,   90,
126391 /*   580 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  335,
126392 /*   590 */   311, 1219,  114,  430,  834,  430,    5,  165,  192,  688,
126393 /*   600 */   832,  780,  430,  723,  430,  234,  325,  189,  163,  316,
126394 /*   610 */   356,  955,  115,  235,  269,  833,   35,  833,   36,  747,
126395 /*   620 */   720,  856,  856,  793,  833,   12,  833,   27,  745,  174,
126396 /*   630 */   968, 1290,  968, 1291, 1290,  310, 1291,  693,  317,  245,
126397 /*   640 */   264,  311,   93,   94,   84,  868,  871,  860,  860,   91,
126398 /*   650 */    91,   92,   92,   92,   92,  832,   90,   90,   90,   90,
126399 /*   660 */    89,   89,   88,   88,   88,   87,  335,  430,  320,  213,
126400 /*   670 */   762,  780,  856,  856,  920,  920,  369,  257,  966,  220,
126401 /*   680 */   966,  396,  663,  664,  665,  242,  259,  244,  262,  833,
126402 /*   690 */    37,  650,    2,   93,   94,   84,  868,  871,  860,  860,
126403 /*   700 */    91,   91,   92,   92,   92,   92,  430,   90,   90,   90,
126404 /*   710 */    90,   89,   89,   88,   88,   88,   87,  335,  311,  430,
126405 /*   720 */   239,  430,  917,  368,  430,  238,  916,  793,  833,   38,
126406 /*   730 */   430,  825,  430,   66,  430,  392,  430,  766,  766,  430,
126407 /*   740 */   367,  833,   39,  833,   28,  430,  833,   29,   68,  856,
126408 /*   750 */   856,  900,  833,   40,  833,   41,  833,   42,  833,   11,
126409 /*   760 */    72,  833,   43,  243,  305,  970,  114,  833,   99,  961,
126410 /*   770 */    93,   94,   84,  868,  871,  860,  860,   91,   91,   92,
126411 /*   780 */    92,   92,   92,  430,   90,   90,   90,   90,   89,   89,
126412 /*   790 */    88,   88,   88,   87,  335,  311,  430,  361,  430,  165,
126413 /*   800 */   147,  430,  186,  185,  184,  833,   44,  430,  289,  430,
126414 /*   810 */   246,  430,  971,  430,  212,  163,  430,  357,  833,   45,
126415 /*   820 */   833,   32,  932,  833,   46,  793,  856,  856,  718,  833,
126416 /*   830 */    47,  833,   33,  833,  117,  833,  118,   75,  833,  119,
126417 /*   840 */   288,  305,  967,  214,  935,  322,  311,   93,   94,   84,
126418 /*   850 */   868,  871,  860,  860,   91,   91,   92,   92,   92,   92,
126419 /*   860 */   430,   90,   90,   90,   90,   89,   89,   88,   88,   88,
126420 /*   870 */    87,  335,  430,  832,  426,  317,  288,  856,  856,  114,
126421 /*   880 */   763,  257,  833,   53,  930,  219,  364,  257,  257,  971,
126422 /*   890 */   361,  396,  257,  257,  833,   34,  257,  311,   93,   94,
126423 /*   900 */    84,  868,  871,  860,  860,   91,   91,   92,   92,   92,
126424 /*   910 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
126425 /*   920 */    88,   87,  335,  430,  217,  318,  124,  253,  856,  856,
126426 /*   930 */   218,  943,  257,  833,  100,  898,  759,  774,  361,  755,
126427 /*   940 */   423,  329,  758, 1017,  289,  833,   50,  682,  311,   93,
126428 /*   950 */    82,   84,  868,  871,  860,  860,   91,   91,   92,   92,
126429 /*   960 */    92,   92,  430,   90,   90,   90,   90,   89,   89,   88,
126430 /*   970 */    88,   88,   87,  335,  430,  256,  419,  114,  249,  856,
126431 /*   980 */   856,  331,  114,  400,  833,  101,  359,  187, 1064,  726,
126432 /*   990 */   725,  739,  401,  416,  420,  360,  833,  102,  424,  311,
126433 /*  1000 */   258,   94,   84,  868,  871,  860,  860,   91,   91,   92,
126434 /*  1010 */    92,   92,   92,  430,   90,   90,   90,   90,   89,   89,
126435 /*  1020 */    88,   88,   88,   87,  335,  430,  221,  261,  114,  114,
126436 /*  1030 */   856,  856,  808,  114,  156,  833,   98,  772,  733,  734,
126437 /*  1040 */   275,  809,  771,  316,  263,  265,  960,  833,  116,  307,
126438 /*  1050 */   741,  274,  722,   84,  868,  871,  860,  860,   91,   91,
126439 /*  1060 */    92,   92,   92,   92,  430,   90,   90,   90,   90,   89,
126440 /*  1070 */    89,   88,   88,   88,   87,  335,   80,  425,  830,    3,
126441 /*  1080 */  1214,  191,  430,  721,  336,  336,  833,  113,  252,   80,
126442 /*  1090 */   425,   68,    3,  913,  913,  428,  270,  336,  336,  430,
126443 /*  1100 */   377,  784,  430,  197,  833,  106,  430,  716,  428,  430,
126444 /*  1110 */   267,  430,  897,   68,  414,  430,  769,  409,  430,   71,
126445 /*  1120 */   430,  833,  105,  123,  833,  103,  847,  414,  833,   49,
126446 /*  1130 */   843,  833,  104,  833,   52,  800,  123,  833,   54,  847,
126447 /*  1140 */   833,   51,  833,   26,  831,  802,   77,   78,  191,  389,
126448 /*  1150 */   430,  372,  114,   79,  432,  431,  911,  911,  835,   77,
126449 /*  1160 */    78,  779,  893,  408,  410,  197,   79,  432,  431,  791,
126450 /*  1170 */   226,  835,  833,   30,  772,   80,  425,  716,    3,  771,
126451 /*  1180 */   411,  412,  897,  336,  336,  290,  291,  839,  703,  840,
126452 /*  1190 */   840,  840,  842,   19,  428,  695,  684,  672,  111,  671,
126453 /*  1200 */   843,  673,  840,  840,  840,  842,   19,  207,  661,  278,
126454 /*  1210 */   148,  304,  280,  414,  282,    6,  822,  348,  248,  241,
126455 /*  1220 */   358,  934,  720,   80,  425,  847,    3,  161,  382,  273,
126456 /*  1230 */   284,  336,  336,  415,  296,  958,  895,  894,  157,  674,
126457 /*  1240 */   107,  194,  428,  948,  135,   77,   78,  777,  953,  951,
126458 /*  1250 */    56,  319,   79,  432,  431,  121,   66,  835,   59,  128,
126459 /*  1260 */   146,  414,  350,  130,  351,  819,  131,  132,  133,  375,
126460 /*  1270 */   173,  149,  138,  847,  936,  365,  178,   70,  425,  827,
126461 /*  1280 */     3,  889,   62,  371,  915,  336,  336,  792,  840,  840,
126462 /*  1290 */   840,  842,   19,   77,   78,  208,  428,  144,  179,  373,
126463 /*  1300 */    79,  432,  431,  255,  180,  835,  260,  675,  181,  308,
126464 /*  1310 */   388,  744,  326,  743,  742,  414,  731,  718,  712,  402,
126465 /*  1320 */   309,  711,  788,   65,  277,  272,  789,  847,  730,  710,
126466 /*  1330 */   709,  279,  193,  787,  281,  876,  840,  840,  840,  842,
126467 /*  1340 */    19,  786,  283,   73,  418,  330,  422,   77,   78,  227,
126468 /*  1350 */    96,  407,   67,  405,   79,  432,  431,  292,  228,  835,
126469 /*  1360 */   215,  202,  229,  293,  767,  303,  302,  301,  204,  299,
126470 /*  1370 */   294,  295,  676,    7,  681,  433,  669,  206,  110,  224,
126471 /*  1380 */   203,  205,  434,  667,  666,  658,  120,  168,  656,  237,
126472 /*  1390 */   840,  840,  840,  842,   19,  337,  155,  233,  236,  341,
126473 /*  1400 */   167,  905,  108,  313,  903,  826,  314,  125,  126,  127,
126474 /*  1410 */   129,  170,  247,  756,  172,  928,  134,  136,  171,   60,
126475 /*  1420 */    61,  123,  169,  137,  175,  933,  176,  927,    8,   13,
126476 /*  1430 */   177,  254,  191,  918,  139,  370,  924,  140,  678,  150,
126477 /*  1440 */   374,  274,  182,  378,  141,  122,   63,   14,  383,  729,
126478 /*  1450 */   268,   15,   64,  225,  846,  845,  874,   16,  765,  770,
126479 /*  1460 */     4,  162,  209,  395,  211,  142,  878,  796,  801,  312,
126480 /*  1470 */   190,   71,   68,  875,  873,  939,  199,  938,   17,  195,
126481 /*  1480 */    18,  196,  417,  975,  152,  653,  976,  198,  153,  421,
126482 /*  1490 */   877,  154,  200,  844,  696,   81,  343,  297, 1019, 1018,
126483 /*  1500 */   300,
126484};
126485static const YYCODETYPE yy_lookahead[] = {
126486 /*     0 */    19,  144,  145,  146,  147,   24,    1,    2,   27,   80,
126487 /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
126488 /*    20 */    91,   92,   93,   94,   95,   91,   92,   93,   94,   95,
126489 /*    30 */    19,   50,   51,   80,   81,   82,   83,  212,   85,   86,
126490 /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,  224,
126491 /*    50 */   225,  226,   71,   72,   73,   74,   75,   76,   77,   78,
126492 /*    60 */    79,   80,   81,   82,   83,   95,   85,   86,   87,   88,
126493 /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   85,
126494 /*    80 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
126495 /*    90 */    66,   33,   27,   28,   27,   28,   22,  201,  152,  152,
126496 /*   100 */    42,   27,  152,  224,  225,  226,   95,  211,   50,   51,
126497 /*   110 */    99,  100,  101,  102,  103,  104,  105,   27,   28,   59,
126498 /*   120 */   174,  175,  243,  112,  174,  175,   66,   94,   95,   71,
126499 /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
126500 /*   140 */    82,   83,  195,   85,   86,   87,   88,   89,   90,   91,
126501 /*   150 */    92,   93,   94,   95,   19,  209,   89,   90,  173,  209,
126502 /*   160 */   210,   26,   97,   98,   97,   98,  181,  100,  108,  109,
126503 /*   170 */   110,   97,  174,  152,  107,  152,  109,   89,   90,   91,
126504 /*   180 */    92,   93,   94,   95,  163,   50,   51,   97,   98,   99,
126505 /*   190 */    55,  244,  102,  103,  104,  174,  175,  174,  175,  132,
126506 /*   200 */   133,   89,   90,  113,   66,   19,   71,   72,   73,   74,
126507 /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  198,
126508 /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
126509 /*   230 */    95,  152,  209,  210,  148,  149,   50,   51,  100,   53,
126510 /*   240 */   154,   59,  156,   22,  132,  133,  119,  120,  163,  163,
126511 /*   250 */    22,  192,  193,  174,  175,   27,   28,   71,   72,   73,
126512 /*   260 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
126513 /*   270 */   174,   85,   86,   87,   88,   89,   90,   91,   92,   93,
126514 /*   280 */    94,   95,   19,  198,  198,  174,  152,   24,  209,  210,
126515 /*   290 */   108,  109,  110,  192,  193,   27,   28,   69,  164,  165,
126516 /*   300 */    79,  119,  120,   27,   28,   27,   99,  222,  152,  102,
126517 /*   310 */   103,  104,   24,   50,   51,   27,   66,   89,   90,  185,
126518 /*   320 */   113,  187,   22,  157,  239,   97,   58,   27,   28,  101,
126519 /*   330 */   174,  175,  246,  163,   71,   72,   73,   74,   75,   76,
126520 /*   340 */    77,   78,   79,   80,   81,   82,   83,   11,   85,   86,
126521 /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
126522 /*   360 */   132,  133,  134,   23,  152,   97,   98,   91,  198,  119,
126523 /*   370 */   120,  152,   22,   97,   98,   97,  152,   27,   28,   27,
126524 /*   380 */    28,   27,   28,  227,  160,   97,  174,  175,  164,  165,
126525 /*   390 */    50,   51,  222,  174,  175,   59,  230,   97,   98,  233,
126526 /*   400 */   188,  137,   66,  139,  234,  187,  177,  188,  152,  239,
126527 /*   410 */    69,   71,   72,   73,   74,   75,   76,   77,   78,   79,
126528 /*   420 */    80,   81,   82,   83,   12,   85,   86,   87,   88,   89,
126529 /*   430 */    90,   91,   92,   93,   94,   95,   19,  177,   97,  152,
126530 /*   440 */    23,   29,  101,  152,  108,  109,  110,   97,   98,   97,
126531 /*   450 */    98,   97,   98,  224,  225,  226,   22,   45,   24,   47,
126532 /*   460 */   152,  152,  152,  152,  152,  174,  175,   50,   51,  249,
126533 /*   470 */   250,   59,   21,  132,  133,  134,  124,  221,  124,  188,
126534 /*   480 */   171,  172,  171,  172,  224,  225,  226,  152,   71,   72,
126535 /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
126536 /*   500 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
126537 /*   510 */    93,   94,   95,   19,  152,  183,   65,   23,  170,  171,
126538 /*   520 */   172,   19,   23,  174,  175,   26,  152,   50,   51,   12,
126539 /*   530 */   196,  197,   37,  170,  171,  172,  174,  175,  224,  225,
126540 /*   540 */   226,  232,  208,  232,   50,   51,   29,   52,  174,  175,
126541 /*   550 */   188,   74,   75,   51,  103,   60,  222,  163,  209,    0,
126542 /*   560 */     1,    2,   45,  152,   47,   71,   72,   73,   74,   75,
126543 /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,  101,   85,
126544 /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
126545 /*   590 */    19,  140,  198,  152,   23,  152,   22,   98,   24,  152,
126546 /*   600 */   152,   27,  152,  183,  152,  152,  111,  213,  214,  107,
126547 /*   610 */   152,  164,  165,  152,  112,  174,  175,  174,  175,  181,
126548 /*   620 */   182,   50,   51,  124,  174,  175,  174,  175,  190,   26,
126549 /*   630 */    22,   23,   22,   23,   26,  166,   26,  168,  169,   16,
126550 /*   640 */    16,   19,   71,   72,   73,   74,   75,   76,   77,   78,
126551 /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
126552 /*   660 */    89,   90,   91,   92,   93,   94,   95,  152,  220,  196,
126553 /*   670 */   197,   97,   50,   51,  108,  109,  110,  152,   70,  221,
126554 /*   680 */    70,  208,    7,    8,    9,   62,   62,   64,   64,  174,
126555 /*   690 */   175,  146,  147,   71,   72,   73,   74,   75,   76,   77,
126556 /*   700 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
126557 /*   710 */    88,   89,   90,   91,   92,   93,   94,   95,   19,  152,
126558 /*   720 */   195,  152,   31,  220,  152,  152,   35,   26,  174,  175,
126559 /*   730 */   152,  163,  152,  130,  152,  115,  152,  117,  118,  152,
126560 /*   740 */    49,  174,  175,  174,  175,  152,  174,  175,   26,   50,
126561 /*   750 */    51,  152,  174,  175,  174,  175,  174,  175,  174,  175,
126562 /*   760 */   138,  174,  175,  140,   22,   23,  198,  174,  175,  152,
126563 /*   770 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
126564 /*   780 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
126565 /*   790 */    91,   92,   93,   94,   95,   19,  152,  152,  152,   98,
126566 /*   800 */    24,  152,  108,  109,  110,  174,  175,  152,  152,  152,
126567 /*   810 */   152,  152,   70,  152,  213,  214,  152,  152,  174,  175,
126568 /*   820 */   174,  175,  152,  174,  175,  124,   50,   51,  106,  174,
126569 /*   830 */   175,  174,  175,  174,  175,  174,  175,  138,  174,  175,
126570 /*   840 */   152,   22,   23,   22,  163,  189,   19,   71,   72,   73,
126571 /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
126572 /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
126573 /*   870 */    94,   95,  152,  152,  168,  169,  152,   50,   51,  198,
126574 /*   880 */   197,  152,  174,  175,  152,  240,  152,  152,  152,   70,
126575 /*   890 */   152,  208,  152,  152,  174,  175,  152,   19,   71,   72,
126576 /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
126577 /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
126578 /*   920 */    93,   94,   95,  152,  195,  247,  248,  152,   50,   51,
126579 /*   930 */   195,  195,  152,  174,  175,  195,  195,   26,  152,  195,
126580 /*   940 */   252,  220,  163,  122,  152,  174,  175,  163,   19,   71,
126581 /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
126582 /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
126583 /*   970 */    92,   93,   94,   95,  152,  195,  252,  198,  240,   50,
126584 /*   980 */    51,  189,  198,   19,  174,  175,   19,   51,   23,  100,
126585 /*   990 */   101,   26,   28,  163,  163,   28,  174,  175,  163,   19,
126586 /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
126587 /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
126588 /*  1020 */    91,   92,   93,   94,   95,  152,  240,  152,  198,  198,
126589 /*  1030 */    50,   51,   33,  198,  123,  174,  175,  116,    7,    8,
126590 /*  1040 */   101,   42,  121,  107,  152,  152,   23,  174,  175,   26,
126591 /*  1050 */   152,  112,  183,   73,   74,   75,   76,   77,   78,   79,
126592 /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
126593 /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,   23,   22,
126594 /*  1080 */    23,   26,  152,  152,   27,   28,  174,  175,   23,   19,
126595 /*  1090 */    20,   26,   22,  132,  133,   38,  152,   27,   28,  152,
126596 /*  1100 */    23,  215,  152,   26,  174,  175,  152,   27,   38,  152,
126597 /*  1110 */    23,  152,   27,   26,   57,  152,   23,  163,  152,   26,
126598 /*  1120 */   152,  174,  175,   66,  174,  175,   69,   57,  174,  175,
126599 /*  1130 */    27,  174,  175,  174,  175,  152,   66,  174,  175,   69,
126600 /*  1140 */   174,  175,  174,  175,  152,   23,   89,   90,   26,   91,
126601 /*  1150 */   152,  236,  198,   96,   97,   98,  132,  133,  101,   89,
126602 /*  1160 */    90,  152,   23,  209,  210,   26,   96,   97,   98,  152,
126603 /*  1170 */   212,  101,  174,  175,  116,   19,   20,   97,   22,  121,
126604 /*  1180 */   152,  193,   97,   27,   28,  152,  152,  152,  152,  132,
126605 /*  1190 */   133,  134,  135,  136,   38,   23,  152,  152,   26,  152,
126606 /*  1200 */    97,  152,  132,  133,  134,  135,  136,  235,  152,  212,
126607 /*  1210 */   199,  150,  212,   57,  212,  200,  203,  216,  241,  216,
126608 /*  1220 */   241,  203,  182,   19,   20,   69,   22,  186,  178,  177,
126609 /*  1230 */   216,   27,   28,  229,  202,   39,  177,  177,  200,  155,
126610 /*  1240 */   245,  122,   38,   41,   22,   89,   90,   91,  159,  159,
126611 /*  1250 */   242,  159,   96,   97,   98,   71,  130,  101,  242,  191,
126612 /*  1260 */   223,   57,   18,  194,  159,  203,  194,  194,  194,   18,
126613 /*  1270 */   158,  223,  191,   69,  203,  159,  158,   19,   20,  191,
126614 /*  1280 */    22,  203,  137,   46,  238,   27,   28,  159,  132,  133,
126615 /*  1290 */   134,  135,  136,   89,   90,  159,   38,   22,  158,  179,
126616 /*  1300 */    96,   97,   98,  237,  158,  101,  159,  159,  158,  179,
126617 /*  1310 */   107,  176,   48,  176,  176,   57,  184,  106,  176,  125,
126618 /*  1320 */   179,  178,  218,  107,  217,  176,  218,   69,  184,  176,
126619 /*  1330 */   176,  217,  159,  218,  217,  159,  132,  133,  134,  135,
126620 /*  1340 */   136,  218,  217,  137,  179,   95,  179,   89,   90,  228,
126621 /*  1350 */   129,  126,  128,  127,   96,   97,   98,  206,  231,  101,
126622 /*  1360 */     5,   25,  231,  205,  207,   10,   11,   12,   13,   14,
126623 /*  1370 */   204,  203,   17,   26,  162,  161,   13,    6,  180,  180,
126624 /*  1380 */   153,  153,  151,  151,  151,  151,  167,   32,    4,   34,
126625 /*  1390 */   132,  133,  134,  135,  136,    3,   22,  142,   43,   68,
126626 /*  1400 */    15,   23,   16,  251,   23,  120,  251,  248,  131,  111,
126627 /*  1410 */   123,   56,   16,   20,  125,    1,  123,  131,   63,   79,
126628 /*  1420 */    79,   66,   67,  111,   36,   28,  122,    1,    5,   22,
126629 /*  1430 */   107,  140,   26,   54,   54,   44,   61,  107,   20,   24,
126630 /*  1440 */    19,  112,  105,   53,   22,   40,   22,   22,   53,   30,
126631 /*  1450 */    23,   22,   22,   53,   23,   23,   23,   22,  116,   23,
126632 /*  1460 */    22,  122,   23,   26,   23,   22,   11,  124,   28,  114,
126633 /*  1470 */    36,   26,   26,   23,   23,   23,  122,   23,   36,   26,
126634 /*  1480 */    36,   22,   24,   23,   22,    1,   23,   26,   22,   24,
126635 /*  1490 */    23,   22,  122,   23,   23,   22,  141,   23,  122,  122,
126636 /*  1500 */    15,
126637};
126638#define YY_SHIFT_USE_DFLT (-72)
126639#define YY_SHIFT_COUNT (435)
126640#define YY_SHIFT_MIN   (-71)
126641#define YY_SHIFT_MAX   (1485)
126642static const short yy_shift_ofst[] = {
126643 /*     0 */     5, 1057, 1355, 1070, 1204, 1204, 1204,   90,   60,  -19,
126644 /*    10 */    58,   58,  186, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126645 /*    20 */    67,   67,  182,  336,   65,  250,  135,  263,  340,  417,
126646 /*    30 */   494,  571,  622,  699,  776,  827,  827,  827,  827,  827,
126647 /*    40 */   827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
126648 /*    50 */   878,  827,  929,  980,  980, 1156, 1204, 1204, 1204, 1204,
126649 /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126650 /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126651 /*    80 */  1204, 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204,
126652 /*    90 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,  -71,  -47,
126653 /*   100 */   -47,  -47,  -47,  -47,   -6,   88,  -66,   65,   65,  451,
126654 /*   110 */   502,  112,  112,   33,  127,  278,  -30,  -72,  -72,  -72,
126655 /*   120 */    11,  412,  412,  268,  608,  610,   65,   65,   65,   65,
126656 /*   130 */    65,   65,   65,   65,   65,   65,   65,   65,   65,   65,
126657 /*   140 */    65,   65,   65,   65,   65,  559,  138,  278,  127,   24,
126658 /*   150 */    24,   24,   24,   24,   24,  -72,  -72,  -72,  228,  341,
126659 /*   160 */   341,  207,  276,  300,  352,  354,  350,   65,   65,   65,
126660 /*   170 */    65,   65,   65,   65,   65,   65,   65,   65,   65,   65,
126661 /*   180 */    65,   65,   65,   65,  495,  495,  495,   65,   65,  499,
126662 /*   190 */    65,   65,   65,  574,   65,   65,  517,   65,   65,   65,
126663 /*   200 */    65,   65,   65,   65,   65,   65,   65,  566,  691,  288,
126664 /*   210 */   288,  288,  701,  620, 1058,  675,  603,  964,  964,  967,
126665 /*   220 */   603,  967,  722,  965,  936,  999,  964,  264,  999,  999,
126666 /*   230 */   911,  921,  434, 1196, 1119, 1119, 1202, 1202, 1119, 1222,
126667 /*   240 */  1184, 1126, 1244, 1244, 1244, 1244, 1119, 1251, 1126, 1222,
126668 /*   250 */  1184, 1184, 1126, 1119, 1251, 1145, 1237, 1119, 1119, 1251,
126669 /*   260 */  1275, 1119, 1251, 1119, 1251, 1275, 1203, 1203, 1203, 1264,
126670 /*   270 */  1275, 1203, 1211, 1203, 1264, 1203, 1203, 1194, 1216, 1194,
126671 /*   280 */  1216, 1194, 1216, 1194, 1216, 1119, 1119, 1206, 1275, 1250,
126672 /*   290 */  1250, 1275, 1221, 1225, 1224, 1226, 1126, 1336, 1347, 1363,
126673 /*   300 */  1363, 1371, 1371, 1371, 1371,  -72,  -72,  -72,  -72,  -72,
126674 /*   310 */   -72,  477,  623,  742,  819,  624,  694,   74, 1023,  221,
126675 /*   320 */  1055, 1065, 1077, 1087, 1080,  889, 1031,  939, 1093, 1122,
126676 /*   330 */  1085, 1139,  961, 1024, 1172, 1103,  821, 1384, 1392, 1374,
126677 /*   340 */  1255, 1385, 1331, 1386, 1378, 1381, 1285, 1277, 1298, 1287,
126678 /*   350 */  1393, 1289, 1396, 1414, 1293, 1286, 1340, 1341, 1312, 1397,
126679 /*   360 */  1388, 1304, 1426, 1423, 1407, 1323, 1291, 1379, 1406, 1380,
126680 /*   370 */  1375, 1391, 1330, 1415, 1418, 1421, 1329, 1337, 1422, 1390,
126681 /*   380 */  1424, 1425, 1427, 1429, 1395, 1419, 1430, 1400, 1405, 1431,
126682 /*   390 */  1432, 1433, 1342, 1435, 1436, 1438, 1437, 1339, 1439, 1441,
126683 /*   400 */  1440, 1434, 1443, 1343, 1445, 1442, 1446, 1444, 1445, 1450,
126684 /*   410 */  1451, 1452, 1453, 1454, 1459, 1455, 1460, 1462, 1458, 1461,
126685 /*   420 */  1463, 1466, 1465, 1461, 1467, 1469, 1470, 1471, 1473, 1354,
126686 /*   430 */  1370, 1376, 1377, 1474, 1485, 1484,
126687};
126688#define YY_REDUCE_USE_DFLT (-176)
126689#define YY_REDUCE_COUNT (310)
126690#define YY_REDUCE_MIN   (-175)
126691#define YY_REDUCE_MAX   (1234)
126692static const short yy_reduce_ofst[] = {
126693 /*     0 */  -143,  954,   86,   21,  -50,   23,   79,  134,  170, -175,
126694 /*    10 */   229,  260, -121,  212,  219,  291,  -54,  349,  362,  156,
126695 /*    20 */   309,  311,  334,   85,  224,  394,  314,  314,  314,  314,
126696 /*    30 */   314,  314,  314,  314,  314,  314,  314,  314,  314,  314,
126697 /*    40 */   314,  314,  314,  314,  314,  314,  314,  314,  314,  314,
126698 /*    50 */   314,  314,  314,  314,  314,  374,  441,  443,  450,  452,
126699 /*    60 */   515,  554,  567,  569,  572,  578,  580,  582,  584,  587,
126700 /*    70 */   593,  631,  644,  646,  649,  655,  657,  659,  661,  664,
126701 /*    80 */   708,  720,  759,  771,  810,  822,  861,  873,  912,  930,
126702 /*    90 */   947,  950,  957,  959,  963,  966,  968,  998,  314,  314,
126703 /*   100 */   314,  314,  314,  314,  314,  314,  314,  447,  -53,  166,
126704 /*   110 */   438,  348,  363,  314,  473,  469,  314,  314,  314,  314,
126705 /*   120 */   -15,   59,  101,  688,  220,  220,  525,  256,  729,  735,
126706 /*   130 */   736,  740,  741,  744,  645,  448,  738,  458,  786,  503,
126707 /*   140 */   780,  656,  721,  724,  792,  545,  568,  706,  683,  681,
126708 /*   150 */   779,  784,  830,  831,  835,  678,  601, -104,   -2,   96,
126709 /*   160 */   111,  218,  287,  308,  310,  312,  335,  411,  453,  461,
126710 /*   170 */   573,  599,  617,  658,  665,  670,  732,  734,  775,  848,
126711 /*   180 */   875,  892,  893,  898,  332,  420,  869,  931,  944,  886,
126712 /*   190 */   983,  992, 1009,  958, 1017, 1028,  988, 1033, 1034, 1035,
126713 /*   200 */   287, 1036, 1044, 1045, 1047, 1049, 1056,  915,  972,  997,
126714 /*   210 */  1000, 1002,  886, 1011, 1015, 1061, 1013, 1001, 1003,  977,
126715 /*   220 */  1018,  979, 1050, 1041, 1040, 1052, 1014, 1004, 1059, 1060,
126716 /*   230 */  1032, 1038, 1084,  995, 1089, 1090, 1008, 1016, 1092, 1037,
126717 /*   240 */  1068, 1062, 1069, 1072, 1073, 1074, 1105, 1112, 1071, 1048,
126718 /*   250 */  1081, 1088, 1078, 1116, 1118, 1046, 1066, 1128, 1136, 1140,
126719 /*   260 */  1120, 1147, 1146, 1148, 1150, 1130, 1135, 1137, 1138, 1132,
126720 /*   270 */  1141, 1142, 1143, 1149, 1144, 1153, 1154, 1104, 1107, 1108,
126721 /*   280 */  1114, 1115, 1117, 1123, 1125, 1173, 1176, 1121, 1165, 1127,
126722 /*   290 */  1131, 1167, 1157, 1151, 1158, 1166, 1168, 1212, 1214, 1227,
126723 /*   300 */  1228, 1231, 1232, 1233, 1234, 1152, 1155, 1159, 1198, 1199,
126724 /*   310 */  1219,
126725};
126726static const YYACTIONTYPE yy_default[] = {
126727 /*     0 */   982, 1300, 1300, 1300, 1214, 1214, 1214, 1305, 1300, 1109,
126728 /*    10 */  1138, 1138, 1274, 1305, 1305, 1305, 1305, 1305, 1305, 1212,
126729 /*    20 */  1305, 1305, 1305, 1300, 1305, 1113, 1144, 1305, 1305, 1305,
126730 /*    30 */  1305, 1305, 1305, 1305, 1305, 1273, 1275, 1152, 1151, 1254,
126731 /*    40 */  1125, 1149, 1142, 1146, 1215, 1208, 1209, 1207, 1211, 1216,
126732 /*    50 */  1305, 1145, 1177, 1192, 1176, 1305, 1305, 1305, 1305, 1305,
126733 /*    60 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126734 /*    70 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126735 /*    80 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126736 /*    90 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1186, 1191,
126737 /*   100 */  1198, 1190, 1187, 1179, 1178, 1180, 1181, 1305, 1305, 1008,
126738 /*   110 */  1074, 1305, 1305, 1182, 1305, 1020, 1183, 1195, 1194, 1193,
126739 /*   120 */  1015, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126740 /*   130 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126741 /*   140 */  1305, 1305, 1305, 1305, 1305,  982, 1300, 1305, 1305, 1300,
126742 /*   150 */  1300, 1300, 1300, 1300, 1300, 1292, 1113, 1103, 1305, 1305,
126743 /*   160 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1280, 1278,
126744 /*   170 */  1305, 1227, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126745 /*   180 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126746 /*   190 */  1305, 1305, 1305, 1109, 1305, 1305, 1305, 1305, 1305, 1305,
126747 /*   200 */  1305, 1305, 1305, 1305, 1305, 1305,  988, 1305, 1247, 1109,
126748 /*   210 */  1109, 1109, 1111, 1089, 1101,  990, 1148, 1127, 1127, 1259,
126749 /*   220 */  1148, 1259, 1045, 1068, 1042, 1138, 1127, 1210, 1138, 1138,
126750 /*   230 */  1110, 1101, 1305, 1285, 1118, 1118, 1277, 1277, 1118, 1157,
126751 /*   240 */  1078, 1148, 1085, 1085, 1085, 1085, 1118, 1005, 1148, 1157,
126752 /*   250 */  1078, 1078, 1148, 1118, 1005, 1253, 1251, 1118, 1118, 1005,
126753 /*   260 */  1220, 1118, 1005, 1118, 1005, 1220, 1076, 1076, 1076, 1060,
126754 /*   270 */  1220, 1076, 1045, 1076, 1060, 1076, 1076, 1131, 1126, 1131,
126755 /*   280 */  1126, 1131, 1126, 1131, 1126, 1118, 1118, 1305, 1220, 1224,
126756 /*   290 */  1224, 1220, 1143, 1132, 1141, 1139, 1148, 1011, 1063,  998,
126757 /*   300 */   998,  987,  987,  987,  987, 1297, 1297, 1292, 1047, 1047,
126758 /*   310 */  1030, 1305, 1305, 1305, 1305, 1305, 1305, 1022, 1305, 1229,
126759 /*   320 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126760 /*   330 */  1305, 1305, 1305, 1305, 1305, 1305, 1164, 1305,  983, 1287,
126761 /*   340 */  1305, 1305, 1284, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126762 /*   350 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126763 /*   360 */  1305, 1257, 1305, 1305, 1305, 1305, 1305, 1305, 1250, 1249,
126764 /*   370 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126765 /*   380 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126766 /*   390 */  1305, 1305, 1092, 1305, 1305, 1305, 1096, 1305, 1305, 1305,
126767 /*   400 */  1305, 1305, 1305, 1305, 1140, 1305, 1133, 1305, 1213, 1305,
126768 /*   410 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1302,
126769 /*   420 */  1305, 1305, 1305, 1301, 1305, 1305, 1305, 1305, 1305, 1166,
126770 /*   430 */  1305, 1165, 1169, 1305,  996, 1305,
126771};
126772
126773/* The next table maps tokens into fallback tokens.  If a construct
126774** like the following:
126775**
126776**      %fallback ID X Y Z.
126777**
126778** appears in the grammar, then ID becomes a fallback token for X, Y,
126779** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
126780** but it does not parse, the type of the token is changed to ID and
126781** the parse is retried before an error is thrown.
126782*/
126783#ifdef YYFALLBACK
126784static const YYCODETYPE yyFallback[] = {
126785    0,  /*          $ => nothing */
126786    0,  /*       SEMI => nothing */
126787   27,  /*    EXPLAIN => ID */
126788   27,  /*      QUERY => ID */
126789   27,  /*       PLAN => ID */
126790   27,  /*      BEGIN => ID */
126791    0,  /* TRANSACTION => nothing */
126792   27,  /*   DEFERRED => ID */
126793   27,  /*  IMMEDIATE => ID */
126794   27,  /*  EXCLUSIVE => ID */
126795    0,  /*     COMMIT => nothing */
126796   27,  /*        END => ID */
126797   27,  /*   ROLLBACK => ID */
126798   27,  /*  SAVEPOINT => ID */
126799   27,  /*    RELEASE => ID */
126800    0,  /*         TO => nothing */
126801    0,  /*      TABLE => nothing */
126802    0,  /*     CREATE => nothing */
126803   27,  /*         IF => ID */
126804    0,  /*        NOT => nothing */
126805    0,  /*     EXISTS => nothing */
126806   27,  /*       TEMP => ID */
126807    0,  /*         LP => nothing */
126808    0,  /*         RP => nothing */
126809    0,  /*         AS => nothing */
126810   27,  /*    WITHOUT => ID */
126811    0,  /*      COMMA => nothing */
126812    0,  /*         ID => nothing */
126813    0,  /*    INDEXED => nothing */
126814   27,  /*      ABORT => ID */
126815   27,  /*     ACTION => ID */
126816   27,  /*      AFTER => ID */
126817   27,  /*    ANALYZE => ID */
126818   27,  /*        ASC => ID */
126819   27,  /*     ATTACH => ID */
126820   27,  /*     BEFORE => ID */
126821   27,  /*         BY => ID */
126822   27,  /*    CASCADE => ID */
126823   27,  /*       CAST => ID */
126824   27,  /*   COLUMNKW => ID */
126825   27,  /*   CONFLICT => ID */
126826   27,  /*   DATABASE => ID */
126827   27,  /*       DESC => ID */
126828   27,  /*     DETACH => ID */
126829   27,  /*       EACH => ID */
126830   27,  /*       FAIL => ID */
126831   27,  /*        FOR => ID */
126832   27,  /*     IGNORE => ID */
126833   27,  /*  INITIALLY => ID */
126834   27,  /*    INSTEAD => ID */
126835   27,  /*    LIKE_KW => ID */
126836   27,  /*      MATCH => ID */
126837   27,  /*         NO => ID */
126838   27,  /*        KEY => ID */
126839   27,  /*         OF => ID */
126840   27,  /*     OFFSET => ID */
126841   27,  /*     PRAGMA => ID */
126842   27,  /*      RAISE => ID */
126843   27,  /*  RECURSIVE => ID */
126844   27,  /*    REPLACE => ID */
126845   27,  /*   RESTRICT => ID */
126846   27,  /*        ROW => ID */
126847   27,  /*    TRIGGER => ID */
126848   27,  /*     VACUUM => ID */
126849   27,  /*       VIEW => ID */
126850   27,  /*    VIRTUAL => ID */
126851   27,  /*       WITH => ID */
126852   27,  /*    REINDEX => ID */
126853   27,  /*     RENAME => ID */
126854   27,  /*   CTIME_KW => ID */
126855};
126856#endif /* YYFALLBACK */
126857
126858/* The following structure represents a single element of the
126859** parser's stack.  Information stored includes:
126860**
126861**   +  The state number for the parser at this level of the stack.
126862**
126863**   +  The value of the token stored at this level of the stack.
126864**      (In other words, the "major" token.)
126865**
126866**   +  The semantic value stored at this level of the stack.  This is
126867**      the information used by the action routines in the grammar.
126868**      It is sometimes called the "minor" token.
126869**
126870** After the "shift" half of a SHIFTREDUCE action, the stateno field
126871** actually contains the reduce action for the second half of the
126872** SHIFTREDUCE.
126873*/
126874struct yyStackEntry {
126875  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
126876  YYCODETYPE major;      /* The major token value.  This is the code
126877                         ** number for the token at this stack level */
126878  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
126879                         ** is the value of the token  */
126880};
126881typedef struct yyStackEntry yyStackEntry;
126882
126883/* The state of the parser is completely contained in an instance of
126884** the following structure */
126885struct yyParser {
126886  int yyidx;                    /* Index of top element in stack */
126887#ifdef YYTRACKMAXSTACKDEPTH
126888  int yyidxMax;                 /* Maximum value of yyidx */
126889#endif
126890  int yyerrcnt;                 /* Shifts left before out of the error */
126891  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
126892#if YYSTACKDEPTH<=0
126893  int yystksz;                  /* Current side of the stack */
126894  yyStackEntry *yystack;        /* The parser's stack */
126895#else
126896  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
126897#endif
126898};
126899typedef struct yyParser yyParser;
126900
126901#ifndef NDEBUG
126902/* #include <stdio.h> */
126903static FILE *yyTraceFILE = 0;
126904static char *yyTracePrompt = 0;
126905#endif /* NDEBUG */
126906
126907#ifndef NDEBUG
126908/*
126909** Turn parser tracing on by giving a stream to which to write the trace
126910** and a prompt to preface each trace message.  Tracing is turned off
126911** by making either argument NULL
126912**
126913** Inputs:
126914** <ul>
126915** <li> A FILE* to which trace output should be written.
126916**      If NULL, then tracing is turned off.
126917** <li> A prefix string written at the beginning of every
126918**      line of trace output.  If NULL, then tracing is
126919**      turned off.
126920** </ul>
126921**
126922** Outputs:
126923** None.
126924*/
126925SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
126926  yyTraceFILE = TraceFILE;
126927  yyTracePrompt = zTracePrompt;
126928  if( yyTraceFILE==0 ) yyTracePrompt = 0;
126929  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
126930}
126931#endif /* NDEBUG */
126932
126933#ifndef NDEBUG
126934/* For tracing shifts, the names of all terminals and nonterminals
126935** are required.  The following table supplies these names */
126936static const char *const yyTokenName[] = {
126937  "$",             "SEMI",          "EXPLAIN",       "QUERY",
126938  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
126939  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
126940  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
126941  "TABLE",         "CREATE",        "IF",            "NOT",
126942  "EXISTS",        "TEMP",          "LP",            "RP",
126943  "AS",            "WITHOUT",       "COMMA",         "ID",
126944  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
126945  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
126946  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
126947  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
126948  "EACH",          "FAIL",          "FOR",           "IGNORE",
126949  "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
126950  "NO",            "KEY",           "OF",            "OFFSET",
126951  "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
126952  "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
126953  "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
126954  "RENAME",        "CTIME_KW",      "ANY",           "OR",
126955  "AND",           "IS",            "BETWEEN",       "IN",
126956  "ISNULL",        "NOTNULL",       "NE",            "EQ",
126957  "GT",            "LE",            "LT",            "GE",
126958  "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
126959  "RSHIFT",        "PLUS",          "MINUS",         "STAR",
126960  "SLASH",         "REM",           "CONCAT",        "COLLATE",
126961  "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
126962  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
126963  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
126964  "INSERT",        "DELETE",        "UPDATE",        "SET",
126965  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
126966  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
126967  "VALUES",        "DISTINCT",      "DOT",           "FROM",
126968  "JOIN",          "USING",         "ORDER",         "GROUP",
126969  "HAVING",        "LIMIT",         "WHERE",         "INTO",
126970  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
126971  "CASE",          "WHEN",          "THEN",          "ELSE",
126972  "INDEX",         "ALTER",         "ADD",           "error",
126973  "input",         "cmdlist",       "ecmd",          "explain",
126974  "cmdx",          "cmd",           "transtype",     "trans_opt",
126975  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
126976  "createkw",      "temp",          "ifnotexists",   "dbnm",
126977  "columnlist",    "conslist_opt",  "table_options",  "select",
126978  "column",        "columnid",      "type",          "carglist",
126979  "typetoken",     "typename",      "signed",        "plus_num",
126980  "minus_num",     "ccons",         "term",          "expr",
126981  "onconf",        "sortorder",     "autoinc",       "eidlist_opt",
126982  "refargs",       "defer_subclause",  "refarg",        "refact",
126983  "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
126984  "sortlist",      "eidlist",       "defer_subclause_opt",  "orconf",
126985  "resolvetype",   "raisetype",     "ifexists",      "fullname",
126986  "selectnowith",  "oneselect",     "with",          "multiselect_op",
126987  "distinct",      "selcollist",    "from",          "where_opt",
126988  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
126989  "values",        "nexprlist",     "exprlist",      "sclp",
126990  "as",            "seltablist",    "stl_prefix",    "joinop",
126991  "indexed_opt",   "on_opt",        "using_opt",     "joinop2",
126992  "idlist",        "setlist",       "insert_cmd",    "idlist_opt",
126993  "likeop",        "between_op",    "in_op",         "case_operand",
126994  "case_exprlist",  "case_else",     "uniqueflag",    "collate",
126995  "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
126996  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
126997  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
126998  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
126999  "vtabarg",       "vtabargtoken",  "lp",            "anylist",
127000  "wqlist",
127001};
127002#endif /* NDEBUG */
127003
127004#ifndef NDEBUG
127005/* For tracing reduce actions, the names of all rules are required.
127006*/
127007static const char *const yyRuleName[] = {
127008 /*   0 */ "input ::= cmdlist",
127009 /*   1 */ "cmdlist ::= cmdlist ecmd",
127010 /*   2 */ "cmdlist ::= ecmd",
127011 /*   3 */ "ecmd ::= SEMI",
127012 /*   4 */ "ecmd ::= explain cmdx SEMI",
127013 /*   5 */ "explain ::=",
127014 /*   6 */ "explain ::= EXPLAIN",
127015 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
127016 /*   8 */ "cmdx ::= cmd",
127017 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
127018 /*  10 */ "trans_opt ::=",
127019 /*  11 */ "trans_opt ::= TRANSACTION",
127020 /*  12 */ "trans_opt ::= TRANSACTION nm",
127021 /*  13 */ "transtype ::=",
127022 /*  14 */ "transtype ::= DEFERRED",
127023 /*  15 */ "transtype ::= IMMEDIATE",
127024 /*  16 */ "transtype ::= EXCLUSIVE",
127025 /*  17 */ "cmd ::= COMMIT trans_opt",
127026 /*  18 */ "cmd ::= END trans_opt",
127027 /*  19 */ "cmd ::= ROLLBACK trans_opt",
127028 /*  20 */ "savepoint_opt ::= SAVEPOINT",
127029 /*  21 */ "savepoint_opt ::=",
127030 /*  22 */ "cmd ::= SAVEPOINT nm",
127031 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
127032 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
127033 /*  25 */ "cmd ::= create_table create_table_args",
127034 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
127035 /*  27 */ "createkw ::= CREATE",
127036 /*  28 */ "ifnotexists ::=",
127037 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
127038 /*  30 */ "temp ::= TEMP",
127039 /*  31 */ "temp ::=",
127040 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
127041 /*  33 */ "create_table_args ::= AS select",
127042 /*  34 */ "table_options ::=",
127043 /*  35 */ "table_options ::= WITHOUT nm",
127044 /*  36 */ "columnlist ::= columnlist COMMA column",
127045 /*  37 */ "columnlist ::= column",
127046 /*  38 */ "column ::= columnid type carglist",
127047 /*  39 */ "columnid ::= nm",
127048 /*  40 */ "nm ::= ID|INDEXED",
127049 /*  41 */ "nm ::= STRING",
127050 /*  42 */ "nm ::= JOIN_KW",
127051 /*  43 */ "type ::=",
127052 /*  44 */ "type ::= typetoken",
127053 /*  45 */ "typetoken ::= typename",
127054 /*  46 */ "typetoken ::= typename LP signed RP",
127055 /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
127056 /*  48 */ "typename ::= ID|STRING",
127057 /*  49 */ "typename ::= typename ID|STRING",
127058 /*  50 */ "signed ::= plus_num",
127059 /*  51 */ "signed ::= minus_num",
127060 /*  52 */ "carglist ::= carglist ccons",
127061 /*  53 */ "carglist ::=",
127062 /*  54 */ "ccons ::= CONSTRAINT nm",
127063 /*  55 */ "ccons ::= DEFAULT term",
127064 /*  56 */ "ccons ::= DEFAULT LP expr RP",
127065 /*  57 */ "ccons ::= DEFAULT PLUS term",
127066 /*  58 */ "ccons ::= DEFAULT MINUS term",
127067 /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
127068 /*  60 */ "ccons ::= NULL onconf",
127069 /*  61 */ "ccons ::= NOT NULL onconf",
127070 /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
127071 /*  63 */ "ccons ::= UNIQUE onconf",
127072 /*  64 */ "ccons ::= CHECK LP expr RP",
127073 /*  65 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
127074 /*  66 */ "ccons ::= defer_subclause",
127075 /*  67 */ "ccons ::= COLLATE ID|STRING",
127076 /*  68 */ "autoinc ::=",
127077 /*  69 */ "autoinc ::= AUTOINCR",
127078 /*  70 */ "refargs ::=",
127079 /*  71 */ "refargs ::= refargs refarg",
127080 /*  72 */ "refarg ::= MATCH nm",
127081 /*  73 */ "refarg ::= ON INSERT refact",
127082 /*  74 */ "refarg ::= ON DELETE refact",
127083 /*  75 */ "refarg ::= ON UPDATE refact",
127084 /*  76 */ "refact ::= SET NULL",
127085 /*  77 */ "refact ::= SET DEFAULT",
127086 /*  78 */ "refact ::= CASCADE",
127087 /*  79 */ "refact ::= RESTRICT",
127088 /*  80 */ "refact ::= NO ACTION",
127089 /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
127090 /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
127091 /*  83 */ "init_deferred_pred_opt ::=",
127092 /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
127093 /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
127094 /*  86 */ "conslist_opt ::=",
127095 /*  87 */ "conslist_opt ::= COMMA conslist",
127096 /*  88 */ "conslist ::= conslist tconscomma tcons",
127097 /*  89 */ "conslist ::= tcons",
127098 /*  90 */ "tconscomma ::= COMMA",
127099 /*  91 */ "tconscomma ::=",
127100 /*  92 */ "tcons ::= CONSTRAINT nm",
127101 /*  93 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
127102 /*  94 */ "tcons ::= UNIQUE LP sortlist RP onconf",
127103 /*  95 */ "tcons ::= CHECK LP expr RP onconf",
127104 /*  96 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
127105 /*  97 */ "defer_subclause_opt ::=",
127106 /*  98 */ "defer_subclause_opt ::= defer_subclause",
127107 /*  99 */ "onconf ::=",
127108 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
127109 /* 101 */ "orconf ::=",
127110 /* 102 */ "orconf ::= OR resolvetype",
127111 /* 103 */ "resolvetype ::= raisetype",
127112 /* 104 */ "resolvetype ::= IGNORE",
127113 /* 105 */ "resolvetype ::= REPLACE",
127114 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
127115 /* 107 */ "ifexists ::= IF EXISTS",
127116 /* 108 */ "ifexists ::=",
127117 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
127118 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
127119 /* 111 */ "cmd ::= select",
127120 /* 112 */ "select ::= with selectnowith",
127121 /* 113 */ "selectnowith ::= oneselect",
127122 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
127123 /* 115 */ "multiselect_op ::= UNION",
127124 /* 116 */ "multiselect_op ::= UNION ALL",
127125 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
127126 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
127127 /* 119 */ "oneselect ::= values",
127128 /* 120 */ "values ::= VALUES LP nexprlist RP",
127129 /* 121 */ "values ::= values COMMA LP exprlist RP",
127130 /* 122 */ "distinct ::= DISTINCT",
127131 /* 123 */ "distinct ::= ALL",
127132 /* 124 */ "distinct ::=",
127133 /* 125 */ "sclp ::= selcollist COMMA",
127134 /* 126 */ "sclp ::=",
127135 /* 127 */ "selcollist ::= sclp expr as",
127136 /* 128 */ "selcollist ::= sclp STAR",
127137 /* 129 */ "selcollist ::= sclp nm DOT STAR",
127138 /* 130 */ "as ::= AS nm",
127139 /* 131 */ "as ::= ID|STRING",
127140 /* 132 */ "as ::=",
127141 /* 133 */ "from ::=",
127142 /* 134 */ "from ::= FROM seltablist",
127143 /* 135 */ "stl_prefix ::= seltablist joinop",
127144 /* 136 */ "stl_prefix ::=",
127145 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
127146 /* 138 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
127147 /* 139 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
127148 /* 140 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
127149 /* 141 */ "dbnm ::=",
127150 /* 142 */ "dbnm ::= DOT nm",
127151 /* 143 */ "fullname ::= nm dbnm",
127152 /* 144 */ "joinop ::= COMMA|JOIN",
127153 /* 145 */ "joinop ::= JOIN_KW JOIN",
127154 /* 146 */ "joinop ::= JOIN_KW nm JOIN",
127155 /* 147 */ "joinop ::= JOIN_KW nm nm JOIN",
127156 /* 148 */ "on_opt ::= ON expr",
127157 /* 149 */ "on_opt ::=",
127158 /* 150 */ "indexed_opt ::=",
127159 /* 151 */ "indexed_opt ::= INDEXED BY nm",
127160 /* 152 */ "indexed_opt ::= NOT INDEXED",
127161 /* 153 */ "using_opt ::= USING LP idlist RP",
127162 /* 154 */ "using_opt ::=",
127163 /* 155 */ "orderby_opt ::=",
127164 /* 156 */ "orderby_opt ::= ORDER BY sortlist",
127165 /* 157 */ "sortlist ::= sortlist COMMA expr sortorder",
127166 /* 158 */ "sortlist ::= expr sortorder",
127167 /* 159 */ "sortorder ::= ASC",
127168 /* 160 */ "sortorder ::= DESC",
127169 /* 161 */ "sortorder ::=",
127170 /* 162 */ "groupby_opt ::=",
127171 /* 163 */ "groupby_opt ::= GROUP BY nexprlist",
127172 /* 164 */ "having_opt ::=",
127173 /* 165 */ "having_opt ::= HAVING expr",
127174 /* 166 */ "limit_opt ::=",
127175 /* 167 */ "limit_opt ::= LIMIT expr",
127176 /* 168 */ "limit_opt ::= LIMIT expr OFFSET expr",
127177 /* 169 */ "limit_opt ::= LIMIT expr COMMA expr",
127178 /* 170 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
127179 /* 171 */ "where_opt ::=",
127180 /* 172 */ "where_opt ::= WHERE expr",
127181 /* 173 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
127182 /* 174 */ "setlist ::= setlist COMMA nm EQ expr",
127183 /* 175 */ "setlist ::= nm EQ expr",
127184 /* 176 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
127185 /* 177 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
127186 /* 178 */ "insert_cmd ::= INSERT orconf",
127187 /* 179 */ "insert_cmd ::= REPLACE",
127188 /* 180 */ "idlist_opt ::=",
127189 /* 181 */ "idlist_opt ::= LP idlist RP",
127190 /* 182 */ "idlist ::= idlist COMMA nm",
127191 /* 183 */ "idlist ::= nm",
127192 /* 184 */ "expr ::= term",
127193 /* 185 */ "expr ::= LP expr RP",
127194 /* 186 */ "term ::= NULL",
127195 /* 187 */ "expr ::= ID|INDEXED",
127196 /* 188 */ "expr ::= JOIN_KW",
127197 /* 189 */ "expr ::= nm DOT nm",
127198 /* 190 */ "expr ::= nm DOT nm DOT nm",
127199 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
127200 /* 192 */ "term ::= STRING",
127201 /* 193 */ "expr ::= VARIABLE",
127202 /* 194 */ "expr ::= expr COLLATE ID|STRING",
127203 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
127204 /* 196 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
127205 /* 197 */ "expr ::= ID|INDEXED LP STAR RP",
127206 /* 198 */ "term ::= CTIME_KW",
127207 /* 199 */ "expr ::= expr AND expr",
127208 /* 200 */ "expr ::= expr OR expr",
127209 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
127210 /* 202 */ "expr ::= expr EQ|NE expr",
127211 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
127212 /* 204 */ "expr ::= expr PLUS|MINUS expr",
127213 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
127214 /* 206 */ "expr ::= expr CONCAT expr",
127215 /* 207 */ "likeop ::= LIKE_KW|MATCH",
127216 /* 208 */ "likeop ::= NOT LIKE_KW|MATCH",
127217 /* 209 */ "expr ::= expr likeop expr",
127218 /* 210 */ "expr ::= expr likeop expr ESCAPE expr",
127219 /* 211 */ "expr ::= expr ISNULL|NOTNULL",
127220 /* 212 */ "expr ::= expr NOT NULL",
127221 /* 213 */ "expr ::= expr IS expr",
127222 /* 214 */ "expr ::= expr IS NOT expr",
127223 /* 215 */ "expr ::= NOT expr",
127224 /* 216 */ "expr ::= BITNOT expr",
127225 /* 217 */ "expr ::= MINUS expr",
127226 /* 218 */ "expr ::= PLUS expr",
127227 /* 219 */ "between_op ::= BETWEEN",
127228 /* 220 */ "between_op ::= NOT BETWEEN",
127229 /* 221 */ "expr ::= expr between_op expr AND expr",
127230 /* 222 */ "in_op ::= IN",
127231 /* 223 */ "in_op ::= NOT IN",
127232 /* 224 */ "expr ::= expr in_op LP exprlist RP",
127233 /* 225 */ "expr ::= LP select RP",
127234 /* 226 */ "expr ::= expr in_op LP select RP",
127235 /* 227 */ "expr ::= expr in_op nm dbnm",
127236 /* 228 */ "expr ::= EXISTS LP select RP",
127237 /* 229 */ "expr ::= CASE case_operand case_exprlist case_else END",
127238 /* 230 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
127239 /* 231 */ "case_exprlist ::= WHEN expr THEN expr",
127240 /* 232 */ "case_else ::= ELSE expr",
127241 /* 233 */ "case_else ::=",
127242 /* 234 */ "case_operand ::= expr",
127243 /* 235 */ "case_operand ::=",
127244 /* 236 */ "exprlist ::= nexprlist",
127245 /* 237 */ "exprlist ::=",
127246 /* 238 */ "nexprlist ::= nexprlist COMMA expr",
127247 /* 239 */ "nexprlist ::= expr",
127248 /* 240 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
127249 /* 241 */ "uniqueflag ::= UNIQUE",
127250 /* 242 */ "uniqueflag ::=",
127251 /* 243 */ "eidlist_opt ::=",
127252 /* 244 */ "eidlist_opt ::= LP eidlist RP",
127253 /* 245 */ "eidlist ::= eidlist COMMA nm collate sortorder",
127254 /* 246 */ "eidlist ::= nm collate sortorder",
127255 /* 247 */ "collate ::=",
127256 /* 248 */ "collate ::= COLLATE ID|STRING",
127257 /* 249 */ "cmd ::= DROP INDEX ifexists fullname",
127258 /* 250 */ "cmd ::= VACUUM",
127259 /* 251 */ "cmd ::= VACUUM nm",
127260 /* 252 */ "cmd ::= PRAGMA nm dbnm",
127261 /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
127262 /* 254 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
127263 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
127264 /* 256 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
127265 /* 257 */ "nmnum ::= plus_num",
127266 /* 258 */ "nmnum ::= nm",
127267 /* 259 */ "nmnum ::= ON",
127268 /* 260 */ "nmnum ::= DELETE",
127269 /* 261 */ "nmnum ::= DEFAULT",
127270 /* 262 */ "plus_num ::= PLUS INTEGER|FLOAT",
127271 /* 263 */ "plus_num ::= INTEGER|FLOAT",
127272 /* 264 */ "minus_num ::= MINUS INTEGER|FLOAT",
127273 /* 265 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
127274 /* 266 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
127275 /* 267 */ "trigger_time ::= BEFORE",
127276 /* 268 */ "trigger_time ::= AFTER",
127277 /* 269 */ "trigger_time ::= INSTEAD OF",
127278 /* 270 */ "trigger_time ::=",
127279 /* 271 */ "trigger_event ::= DELETE|INSERT",
127280 /* 272 */ "trigger_event ::= UPDATE",
127281 /* 273 */ "trigger_event ::= UPDATE OF idlist",
127282 /* 274 */ "foreach_clause ::=",
127283 /* 275 */ "foreach_clause ::= FOR EACH ROW",
127284 /* 276 */ "when_clause ::=",
127285 /* 277 */ "when_clause ::= WHEN expr",
127286 /* 278 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
127287 /* 279 */ "trigger_cmd_list ::= trigger_cmd SEMI",
127288 /* 280 */ "trnm ::= nm",
127289 /* 281 */ "trnm ::= nm DOT nm",
127290 /* 282 */ "tridxby ::=",
127291 /* 283 */ "tridxby ::= INDEXED BY nm",
127292 /* 284 */ "tridxby ::= NOT INDEXED",
127293 /* 285 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
127294 /* 286 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
127295 /* 287 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
127296 /* 288 */ "trigger_cmd ::= select",
127297 /* 289 */ "expr ::= RAISE LP IGNORE RP",
127298 /* 290 */ "expr ::= RAISE LP raisetype COMMA nm RP",
127299 /* 291 */ "raisetype ::= ROLLBACK",
127300 /* 292 */ "raisetype ::= ABORT",
127301 /* 293 */ "raisetype ::= FAIL",
127302 /* 294 */ "cmd ::= DROP TRIGGER ifexists fullname",
127303 /* 295 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
127304 /* 296 */ "cmd ::= DETACH database_kw_opt expr",
127305 /* 297 */ "key_opt ::=",
127306 /* 298 */ "key_opt ::= KEY expr",
127307 /* 299 */ "database_kw_opt ::= DATABASE",
127308 /* 300 */ "database_kw_opt ::=",
127309 /* 301 */ "cmd ::= REINDEX",
127310 /* 302 */ "cmd ::= REINDEX nm dbnm",
127311 /* 303 */ "cmd ::= ANALYZE",
127312 /* 304 */ "cmd ::= ANALYZE nm dbnm",
127313 /* 305 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
127314 /* 306 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
127315 /* 307 */ "add_column_fullname ::= fullname",
127316 /* 308 */ "kwcolumn_opt ::=",
127317 /* 309 */ "kwcolumn_opt ::= COLUMNKW",
127318 /* 310 */ "cmd ::= create_vtab",
127319 /* 311 */ "cmd ::= create_vtab LP vtabarglist RP",
127320 /* 312 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
127321 /* 313 */ "vtabarglist ::= vtabarg",
127322 /* 314 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
127323 /* 315 */ "vtabarg ::=",
127324 /* 316 */ "vtabarg ::= vtabarg vtabargtoken",
127325 /* 317 */ "vtabargtoken ::= ANY",
127326 /* 318 */ "vtabargtoken ::= lp anylist RP",
127327 /* 319 */ "lp ::= LP",
127328 /* 320 */ "anylist ::=",
127329 /* 321 */ "anylist ::= anylist LP anylist RP",
127330 /* 322 */ "anylist ::= anylist ANY",
127331 /* 323 */ "with ::=",
127332 /* 324 */ "with ::= WITH wqlist",
127333 /* 325 */ "with ::= WITH RECURSIVE wqlist",
127334 /* 326 */ "wqlist ::= nm eidlist_opt AS LP select RP",
127335 /* 327 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
127336};
127337#endif /* NDEBUG */
127338
127339
127340#if YYSTACKDEPTH<=0
127341/*
127342** Try to increase the size of the parser stack.
127343*/
127344static void yyGrowStack(yyParser *p){
127345  int newSize;
127346  yyStackEntry *pNew;
127347
127348  newSize = p->yystksz*2 + 100;
127349  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
127350  if( pNew ){
127351    p->yystack = pNew;
127352    p->yystksz = newSize;
127353#ifndef NDEBUG
127354    if( yyTraceFILE ){
127355      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
127356              yyTracePrompt, p->yystksz);
127357    }
127358#endif
127359  }
127360}
127361#endif
127362
127363/*
127364** This function allocates a new parser.
127365** The only argument is a pointer to a function which works like
127366** malloc.
127367**
127368** Inputs:
127369** A pointer to the function used to allocate memory.
127370**
127371** Outputs:
127372** A pointer to a parser.  This pointer is used in subsequent calls
127373** to sqlite3Parser and sqlite3ParserFree.
127374*/
127375SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
127376  yyParser *pParser;
127377  pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
127378  if( pParser ){
127379    pParser->yyidx = -1;
127380#ifdef YYTRACKMAXSTACKDEPTH
127381    pParser->yyidxMax = 0;
127382#endif
127383#if YYSTACKDEPTH<=0
127384    pParser->yystack = NULL;
127385    pParser->yystksz = 0;
127386    yyGrowStack(pParser);
127387#endif
127388  }
127389  return pParser;
127390}
127391
127392/* The following function deletes the value associated with a
127393** symbol.  The symbol can be either a terminal or nonterminal.
127394** "yymajor" is the symbol code, and "yypminor" is a pointer to
127395** the value.
127396*/
127397static void yy_destructor(
127398  yyParser *yypParser,    /* The parser */
127399  YYCODETYPE yymajor,     /* Type code for object to destroy */
127400  YYMINORTYPE *yypminor   /* The object to be destroyed */
127401){
127402  sqlite3ParserARG_FETCH;
127403  switch( yymajor ){
127404    /* Here is inserted the actions which take place when a
127405    ** terminal or non-terminal is destroyed.  This can happen
127406    ** when the symbol is popped from the stack during a
127407    ** reduce or during error processing or when a parser is
127408    ** being destroyed before it is finished parsing.
127409    **
127410    ** Note: during a reduce, the only symbols destroyed are those
127411    ** which appear on the RHS of the rule, but which are not used
127412    ** inside the C code.
127413    */
127414    case 163: /* select */
127415    case 196: /* selectnowith */
127416    case 197: /* oneselect */
127417    case 208: /* values */
127418{
127419sqlite3SelectDelete(pParse->db, (yypminor->yy3));
127420}
127421      break;
127422    case 174: /* term */
127423    case 175: /* expr */
127424{
127425sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
127426}
127427      break;
127428    case 179: /* eidlist_opt */
127429    case 188: /* sortlist */
127430    case 189: /* eidlist */
127431    case 201: /* selcollist */
127432    case 204: /* groupby_opt */
127433    case 206: /* orderby_opt */
127434    case 209: /* nexprlist */
127435    case 210: /* exprlist */
127436    case 211: /* sclp */
127437    case 221: /* setlist */
127438    case 228: /* case_exprlist */
127439{
127440sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
127441}
127442      break;
127443    case 195: /* fullname */
127444    case 202: /* from */
127445    case 213: /* seltablist */
127446    case 214: /* stl_prefix */
127447{
127448sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
127449}
127450      break;
127451    case 198: /* with */
127452    case 252: /* wqlist */
127453{
127454sqlite3WithDelete(pParse->db, (yypminor->yy59));
127455}
127456      break;
127457    case 203: /* where_opt */
127458    case 205: /* having_opt */
127459    case 217: /* on_opt */
127460    case 227: /* case_operand */
127461    case 229: /* case_else */
127462    case 238: /* when_clause */
127463    case 243: /* key_opt */
127464{
127465sqlite3ExprDelete(pParse->db, (yypminor->yy132));
127466}
127467      break;
127468    case 218: /* using_opt */
127469    case 220: /* idlist */
127470    case 223: /* idlist_opt */
127471{
127472sqlite3IdListDelete(pParse->db, (yypminor->yy408));
127473}
127474      break;
127475    case 234: /* trigger_cmd_list */
127476    case 239: /* trigger_cmd */
127477{
127478sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
127479}
127480      break;
127481    case 236: /* trigger_event */
127482{
127483sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
127484}
127485      break;
127486    default:  break;   /* If no destructor action specified: do nothing */
127487  }
127488}
127489
127490/*
127491** Pop the parser's stack once.
127492**
127493** If there is a destructor routine associated with the token which
127494** is popped from the stack, then call it.
127495**
127496** Return the major token number for the symbol popped.
127497*/
127498static int yy_pop_parser_stack(yyParser *pParser){
127499  YYCODETYPE yymajor;
127500  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
127501
127502  /* There is no mechanism by which the parser stack can be popped below
127503  ** empty in SQLite.  */
127504  assert( pParser->yyidx>=0 );
127505#ifndef NDEBUG
127506  if( yyTraceFILE && pParser->yyidx>=0 ){
127507    fprintf(yyTraceFILE,"%sPopping %s\n",
127508      yyTracePrompt,
127509      yyTokenName[yytos->major]);
127510  }
127511#endif
127512  yymajor = yytos->major;
127513  yy_destructor(pParser, yymajor, &yytos->minor);
127514  pParser->yyidx--;
127515  return yymajor;
127516}
127517
127518/*
127519** Deallocate and destroy a parser.  Destructors are all called for
127520** all stack elements before shutting the parser down.
127521**
127522** Inputs:
127523** <ul>
127524** <li>  A pointer to the parser.  This should be a pointer
127525**       obtained from sqlite3ParserAlloc.
127526** <li>  A pointer to a function used to reclaim memory obtained
127527**       from malloc.
127528** </ul>
127529*/
127530SQLITE_PRIVATE void sqlite3ParserFree(
127531  void *p,                    /* The parser to be deleted */
127532  void (*freeProc)(void*)     /* Function used to reclaim memory */
127533){
127534  yyParser *pParser = (yyParser*)p;
127535  /* In SQLite, we never try to destroy a parser that was not successfully
127536  ** created in the first place. */
127537  if( NEVER(pParser==0) ) return;
127538  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
127539#if YYSTACKDEPTH<=0
127540  free(pParser->yystack);
127541#endif
127542  (*freeProc)((void*)pParser);
127543}
127544
127545/*
127546** Return the peak depth of the stack for a parser.
127547*/
127548#ifdef YYTRACKMAXSTACKDEPTH
127549SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
127550  yyParser *pParser = (yyParser*)p;
127551  return pParser->yyidxMax;
127552}
127553#endif
127554
127555/*
127556** Find the appropriate action for a parser given the terminal
127557** look-ahead token iLookAhead.
127558**
127559** If the look-ahead token is YYNOCODE, then check to see if the action is
127560** independent of the look-ahead.  If it is, return the action, otherwise
127561** return YY_NO_ACTION.
127562*/
127563static int yy_find_shift_action(
127564  yyParser *pParser,        /* The parser */
127565  YYCODETYPE iLookAhead     /* The look-ahead token */
127566){
127567  int i;
127568  int stateno = pParser->yystack[pParser->yyidx].stateno;
127569
127570  if( stateno>=YY_MIN_REDUCE ) return stateno;
127571  assert( stateno <= YY_SHIFT_COUNT );
127572  i = yy_shift_ofst[stateno];
127573  if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
127574  assert( iLookAhead!=YYNOCODE );
127575  i += iLookAhead;
127576  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
127577    if( iLookAhead>0 ){
127578#ifdef YYFALLBACK
127579      YYCODETYPE iFallback;            /* Fallback token */
127580      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
127581             && (iFallback = yyFallback[iLookAhead])!=0 ){
127582#ifndef NDEBUG
127583        if( yyTraceFILE ){
127584          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
127585             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
127586        }
127587#endif
127588        return yy_find_shift_action(pParser, iFallback);
127589      }
127590#endif
127591#ifdef YYWILDCARD
127592      {
127593        int j = i - iLookAhead + YYWILDCARD;
127594        if(
127595#if YY_SHIFT_MIN+YYWILDCARD<0
127596          j>=0 &&
127597#endif
127598#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
127599          j<YY_ACTTAB_COUNT &&
127600#endif
127601          yy_lookahead[j]==YYWILDCARD
127602        ){
127603#ifndef NDEBUG
127604          if( yyTraceFILE ){
127605            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
127606               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
127607          }
127608#endif /* NDEBUG */
127609          return yy_action[j];
127610        }
127611      }
127612#endif /* YYWILDCARD */
127613    }
127614    return yy_default[stateno];
127615  }else{
127616    return yy_action[i];
127617  }
127618}
127619
127620/*
127621** Find the appropriate action for a parser given the non-terminal
127622** look-ahead token iLookAhead.
127623**
127624** If the look-ahead token is YYNOCODE, then check to see if the action is
127625** independent of the look-ahead.  If it is, return the action, otherwise
127626** return YY_NO_ACTION.
127627*/
127628static int yy_find_reduce_action(
127629  int stateno,              /* Current state number */
127630  YYCODETYPE iLookAhead     /* The look-ahead token */
127631){
127632  int i;
127633#ifdef YYERRORSYMBOL
127634  if( stateno>YY_REDUCE_COUNT ){
127635    return yy_default[stateno];
127636  }
127637#else
127638  assert( stateno<=YY_REDUCE_COUNT );
127639#endif
127640  i = yy_reduce_ofst[stateno];
127641  assert( i!=YY_REDUCE_USE_DFLT );
127642  assert( iLookAhead!=YYNOCODE );
127643  i += iLookAhead;
127644#ifdef YYERRORSYMBOL
127645  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
127646    return yy_default[stateno];
127647  }
127648#else
127649  assert( i>=0 && i<YY_ACTTAB_COUNT );
127650  assert( yy_lookahead[i]==iLookAhead );
127651#endif
127652  return yy_action[i];
127653}
127654
127655/*
127656** The following routine is called if the stack overflows.
127657*/
127658static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
127659   sqlite3ParserARG_FETCH;
127660   yypParser->yyidx--;
127661#ifndef NDEBUG
127662   if( yyTraceFILE ){
127663     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
127664   }
127665#endif
127666   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
127667   /* Here code is inserted which will execute if the parser
127668   ** stack every overflows */
127669
127670  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
127671  sqlite3ErrorMsg(pParse, "parser stack overflow");
127672   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
127673}
127674
127675/*
127676** Print tracing information for a SHIFT action
127677*/
127678#ifndef NDEBUG
127679static void yyTraceShift(yyParser *yypParser, int yyNewState){
127680  if( yyTraceFILE ){
127681    int i;
127682    if( yyNewState<YYNSTATE ){
127683      fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
127684      fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
127685      for(i=1; i<=yypParser->yyidx; i++)
127686        fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
127687      fprintf(yyTraceFILE,"\n");
127688    }else{
127689      fprintf(yyTraceFILE,"%sShift *\n",yyTracePrompt);
127690    }
127691  }
127692}
127693#else
127694# define yyTraceShift(X,Y)
127695#endif
127696
127697/*
127698** Perform a shift action.  Return the number of errors.
127699*/
127700static void yy_shift(
127701  yyParser *yypParser,          /* The parser to be shifted */
127702  int yyNewState,               /* The new state to shift in */
127703  int yyMajor,                  /* The major token to shift in */
127704  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
127705){
127706  yyStackEntry *yytos;
127707  yypParser->yyidx++;
127708#ifdef YYTRACKMAXSTACKDEPTH
127709  if( yypParser->yyidx>yypParser->yyidxMax ){
127710    yypParser->yyidxMax = yypParser->yyidx;
127711  }
127712#endif
127713#if YYSTACKDEPTH>0
127714  if( yypParser->yyidx>=YYSTACKDEPTH ){
127715    yyStackOverflow(yypParser, yypMinor);
127716    return;
127717  }
127718#else
127719  if( yypParser->yyidx>=yypParser->yystksz ){
127720    yyGrowStack(yypParser);
127721    if( yypParser->yyidx>=yypParser->yystksz ){
127722      yyStackOverflow(yypParser, yypMinor);
127723      return;
127724    }
127725  }
127726#endif
127727  yytos = &yypParser->yystack[yypParser->yyidx];
127728  yytos->stateno = (YYACTIONTYPE)yyNewState;
127729  yytos->major = (YYCODETYPE)yyMajor;
127730  yytos->minor = *yypMinor;
127731  yyTraceShift(yypParser, yyNewState);
127732}
127733
127734/* The following table contains information about every rule that
127735** is used during the reduce.
127736*/
127737static const struct {
127738  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
127739  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
127740} yyRuleInfo[] = {
127741  { 144, 1 },
127742  { 145, 2 },
127743  { 145, 1 },
127744  { 146, 1 },
127745  { 146, 3 },
127746  { 147, 0 },
127747  { 147, 1 },
127748  { 147, 3 },
127749  { 148, 1 },
127750  { 149, 3 },
127751  { 151, 0 },
127752  { 151, 1 },
127753  { 151, 2 },
127754  { 150, 0 },
127755  { 150, 1 },
127756  { 150, 1 },
127757  { 150, 1 },
127758  { 149, 2 },
127759  { 149, 2 },
127760  { 149, 2 },
127761  { 153, 1 },
127762  { 153, 0 },
127763  { 149, 2 },
127764  { 149, 3 },
127765  { 149, 5 },
127766  { 149, 2 },
127767  { 154, 6 },
127768  { 156, 1 },
127769  { 158, 0 },
127770  { 158, 3 },
127771  { 157, 1 },
127772  { 157, 0 },
127773  { 155, 5 },
127774  { 155, 2 },
127775  { 162, 0 },
127776  { 162, 2 },
127777  { 160, 3 },
127778  { 160, 1 },
127779  { 164, 3 },
127780  { 165, 1 },
127781  { 152, 1 },
127782  { 152, 1 },
127783  { 152, 1 },
127784  { 166, 0 },
127785  { 166, 1 },
127786  { 168, 1 },
127787  { 168, 4 },
127788  { 168, 6 },
127789  { 169, 1 },
127790  { 169, 2 },
127791  { 170, 1 },
127792  { 170, 1 },
127793  { 167, 2 },
127794  { 167, 0 },
127795  { 173, 2 },
127796  { 173, 2 },
127797  { 173, 4 },
127798  { 173, 3 },
127799  { 173, 3 },
127800  { 173, 2 },
127801  { 173, 2 },
127802  { 173, 3 },
127803  { 173, 5 },
127804  { 173, 2 },
127805  { 173, 4 },
127806  { 173, 4 },
127807  { 173, 1 },
127808  { 173, 2 },
127809  { 178, 0 },
127810  { 178, 1 },
127811  { 180, 0 },
127812  { 180, 2 },
127813  { 182, 2 },
127814  { 182, 3 },
127815  { 182, 3 },
127816  { 182, 3 },
127817  { 183, 2 },
127818  { 183, 2 },
127819  { 183, 1 },
127820  { 183, 1 },
127821  { 183, 2 },
127822  { 181, 3 },
127823  { 181, 2 },
127824  { 184, 0 },
127825  { 184, 2 },
127826  { 184, 2 },
127827  { 161, 0 },
127828  { 161, 2 },
127829  { 185, 3 },
127830  { 185, 1 },
127831  { 186, 1 },
127832  { 186, 0 },
127833  { 187, 2 },
127834  { 187, 7 },
127835  { 187, 5 },
127836  { 187, 5 },
127837  { 187, 10 },
127838  { 190, 0 },
127839  { 190, 1 },
127840  { 176, 0 },
127841  { 176, 3 },
127842  { 191, 0 },
127843  { 191, 2 },
127844  { 192, 1 },
127845  { 192, 1 },
127846  { 192, 1 },
127847  { 149, 4 },
127848  { 194, 2 },
127849  { 194, 0 },
127850  { 149, 9 },
127851  { 149, 4 },
127852  { 149, 1 },
127853  { 163, 2 },
127854  { 196, 1 },
127855  { 196, 3 },
127856  { 199, 1 },
127857  { 199, 2 },
127858  { 199, 1 },
127859  { 197, 9 },
127860  { 197, 1 },
127861  { 208, 4 },
127862  { 208, 5 },
127863  { 200, 1 },
127864  { 200, 1 },
127865  { 200, 0 },
127866  { 211, 2 },
127867  { 211, 0 },
127868  { 201, 3 },
127869  { 201, 2 },
127870  { 201, 4 },
127871  { 212, 2 },
127872  { 212, 1 },
127873  { 212, 0 },
127874  { 202, 0 },
127875  { 202, 2 },
127876  { 214, 2 },
127877  { 214, 0 },
127878  { 213, 7 },
127879  { 213, 9 },
127880  { 213, 7 },
127881  { 213, 7 },
127882  { 159, 0 },
127883  { 159, 2 },
127884  { 195, 2 },
127885  { 215, 1 },
127886  { 215, 2 },
127887  { 215, 3 },
127888  { 215, 4 },
127889  { 217, 2 },
127890  { 217, 0 },
127891  { 216, 0 },
127892  { 216, 3 },
127893  { 216, 2 },
127894  { 218, 4 },
127895  { 218, 0 },
127896  { 206, 0 },
127897  { 206, 3 },
127898  { 188, 4 },
127899  { 188, 2 },
127900  { 177, 1 },
127901  { 177, 1 },
127902  { 177, 0 },
127903  { 204, 0 },
127904  { 204, 3 },
127905  { 205, 0 },
127906  { 205, 2 },
127907  { 207, 0 },
127908  { 207, 2 },
127909  { 207, 4 },
127910  { 207, 4 },
127911  { 149, 6 },
127912  { 203, 0 },
127913  { 203, 2 },
127914  { 149, 8 },
127915  { 221, 5 },
127916  { 221, 3 },
127917  { 149, 6 },
127918  { 149, 7 },
127919  { 222, 2 },
127920  { 222, 1 },
127921  { 223, 0 },
127922  { 223, 3 },
127923  { 220, 3 },
127924  { 220, 1 },
127925  { 175, 1 },
127926  { 175, 3 },
127927  { 174, 1 },
127928  { 175, 1 },
127929  { 175, 1 },
127930  { 175, 3 },
127931  { 175, 5 },
127932  { 174, 1 },
127933  { 174, 1 },
127934  { 175, 1 },
127935  { 175, 3 },
127936  { 175, 6 },
127937  { 175, 5 },
127938  { 175, 4 },
127939  { 174, 1 },
127940  { 175, 3 },
127941  { 175, 3 },
127942  { 175, 3 },
127943  { 175, 3 },
127944  { 175, 3 },
127945  { 175, 3 },
127946  { 175, 3 },
127947  { 175, 3 },
127948  { 224, 1 },
127949  { 224, 2 },
127950  { 175, 3 },
127951  { 175, 5 },
127952  { 175, 2 },
127953  { 175, 3 },
127954  { 175, 3 },
127955  { 175, 4 },
127956  { 175, 2 },
127957  { 175, 2 },
127958  { 175, 2 },
127959  { 175, 2 },
127960  { 225, 1 },
127961  { 225, 2 },
127962  { 175, 5 },
127963  { 226, 1 },
127964  { 226, 2 },
127965  { 175, 5 },
127966  { 175, 3 },
127967  { 175, 5 },
127968  { 175, 4 },
127969  { 175, 4 },
127970  { 175, 5 },
127971  { 228, 5 },
127972  { 228, 4 },
127973  { 229, 2 },
127974  { 229, 0 },
127975  { 227, 1 },
127976  { 227, 0 },
127977  { 210, 1 },
127978  { 210, 0 },
127979  { 209, 3 },
127980  { 209, 1 },
127981  { 149, 12 },
127982  { 230, 1 },
127983  { 230, 0 },
127984  { 179, 0 },
127985  { 179, 3 },
127986  { 189, 5 },
127987  { 189, 3 },
127988  { 231, 0 },
127989  { 231, 2 },
127990  { 149, 4 },
127991  { 149, 1 },
127992  { 149, 2 },
127993  { 149, 3 },
127994  { 149, 5 },
127995  { 149, 6 },
127996  { 149, 5 },
127997  { 149, 6 },
127998  { 232, 1 },
127999  { 232, 1 },
128000  { 232, 1 },
128001  { 232, 1 },
128002  { 232, 1 },
128003  { 171, 2 },
128004  { 171, 1 },
128005  { 172, 2 },
128006  { 149, 5 },
128007  { 233, 11 },
128008  { 235, 1 },
128009  { 235, 1 },
128010  { 235, 2 },
128011  { 235, 0 },
128012  { 236, 1 },
128013  { 236, 1 },
128014  { 236, 3 },
128015  { 237, 0 },
128016  { 237, 3 },
128017  { 238, 0 },
128018  { 238, 2 },
128019  { 234, 3 },
128020  { 234, 2 },
128021  { 240, 1 },
128022  { 240, 3 },
128023  { 241, 0 },
128024  { 241, 3 },
128025  { 241, 2 },
128026  { 239, 7 },
128027  { 239, 5 },
128028  { 239, 5 },
128029  { 239, 1 },
128030  { 175, 4 },
128031  { 175, 6 },
128032  { 193, 1 },
128033  { 193, 1 },
128034  { 193, 1 },
128035  { 149, 4 },
128036  { 149, 6 },
128037  { 149, 3 },
128038  { 243, 0 },
128039  { 243, 2 },
128040  { 242, 1 },
128041  { 242, 0 },
128042  { 149, 1 },
128043  { 149, 3 },
128044  { 149, 1 },
128045  { 149, 3 },
128046  { 149, 6 },
128047  { 149, 6 },
128048  { 244, 1 },
128049  { 245, 0 },
128050  { 245, 1 },
128051  { 149, 1 },
128052  { 149, 4 },
128053  { 246, 8 },
128054  { 247, 1 },
128055  { 247, 3 },
128056  { 248, 0 },
128057  { 248, 2 },
128058  { 249, 1 },
128059  { 249, 3 },
128060  { 250, 1 },
128061  { 251, 0 },
128062  { 251, 4 },
128063  { 251, 2 },
128064  { 198, 0 },
128065  { 198, 2 },
128066  { 198, 3 },
128067  { 252, 6 },
128068  { 252, 8 },
128069};
128070
128071static void yy_accept(yyParser*);  /* Forward Declaration */
128072
128073/*
128074** Perform a reduce action and the shift that must immediately
128075** follow the reduce.
128076*/
128077static void yy_reduce(
128078  yyParser *yypParser,         /* The parser */
128079  int yyruleno                 /* Number of the rule by which to reduce */
128080){
128081  int yygoto;                     /* The next state */
128082  int yyact;                      /* The next action */
128083  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
128084  yyStackEntry *yymsp;            /* The top of the parser's stack */
128085  int yysize;                     /* Amount to pop the stack */
128086  sqlite3ParserARG_FETCH;
128087  yymsp = &yypParser->yystack[yypParser->yyidx];
128088#ifndef NDEBUG
128089  if( yyTraceFILE && yyruleno>=0
128090        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
128091    yysize = yyRuleInfo[yyruleno].nrhs;
128092    fprintf(yyTraceFILE, "%sReduce [%s] -> state %d.\n", yyTracePrompt,
128093      yyRuleName[yyruleno], yymsp[-yysize].stateno);
128094  }
128095#endif /* NDEBUG */
128096
128097  /* Silence complaints from purify about yygotominor being uninitialized
128098  ** in some cases when it is copied into the stack after the following
128099  ** switch.  yygotominor is uninitialized when a rule reduces that does
128100  ** not set the value of its left-hand side nonterminal.  Leaving the
128101  ** value of the nonterminal uninitialized is utterly harmless as long
128102  ** as the value is never used.  So really the only thing this code
128103  ** accomplishes is to quieten purify.
128104  **
128105  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
128106  ** without this code, their parser segfaults.  I'm not sure what there
128107  ** parser is doing to make this happen.  This is the second bug report
128108  ** from wireshark this week.  Clearly they are stressing Lemon in ways
128109  ** that it has not been previously stressed...  (SQLite ticket #2172)
128110  */
128111  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
128112  yygotominor = yyzerominor;
128113
128114
128115  switch( yyruleno ){
128116  /* Beginning here are the reduction cases.  A typical example
128117  ** follows:
128118  **   case 0:
128119  **  #line <lineno> <grammarfile>
128120  **     { ... }           // User supplied code
128121  **  #line <lineno> <thisfile>
128122  **     break;
128123  */
128124      case 5: /* explain ::= */
128125{ sqlite3BeginParse(pParse, 0); }
128126        break;
128127      case 6: /* explain ::= EXPLAIN */
128128{ sqlite3BeginParse(pParse, 1); }
128129        break;
128130      case 7: /* explain ::= EXPLAIN QUERY PLAN */
128131{ sqlite3BeginParse(pParse, 2); }
128132        break;
128133      case 8: /* cmdx ::= cmd */
128134{ sqlite3FinishCoding(pParse); }
128135        break;
128136      case 9: /* cmd ::= BEGIN transtype trans_opt */
128137{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
128138        break;
128139      case 13: /* transtype ::= */
128140{yygotominor.yy328 = TK_DEFERRED;}
128141        break;
128142      case 14: /* transtype ::= DEFERRED */
128143      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
128144      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
128145      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
128146      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
128147{yygotominor.yy328 = yymsp[0].major;}
128148        break;
128149      case 17: /* cmd ::= COMMIT trans_opt */
128150      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
128151{sqlite3CommitTransaction(pParse);}
128152        break;
128153      case 19: /* cmd ::= ROLLBACK trans_opt */
128154{sqlite3RollbackTransaction(pParse);}
128155        break;
128156      case 22: /* cmd ::= SAVEPOINT nm */
128157{
128158  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
128159}
128160        break;
128161      case 23: /* cmd ::= RELEASE savepoint_opt nm */
128162{
128163  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
128164}
128165        break;
128166      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
128167{
128168  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
128169}
128170        break;
128171      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
128172{
128173   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
128174}
128175        break;
128176      case 27: /* createkw ::= CREATE */
128177{
128178  pParse->db->lookaside.bEnabled = 0;
128179  yygotominor.yy0 = yymsp[0].minor.yy0;
128180}
128181        break;
128182      case 28: /* ifnotexists ::= */
128183      case 31: /* temp ::= */ yytestcase(yyruleno==31);
128184      case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
128185      case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
128186      case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
128187      case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
128188      case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
128189      case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
128190      case 219: /* between_op ::= BETWEEN */ yytestcase(yyruleno==219);
128191      case 222: /* in_op ::= IN */ yytestcase(yyruleno==222);
128192      case 247: /* collate ::= */ yytestcase(yyruleno==247);
128193{yygotominor.yy328 = 0;}
128194        break;
128195      case 29: /* ifnotexists ::= IF NOT EXISTS */
128196      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
128197      case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
128198      case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
128199      case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
128200      case 220: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==220);
128201      case 223: /* in_op ::= NOT IN */ yytestcase(yyruleno==223);
128202      case 248: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==248);
128203{yygotominor.yy328 = 1;}
128204        break;
128205      case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
128206{
128207  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
128208}
128209        break;
128210      case 33: /* create_table_args ::= AS select */
128211{
128212  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
128213  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
128214}
128215        break;
128216      case 34: /* table_options ::= */
128217{yygotominor.yy186 = 0;}
128218        break;
128219      case 35: /* table_options ::= WITHOUT nm */
128220{
128221  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
128222    yygotominor.yy186 = TF_WithoutRowid | TF_NoVisibleRowid;
128223  }else{
128224    yygotominor.yy186 = 0;
128225    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
128226  }
128227}
128228        break;
128229      case 38: /* column ::= columnid type carglist */
128230{
128231  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
128232  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
128233}
128234        break;
128235      case 39: /* columnid ::= nm */
128236{
128237  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
128238  yygotominor.yy0 = yymsp[0].minor.yy0;
128239  pParse->constraintName.n = 0;
128240}
128241        break;
128242      case 40: /* nm ::= ID|INDEXED */
128243      case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
128244      case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
128245      case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
128246      case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
128247      case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
128248      case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
128249      case 142: /* dbnm ::= DOT nm */ yytestcase(yyruleno==142);
128250      case 151: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==151);
128251      case 257: /* nmnum ::= plus_num */ yytestcase(yyruleno==257);
128252      case 258: /* nmnum ::= nm */ yytestcase(yyruleno==258);
128253      case 259: /* nmnum ::= ON */ yytestcase(yyruleno==259);
128254      case 260: /* nmnum ::= DELETE */ yytestcase(yyruleno==260);
128255      case 261: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==261);
128256      case 262: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==262);
128257      case 263: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==263);
128258      case 264: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==264);
128259      case 280: /* trnm ::= nm */ yytestcase(yyruleno==280);
128260{yygotominor.yy0 = yymsp[0].minor.yy0;}
128261        break;
128262      case 44: /* type ::= typetoken */
128263{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
128264        break;
128265      case 46: /* typetoken ::= typename LP signed RP */
128266{
128267  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
128268  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
128269}
128270        break;
128271      case 47: /* typetoken ::= typename LP signed COMMA signed RP */
128272{
128273  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
128274  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
128275}
128276        break;
128277      case 49: /* typename ::= typename ID|STRING */
128278{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
128279        break;
128280      case 54: /* ccons ::= CONSTRAINT nm */
128281      case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
128282{pParse->constraintName = yymsp[0].minor.yy0;}
128283        break;
128284      case 55: /* ccons ::= DEFAULT term */
128285      case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
128286{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
128287        break;
128288      case 56: /* ccons ::= DEFAULT LP expr RP */
128289{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
128290        break;
128291      case 58: /* ccons ::= DEFAULT MINUS term */
128292{
128293  ExprSpan v;
128294  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
128295  v.zStart = yymsp[-1].minor.yy0.z;
128296  v.zEnd = yymsp[0].minor.yy346.zEnd;
128297  sqlite3AddDefaultValue(pParse,&v);
128298}
128299        break;
128300      case 59: /* ccons ::= DEFAULT ID|INDEXED */
128301{
128302  ExprSpan v;
128303  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
128304  sqlite3AddDefaultValue(pParse,&v);
128305}
128306        break;
128307      case 61: /* ccons ::= NOT NULL onconf */
128308{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
128309        break;
128310      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
128311{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
128312        break;
128313      case 63: /* ccons ::= UNIQUE onconf */
128314{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
128315        break;
128316      case 64: /* ccons ::= CHECK LP expr RP */
128317{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
128318        break;
128319      case 65: /* ccons ::= REFERENCES nm eidlist_opt refargs */
128320{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
128321        break;
128322      case 66: /* ccons ::= defer_subclause */
128323{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
128324        break;
128325      case 67: /* ccons ::= COLLATE ID|STRING */
128326{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
128327        break;
128328      case 70: /* refargs ::= */
128329{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
128330        break;
128331      case 71: /* refargs ::= refargs refarg */
128332{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
128333        break;
128334      case 72: /* refarg ::= MATCH nm */
128335      case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
128336{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
128337        break;
128338      case 74: /* refarg ::= ON DELETE refact */
128339{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
128340        break;
128341      case 75: /* refarg ::= ON UPDATE refact */
128342{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
128343        break;
128344      case 76: /* refact ::= SET NULL */
128345{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
128346        break;
128347      case 77: /* refact ::= SET DEFAULT */
128348{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
128349        break;
128350      case 78: /* refact ::= CASCADE */
128351{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
128352        break;
128353      case 79: /* refact ::= RESTRICT */
128354{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
128355        break;
128356      case 80: /* refact ::= NO ACTION */
128357{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
128358        break;
128359      case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
128360      case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
128361      case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
128362      case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
128363{yygotominor.yy328 = yymsp[0].minor.yy328;}
128364        break;
128365      case 86: /* conslist_opt ::= */
128366{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
128367        break;
128368      case 87: /* conslist_opt ::= COMMA conslist */
128369{yygotominor.yy0 = yymsp[-1].minor.yy0;}
128370        break;
128371      case 90: /* tconscomma ::= COMMA */
128372{pParse->constraintName.n = 0;}
128373        break;
128374      case 93: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
128375{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
128376        break;
128377      case 94: /* tcons ::= UNIQUE LP sortlist RP onconf */
128378{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
128379        break;
128380      case 95: /* tcons ::= CHECK LP expr RP onconf */
128381{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
128382        break;
128383      case 96: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
128384{
128385    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
128386    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
128387}
128388        break;
128389      case 99: /* onconf ::= */
128390{yygotominor.yy328 = OE_Default;}
128391        break;
128392      case 101: /* orconf ::= */
128393{yygotominor.yy186 = OE_Default;}
128394        break;
128395      case 102: /* orconf ::= OR resolvetype */
128396{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
128397        break;
128398      case 104: /* resolvetype ::= IGNORE */
128399{yygotominor.yy328 = OE_Ignore;}
128400        break;
128401      case 105: /* resolvetype ::= REPLACE */
128402{yygotominor.yy328 = OE_Replace;}
128403        break;
128404      case 106: /* cmd ::= DROP TABLE ifexists fullname */
128405{
128406  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
128407}
128408        break;
128409      case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
128410{
128411  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[0].minor.yy3, yymsp[-7].minor.yy328, yymsp[-5].minor.yy328);
128412}
128413        break;
128414      case 110: /* cmd ::= DROP VIEW ifexists fullname */
128415{
128416  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
128417}
128418        break;
128419      case 111: /* cmd ::= select */
128420{
128421  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
128422  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
128423  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
128424}
128425        break;
128426      case 112: /* select ::= with selectnowith */
128427{
128428  Select *p = yymsp[0].minor.yy3;
128429  if( p ){
128430    p->pWith = yymsp[-1].minor.yy59;
128431    parserDoubleLinkSelect(pParse, p);
128432  }else{
128433    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
128434  }
128435  yygotominor.yy3 = p;
128436}
128437        break;
128438      case 113: /* selectnowith ::= oneselect */
128439      case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
128440{yygotominor.yy3 = yymsp[0].minor.yy3;}
128441        break;
128442      case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
128443{
128444  Select *pRhs = yymsp[0].minor.yy3;
128445  Select *pLhs = yymsp[-2].minor.yy3;
128446  if( pRhs && pRhs->pPrior ){
128447    SrcList *pFrom;
128448    Token x;
128449    x.n = 0;
128450    parserDoubleLinkSelect(pParse, pRhs);
128451    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
128452    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
128453  }
128454  if( pRhs ){
128455    pRhs->op = (u8)yymsp[-1].minor.yy328;
128456    pRhs->pPrior = pLhs;
128457    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
128458    pRhs->selFlags &= ~SF_MultiValue;
128459    if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
128460  }else{
128461    sqlite3SelectDelete(pParse->db, pLhs);
128462  }
128463  yygotominor.yy3 = pRhs;
128464}
128465        break;
128466      case 116: /* multiselect_op ::= UNION ALL */
128467{yygotominor.yy328 = TK_ALL;}
128468        break;
128469      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
128470{
128471  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
128472#if SELECTTRACE_ENABLED
128473  /* Populate the Select.zSelName[] string that is used to help with
128474  ** query planner debugging, to differentiate between multiple Select
128475  ** objects in a complex query.
128476  **
128477  ** If the SELECT keyword is immediately followed by a C-style comment
128478  ** then extract the first few alphanumeric characters from within that
128479  ** comment to be the zSelName value.  Otherwise, the label is #N where
128480  ** is an integer that is incremented with each SELECT statement seen.
128481  */
128482  if( yygotominor.yy3!=0 ){
128483    const char *z = yymsp[-8].minor.yy0.z+6;
128484    int i;
128485    sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
128486                     ++pParse->nSelect);
128487    while( z[0]==' ' ) z++;
128488    if( z[0]=='/' && z[1]=='*' ){
128489      z += 2;
128490      while( z[0]==' ' ) z++;
128491      for(i=0; sqlite3Isalnum(z[i]); i++){}
128492      sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
128493    }
128494  }
128495#endif /* SELECTRACE_ENABLED */
128496}
128497        break;
128498      case 120: /* values ::= VALUES LP nexprlist RP */
128499{
128500  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
128501}
128502        break;
128503      case 121: /* values ::= values COMMA LP exprlist RP */
128504{
128505  Select *pRight, *pLeft = yymsp[-4].minor.yy3;
128506  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
128507  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
128508  if( pRight ){
128509    pRight->op = TK_ALL;
128510    pLeft = yymsp[-4].minor.yy3;
128511    pRight->pPrior = pLeft;
128512    yygotominor.yy3 = pRight;
128513  }else{
128514    yygotominor.yy3 = pLeft;
128515  }
128516}
128517        break;
128518      case 122: /* distinct ::= DISTINCT */
128519{yygotominor.yy381 = SF_Distinct;}
128520        break;
128521      case 123: /* distinct ::= ALL */
128522{yygotominor.yy381 = SF_All;}
128523        break;
128524      case 124: /* distinct ::= */
128525{yygotominor.yy381 = 0;}
128526        break;
128527      case 125: /* sclp ::= selcollist COMMA */
128528      case 244: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==244);
128529{yygotominor.yy14 = yymsp[-1].minor.yy14;}
128530        break;
128531      case 126: /* sclp ::= */
128532      case 155: /* orderby_opt ::= */ yytestcase(yyruleno==155);
128533      case 162: /* groupby_opt ::= */ yytestcase(yyruleno==162);
128534      case 237: /* exprlist ::= */ yytestcase(yyruleno==237);
128535      case 243: /* eidlist_opt ::= */ yytestcase(yyruleno==243);
128536{yygotominor.yy14 = 0;}
128537        break;
128538      case 127: /* selcollist ::= sclp expr as */
128539{
128540   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
128541   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
128542   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
128543}
128544        break;
128545      case 128: /* selcollist ::= sclp STAR */
128546{
128547  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
128548  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
128549}
128550        break;
128551      case 129: /* selcollist ::= sclp nm DOT STAR */
128552{
128553  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
128554  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128555  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
128556  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
128557}
128558        break;
128559      case 132: /* as ::= */
128560{yygotominor.yy0.n = 0;}
128561        break;
128562      case 133: /* from ::= */
128563{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
128564        break;
128565      case 134: /* from ::= FROM seltablist */
128566{
128567  yygotominor.yy65 = yymsp[0].minor.yy65;
128568  sqlite3SrcListShiftJoinType(yygotominor.yy65);
128569}
128570        break;
128571      case 135: /* stl_prefix ::= seltablist joinop */
128572{
128573   yygotominor.yy65 = yymsp[-1].minor.yy65;
128574   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy328;
128575}
128576        break;
128577      case 136: /* stl_prefix ::= */
128578{yygotominor.yy65 = 0;}
128579        break;
128580      case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
128581{
128582  yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128583  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
128584}
128585        break;
128586      case 138: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
128587{
128588  yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy65,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128589  sqlite3SrcListFuncArgs(pParse, yygotominor.yy65, yymsp[-4].minor.yy14);
128590}
128591        break;
128592      case 139: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
128593{
128594    yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128595  }
128596        break;
128597      case 140: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
128598{
128599    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
128600      yygotominor.yy65 = yymsp[-4].minor.yy65;
128601    }else if( yymsp[-4].minor.yy65->nSrc==1 ){
128602      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128603      if( yygotominor.yy65 ){
128604        struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
128605        struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
128606        pNew->zName = pOld->zName;
128607        pNew->zDatabase = pOld->zDatabase;
128608        pNew->pSelect = pOld->pSelect;
128609        pOld->zName = pOld->zDatabase = 0;
128610        pOld->pSelect = 0;
128611      }
128612      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
128613    }else{
128614      Select *pSubquery;
128615      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
128616      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
128617      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128618    }
128619  }
128620        break;
128621      case 141: /* dbnm ::= */
128622      case 150: /* indexed_opt ::= */ yytestcase(yyruleno==150);
128623{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
128624        break;
128625      case 143: /* fullname ::= nm dbnm */
128626{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
128627        break;
128628      case 144: /* joinop ::= COMMA|JOIN */
128629{ yygotominor.yy328 = JT_INNER; }
128630        break;
128631      case 145: /* joinop ::= JOIN_KW JOIN */
128632{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
128633        break;
128634      case 146: /* joinop ::= JOIN_KW nm JOIN */
128635{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
128636        break;
128637      case 147: /* joinop ::= JOIN_KW nm nm JOIN */
128638{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
128639        break;
128640      case 148: /* on_opt ::= ON expr */
128641      case 165: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==165);
128642      case 172: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==172);
128643      case 232: /* case_else ::= ELSE expr */ yytestcase(yyruleno==232);
128644      case 234: /* case_operand ::= expr */ yytestcase(yyruleno==234);
128645{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
128646        break;
128647      case 149: /* on_opt ::= */
128648      case 164: /* having_opt ::= */ yytestcase(yyruleno==164);
128649      case 171: /* where_opt ::= */ yytestcase(yyruleno==171);
128650      case 233: /* case_else ::= */ yytestcase(yyruleno==233);
128651      case 235: /* case_operand ::= */ yytestcase(yyruleno==235);
128652{yygotominor.yy132 = 0;}
128653        break;
128654      case 152: /* indexed_opt ::= NOT INDEXED */
128655{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
128656        break;
128657      case 153: /* using_opt ::= USING LP idlist RP */
128658      case 181: /* idlist_opt ::= LP idlist RP */ yytestcase(yyruleno==181);
128659{yygotominor.yy408 = yymsp[-1].minor.yy408;}
128660        break;
128661      case 154: /* using_opt ::= */
128662      case 180: /* idlist_opt ::= */ yytestcase(yyruleno==180);
128663{yygotominor.yy408 = 0;}
128664        break;
128665      case 156: /* orderby_opt ::= ORDER BY sortlist */
128666      case 163: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==163);
128667      case 236: /* exprlist ::= nexprlist */ yytestcase(yyruleno==236);
128668{yygotominor.yy14 = yymsp[0].minor.yy14;}
128669        break;
128670      case 157: /* sortlist ::= sortlist COMMA expr sortorder */
128671{
128672  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
128673  sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
128674}
128675        break;
128676      case 158: /* sortlist ::= expr sortorder */
128677{
128678  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
128679  sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
128680}
128681        break;
128682      case 159: /* sortorder ::= ASC */
128683{yygotominor.yy328 = SQLITE_SO_ASC;}
128684        break;
128685      case 160: /* sortorder ::= DESC */
128686{yygotominor.yy328 = SQLITE_SO_DESC;}
128687        break;
128688      case 161: /* sortorder ::= */
128689{yygotominor.yy328 = SQLITE_SO_UNDEFINED;}
128690        break;
128691      case 166: /* limit_opt ::= */
128692{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
128693        break;
128694      case 167: /* limit_opt ::= LIMIT expr */
128695{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
128696        break;
128697      case 168: /* limit_opt ::= LIMIT expr OFFSET expr */
128698{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
128699        break;
128700      case 169: /* limit_opt ::= LIMIT expr COMMA expr */
128701{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
128702        break;
128703      case 170: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
128704{
128705  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
128706  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
128707  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
128708}
128709        break;
128710      case 173: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
128711{
128712  sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
128713  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
128714  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
128715  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
128716}
128717        break;
128718      case 174: /* setlist ::= setlist COMMA nm EQ expr */
128719{
128720  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
128721  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
128722}
128723        break;
128724      case 175: /* setlist ::= nm EQ expr */
128725{
128726  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
128727  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
128728}
128729        break;
128730      case 176: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
128731{
128732  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
128733  sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
128734}
128735        break;
128736      case 177: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
128737{
128738  sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
128739  sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
128740}
128741        break;
128742      case 178: /* insert_cmd ::= INSERT orconf */
128743{yygotominor.yy186 = yymsp[0].minor.yy186;}
128744        break;
128745      case 179: /* insert_cmd ::= REPLACE */
128746{yygotominor.yy186 = OE_Replace;}
128747        break;
128748      case 182: /* idlist ::= idlist COMMA nm */
128749{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
128750        break;
128751      case 183: /* idlist ::= nm */
128752{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
128753        break;
128754      case 184: /* expr ::= term */
128755{yygotominor.yy346 = yymsp[0].minor.yy346;}
128756        break;
128757      case 185: /* expr ::= LP expr RP */
128758{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
128759        break;
128760      case 186: /* term ::= NULL */
128761      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
128762      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
128763{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
128764        break;
128765      case 187: /* expr ::= ID|INDEXED */
128766      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
128767{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
128768        break;
128769      case 189: /* expr ::= nm DOT nm */
128770{
128771  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128772  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
128773  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
128774  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
128775}
128776        break;
128777      case 190: /* expr ::= nm DOT nm DOT nm */
128778{
128779  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
128780  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128781  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
128782  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
128783  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
128784  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
128785}
128786        break;
128787      case 193: /* expr ::= VARIABLE */
128788{
128789  if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
128790    /* When doing a nested parse, one can include terms in an expression
128791    ** that look like this:   #1 #2 ...  These terms refer to registers
128792    ** in the virtual machine.  #N is the N-th register. */
128793    if( pParse->nested==0 ){
128794      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
128795      yygotominor.yy346.pExpr = 0;
128796    }else{
128797      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
128798      if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
128799    }
128800  }else{
128801    spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
128802    sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
128803  }
128804  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
128805}
128806        break;
128807      case 194: /* expr ::= expr COLLATE ID|STRING */
128808{
128809  yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
128810  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
128811  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
128812}
128813        break;
128814      case 195: /* expr ::= CAST LP expr AS typetoken RP */
128815{
128816  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
128817  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
128818}
128819        break;
128820      case 196: /* expr ::= ID|INDEXED LP distinct exprlist RP */
128821{
128822  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
128823    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
128824  }
128825  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
128826  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
128827  if( yymsp[-2].minor.yy381==SF_Distinct && yygotominor.yy346.pExpr ){
128828    yygotominor.yy346.pExpr->flags |= EP_Distinct;
128829  }
128830}
128831        break;
128832      case 197: /* expr ::= ID|INDEXED LP STAR RP */
128833{
128834  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
128835  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
128836}
128837        break;
128838      case 198: /* term ::= CTIME_KW */
128839{
128840  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
128841  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
128842}
128843        break;
128844      case 199: /* expr ::= expr AND expr */
128845      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
128846      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
128847      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
128848      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
128849      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
128850      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
128851      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
128852{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
128853        break;
128854      case 207: /* likeop ::= LIKE_KW|MATCH */
128855{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
128856        break;
128857      case 208: /* likeop ::= NOT LIKE_KW|MATCH */
128858{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
128859        break;
128860      case 209: /* expr ::= expr likeop expr */
128861{
128862  ExprList *pList;
128863  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
128864  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
128865  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
128866  if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128867  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
128868  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128869  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
128870}
128871        break;
128872      case 210: /* expr ::= expr likeop expr ESCAPE expr */
128873{
128874  ExprList *pList;
128875  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
128876  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
128877  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
128878  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
128879  if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128880  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128881  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128882  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
128883}
128884        break;
128885      case 211: /* expr ::= expr ISNULL|NOTNULL */
128886{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
128887        break;
128888      case 212: /* expr ::= expr NOT NULL */
128889{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
128890        break;
128891      case 213: /* expr ::= expr IS expr */
128892{
128893  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
128894  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
128895}
128896        break;
128897      case 214: /* expr ::= expr IS NOT expr */
128898{
128899  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
128900  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
128901}
128902        break;
128903      case 215: /* expr ::= NOT expr */
128904      case 216: /* expr ::= BITNOT expr */ yytestcase(yyruleno==216);
128905{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128906        break;
128907      case 217: /* expr ::= MINUS expr */
128908{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128909        break;
128910      case 218: /* expr ::= PLUS expr */
128911{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128912        break;
128913      case 221: /* expr ::= expr between_op expr AND expr */
128914{
128915  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
128916  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
128917  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
128918  if( yygotominor.yy346.pExpr ){
128919    yygotominor.yy346.pExpr->x.pList = pList;
128920  }else{
128921    sqlite3ExprListDelete(pParse->db, pList);
128922  }
128923  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128924  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128925  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128926}
128927        break;
128928      case 224: /* expr ::= expr in_op LP exprlist RP */
128929{
128930    if( yymsp[-1].minor.yy14==0 ){
128931      /* Expressions of the form
128932      **
128933      **      expr1 IN ()
128934      **      expr1 NOT IN ()
128935      **
128936      ** simplify to constants 0 (false) and 1 (true), respectively,
128937      ** regardless of the value of expr1.
128938      */
128939      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
128940      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
128941    }else if( yymsp[-1].minor.yy14->nExpr==1 ){
128942      /* Expressions of the form:
128943      **
128944      **      expr1 IN (?1)
128945      **      expr1 NOT IN (?2)
128946      **
128947      ** with exactly one value on the RHS can be simplified to something
128948      ** like this:
128949      **
128950      **      expr1 == ?1
128951      **      expr1 <> ?2
128952      **
128953      ** But, the RHS of the == or <> is marked with the EP_Generic flag
128954      ** so that it may not contribute to the computation of comparison
128955      ** affinity or the collating sequence to use for comparison.  Otherwise,
128956      ** the semantics would be subtly different from IN or NOT IN.
128957      */
128958      Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
128959      yymsp[-1].minor.yy14->a[0].pExpr = 0;
128960      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
128961      /* pRHS cannot be NULL because a malloc error would have been detected
128962      ** before now and control would have never reached this point */
128963      if( ALWAYS(pRHS) ){
128964        pRHS->flags &= ~EP_Collate;
128965        pRHS->flags |= EP_Generic;
128966      }
128967      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
128968    }else{
128969      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
128970      if( yygotominor.yy346.pExpr ){
128971        yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
128972        sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
128973      }else{
128974        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
128975      }
128976      if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128977    }
128978    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128979    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
128980  }
128981        break;
128982      case 225: /* expr ::= LP select RP */
128983{
128984    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
128985    if( yygotominor.yy346.pExpr ){
128986      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
128987      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
128988      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
128989    }else{
128990      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
128991    }
128992    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
128993    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
128994  }
128995        break;
128996      case 226: /* expr ::= expr in_op LP select RP */
128997{
128998    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
128999    if( yygotominor.yy346.pExpr ){
129000      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
129001      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
129002      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129003    }else{
129004      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
129005    }
129006    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
129007    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
129008    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129009  }
129010        break;
129011      case 227: /* expr ::= expr in_op nm dbnm */
129012{
129013    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
129014    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
129015    if( yygotominor.yy346.pExpr ){
129016      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
129017      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
129018      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129019    }else{
129020      sqlite3SrcListDelete(pParse->db, pSrc);
129021    }
129022    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
129023    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
129024    yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
129025  }
129026        break;
129027      case 228: /* expr ::= EXISTS LP select RP */
129028{
129029    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
129030    if( p ){
129031      p->x.pSelect = yymsp[-1].minor.yy3;
129032      ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
129033      sqlite3ExprSetHeightAndFlags(pParse, p);
129034    }else{
129035      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
129036    }
129037    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
129038    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129039  }
129040        break;
129041      case 229: /* expr ::= CASE case_operand case_exprlist case_else END */
129042{
129043  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
129044  if( yygotominor.yy346.pExpr ){
129045    yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
129046    sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129047  }else{
129048    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
129049    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
129050  }
129051  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
129052  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129053}
129054        break;
129055      case 230: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
129056{
129057  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
129058  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
129059}
129060        break;
129061      case 231: /* case_exprlist ::= WHEN expr THEN expr */
129062{
129063  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
129064  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
129065}
129066        break;
129067      case 238: /* nexprlist ::= nexprlist COMMA expr */
129068{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
129069        break;
129070      case 239: /* nexprlist ::= expr */
129071{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
129072        break;
129073      case 240: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
129074{
129075  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
129076                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
129077                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
129078}
129079        break;
129080      case 241: /* uniqueflag ::= UNIQUE */
129081      case 292: /* raisetype ::= ABORT */ yytestcase(yyruleno==292);
129082{yygotominor.yy328 = OE_Abort;}
129083        break;
129084      case 242: /* uniqueflag ::= */
129085{yygotominor.yy328 = OE_None;}
129086        break;
129087      case 245: /* eidlist ::= eidlist COMMA nm collate sortorder */
129088{
129089  yygotominor.yy14 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy14, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
129090}
129091        break;
129092      case 246: /* eidlist ::= nm collate sortorder */
129093{
129094  yygotominor.yy14 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
129095}
129096        break;
129097      case 249: /* cmd ::= DROP INDEX ifexists fullname */
129098{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
129099        break;
129100      case 250: /* cmd ::= VACUUM */
129101      case 251: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==251);
129102{sqlite3Vacuum(pParse);}
129103        break;
129104      case 252: /* cmd ::= PRAGMA nm dbnm */
129105{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
129106        break;
129107      case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
129108{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
129109        break;
129110      case 254: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
129111{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
129112        break;
129113      case 255: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
129114{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
129115        break;
129116      case 256: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
129117{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
129118        break;
129119      case 265: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
129120{
129121  Token all;
129122  all.z = yymsp[-3].minor.yy0.z;
129123  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
129124  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
129125}
129126        break;
129127      case 266: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
129128{
129129  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
129130  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
129131}
129132        break;
129133      case 267: /* trigger_time ::= BEFORE */
129134      case 270: /* trigger_time ::= */ yytestcase(yyruleno==270);
129135{ yygotominor.yy328 = TK_BEFORE; }
129136        break;
129137      case 268: /* trigger_time ::= AFTER */
129138{ yygotominor.yy328 = TK_AFTER;  }
129139        break;
129140      case 269: /* trigger_time ::= INSTEAD OF */
129141{ yygotominor.yy328 = TK_INSTEAD;}
129142        break;
129143      case 271: /* trigger_event ::= DELETE|INSERT */
129144      case 272: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==272);
129145{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
129146        break;
129147      case 273: /* trigger_event ::= UPDATE OF idlist */
129148{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
129149        break;
129150      case 276: /* when_clause ::= */
129151      case 297: /* key_opt ::= */ yytestcase(yyruleno==297);
129152{ yygotominor.yy132 = 0; }
129153        break;
129154      case 277: /* when_clause ::= WHEN expr */
129155      case 298: /* key_opt ::= KEY expr */ yytestcase(yyruleno==298);
129156{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
129157        break;
129158      case 278: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
129159{
129160  assert( yymsp[-2].minor.yy473!=0 );
129161  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
129162  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
129163  yygotominor.yy473 = yymsp[-2].minor.yy473;
129164}
129165        break;
129166      case 279: /* trigger_cmd_list ::= trigger_cmd SEMI */
129167{
129168  assert( yymsp[-1].minor.yy473!=0 );
129169  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
129170  yygotominor.yy473 = yymsp[-1].minor.yy473;
129171}
129172        break;
129173      case 281: /* trnm ::= nm DOT nm */
129174{
129175  yygotominor.yy0 = yymsp[0].minor.yy0;
129176  sqlite3ErrorMsg(pParse,
129177        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
129178        "statements within triggers");
129179}
129180        break;
129181      case 283: /* tridxby ::= INDEXED BY nm */
129182{
129183  sqlite3ErrorMsg(pParse,
129184        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
129185        "within triggers");
129186}
129187        break;
129188      case 284: /* tridxby ::= NOT INDEXED */
129189{
129190  sqlite3ErrorMsg(pParse,
129191        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
129192        "within triggers");
129193}
129194        break;
129195      case 285: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
129196{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
129197        break;
129198      case 286: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
129199{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
129200        break;
129201      case 287: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
129202{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
129203        break;
129204      case 288: /* trigger_cmd ::= select */
129205{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
129206        break;
129207      case 289: /* expr ::= RAISE LP IGNORE RP */
129208{
129209  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
129210  if( yygotominor.yy346.pExpr ){
129211    yygotominor.yy346.pExpr->affinity = OE_Ignore;
129212  }
129213  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
129214  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129215}
129216        break;
129217      case 290: /* expr ::= RAISE LP raisetype COMMA nm RP */
129218{
129219  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
129220  if( yygotominor.yy346.pExpr ) {
129221    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
129222  }
129223  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
129224  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129225}
129226        break;
129227      case 291: /* raisetype ::= ROLLBACK */
129228{yygotominor.yy328 = OE_Rollback;}
129229        break;
129230      case 293: /* raisetype ::= FAIL */
129231{yygotominor.yy328 = OE_Fail;}
129232        break;
129233      case 294: /* cmd ::= DROP TRIGGER ifexists fullname */
129234{
129235  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
129236}
129237        break;
129238      case 295: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
129239{
129240  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
129241}
129242        break;
129243      case 296: /* cmd ::= DETACH database_kw_opt expr */
129244{
129245  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
129246}
129247        break;
129248      case 301: /* cmd ::= REINDEX */
129249{sqlite3Reindex(pParse, 0, 0);}
129250        break;
129251      case 302: /* cmd ::= REINDEX nm dbnm */
129252{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
129253        break;
129254      case 303: /* cmd ::= ANALYZE */
129255{sqlite3Analyze(pParse, 0, 0);}
129256        break;
129257      case 304: /* cmd ::= ANALYZE nm dbnm */
129258{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
129259        break;
129260      case 305: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
129261{
129262  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
129263}
129264        break;
129265      case 306: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
129266{
129267  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
129268}
129269        break;
129270      case 307: /* add_column_fullname ::= fullname */
129271{
129272  pParse->db->lookaside.bEnabled = 0;
129273  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
129274}
129275        break;
129276      case 310: /* cmd ::= create_vtab */
129277{sqlite3VtabFinishParse(pParse,0);}
129278        break;
129279      case 311: /* cmd ::= create_vtab LP vtabarglist RP */
129280{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
129281        break;
129282      case 312: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
129283{
129284    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
129285}
129286        break;
129287      case 315: /* vtabarg ::= */
129288{sqlite3VtabArgInit(pParse);}
129289        break;
129290      case 317: /* vtabargtoken ::= ANY */
129291      case 318: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==318);
129292      case 319: /* lp ::= LP */ yytestcase(yyruleno==319);
129293{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
129294        break;
129295      case 323: /* with ::= */
129296{yygotominor.yy59 = 0;}
129297        break;
129298      case 324: /* with ::= WITH wqlist */
129299      case 325: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==325);
129300{ yygotominor.yy59 = yymsp[0].minor.yy59; }
129301        break;
129302      case 326: /* wqlist ::= nm eidlist_opt AS LP select RP */
129303{
129304  yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
129305}
129306        break;
129307      case 327: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
129308{
129309  yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
129310}
129311        break;
129312      default:
129313      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
129314      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
129315      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
129316      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
129317      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
129318      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
129319      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
129320      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
129321      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
129322      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
129323      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
129324      /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
129325      /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
129326      /* (43) type ::= */ yytestcase(yyruleno==43);
129327      /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
129328      /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
129329      /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
129330      /* (53) carglist ::= */ yytestcase(yyruleno==53);
129331      /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
129332      /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
129333      /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
129334      /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
129335      /* (274) foreach_clause ::= */ yytestcase(yyruleno==274);
129336      /* (275) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==275);
129337      /* (282) tridxby ::= */ yytestcase(yyruleno==282);
129338      /* (299) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==299);
129339      /* (300) database_kw_opt ::= */ yytestcase(yyruleno==300);
129340      /* (308) kwcolumn_opt ::= */ yytestcase(yyruleno==308);
129341      /* (309) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==309);
129342      /* (313) vtabarglist ::= vtabarg */ yytestcase(yyruleno==313);
129343      /* (314) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==314);
129344      /* (316) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==316);
129345      /* (320) anylist ::= */ yytestcase(yyruleno==320);
129346      /* (321) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==321);
129347      /* (322) anylist ::= anylist ANY */ yytestcase(yyruleno==322);
129348        break;
129349  };
129350  assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
129351  yygoto = yyRuleInfo[yyruleno].lhs;
129352  yysize = yyRuleInfo[yyruleno].nrhs;
129353  yypParser->yyidx -= yysize;
129354  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
129355  if( yyact <= YY_MAX_SHIFTREDUCE ){
129356    if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
129357    /* If the reduce action popped at least
129358    ** one element off the stack, then we can push the new element back
129359    ** onto the stack here, and skip the stack overflow test in yy_shift().
129360    ** That gives a significant speed improvement. */
129361    if( yysize ){
129362      yypParser->yyidx++;
129363      yymsp -= yysize-1;
129364      yymsp->stateno = (YYACTIONTYPE)yyact;
129365      yymsp->major = (YYCODETYPE)yygoto;
129366      yymsp->minor = yygotominor;
129367      yyTraceShift(yypParser, yyact);
129368    }else{
129369      yy_shift(yypParser,yyact,yygoto,&yygotominor);
129370    }
129371  }else{
129372    assert( yyact == YY_ACCEPT_ACTION );
129373    yy_accept(yypParser);
129374  }
129375}
129376
129377/*
129378** The following code executes when the parse fails
129379*/
129380#ifndef YYNOERRORRECOVERY
129381static void yy_parse_failed(
129382  yyParser *yypParser           /* The parser */
129383){
129384  sqlite3ParserARG_FETCH;
129385#ifndef NDEBUG
129386  if( yyTraceFILE ){
129387    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
129388  }
129389#endif
129390  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
129391  /* Here code is inserted which will be executed whenever the
129392  ** parser fails */
129393  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129394}
129395#endif /* YYNOERRORRECOVERY */
129396
129397/*
129398** The following code executes when a syntax error first occurs.
129399*/
129400static void yy_syntax_error(
129401  yyParser *yypParser,           /* The parser */
129402  int yymajor,                   /* The major type of the error token */
129403  YYMINORTYPE yyminor            /* The minor type of the error token */
129404){
129405  sqlite3ParserARG_FETCH;
129406#define TOKEN (yyminor.yy0)
129407
129408  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
129409  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
129410  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
129411  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129412}
129413
129414/*
129415** The following is executed when the parser accepts
129416*/
129417static void yy_accept(
129418  yyParser *yypParser           /* The parser */
129419){
129420  sqlite3ParserARG_FETCH;
129421#ifndef NDEBUG
129422  if( yyTraceFILE ){
129423    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
129424  }
129425#endif
129426  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
129427  /* Here code is inserted which will be executed whenever the
129428  ** parser accepts */
129429  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129430}
129431
129432/* The main parser program.
129433** The first argument is a pointer to a structure obtained from
129434** "sqlite3ParserAlloc" which describes the current state of the parser.
129435** The second argument is the major token number.  The third is
129436** the minor token.  The fourth optional argument is whatever the
129437** user wants (and specified in the grammar) and is available for
129438** use by the action routines.
129439**
129440** Inputs:
129441** <ul>
129442** <li> A pointer to the parser (an opaque structure.)
129443** <li> The major token number.
129444** <li> The minor token number.
129445** <li> An option argument of a grammar-specified type.
129446** </ul>
129447**
129448** Outputs:
129449** None.
129450*/
129451SQLITE_PRIVATE void sqlite3Parser(
129452  void *yyp,                   /* The parser */
129453  int yymajor,                 /* The major token code number */
129454  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
129455  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
129456){
129457  YYMINORTYPE yyminorunion;
129458  int yyact;            /* The parser action. */
129459#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
129460  int yyendofinput;     /* True if we are at the end of input */
129461#endif
129462#ifdef YYERRORSYMBOL
129463  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
129464#endif
129465  yyParser *yypParser;  /* The parser */
129466
129467  /* (re)initialize the parser, if necessary */
129468  yypParser = (yyParser*)yyp;
129469  if( yypParser->yyidx<0 ){
129470#if YYSTACKDEPTH<=0
129471    if( yypParser->yystksz <=0 ){
129472      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
129473      yyminorunion = yyzerominor;
129474      yyStackOverflow(yypParser, &yyminorunion);
129475      return;
129476    }
129477#endif
129478    yypParser->yyidx = 0;
129479    yypParser->yyerrcnt = -1;
129480    yypParser->yystack[0].stateno = 0;
129481    yypParser->yystack[0].major = 0;
129482  }
129483  yyminorunion.yy0 = yyminor;
129484#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
129485  yyendofinput = (yymajor==0);
129486#endif
129487  sqlite3ParserARG_STORE;
129488
129489#ifndef NDEBUG
129490  if( yyTraceFILE ){
129491    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
129492  }
129493#endif
129494
129495  do{
129496    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
129497    if( yyact <= YY_MAX_SHIFTREDUCE ){
129498      if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
129499      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
129500      yypParser->yyerrcnt--;
129501      yymajor = YYNOCODE;
129502    }else if( yyact <= YY_MAX_REDUCE ){
129503      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
129504    }else{
129505      assert( yyact == YY_ERROR_ACTION );
129506#ifdef YYERRORSYMBOL
129507      int yymx;
129508#endif
129509#ifndef NDEBUG
129510      if( yyTraceFILE ){
129511        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
129512      }
129513#endif
129514#ifdef YYERRORSYMBOL
129515      /* A syntax error has occurred.
129516      ** The response to an error depends upon whether or not the
129517      ** grammar defines an error token "ERROR".
129518      **
129519      ** This is what we do if the grammar does define ERROR:
129520      **
129521      **  * Call the %syntax_error function.
129522      **
129523      **  * Begin popping the stack until we enter a state where
129524      **    it is legal to shift the error symbol, then shift
129525      **    the error symbol.
129526      **
129527      **  * Set the error count to three.
129528      **
129529      **  * Begin accepting and shifting new tokens.  No new error
129530      **    processing will occur until three tokens have been
129531      **    shifted successfully.
129532      **
129533      */
129534      if( yypParser->yyerrcnt<0 ){
129535        yy_syntax_error(yypParser,yymajor,yyminorunion);
129536      }
129537      yymx = yypParser->yystack[yypParser->yyidx].major;
129538      if( yymx==YYERRORSYMBOL || yyerrorhit ){
129539#ifndef NDEBUG
129540        if( yyTraceFILE ){
129541          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
129542             yyTracePrompt,yyTokenName[yymajor]);
129543        }
129544#endif
129545        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
129546        yymajor = YYNOCODE;
129547      }else{
129548         while(
129549          yypParser->yyidx >= 0 &&
129550          yymx != YYERRORSYMBOL &&
129551          (yyact = yy_find_reduce_action(
129552                        yypParser->yystack[yypParser->yyidx].stateno,
129553                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
129554        ){
129555          yy_pop_parser_stack(yypParser);
129556        }
129557        if( yypParser->yyidx < 0 || yymajor==0 ){
129558          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129559          yy_parse_failed(yypParser);
129560          yymajor = YYNOCODE;
129561        }else if( yymx!=YYERRORSYMBOL ){
129562          YYMINORTYPE u2;
129563          u2.YYERRSYMDT = 0;
129564          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
129565        }
129566      }
129567      yypParser->yyerrcnt = 3;
129568      yyerrorhit = 1;
129569#elif defined(YYNOERRORRECOVERY)
129570      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
129571      ** do any kind of error recovery.  Instead, simply invoke the syntax
129572      ** error routine and continue going as if nothing had happened.
129573      **
129574      ** Applications can set this macro (for example inside %include) if
129575      ** they intend to abandon the parse upon the first syntax error seen.
129576      */
129577      yy_syntax_error(yypParser,yymajor,yyminorunion);
129578      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129579      yymajor = YYNOCODE;
129580
129581#else  /* YYERRORSYMBOL is not defined */
129582      /* This is what we do if the grammar does not define ERROR:
129583      **
129584      **  * Report an error message, and throw away the input token.
129585      **
129586      **  * If the input token is $, then fail the parse.
129587      **
129588      ** As before, subsequent error messages are suppressed until
129589      ** three input tokens have been successfully shifted.
129590      */
129591      if( yypParser->yyerrcnt<=0 ){
129592        yy_syntax_error(yypParser,yymajor,yyminorunion);
129593      }
129594      yypParser->yyerrcnt = 3;
129595      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129596      if( yyendofinput ){
129597        yy_parse_failed(yypParser);
129598      }
129599      yymajor = YYNOCODE;
129600#endif
129601    }
129602  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
129603#ifndef NDEBUG
129604  if( yyTraceFILE ){
129605    fprintf(yyTraceFILE,"%sReturn\n",yyTracePrompt);
129606  }
129607#endif
129608  return;
129609}
129610
129611/************** End of parse.c ***********************************************/
129612/************** Begin file tokenize.c ****************************************/
129613/*
129614** 2001 September 15
129615**
129616** The author disclaims copyright to this source code.  In place of
129617** a legal notice, here is a blessing:
129618**
129619**    May you do good and not evil.
129620**    May you find forgiveness for yourself and forgive others.
129621**    May you share freely, never taking more than you give.
129622**
129623*************************************************************************
129624** An tokenizer for SQL
129625**
129626** This file contains C code that splits an SQL input string up into
129627** individual tokens and sends those tokens one-by-one over to the
129628** parser for analysis.
129629*/
129630/* #include "sqliteInt.h" */
129631/* #include <stdlib.h> */
129632
129633/*
129634** The charMap() macro maps alphabetic characters into their
129635** lower-case ASCII equivalent.  On ASCII machines, this is just
129636** an upper-to-lower case map.  On EBCDIC machines we also need
129637** to adjust the encoding.  Only alphabetic characters and underscores
129638** need to be translated.
129639*/
129640#ifdef SQLITE_ASCII
129641# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
129642#endif
129643#ifdef SQLITE_EBCDIC
129644# define charMap(X) ebcdicToAscii[(unsigned char)X]
129645const unsigned char ebcdicToAscii[] = {
129646/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
129647   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
129648   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
129649   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
129650   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
129651   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
129652   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
129653   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
129654   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
129655   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
129656   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
129657   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
129658   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
129659   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
129660   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
129661   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
129662   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
129663};
129664#endif
129665
129666/*
129667** The sqlite3KeywordCode function looks up an identifier to determine if
129668** it is a keyword.  If it is a keyword, the token code of that keyword is
129669** returned.  If the input is not a keyword, TK_ID is returned.
129670**
129671** The implementation of this routine was generated by a program,
129672** mkkeywordhash.h, located in the tool subdirectory of the distribution.
129673** The output of the mkkeywordhash.c program is written into a file
129674** named keywordhash.h and then included into this source file by
129675** the #include below.
129676*/
129677/************** Include keywordhash.h in the middle of tokenize.c ************/
129678/************** Begin file keywordhash.h *************************************/
129679/***** This file contains automatically generated code ******
129680**
129681** The code in this file has been automatically generated by
129682**
129683**   sqlite/tool/mkkeywordhash.c
129684**
129685** The code in this file implements a function that determines whether
129686** or not a given identifier is really an SQL keyword.  The same thing
129687** might be implemented more directly using a hand-written hash table.
129688** But by using this automatically generated code, the size of the code
129689** is substantially reduced.  This is important for embedded applications
129690** on platforms with limited memory.
129691*/
129692/* Hash score: 182 */
129693static int keywordCode(const char *z, int n){
129694  /* zText[] encodes 834 bytes of keywords in 554 bytes */
129695  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
129696  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
129697  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
129698  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
129699  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
129700  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
129701  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
129702  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
129703  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
129704  /*   VACUUMVIEWINITIALLY                                                */
129705  static const char zText[553] = {
129706    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
129707    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
129708    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
129709    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
129710    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
129711    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
129712    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
129713    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
129714    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
129715    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
129716    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
129717    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
129718    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
129719    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
129720    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
129721    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
129722    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
129723    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
129724    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
129725    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
129726    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
129727    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
129728    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
129729    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
129730    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
129731    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
129732    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
129733    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
129734    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
129735    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
129736    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
129737  };
129738  static const unsigned char aHash[127] = {
129739      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
129740      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
129741     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
129742       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
129743       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
129744      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
129745     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
129746      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
129747      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
129748      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
129749  };
129750  static const unsigned char aNext[124] = {
129751       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
129752       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
129753       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
129754       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
129755       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
129756       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
129757       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
129758      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
129759       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
129760      73,  83,   0,  35,  68,   0,   0,
129761  };
129762  static const unsigned char aLen[124] = {
129763       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
129764       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
129765      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
129766       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
129767       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
129768       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
129769       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
129770      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
129771       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
129772       3,   5,   5,   6,   4,   9,   3,
129773  };
129774  static const unsigned short int aOffset[124] = {
129775       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
129776      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
129777      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
129778     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
129779     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
129780     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
129781     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
129782     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
129783     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
129784     521, 524, 529, 534, 540, 544, 549,
129785  };
129786  static const unsigned char aCode[124] = {
129787    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
129788    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
129789    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
129790    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
129791    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
129792    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
129793    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
129794    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
129795    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
129796    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
129797    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
129798    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
129799    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
129800    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
129801    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
129802    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
129803    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
129804    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
129805    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
129806    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
129807    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
129808    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
129809    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
129810    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
129811    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
129812  };
129813  int h, i;
129814  if( n<2 ) return TK_ID;
129815  h = ((charMap(z[0])*4) ^
129816      (charMap(z[n-1])*3) ^
129817      n) % 127;
129818  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
129819    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
129820      testcase( i==0 ); /* REINDEX */
129821      testcase( i==1 ); /* INDEXED */
129822      testcase( i==2 ); /* INDEX */
129823      testcase( i==3 ); /* DESC */
129824      testcase( i==4 ); /* ESCAPE */
129825      testcase( i==5 ); /* EACH */
129826      testcase( i==6 ); /* CHECK */
129827      testcase( i==7 ); /* KEY */
129828      testcase( i==8 ); /* BEFORE */
129829      testcase( i==9 ); /* FOREIGN */
129830      testcase( i==10 ); /* FOR */
129831      testcase( i==11 ); /* IGNORE */
129832      testcase( i==12 ); /* REGEXP */
129833      testcase( i==13 ); /* EXPLAIN */
129834      testcase( i==14 ); /* INSTEAD */
129835      testcase( i==15 ); /* ADD */
129836      testcase( i==16 ); /* DATABASE */
129837      testcase( i==17 ); /* AS */
129838      testcase( i==18 ); /* SELECT */
129839      testcase( i==19 ); /* TABLE */
129840      testcase( i==20 ); /* LEFT */
129841      testcase( i==21 ); /* THEN */
129842      testcase( i==22 ); /* END */
129843      testcase( i==23 ); /* DEFERRABLE */
129844      testcase( i==24 ); /* ELSE */
129845      testcase( i==25 ); /* EXCEPT */
129846      testcase( i==26 ); /* TRANSACTION */
129847      testcase( i==27 ); /* ACTION */
129848      testcase( i==28 ); /* ON */
129849      testcase( i==29 ); /* NATURAL */
129850      testcase( i==30 ); /* ALTER */
129851      testcase( i==31 ); /* RAISE */
129852      testcase( i==32 ); /* EXCLUSIVE */
129853      testcase( i==33 ); /* EXISTS */
129854      testcase( i==34 ); /* SAVEPOINT */
129855      testcase( i==35 ); /* INTERSECT */
129856      testcase( i==36 ); /* TRIGGER */
129857      testcase( i==37 ); /* REFERENCES */
129858      testcase( i==38 ); /* CONSTRAINT */
129859      testcase( i==39 ); /* INTO */
129860      testcase( i==40 ); /* OFFSET */
129861      testcase( i==41 ); /* OF */
129862      testcase( i==42 ); /* SET */
129863      testcase( i==43 ); /* TEMPORARY */
129864      testcase( i==44 ); /* TEMP */
129865      testcase( i==45 ); /* OR */
129866      testcase( i==46 ); /* UNIQUE */
129867      testcase( i==47 ); /* QUERY */
129868      testcase( i==48 ); /* WITHOUT */
129869      testcase( i==49 ); /* WITH */
129870      testcase( i==50 ); /* OUTER */
129871      testcase( i==51 ); /* RELEASE */
129872      testcase( i==52 ); /* ATTACH */
129873      testcase( i==53 ); /* HAVING */
129874      testcase( i==54 ); /* GROUP */
129875      testcase( i==55 ); /* UPDATE */
129876      testcase( i==56 ); /* BEGIN */
129877      testcase( i==57 ); /* INNER */
129878      testcase( i==58 ); /* RECURSIVE */
129879      testcase( i==59 ); /* BETWEEN */
129880      testcase( i==60 ); /* NOTNULL */
129881      testcase( i==61 ); /* NOT */
129882      testcase( i==62 ); /* NO */
129883      testcase( i==63 ); /* NULL */
129884      testcase( i==64 ); /* LIKE */
129885      testcase( i==65 ); /* CASCADE */
129886      testcase( i==66 ); /* ASC */
129887      testcase( i==67 ); /* DELETE */
129888      testcase( i==68 ); /* CASE */
129889      testcase( i==69 ); /* COLLATE */
129890      testcase( i==70 ); /* CREATE */
129891      testcase( i==71 ); /* CURRENT_DATE */
129892      testcase( i==72 ); /* DETACH */
129893      testcase( i==73 ); /* IMMEDIATE */
129894      testcase( i==74 ); /* JOIN */
129895      testcase( i==75 ); /* INSERT */
129896      testcase( i==76 ); /* MATCH */
129897      testcase( i==77 ); /* PLAN */
129898      testcase( i==78 ); /* ANALYZE */
129899      testcase( i==79 ); /* PRAGMA */
129900      testcase( i==80 ); /* ABORT */
129901      testcase( i==81 ); /* VALUES */
129902      testcase( i==82 ); /* VIRTUAL */
129903      testcase( i==83 ); /* LIMIT */
129904      testcase( i==84 ); /* WHEN */
129905      testcase( i==85 ); /* WHERE */
129906      testcase( i==86 ); /* RENAME */
129907      testcase( i==87 ); /* AFTER */
129908      testcase( i==88 ); /* REPLACE */
129909      testcase( i==89 ); /* AND */
129910      testcase( i==90 ); /* DEFAULT */
129911      testcase( i==91 ); /* AUTOINCREMENT */
129912      testcase( i==92 ); /* TO */
129913      testcase( i==93 ); /* IN */
129914      testcase( i==94 ); /* CAST */
129915      testcase( i==95 ); /* COLUMN */
129916      testcase( i==96 ); /* COMMIT */
129917      testcase( i==97 ); /* CONFLICT */
129918      testcase( i==98 ); /* CROSS */
129919      testcase( i==99 ); /* CURRENT_TIMESTAMP */
129920      testcase( i==100 ); /* CURRENT_TIME */
129921      testcase( i==101 ); /* PRIMARY */
129922      testcase( i==102 ); /* DEFERRED */
129923      testcase( i==103 ); /* DISTINCT */
129924      testcase( i==104 ); /* IS */
129925      testcase( i==105 ); /* DROP */
129926      testcase( i==106 ); /* FAIL */
129927      testcase( i==107 ); /* FROM */
129928      testcase( i==108 ); /* FULL */
129929      testcase( i==109 ); /* GLOB */
129930      testcase( i==110 ); /* BY */
129931      testcase( i==111 ); /* IF */
129932      testcase( i==112 ); /* ISNULL */
129933      testcase( i==113 ); /* ORDER */
129934      testcase( i==114 ); /* RESTRICT */
129935      testcase( i==115 ); /* RIGHT */
129936      testcase( i==116 ); /* ROLLBACK */
129937      testcase( i==117 ); /* ROW */
129938      testcase( i==118 ); /* UNION */
129939      testcase( i==119 ); /* USING */
129940      testcase( i==120 ); /* VACUUM */
129941      testcase( i==121 ); /* VIEW */
129942      testcase( i==122 ); /* INITIALLY */
129943      testcase( i==123 ); /* ALL */
129944      return aCode[i];
129945    }
129946  }
129947  return TK_ID;
129948}
129949SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
129950  return keywordCode((char*)z, n);
129951}
129952#define SQLITE_N_KEYWORD 124
129953
129954/************** End of keywordhash.h *****************************************/
129955/************** Continuing where we left off in tokenize.c *******************/
129956
129957
129958/*
129959** If X is a character that can be used in an identifier then
129960** IdChar(X) will be true.  Otherwise it is false.
129961**
129962** For ASCII, any character with the high-order bit set is
129963** allowed in an identifier.  For 7-bit characters,
129964** sqlite3IsIdChar[X] must be 1.
129965**
129966** For EBCDIC, the rules are more complex but have the same
129967** end result.
129968**
129969** Ticket #1066.  the SQL standard does not allow '$' in the
129970** middle of identifiers.  But many SQL implementations do.
129971** SQLite will allow '$' in identifiers for compatibility.
129972** But the feature is undocumented.
129973*/
129974#ifdef SQLITE_ASCII
129975#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
129976#endif
129977#ifdef SQLITE_EBCDIC
129978SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
129979/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
129980    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
129981    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
129982    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
129983    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
129984    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
129985    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
129986    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
129987    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
129988    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
129989    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
129990    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
129991    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
129992};
129993#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
129994#endif
129995
129996/* Make the IdChar function accessible from ctime.c */
129997#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
129998SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
129999#endif
130000
130001
130002/*
130003** Return the length of the token that begins at z[0].
130004** Store the token type in *tokenType before returning.
130005*/
130006SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
130007  int i, c;
130008  switch( *z ){
130009    case ' ': case '\t': case '\n': case '\f': case '\r': {
130010      testcase( z[0]==' ' );
130011      testcase( z[0]=='\t' );
130012      testcase( z[0]=='\n' );
130013      testcase( z[0]=='\f' );
130014      testcase( z[0]=='\r' );
130015      for(i=1; sqlite3Isspace(z[i]); i++){}
130016      *tokenType = TK_SPACE;
130017      return i;
130018    }
130019    case '-': {
130020      if( z[1]=='-' ){
130021        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
130022        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
130023        return i;
130024      }
130025      *tokenType = TK_MINUS;
130026      return 1;
130027    }
130028    case '(': {
130029      *tokenType = TK_LP;
130030      return 1;
130031    }
130032    case ')': {
130033      *tokenType = TK_RP;
130034      return 1;
130035    }
130036    case ';': {
130037      *tokenType = TK_SEMI;
130038      return 1;
130039    }
130040    case '+': {
130041      *tokenType = TK_PLUS;
130042      return 1;
130043    }
130044    case '*': {
130045      *tokenType = TK_STAR;
130046      return 1;
130047    }
130048    case '/': {
130049      if( z[1]!='*' || z[2]==0 ){
130050        *tokenType = TK_SLASH;
130051        return 1;
130052      }
130053      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
130054      if( c ) i++;
130055      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
130056      return i;
130057    }
130058    case '%': {
130059      *tokenType = TK_REM;
130060      return 1;
130061    }
130062    case '=': {
130063      *tokenType = TK_EQ;
130064      return 1 + (z[1]=='=');
130065    }
130066    case '<': {
130067      if( (c=z[1])=='=' ){
130068        *tokenType = TK_LE;
130069        return 2;
130070      }else if( c=='>' ){
130071        *tokenType = TK_NE;
130072        return 2;
130073      }else if( c=='<' ){
130074        *tokenType = TK_LSHIFT;
130075        return 2;
130076      }else{
130077        *tokenType = TK_LT;
130078        return 1;
130079      }
130080    }
130081    case '>': {
130082      if( (c=z[1])=='=' ){
130083        *tokenType = TK_GE;
130084        return 2;
130085      }else if( c=='>' ){
130086        *tokenType = TK_RSHIFT;
130087        return 2;
130088      }else{
130089        *tokenType = TK_GT;
130090        return 1;
130091      }
130092    }
130093    case '!': {
130094      if( z[1]!='=' ){
130095        *tokenType = TK_ILLEGAL;
130096        return 2;
130097      }else{
130098        *tokenType = TK_NE;
130099        return 2;
130100      }
130101    }
130102    case '|': {
130103      if( z[1]!='|' ){
130104        *tokenType = TK_BITOR;
130105        return 1;
130106      }else{
130107        *tokenType = TK_CONCAT;
130108        return 2;
130109      }
130110    }
130111    case ',': {
130112      *tokenType = TK_COMMA;
130113      return 1;
130114    }
130115    case '&': {
130116      *tokenType = TK_BITAND;
130117      return 1;
130118    }
130119    case '~': {
130120      *tokenType = TK_BITNOT;
130121      return 1;
130122    }
130123    case '`':
130124    case '\'':
130125    case '"': {
130126      int delim = z[0];
130127      testcase( delim=='`' );
130128      testcase( delim=='\'' );
130129      testcase( delim=='"' );
130130      for(i=1; (c=z[i])!=0; i++){
130131        if( c==delim ){
130132          if( z[i+1]==delim ){
130133            i++;
130134          }else{
130135            break;
130136          }
130137        }
130138      }
130139      if( c=='\'' ){
130140        *tokenType = TK_STRING;
130141        return i+1;
130142      }else if( c!=0 ){
130143        *tokenType = TK_ID;
130144        return i+1;
130145      }else{
130146        *tokenType = TK_ILLEGAL;
130147        return i;
130148      }
130149    }
130150    case '.': {
130151#ifndef SQLITE_OMIT_FLOATING_POINT
130152      if( !sqlite3Isdigit(z[1]) )
130153#endif
130154      {
130155        *tokenType = TK_DOT;
130156        return 1;
130157      }
130158      /* If the next character is a digit, this is a floating point
130159      ** number that begins with ".".  Fall thru into the next case */
130160    }
130161    case '0': case '1': case '2': case '3': case '4':
130162    case '5': case '6': case '7': case '8': case '9': {
130163      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
130164      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
130165      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
130166      testcase( z[0]=='9' );
130167      *tokenType = TK_INTEGER;
130168#ifndef SQLITE_OMIT_HEX_INTEGER
130169      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
130170        for(i=3; sqlite3Isxdigit(z[i]); i++){}
130171        return i;
130172      }
130173#endif
130174      for(i=0; sqlite3Isdigit(z[i]); i++){}
130175#ifndef SQLITE_OMIT_FLOATING_POINT
130176      if( z[i]=='.' ){
130177        i++;
130178        while( sqlite3Isdigit(z[i]) ){ i++; }
130179        *tokenType = TK_FLOAT;
130180      }
130181      if( (z[i]=='e' || z[i]=='E') &&
130182           ( sqlite3Isdigit(z[i+1])
130183            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
130184           )
130185      ){
130186        i += 2;
130187        while( sqlite3Isdigit(z[i]) ){ i++; }
130188        *tokenType = TK_FLOAT;
130189      }
130190#endif
130191      while( IdChar(z[i]) ){
130192        *tokenType = TK_ILLEGAL;
130193        i++;
130194      }
130195      return i;
130196    }
130197    case '[': {
130198      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
130199      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
130200      return i;
130201    }
130202    case '?': {
130203      *tokenType = TK_VARIABLE;
130204      for(i=1; sqlite3Isdigit(z[i]); i++){}
130205      return i;
130206    }
130207#ifndef SQLITE_OMIT_TCL_VARIABLE
130208    case '$':
130209#endif
130210    case '@':  /* For compatibility with MS SQL Server */
130211    case '#':
130212    case ':': {
130213      int n = 0;
130214      testcase( z[0]=='$' );  testcase( z[0]=='@' );
130215      testcase( z[0]==':' );  testcase( z[0]=='#' );
130216      *tokenType = TK_VARIABLE;
130217      for(i=1; (c=z[i])!=0; i++){
130218        if( IdChar(c) ){
130219          n++;
130220#ifndef SQLITE_OMIT_TCL_VARIABLE
130221        }else if( c=='(' && n>0 ){
130222          do{
130223            i++;
130224          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
130225          if( c==')' ){
130226            i++;
130227          }else{
130228            *tokenType = TK_ILLEGAL;
130229          }
130230          break;
130231        }else if( c==':' && z[i+1]==':' ){
130232          i++;
130233#endif
130234        }else{
130235          break;
130236        }
130237      }
130238      if( n==0 ) *tokenType = TK_ILLEGAL;
130239      return i;
130240    }
130241#ifndef SQLITE_OMIT_BLOB_LITERAL
130242    case 'x': case 'X': {
130243      testcase( z[0]=='x' ); testcase( z[0]=='X' );
130244      if( z[1]=='\'' ){
130245        *tokenType = TK_BLOB;
130246        for(i=2; sqlite3Isxdigit(z[i]); i++){}
130247        if( z[i]!='\'' || i%2 ){
130248          *tokenType = TK_ILLEGAL;
130249          while( z[i] && z[i]!='\'' ){ i++; }
130250        }
130251        if( z[i] ) i++;
130252        return i;
130253      }
130254      /* Otherwise fall through to the next case */
130255    }
130256#endif
130257    default: {
130258      if( !IdChar(*z) ){
130259        break;
130260      }
130261      for(i=1; IdChar(z[i]); i++){}
130262      *tokenType = keywordCode((char*)z, i);
130263      return i;
130264    }
130265  }
130266  *tokenType = TK_ILLEGAL;
130267  return 1;
130268}
130269
130270/*
130271** Run the parser on the given SQL string.  The parser structure is
130272** passed in.  An SQLITE_ status code is returned.  If an error occurs
130273** then an and attempt is made to write an error message into
130274** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
130275** error message.
130276*/
130277SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
130278  int nErr = 0;                   /* Number of errors encountered */
130279  int i;                          /* Loop counter */
130280  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
130281  int tokenType;                  /* type of the next token */
130282  int lastTokenParsed = -1;       /* type of the previous token */
130283  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
130284  sqlite3 *db = pParse->db;       /* The database connection */
130285  int mxSqlLen;                   /* Max length of an SQL string */
130286
130287  assert( zSql!=0 );
130288  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
130289  if( db->nVdbeActive==0 ){
130290    db->u1.isInterrupted = 0;
130291  }
130292  pParse->rc = SQLITE_OK;
130293  pParse->zTail = zSql;
130294  i = 0;
130295  assert( pzErrMsg!=0 );
130296  /* sqlite3ParserTrace(stdout, "parser: "); */
130297  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
130298  if( pEngine==0 ){
130299    db->mallocFailed = 1;
130300    return SQLITE_NOMEM;
130301  }
130302  assert( pParse->pNewTable==0 );
130303  assert( pParse->pNewTrigger==0 );
130304  assert( pParse->nVar==0 );
130305  assert( pParse->nzVar==0 );
130306  assert( pParse->azVar==0 );
130307  enableLookaside = db->lookaside.bEnabled;
130308  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
130309  while( !db->mallocFailed && zSql[i]!=0 ){
130310    assert( i>=0 );
130311    pParse->sLastToken.z = &zSql[i];
130312    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
130313    i += pParse->sLastToken.n;
130314    if( i>mxSqlLen ){
130315      pParse->rc = SQLITE_TOOBIG;
130316      break;
130317    }
130318    switch( tokenType ){
130319      case TK_SPACE: {
130320        if( db->u1.isInterrupted ){
130321          sqlite3ErrorMsg(pParse, "interrupt");
130322          pParse->rc = SQLITE_INTERRUPT;
130323          goto abort_parse;
130324        }
130325        break;
130326      }
130327      case TK_ILLEGAL: {
130328        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
130329                        &pParse->sLastToken);
130330        goto abort_parse;
130331      }
130332      case TK_SEMI: {
130333        pParse->zTail = &zSql[i];
130334        /* Fall thru into the default case */
130335      }
130336      default: {
130337        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
130338        lastTokenParsed = tokenType;
130339        if( pParse->rc!=SQLITE_OK ){
130340          goto abort_parse;
130341        }
130342        break;
130343      }
130344    }
130345  }
130346abort_parse:
130347  assert( nErr==0 );
130348  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
130349    assert( zSql[i]==0 );
130350    if( lastTokenParsed!=TK_SEMI ){
130351      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
130352      pParse->zTail = &zSql[i];
130353    }
130354    if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
130355      sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
130356    }
130357  }
130358#ifdef YYTRACKMAXSTACKDEPTH
130359  sqlite3_mutex_enter(sqlite3MallocMutex());
130360  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
130361      sqlite3ParserStackPeak(pEngine)
130362  );
130363  sqlite3_mutex_leave(sqlite3MallocMutex());
130364#endif /* YYDEBUG */
130365  sqlite3ParserFree(pEngine, sqlite3_free);
130366  db->lookaside.bEnabled = enableLookaside;
130367  if( db->mallocFailed ){
130368    pParse->rc = SQLITE_NOMEM;
130369  }
130370  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
130371    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
130372  }
130373  assert( pzErrMsg!=0 );
130374  if( pParse->zErrMsg ){
130375    *pzErrMsg = pParse->zErrMsg;
130376    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
130377    pParse->zErrMsg = 0;
130378    nErr++;
130379  }
130380  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
130381    sqlite3VdbeDelete(pParse->pVdbe);
130382    pParse->pVdbe = 0;
130383  }
130384#ifndef SQLITE_OMIT_SHARED_CACHE
130385  if( pParse->nested==0 ){
130386    sqlite3DbFree(db, pParse->aTableLock);
130387    pParse->aTableLock = 0;
130388    pParse->nTableLock = 0;
130389  }
130390#endif
130391#ifndef SQLITE_OMIT_VIRTUALTABLE
130392  sqlite3_free(pParse->apVtabLock);
130393#endif
130394
130395  if( !IN_DECLARE_VTAB ){
130396    /* If the pParse->declareVtab flag is set, do not delete any table
130397    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
130398    ** will take responsibility for freeing the Table structure.
130399    */
130400    sqlite3DeleteTable(db, pParse->pNewTable);
130401  }
130402
130403  if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
130404  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
130405  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
130406  sqlite3DbFree(db, pParse->azVar);
130407  while( pParse->pAinc ){
130408    AutoincInfo *p = pParse->pAinc;
130409    pParse->pAinc = p->pNext;
130410    sqlite3DbFree(db, p);
130411  }
130412  while( pParse->pZombieTab ){
130413    Table *p = pParse->pZombieTab;
130414    pParse->pZombieTab = p->pNextZombie;
130415    sqlite3DeleteTable(db, p);
130416  }
130417  assert( nErr==0 || pParse->rc!=SQLITE_OK );
130418  return nErr;
130419}
130420
130421/************** End of tokenize.c ********************************************/
130422/************** Begin file complete.c ****************************************/
130423/*
130424** 2001 September 15
130425**
130426** The author disclaims copyright to this source code.  In place of
130427** a legal notice, here is a blessing:
130428**
130429**    May you do good and not evil.
130430**    May you find forgiveness for yourself and forgive others.
130431**    May you share freely, never taking more than you give.
130432**
130433*************************************************************************
130434** An tokenizer for SQL
130435**
130436** This file contains C code that implements the sqlite3_complete() API.
130437** This code used to be part of the tokenizer.c source file.  But by
130438** separating it out, the code will be automatically omitted from
130439** static links that do not use it.
130440*/
130441/* #include "sqliteInt.h" */
130442#ifndef SQLITE_OMIT_COMPLETE
130443
130444/*
130445** This is defined in tokenize.c.  We just have to import the definition.
130446*/
130447#ifndef SQLITE_AMALGAMATION
130448#ifdef SQLITE_ASCII
130449#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
130450#endif
130451#ifdef SQLITE_EBCDIC
130452SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
130453#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
130454#endif
130455#endif /* SQLITE_AMALGAMATION */
130456
130457
130458/*
130459** Token types used by the sqlite3_complete() routine.  See the header
130460** comments on that procedure for additional information.
130461*/
130462#define tkSEMI    0
130463#define tkWS      1
130464#define tkOTHER   2
130465#ifndef SQLITE_OMIT_TRIGGER
130466#define tkEXPLAIN 3
130467#define tkCREATE  4
130468#define tkTEMP    5
130469#define tkTRIGGER 6
130470#define tkEND     7
130471#endif
130472
130473/*
130474** Return TRUE if the given SQL string ends in a semicolon.
130475**
130476** Special handling is require for CREATE TRIGGER statements.
130477** Whenever the CREATE TRIGGER keywords are seen, the statement
130478** must end with ";END;".
130479**
130480** This implementation uses a state machine with 8 states:
130481**
130482**   (0) INVALID   We have not yet seen a non-whitespace character.
130483**
130484**   (1) START     At the beginning or end of an SQL statement.  This routine
130485**                 returns 1 if it ends in the START state and 0 if it ends
130486**                 in any other state.
130487**
130488**   (2) NORMAL    We are in the middle of statement which ends with a single
130489**                 semicolon.
130490**
130491**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
130492**                 a statement.
130493**
130494**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
130495**                 statement, possibly preceded by EXPLAIN and/or followed by
130496**                 TEMP or TEMPORARY
130497**
130498**   (5) TRIGGER   We are in the middle of a trigger definition that must be
130499**                 ended by a semicolon, the keyword END, and another semicolon.
130500**
130501**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
130502**                 the end of a trigger definition.
130503**
130504**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
130505**                 of a trigger definition.
130506**
130507** Transitions between states above are determined by tokens extracted
130508** from the input.  The following tokens are significant:
130509**
130510**   (0) tkSEMI      A semicolon.
130511**   (1) tkWS        Whitespace.
130512**   (2) tkOTHER     Any other SQL token.
130513**   (3) tkEXPLAIN   The "explain" keyword.
130514**   (4) tkCREATE    The "create" keyword.
130515**   (5) tkTEMP      The "temp" or "temporary" keyword.
130516**   (6) tkTRIGGER   The "trigger" keyword.
130517**   (7) tkEND       The "end" keyword.
130518**
130519** Whitespace never causes a state transition and is always ignored.
130520** This means that a SQL string of all whitespace is invalid.
130521**
130522** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
130523** to recognize the end of a trigger can be omitted.  All we have to do
130524** is look for a semicolon that is not part of an string or comment.
130525*/
130526SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
130527  u8 state = 0;   /* Current state, using numbers defined in header comment */
130528  u8 token;       /* Value of the next token */
130529
130530#ifndef SQLITE_OMIT_TRIGGER
130531  /* A complex statement machine used to detect the end of a CREATE TRIGGER
130532  ** statement.  This is the normal case.
130533  */
130534  static const u8 trans[8][8] = {
130535                     /* Token:                                                */
130536     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
130537     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
130538     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
130539     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
130540     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
130541     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
130542     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
130543     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
130544     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
130545  };
130546#else
130547  /* If triggers are not supported by this compile then the statement machine
130548  ** used to detect the end of a statement is much simpler
130549  */
130550  static const u8 trans[3][3] = {
130551                     /* Token:           */
130552     /* State:       **  SEMI  WS  OTHER */
130553     /* 0 INVALID: */ {    1,  0,     2, },
130554     /* 1   START: */ {    1,  1,     2, },
130555     /* 2  NORMAL: */ {    1,  2,     2, },
130556  };
130557#endif /* SQLITE_OMIT_TRIGGER */
130558
130559#ifdef SQLITE_ENABLE_API_ARMOR
130560  if( zSql==0 ){
130561    (void)SQLITE_MISUSE_BKPT;
130562    return 0;
130563  }
130564#endif
130565
130566  while( *zSql ){
130567    switch( *zSql ){
130568      case ';': {  /* A semicolon */
130569        token = tkSEMI;
130570        break;
130571      }
130572      case ' ':
130573      case '\r':
130574      case '\t':
130575      case '\n':
130576      case '\f': {  /* White space is ignored */
130577        token = tkWS;
130578        break;
130579      }
130580      case '/': {   /* C-style comments */
130581        if( zSql[1]!='*' ){
130582          token = tkOTHER;
130583          break;
130584        }
130585        zSql += 2;
130586        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
130587        if( zSql[0]==0 ) return 0;
130588        zSql++;
130589        token = tkWS;
130590        break;
130591      }
130592      case '-': {   /* SQL-style comments from "--" to end of line */
130593        if( zSql[1]!='-' ){
130594          token = tkOTHER;
130595          break;
130596        }
130597        while( *zSql && *zSql!='\n' ){ zSql++; }
130598        if( *zSql==0 ) return state==1;
130599        token = tkWS;
130600        break;
130601      }
130602      case '[': {   /* Microsoft-style identifiers in [...] */
130603        zSql++;
130604        while( *zSql && *zSql!=']' ){ zSql++; }
130605        if( *zSql==0 ) return 0;
130606        token = tkOTHER;
130607        break;
130608      }
130609      case '`':     /* Grave-accent quoted symbols used by MySQL */
130610      case '"':     /* single- and double-quoted strings */
130611      case '\'': {
130612        int c = *zSql;
130613        zSql++;
130614        while( *zSql && *zSql!=c ){ zSql++; }
130615        if( *zSql==0 ) return 0;
130616        token = tkOTHER;
130617        break;
130618      }
130619      default: {
130620#ifdef SQLITE_EBCDIC
130621        unsigned char c;
130622#endif
130623        if( IdChar((u8)*zSql) ){
130624          /* Keywords and unquoted identifiers */
130625          int nId;
130626          for(nId=1; IdChar(zSql[nId]); nId++){}
130627#ifdef SQLITE_OMIT_TRIGGER
130628          token = tkOTHER;
130629#else
130630          switch( *zSql ){
130631            case 'c': case 'C': {
130632              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
130633                token = tkCREATE;
130634              }else{
130635                token = tkOTHER;
130636              }
130637              break;
130638            }
130639            case 't': case 'T': {
130640              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
130641                token = tkTRIGGER;
130642              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
130643                token = tkTEMP;
130644              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
130645                token = tkTEMP;
130646              }else{
130647                token = tkOTHER;
130648              }
130649              break;
130650            }
130651            case 'e':  case 'E': {
130652              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
130653                token = tkEND;
130654              }else
130655#ifndef SQLITE_OMIT_EXPLAIN
130656              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
130657                token = tkEXPLAIN;
130658              }else
130659#endif
130660              {
130661                token = tkOTHER;
130662              }
130663              break;
130664            }
130665            default: {
130666              token = tkOTHER;
130667              break;
130668            }
130669          }
130670#endif /* SQLITE_OMIT_TRIGGER */
130671          zSql += nId-1;
130672        }else{
130673          /* Operators and special symbols */
130674          token = tkOTHER;
130675        }
130676        break;
130677      }
130678    }
130679    state = trans[state][token];
130680    zSql++;
130681  }
130682  return state==1;
130683}
130684
130685#ifndef SQLITE_OMIT_UTF16
130686/*
130687** This routine is the same as the sqlite3_complete() routine described
130688** above, except that the parameter is required to be UTF-16 encoded, not
130689** UTF-8.
130690*/
130691SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
130692  sqlite3_value *pVal;
130693  char const *zSql8;
130694  int rc;
130695
130696#ifndef SQLITE_OMIT_AUTOINIT
130697  rc = sqlite3_initialize();
130698  if( rc ) return rc;
130699#endif
130700  pVal = sqlite3ValueNew(0);
130701  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
130702  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
130703  if( zSql8 ){
130704    rc = sqlite3_complete(zSql8);
130705  }else{
130706    rc = SQLITE_NOMEM;
130707  }
130708  sqlite3ValueFree(pVal);
130709  return rc & 0xff;
130710}
130711#endif /* SQLITE_OMIT_UTF16 */
130712#endif /* SQLITE_OMIT_COMPLETE */
130713
130714/************** End of complete.c ********************************************/
130715/************** Begin file main.c ********************************************/
130716/*
130717** 2001 September 15
130718**
130719** The author disclaims copyright to this source code.  In place of
130720** a legal notice, here is a blessing:
130721**
130722**    May you do good and not evil.
130723**    May you find forgiveness for yourself and forgive others.
130724**    May you share freely, never taking more than you give.
130725**
130726*************************************************************************
130727** Main file for the SQLite library.  The routines in this file
130728** implement the programmer interface to the library.  Routines in
130729** other files are for internal use by SQLite and should not be
130730** accessed by users of the library.
130731*/
130732/* #include "sqliteInt.h" */
130733
130734#ifdef SQLITE_ENABLE_FTS3
130735/************** Include fts3.h in the middle of main.c ***********************/
130736/************** Begin file fts3.h ********************************************/
130737/*
130738** 2006 Oct 10
130739**
130740** The author disclaims copyright to this source code.  In place of
130741** a legal notice, here is a blessing:
130742**
130743**    May you do good and not evil.
130744**    May you find forgiveness for yourself and forgive others.
130745**    May you share freely, never taking more than you give.
130746**
130747******************************************************************************
130748**
130749** This header file is used by programs that want to link against the
130750** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
130751*/
130752/* #include "sqlite3.h" */
130753
130754#if 0
130755extern "C" {
130756#endif  /* __cplusplus */
130757
130758SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
130759
130760#if 0
130761}  /* extern "C" */
130762#endif  /* __cplusplus */
130763
130764/************** End of fts3.h ************************************************/
130765/************** Continuing where we left off in main.c ***********************/
130766#endif
130767#ifdef SQLITE_ENABLE_RTREE
130768/************** Include rtree.h in the middle of main.c **********************/
130769/************** Begin file rtree.h *******************************************/
130770/*
130771** 2008 May 26
130772**
130773** The author disclaims copyright to this source code.  In place of
130774** a legal notice, here is a blessing:
130775**
130776**    May you do good and not evil.
130777**    May you find forgiveness for yourself and forgive others.
130778**    May you share freely, never taking more than you give.
130779**
130780******************************************************************************
130781**
130782** This header file is used by programs that want to link against the
130783** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
130784*/
130785/* #include "sqlite3.h" */
130786
130787#if 0
130788extern "C" {
130789#endif  /* __cplusplus */
130790
130791SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
130792
130793#if 0
130794}  /* extern "C" */
130795#endif  /* __cplusplus */
130796
130797/************** End of rtree.h ***********************************************/
130798/************** Continuing where we left off in main.c ***********************/
130799#endif
130800#ifdef SQLITE_ENABLE_ICU
130801/************** Include sqliteicu.h in the middle of main.c ******************/
130802/************** Begin file sqliteicu.h ***************************************/
130803/*
130804** 2008 May 26
130805**
130806** The author disclaims copyright to this source code.  In place of
130807** a legal notice, here is a blessing:
130808**
130809**    May you do good and not evil.
130810**    May you find forgiveness for yourself and forgive others.
130811**    May you share freely, never taking more than you give.
130812**
130813******************************************************************************
130814**
130815** This header file is used by programs that want to link against the
130816** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
130817*/
130818/* #include "sqlite3.h" */
130819
130820#if 0
130821extern "C" {
130822#endif  /* __cplusplus */
130823
130824SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
130825
130826#if 0
130827}  /* extern "C" */
130828#endif  /* __cplusplus */
130829
130830
130831/************** End of sqliteicu.h *******************************************/
130832/************** Continuing where we left off in main.c ***********************/
130833#endif
130834#ifdef SQLITE_ENABLE_JSON1
130835SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
130836#endif
130837#ifdef SQLITE_ENABLE_FTS5
130838SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
130839#endif
130840
130841#ifndef SQLITE_AMALGAMATION
130842/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
130843** contains the text of SQLITE_VERSION macro.
130844*/
130845SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
130846#endif
130847
130848/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
130849** a pointer to the to the sqlite3_version[] string constant.
130850*/
130851SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
130852
130853/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
130854** pointer to a string constant whose value is the same as the
130855** SQLITE_SOURCE_ID C preprocessor macro.
130856*/
130857SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
130858
130859/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
130860** returns an integer equal to SQLITE_VERSION_NUMBER.
130861*/
130862SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
130863
130864/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
130865** zero if and only if SQLite was compiled with mutexing code omitted due to
130866** the SQLITE_THREADSAFE compile-time option being set to 0.
130867*/
130868SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
130869
130870/*
130871** When compiling the test fixture or with debugging enabled (on Win32),
130872** this variable being set to non-zero will cause OSTRACE macros to emit
130873** extra diagnostic information.
130874*/
130875#ifdef SQLITE_HAVE_OS_TRACE
130876# ifndef SQLITE_DEBUG_OS_TRACE
130877#   define SQLITE_DEBUG_OS_TRACE 0
130878# endif
130879  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
130880#endif
130881
130882#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
130883/*
130884** If the following function pointer is not NULL and if
130885** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
130886** I/O active are written using this function.  These messages
130887** are intended for debugging activity only.
130888*/
130889SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
130890#endif
130891
130892/*
130893** If the following global variable points to a string which is the
130894** name of a directory, then that directory will be used to store
130895** temporary files.
130896**
130897** See also the "PRAGMA temp_store_directory" SQL command.
130898*/
130899SQLITE_API char *sqlite3_temp_directory = 0;
130900
130901/*
130902** If the following global variable points to a string which is the
130903** name of a directory, then that directory will be used to store
130904** all database files specified with a relative pathname.
130905**
130906** See also the "PRAGMA data_store_directory" SQL command.
130907*/
130908SQLITE_API char *sqlite3_data_directory = 0;
130909
130910/*
130911** Initialize SQLite.
130912**
130913** This routine must be called to initialize the memory allocation,
130914** VFS, and mutex subsystems prior to doing any serious work with
130915** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
130916** this routine will be called automatically by key routines such as
130917** sqlite3_open().
130918**
130919** This routine is a no-op except on its very first call for the process,
130920** or for the first call after a call to sqlite3_shutdown.
130921**
130922** The first thread to call this routine runs the initialization to
130923** completion.  If subsequent threads call this routine before the first
130924** thread has finished the initialization process, then the subsequent
130925** threads must block until the first thread finishes with the initialization.
130926**
130927** The first thread might call this routine recursively.  Recursive
130928** calls to this routine should not block, of course.  Otherwise the
130929** initialization process would never complete.
130930**
130931** Let X be the first thread to enter this routine.  Let Y be some other
130932** thread.  Then while the initial invocation of this routine by X is
130933** incomplete, it is required that:
130934**
130935**    *  Calls to this routine from Y must block until the outer-most
130936**       call by X completes.
130937**
130938**    *  Recursive calls to this routine from thread X return immediately
130939**       without blocking.
130940*/
130941SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
130942  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
130943  int rc;                                      /* Result code */
130944#ifdef SQLITE_EXTRA_INIT
130945  int bRunExtraInit = 0;                       /* Extra initialization needed */
130946#endif
130947
130948#ifdef SQLITE_OMIT_WSD
130949  rc = sqlite3_wsd_init(4096, 24);
130950  if( rc!=SQLITE_OK ){
130951    return rc;
130952  }
130953#endif
130954
130955  /* If the following assert() fails on some obscure processor/compiler
130956  ** combination, the work-around is to set the correct pointer
130957  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
130958  assert( SQLITE_PTRSIZE==sizeof(char*) );
130959
130960  /* If SQLite is already completely initialized, then this call
130961  ** to sqlite3_initialize() should be a no-op.  But the initialization
130962  ** must be complete.  So isInit must not be set until the very end
130963  ** of this routine.
130964  */
130965  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
130966
130967  /* Make sure the mutex subsystem is initialized.  If unable to
130968  ** initialize the mutex subsystem, return early with the error.
130969  ** If the system is so sick that we are unable to allocate a mutex,
130970  ** there is not much SQLite is going to be able to do.
130971  **
130972  ** The mutex subsystem must take care of serializing its own
130973  ** initialization.
130974  */
130975  rc = sqlite3MutexInit();
130976  if( rc ) return rc;
130977
130978  /* Initialize the malloc() system and the recursive pInitMutex mutex.
130979  ** This operation is protected by the STATIC_MASTER mutex.  Note that
130980  ** MutexAlloc() is called for a static mutex prior to initializing the
130981  ** malloc subsystem - this implies that the allocation of a static
130982  ** mutex must not require support from the malloc subsystem.
130983  */
130984  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
130985  sqlite3_mutex_enter(pMaster);
130986  sqlite3GlobalConfig.isMutexInit = 1;
130987  if( !sqlite3GlobalConfig.isMallocInit ){
130988    rc = sqlite3MallocInit();
130989  }
130990  if( rc==SQLITE_OK ){
130991    sqlite3GlobalConfig.isMallocInit = 1;
130992    if( !sqlite3GlobalConfig.pInitMutex ){
130993      sqlite3GlobalConfig.pInitMutex =
130994           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
130995      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
130996        rc = SQLITE_NOMEM;
130997      }
130998    }
130999  }
131000  if( rc==SQLITE_OK ){
131001    sqlite3GlobalConfig.nRefInitMutex++;
131002  }
131003  sqlite3_mutex_leave(pMaster);
131004
131005  /* If rc is not SQLITE_OK at this point, then either the malloc
131006  ** subsystem could not be initialized or the system failed to allocate
131007  ** the pInitMutex mutex. Return an error in either case.  */
131008  if( rc!=SQLITE_OK ){
131009    return rc;
131010  }
131011
131012  /* Do the rest of the initialization under the recursive mutex so
131013  ** that we will be able to handle recursive calls into
131014  ** sqlite3_initialize().  The recursive calls normally come through
131015  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
131016  ** recursive calls might also be possible.
131017  **
131018  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
131019  ** to the xInit method, so the xInit method need not be threadsafe.
131020  **
131021  ** The following mutex is what serializes access to the appdef pcache xInit
131022  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
131023  ** call to sqlite3PcacheInitialize().
131024  */
131025  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
131026  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
131027    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
131028    sqlite3GlobalConfig.inProgress = 1;
131029    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
131030    sqlite3RegisterGlobalFunctions();
131031    if( sqlite3GlobalConfig.isPCacheInit==0 ){
131032      rc = sqlite3PcacheInitialize();
131033    }
131034    if( rc==SQLITE_OK ){
131035      sqlite3GlobalConfig.isPCacheInit = 1;
131036      rc = sqlite3OsInit();
131037    }
131038    if( rc==SQLITE_OK ){
131039      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
131040          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
131041      sqlite3GlobalConfig.isInit = 1;
131042#ifdef SQLITE_EXTRA_INIT
131043      bRunExtraInit = 1;
131044#endif
131045    }
131046    sqlite3GlobalConfig.inProgress = 0;
131047  }
131048  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
131049
131050  /* Go back under the static mutex and clean up the recursive
131051  ** mutex to prevent a resource leak.
131052  */
131053  sqlite3_mutex_enter(pMaster);
131054  sqlite3GlobalConfig.nRefInitMutex--;
131055  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
131056    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
131057    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
131058    sqlite3GlobalConfig.pInitMutex = 0;
131059  }
131060  sqlite3_mutex_leave(pMaster);
131061
131062  /* The following is just a sanity check to make sure SQLite has
131063  ** been compiled correctly.  It is important to run this code, but
131064  ** we don't want to run it too often and soak up CPU cycles for no
131065  ** reason.  So we run it once during initialization.
131066  */
131067#ifndef NDEBUG
131068#ifndef SQLITE_OMIT_FLOATING_POINT
131069  /* This section of code's only "output" is via assert() statements. */
131070  if ( rc==SQLITE_OK ){
131071    u64 x = (((u64)1)<<63)-1;
131072    double y;
131073    assert(sizeof(x)==8);
131074    assert(sizeof(x)==sizeof(y));
131075    memcpy(&y, &x, 8);
131076    assert( sqlite3IsNaN(y) );
131077  }
131078#endif
131079#endif
131080
131081  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
131082  ** compile-time option.
131083  */
131084#ifdef SQLITE_EXTRA_INIT
131085  if( bRunExtraInit ){
131086    int SQLITE_EXTRA_INIT(const char*);
131087    rc = SQLITE_EXTRA_INIT(0);
131088  }
131089#endif
131090
131091  return rc;
131092}
131093
131094/*
131095** Undo the effects of sqlite3_initialize().  Must not be called while
131096** there are outstanding database connections or memory allocations or
131097** while any part of SQLite is otherwise in use in any thread.  This
131098** routine is not threadsafe.  But it is safe to invoke this routine
131099** on when SQLite is already shut down.  If SQLite is already shut down
131100** when this routine is invoked, then this routine is a harmless no-op.
131101*/
131102SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
131103#ifdef SQLITE_OMIT_WSD
131104  int rc = sqlite3_wsd_init(4096, 24);
131105  if( rc!=SQLITE_OK ){
131106    return rc;
131107  }
131108#endif
131109
131110  if( sqlite3GlobalConfig.isInit ){
131111#ifdef SQLITE_EXTRA_SHUTDOWN
131112    void SQLITE_EXTRA_SHUTDOWN(void);
131113    SQLITE_EXTRA_SHUTDOWN();
131114#endif
131115    sqlite3_os_end();
131116    sqlite3_reset_auto_extension();
131117    sqlite3GlobalConfig.isInit = 0;
131118  }
131119  if( sqlite3GlobalConfig.isPCacheInit ){
131120    sqlite3PcacheShutdown();
131121    sqlite3GlobalConfig.isPCacheInit = 0;
131122  }
131123  if( sqlite3GlobalConfig.isMallocInit ){
131124    sqlite3MallocEnd();
131125    sqlite3GlobalConfig.isMallocInit = 0;
131126
131127#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
131128    /* The heap subsystem has now been shutdown and these values are supposed
131129    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
131130    ** which would rely on that heap subsystem; therefore, make sure these
131131    ** values cannot refer to heap memory that was just invalidated when the
131132    ** heap subsystem was shutdown.  This is only done if the current call to
131133    ** this function resulted in the heap subsystem actually being shutdown.
131134    */
131135    sqlite3_data_directory = 0;
131136    sqlite3_temp_directory = 0;
131137#endif
131138  }
131139  if( sqlite3GlobalConfig.isMutexInit ){
131140    sqlite3MutexEnd();
131141    sqlite3GlobalConfig.isMutexInit = 0;
131142  }
131143
131144  return SQLITE_OK;
131145}
131146
131147/*
131148** This API allows applications to modify the global configuration of
131149** the SQLite library at run-time.
131150**
131151** This routine should only be called when there are no outstanding
131152** database connections or memory allocations.  This routine is not
131153** threadsafe.  Failure to heed these warnings can lead to unpredictable
131154** behavior.
131155*/
131156SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
131157  va_list ap;
131158  int rc = SQLITE_OK;
131159
131160  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
131161  ** the SQLite library is in use. */
131162  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
131163
131164  va_start(ap, op);
131165  switch( op ){
131166
131167    /* Mutex configuration options are only available in a threadsafe
131168    ** compile.
131169    */
131170#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
131171    case SQLITE_CONFIG_SINGLETHREAD: {
131172      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
131173      ** Single-thread. */
131174      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
131175      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
131176      break;
131177    }
131178#endif
131179#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
131180    case SQLITE_CONFIG_MULTITHREAD: {
131181      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
131182      ** Multi-thread. */
131183      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
131184      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
131185      break;
131186    }
131187#endif
131188#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
131189    case SQLITE_CONFIG_SERIALIZED: {
131190      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
131191      ** Serialized. */
131192      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
131193      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
131194      break;
131195    }
131196#endif
131197#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
131198    case SQLITE_CONFIG_MUTEX: {
131199      /* Specify an alternative mutex implementation */
131200      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
131201      break;
131202    }
131203#endif
131204#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
131205    case SQLITE_CONFIG_GETMUTEX: {
131206      /* Retrieve the current mutex implementation */
131207      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
131208      break;
131209    }
131210#endif
131211
131212    case SQLITE_CONFIG_MALLOC: {
131213      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
131214      ** single argument which is a pointer to an instance of the
131215      ** sqlite3_mem_methods structure. The argument specifies alternative
131216      ** low-level memory allocation routines to be used in place of the memory
131217      ** allocation routines built into SQLite. */
131218      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
131219      break;
131220    }
131221    case SQLITE_CONFIG_GETMALLOC: {
131222      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
131223      ** single argument which is a pointer to an instance of the
131224      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
131225      ** filled with the currently defined memory allocation routines. */
131226      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
131227      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
131228      break;
131229    }
131230    case SQLITE_CONFIG_MEMSTATUS: {
131231      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
131232      ** single argument of type int, interpreted as a boolean, which enables
131233      ** or disables the collection of memory allocation statistics. */
131234      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
131235      break;
131236    }
131237    case SQLITE_CONFIG_SCRATCH: {
131238      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
131239      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
131240      ** which the scratch allocations will be drawn, the size of each scratch
131241      ** allocation (sz), and the maximum number of scratch allocations (N). */
131242      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
131243      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
131244      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
131245      break;
131246    }
131247    case SQLITE_CONFIG_PAGECACHE: {
131248      /* EVIDENCE-OF: R-31408-40510 There are three arguments to
131249      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
131250      ** of each page buffer (sz), and the number of pages (N). */
131251      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
131252      sqlite3GlobalConfig.szPage = va_arg(ap, int);
131253      sqlite3GlobalConfig.nPage = va_arg(ap, int);
131254      break;
131255    }
131256    case SQLITE_CONFIG_PCACHE_HDRSZ: {
131257      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
131258      ** a single parameter which is a pointer to an integer and writes into
131259      ** that integer the number of extra bytes per page required for each page
131260      ** in SQLITE_CONFIG_PAGECACHE. */
131261      *va_arg(ap, int*) =
131262          sqlite3HeaderSizeBtree() +
131263          sqlite3HeaderSizePcache() +
131264          sqlite3HeaderSizePcache1();
131265      break;
131266    }
131267
131268    case SQLITE_CONFIG_PCACHE: {
131269      /* no-op */
131270      break;
131271    }
131272    case SQLITE_CONFIG_GETPCACHE: {
131273      /* now an error */
131274      rc = SQLITE_ERROR;
131275      break;
131276    }
131277
131278    case SQLITE_CONFIG_PCACHE2: {
131279      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
131280      ** single argument which is a pointer to an sqlite3_pcache_methods2
131281      ** object. This object specifies the interface to a custom page cache
131282      ** implementation. */
131283      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
131284      break;
131285    }
131286    case SQLITE_CONFIG_GETPCACHE2: {
131287      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
131288      ** single argument which is a pointer to an sqlite3_pcache_methods2
131289      ** object. SQLite copies of the current page cache implementation into
131290      ** that object. */
131291      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
131292        sqlite3PCacheSetDefault();
131293      }
131294      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
131295      break;
131296    }
131297
131298/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
131299** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
131300** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
131301#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
131302    case SQLITE_CONFIG_HEAP: {
131303      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
131304      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
131305      ** number of bytes in the memory buffer, and the minimum allocation size.
131306      */
131307      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
131308      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
131309      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
131310
131311      if( sqlite3GlobalConfig.mnReq<1 ){
131312        sqlite3GlobalConfig.mnReq = 1;
131313      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
131314        /* cap min request size at 2^12 */
131315        sqlite3GlobalConfig.mnReq = (1<<12);
131316      }
131317
131318      if( sqlite3GlobalConfig.pHeap==0 ){
131319        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
131320        ** is NULL, then SQLite reverts to using its default memory allocator
131321        ** (the system malloc() implementation), undoing any prior invocation of
131322        ** SQLITE_CONFIG_MALLOC.
131323        **
131324        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
131325        ** revert to its default implementation when sqlite3_initialize() is run
131326        */
131327        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
131328      }else{
131329        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
131330        ** alternative memory allocator is engaged to handle all of SQLites
131331        ** memory allocation needs. */
131332#ifdef SQLITE_ENABLE_MEMSYS3
131333        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
131334#endif
131335#ifdef SQLITE_ENABLE_MEMSYS5
131336        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
131337#endif
131338      }
131339      break;
131340    }
131341#endif
131342
131343    case SQLITE_CONFIG_LOOKASIDE: {
131344      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
131345      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
131346      break;
131347    }
131348
131349    /* Record a pointer to the logger function and its first argument.
131350    ** The default is NULL.  Logging is disabled if the function pointer is
131351    ** NULL.
131352    */
131353    case SQLITE_CONFIG_LOG: {
131354      /* MSVC is picky about pulling func ptrs from va lists.
131355      ** http://support.microsoft.com/kb/47961
131356      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
131357      */
131358      typedef void(*LOGFUNC_t)(void*,int,const char*);
131359      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
131360      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
131361      break;
131362    }
131363
131364    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
131365    ** can be changed at start-time using the
131366    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
131367    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
131368    */
131369    case SQLITE_CONFIG_URI: {
131370      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
131371      ** argument of type int. If non-zero, then URI handling is globally
131372      ** enabled. If the parameter is zero, then URI handling is globally
131373      ** disabled. */
131374      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
131375      break;
131376    }
131377
131378    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
131379      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
131380      ** option takes a single integer argument which is interpreted as a
131381      ** boolean in order to enable or disable the use of covering indices for
131382      ** full table scans in the query optimizer. */
131383      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
131384      break;
131385    }
131386
131387#ifdef SQLITE_ENABLE_SQLLOG
131388    case SQLITE_CONFIG_SQLLOG: {
131389      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
131390      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
131391      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
131392      break;
131393    }
131394#endif
131395
131396    case SQLITE_CONFIG_MMAP_SIZE: {
131397      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
131398      ** integer (sqlite3_int64) values that are the default mmap size limit
131399      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
131400      ** mmap size limit. */
131401      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
131402      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
131403      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
131404      ** negative, then that argument is changed to its compile-time default.
131405      **
131406      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
131407      ** silently truncated if necessary so that it does not exceed the
131408      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
131409      ** compile-time option.
131410      */
131411      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
131412        mxMmap = SQLITE_MAX_MMAP_SIZE;
131413      }
131414      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
131415      if( szMmap>mxMmap) szMmap = mxMmap;
131416      sqlite3GlobalConfig.mxMmap = mxMmap;
131417      sqlite3GlobalConfig.szMmap = szMmap;
131418      break;
131419    }
131420
131421#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
131422    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
131423      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
131424      ** unsigned integer value that specifies the maximum size of the created
131425      ** heap. */
131426      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
131427      break;
131428    }
131429#endif
131430
131431    case SQLITE_CONFIG_PMASZ: {
131432      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
131433      break;
131434    }
131435
131436    default: {
131437      rc = SQLITE_ERROR;
131438      break;
131439    }
131440  }
131441  va_end(ap);
131442  return rc;
131443}
131444
131445/*
131446** Set up the lookaside buffers for a database connection.
131447** Return SQLITE_OK on success.
131448** If lookaside is already active, return SQLITE_BUSY.
131449**
131450** The sz parameter is the number of bytes in each lookaside slot.
131451** The cnt parameter is the number of slots.  If pStart is NULL the
131452** space for the lookaside memory is obtained from sqlite3_malloc().
131453** If pStart is not NULL then it is sz*cnt bytes of memory to use for
131454** the lookaside memory.
131455*/
131456static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
131457#ifndef SQLITE_OMIT_LOOKASIDE
131458  void *pStart;
131459  if( db->lookaside.nOut ){
131460    return SQLITE_BUSY;
131461  }
131462  /* Free any existing lookaside buffer for this handle before
131463  ** allocating a new one so we don't have to have space for
131464  ** both at the same time.
131465  */
131466  if( db->lookaside.bMalloced ){
131467    sqlite3_free(db->lookaside.pStart);
131468  }
131469  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
131470  ** than a pointer to be useful.
131471  */
131472  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
131473  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
131474  if( cnt<0 ) cnt = 0;
131475  if( sz==0 || cnt==0 ){
131476    sz = 0;
131477    pStart = 0;
131478  }else if( pBuf==0 ){
131479    sqlite3BeginBenignMalloc();
131480    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
131481    sqlite3EndBenignMalloc();
131482    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
131483  }else{
131484    pStart = pBuf;
131485  }
131486  db->lookaside.pStart = pStart;
131487  db->lookaside.pFree = 0;
131488  db->lookaside.sz = (u16)sz;
131489  if( pStart ){
131490    int i;
131491    LookasideSlot *p;
131492    assert( sz > (int)sizeof(LookasideSlot*) );
131493    p = (LookasideSlot*)pStart;
131494    for(i=cnt-1; i>=0; i--){
131495      p->pNext = db->lookaside.pFree;
131496      db->lookaside.pFree = p;
131497      p = (LookasideSlot*)&((u8*)p)[sz];
131498    }
131499    db->lookaside.pEnd = p;
131500    db->lookaside.bEnabled = 1;
131501    db->lookaside.bMalloced = pBuf==0 ?1:0;
131502  }else{
131503    db->lookaside.pStart = db;
131504    db->lookaside.pEnd = db;
131505    db->lookaside.bEnabled = 0;
131506    db->lookaside.bMalloced = 0;
131507  }
131508#endif /* SQLITE_OMIT_LOOKASIDE */
131509  return SQLITE_OK;
131510}
131511
131512/*
131513** Return the mutex associated with a database connection.
131514*/
131515SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
131516#ifdef SQLITE_ENABLE_API_ARMOR
131517  if( !sqlite3SafetyCheckOk(db) ){
131518    (void)SQLITE_MISUSE_BKPT;
131519    return 0;
131520  }
131521#endif
131522  return db->mutex;
131523}
131524
131525/*
131526** Free up as much memory as we can from the given database
131527** connection.
131528*/
131529SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
131530  int i;
131531
131532#ifdef SQLITE_ENABLE_API_ARMOR
131533  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131534#endif
131535  sqlite3_mutex_enter(db->mutex);
131536  sqlite3BtreeEnterAll(db);
131537  for(i=0; i<db->nDb; i++){
131538    Btree *pBt = db->aDb[i].pBt;
131539    if( pBt ){
131540      Pager *pPager = sqlite3BtreePager(pBt);
131541      sqlite3PagerShrink(pPager);
131542    }
131543  }
131544  sqlite3BtreeLeaveAll(db);
131545  sqlite3_mutex_leave(db->mutex);
131546  return SQLITE_OK;
131547}
131548
131549/*
131550** Configuration settings for an individual database connection
131551*/
131552SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
131553  va_list ap;
131554  int rc;
131555  va_start(ap, op);
131556  switch( op ){
131557    case SQLITE_DBCONFIG_LOOKASIDE: {
131558      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
131559      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
131560      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
131561      rc = setupLookaside(db, pBuf, sz, cnt);
131562      break;
131563    }
131564    default: {
131565      static const struct {
131566        int op;      /* The opcode */
131567        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
131568      } aFlagOp[] = {
131569        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
131570        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
131571      };
131572      unsigned int i;
131573      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
131574      for(i=0; i<ArraySize(aFlagOp); i++){
131575        if( aFlagOp[i].op==op ){
131576          int onoff = va_arg(ap, int);
131577          int *pRes = va_arg(ap, int*);
131578          int oldFlags = db->flags;
131579          if( onoff>0 ){
131580            db->flags |= aFlagOp[i].mask;
131581          }else if( onoff==0 ){
131582            db->flags &= ~aFlagOp[i].mask;
131583          }
131584          if( oldFlags!=db->flags ){
131585            sqlite3ExpirePreparedStatements(db);
131586          }
131587          if( pRes ){
131588            *pRes = (db->flags & aFlagOp[i].mask)!=0;
131589          }
131590          rc = SQLITE_OK;
131591          break;
131592        }
131593      }
131594      break;
131595    }
131596  }
131597  va_end(ap);
131598  return rc;
131599}
131600
131601
131602/*
131603** Return true if the buffer z[0..n-1] contains all spaces.
131604*/
131605static int allSpaces(const char *z, int n){
131606  while( n>0 && z[n-1]==' ' ){ n--; }
131607  return n==0;
131608}
131609
131610/*
131611** This is the default collating function named "BINARY" which is always
131612** available.
131613**
131614** If the padFlag argument is not NULL then space padding at the end
131615** of strings is ignored.  This implements the RTRIM collation.
131616*/
131617static int binCollFunc(
131618  void *padFlag,
131619  int nKey1, const void *pKey1,
131620  int nKey2, const void *pKey2
131621){
131622  int rc, n;
131623  n = nKey1<nKey2 ? nKey1 : nKey2;
131624  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
131625  ** strings byte by byte using the memcmp() function from the standard C
131626  ** library. */
131627  rc = memcmp(pKey1, pKey2, n);
131628  if( rc==0 ){
131629    if( padFlag
131630     && allSpaces(((char*)pKey1)+n, nKey1-n)
131631     && allSpaces(((char*)pKey2)+n, nKey2-n)
131632    ){
131633      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
131634      ** spaces at the end of either string do not change the result. In other
131635      ** words, strings will compare equal to one another as long as they
131636      ** differ only in the number of spaces at the end.
131637      */
131638    }else{
131639      rc = nKey1 - nKey2;
131640    }
131641  }
131642  return rc;
131643}
131644
131645/*
131646** Another built-in collating sequence: NOCASE.
131647**
131648** This collating sequence is intended to be used for "case independent
131649** comparison". SQLite's knowledge of upper and lower case equivalents
131650** extends only to the 26 characters used in the English language.
131651**
131652** At the moment there is only a UTF-8 implementation.
131653*/
131654static int nocaseCollatingFunc(
131655  void *NotUsed,
131656  int nKey1, const void *pKey1,
131657  int nKey2, const void *pKey2
131658){
131659  int r = sqlite3StrNICmp(
131660      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
131661  UNUSED_PARAMETER(NotUsed);
131662  if( 0==r ){
131663    r = nKey1-nKey2;
131664  }
131665  return r;
131666}
131667
131668/*
131669** Return the ROWID of the most recent insert
131670*/
131671SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
131672#ifdef SQLITE_ENABLE_API_ARMOR
131673  if( !sqlite3SafetyCheckOk(db) ){
131674    (void)SQLITE_MISUSE_BKPT;
131675    return 0;
131676  }
131677#endif
131678  return db->lastRowid;
131679}
131680
131681/*
131682** Return the number of changes in the most recent call to sqlite3_exec().
131683*/
131684SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
131685#ifdef SQLITE_ENABLE_API_ARMOR
131686  if( !sqlite3SafetyCheckOk(db) ){
131687    (void)SQLITE_MISUSE_BKPT;
131688    return 0;
131689  }
131690#endif
131691  return db->nChange;
131692}
131693
131694/*
131695** Return the number of changes since the database handle was opened.
131696*/
131697SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
131698#ifdef SQLITE_ENABLE_API_ARMOR
131699  if( !sqlite3SafetyCheckOk(db) ){
131700    (void)SQLITE_MISUSE_BKPT;
131701    return 0;
131702  }
131703#endif
131704  return db->nTotalChange;
131705}
131706
131707/*
131708** Close all open savepoints. This function only manipulates fields of the
131709** database handle object, it does not close any savepoints that may be open
131710** at the b-tree/pager level.
131711*/
131712SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
131713  while( db->pSavepoint ){
131714    Savepoint *pTmp = db->pSavepoint;
131715    db->pSavepoint = pTmp->pNext;
131716    sqlite3DbFree(db, pTmp);
131717  }
131718  db->nSavepoint = 0;
131719  db->nStatement = 0;
131720  db->isTransactionSavepoint = 0;
131721}
131722
131723/*
131724** Invoke the destructor function associated with FuncDef p, if any. Except,
131725** if this is not the last copy of the function, do not invoke it. Multiple
131726** copies of a single function are created when create_function() is called
131727** with SQLITE_ANY as the encoding.
131728*/
131729static void functionDestroy(sqlite3 *db, FuncDef *p){
131730  FuncDestructor *pDestructor = p->pDestructor;
131731  if( pDestructor ){
131732    pDestructor->nRef--;
131733    if( pDestructor->nRef==0 ){
131734      pDestructor->xDestroy(pDestructor->pUserData);
131735      sqlite3DbFree(db, pDestructor);
131736    }
131737  }
131738}
131739
131740/*
131741** Disconnect all sqlite3_vtab objects that belong to database connection
131742** db. This is called when db is being closed.
131743*/
131744static void disconnectAllVtab(sqlite3 *db){
131745#ifndef SQLITE_OMIT_VIRTUALTABLE
131746  int i;
131747  HashElem *p;
131748  sqlite3BtreeEnterAll(db);
131749  for(i=0; i<db->nDb; i++){
131750    Schema *pSchema = db->aDb[i].pSchema;
131751    if( db->aDb[i].pSchema ){
131752      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
131753        Table *pTab = (Table *)sqliteHashData(p);
131754        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
131755      }
131756    }
131757  }
131758  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
131759    Module *pMod = (Module *)sqliteHashData(p);
131760    if( pMod->pEpoTab ){
131761      sqlite3VtabDisconnect(db, pMod->pEpoTab);
131762    }
131763  }
131764  sqlite3VtabUnlockList(db);
131765  sqlite3BtreeLeaveAll(db);
131766#else
131767  UNUSED_PARAMETER(db);
131768#endif
131769}
131770
131771/*
131772** Return TRUE if database connection db has unfinalized prepared
131773** statements or unfinished sqlite3_backup objects.
131774*/
131775static int connectionIsBusy(sqlite3 *db){
131776  int j;
131777  assert( sqlite3_mutex_held(db->mutex) );
131778  if( db->pVdbe ) return 1;
131779  for(j=0; j<db->nDb; j++){
131780    Btree *pBt = db->aDb[j].pBt;
131781    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
131782  }
131783  return 0;
131784}
131785
131786/*
131787** Close an existing SQLite database
131788*/
131789static int sqlite3Close(sqlite3 *db, int forceZombie){
131790  if( !db ){
131791    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
131792    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
131793    return SQLITE_OK;
131794  }
131795  if( !sqlite3SafetyCheckSickOrOk(db) ){
131796    return SQLITE_MISUSE_BKPT;
131797  }
131798  sqlite3_mutex_enter(db->mutex);
131799
131800  /* Force xDisconnect calls on all virtual tables */
131801  disconnectAllVtab(db);
131802
131803  /* If a transaction is open, the disconnectAllVtab() call above
131804  ** will not have called the xDisconnect() method on any virtual
131805  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
131806  ** call will do so. We need to do this before the check for active
131807  ** SQL statements below, as the v-table implementation may be storing
131808  ** some prepared statements internally.
131809  */
131810  sqlite3VtabRollback(db);
131811
131812  /* Legacy behavior (sqlite3_close() behavior) is to return
131813  ** SQLITE_BUSY if the connection can not be closed immediately.
131814  */
131815  if( !forceZombie && connectionIsBusy(db) ){
131816    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
131817       "statements or unfinished backups");
131818    sqlite3_mutex_leave(db->mutex);
131819    return SQLITE_BUSY;
131820  }
131821
131822#ifdef SQLITE_ENABLE_SQLLOG
131823  if( sqlite3GlobalConfig.xSqllog ){
131824    /* Closing the handle. Fourth parameter is passed the value 2. */
131825    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
131826  }
131827#endif
131828
131829  /* Convert the connection into a zombie and then close it.
131830  */
131831  db->magic = SQLITE_MAGIC_ZOMBIE;
131832  sqlite3LeaveMutexAndCloseZombie(db);
131833  return SQLITE_OK;
131834}
131835
131836/*
131837** Two variations on the public interface for closing a database
131838** connection. The sqlite3_close() version returns SQLITE_BUSY and
131839** leaves the connection option if there are unfinalized prepared
131840** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
131841** version forces the connection to become a zombie if there are
131842** unclosed resources, and arranges for deallocation when the last
131843** prepare statement or sqlite3_backup closes.
131844*/
131845SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
131846SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
131847
131848
131849/*
131850** Close the mutex on database connection db.
131851**
131852** Furthermore, if database connection db is a zombie (meaning that there
131853** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
131854** every sqlite3_stmt has now been finalized and every sqlite3_backup has
131855** finished, then free all resources.
131856*/
131857SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
131858  HashElem *i;                    /* Hash table iterator */
131859  int j;
131860
131861  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
131862  ** or if the connection has not yet been closed by sqlite3_close_v2(),
131863  ** then just leave the mutex and return.
131864  */
131865  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
131866    sqlite3_mutex_leave(db->mutex);
131867    return;
131868  }
131869
131870  /* If we reach this point, it means that the database connection has
131871  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
131872  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
131873  ** go ahead and free all resources.
131874  */
131875
131876  /* If a transaction is open, roll it back. This also ensures that if
131877  ** any database schemas have been modified by an uncommitted transaction
131878  ** they are reset. And that the required b-tree mutex is held to make
131879  ** the pager rollback and schema reset an atomic operation. */
131880  sqlite3RollbackAll(db, SQLITE_OK);
131881
131882  /* Free any outstanding Savepoint structures. */
131883  sqlite3CloseSavepoints(db);
131884
131885  /* Close all database connections */
131886  for(j=0; j<db->nDb; j++){
131887    struct Db *pDb = &db->aDb[j];
131888    if( pDb->pBt ){
131889      sqlite3BtreeClose(pDb->pBt);
131890      pDb->pBt = 0;
131891      if( j!=1 ){
131892        pDb->pSchema = 0;
131893      }
131894    }
131895  }
131896  /* Clear the TEMP schema separately and last */
131897  if( db->aDb[1].pSchema ){
131898    sqlite3SchemaClear(db->aDb[1].pSchema);
131899  }
131900  sqlite3VtabUnlockList(db);
131901
131902  /* Free up the array of auxiliary databases */
131903  sqlite3CollapseDatabaseArray(db);
131904  assert( db->nDb<=2 );
131905  assert( db->aDb==db->aDbStatic );
131906
131907  /* Tell the code in notify.c that the connection no longer holds any
131908  ** locks and does not require any further unlock-notify callbacks.
131909  */
131910  sqlite3ConnectionClosed(db);
131911
131912  for(j=0; j<ArraySize(db->aFunc.a); j++){
131913    FuncDef *pNext, *pHash, *p;
131914    for(p=db->aFunc.a[j]; p; p=pHash){
131915      pHash = p->pHash;
131916      while( p ){
131917        functionDestroy(db, p);
131918        pNext = p->pNext;
131919        sqlite3DbFree(db, p);
131920        p = pNext;
131921      }
131922    }
131923  }
131924  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
131925    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
131926    /* Invoke any destructors registered for collation sequence user data. */
131927    for(j=0; j<3; j++){
131928      if( pColl[j].xDel ){
131929        pColl[j].xDel(pColl[j].pUser);
131930      }
131931    }
131932    sqlite3DbFree(db, pColl);
131933  }
131934  sqlite3HashClear(&db->aCollSeq);
131935#ifndef SQLITE_OMIT_VIRTUALTABLE
131936  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
131937    Module *pMod = (Module *)sqliteHashData(i);
131938    if( pMod->xDestroy ){
131939      pMod->xDestroy(pMod->pAux);
131940    }
131941    sqlite3VtabEponymousTableClear(db, pMod);
131942    sqlite3DbFree(db, pMod);
131943  }
131944  sqlite3HashClear(&db->aModule);
131945#endif
131946
131947  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
131948  sqlite3ValueFree(db->pErr);
131949  sqlite3CloseExtensions(db);
131950#if SQLITE_USER_AUTHENTICATION
131951  sqlite3_free(db->auth.zAuthUser);
131952  sqlite3_free(db->auth.zAuthPW);
131953#endif
131954
131955  db->magic = SQLITE_MAGIC_ERROR;
131956
131957  /* The temp-database schema is allocated differently from the other schema
131958  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
131959  ** So it needs to be freed here. Todo: Why not roll the temp schema into
131960  ** the same sqliteMalloc() as the one that allocates the database
131961  ** structure?
131962  */
131963  sqlite3DbFree(db, db->aDb[1].pSchema);
131964  sqlite3_mutex_leave(db->mutex);
131965  db->magic = SQLITE_MAGIC_CLOSED;
131966  sqlite3_mutex_free(db->mutex);
131967  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
131968  if( db->lookaside.bMalloced ){
131969    sqlite3_free(db->lookaside.pStart);
131970  }
131971  sqlite3_free(db);
131972}
131973
131974/*
131975** Rollback all database files.  If tripCode is not SQLITE_OK, then
131976** any write cursors are invalidated ("tripped" - as in "tripping a circuit
131977** breaker") and made to return tripCode if there are any further
131978** attempts to use that cursor.  Read cursors remain open and valid
131979** but are "saved" in case the table pages are moved around.
131980*/
131981SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
131982  int i;
131983  int inTrans = 0;
131984  int schemaChange;
131985  assert( sqlite3_mutex_held(db->mutex) );
131986  sqlite3BeginBenignMalloc();
131987
131988  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
131989  ** This is important in case the transaction being rolled back has
131990  ** modified the database schema. If the b-tree mutexes are not taken
131991  ** here, then another shared-cache connection might sneak in between
131992  ** the database rollback and schema reset, which can cause false
131993  ** corruption reports in some cases.  */
131994  sqlite3BtreeEnterAll(db);
131995  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
131996
131997  for(i=0; i<db->nDb; i++){
131998    Btree *p = db->aDb[i].pBt;
131999    if( p ){
132000      if( sqlite3BtreeIsInTrans(p) ){
132001        inTrans = 1;
132002      }
132003      sqlite3BtreeRollback(p, tripCode, !schemaChange);
132004    }
132005  }
132006  sqlite3VtabRollback(db);
132007  sqlite3EndBenignMalloc();
132008
132009  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
132010    sqlite3ExpirePreparedStatements(db);
132011    sqlite3ResetAllSchemasOfConnection(db);
132012  }
132013  sqlite3BtreeLeaveAll(db);
132014
132015  /* Any deferred constraint violations have now been resolved. */
132016  db->nDeferredCons = 0;
132017  db->nDeferredImmCons = 0;
132018  db->flags &= ~SQLITE_DeferFKs;
132019
132020  /* If one has been configured, invoke the rollback-hook callback */
132021  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
132022    db->xRollbackCallback(db->pRollbackArg);
132023  }
132024}
132025
132026/*
132027** Return a static string containing the name corresponding to the error code
132028** specified in the argument.
132029*/
132030#if defined(SQLITE_NEED_ERR_NAME)
132031SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
132032  const char *zName = 0;
132033  int i, origRc = rc;
132034  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
132035    switch( rc ){
132036      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
132037      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
132038      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
132039      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
132040      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
132041      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
132042      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
132043      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
132044      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
132045      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
132046      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
132047      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
132048      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
132049      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
132050      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
132051      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
132052      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
132053      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
132054      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
132055      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
132056      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
132057      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
132058      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
132059      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
132060      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
132061      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
132062      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
132063      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
132064      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
132065      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
132066      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
132067      case SQLITE_IOERR_CHECKRESERVEDLOCK:
132068                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
132069      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
132070      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
132071      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
132072      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
132073      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
132074      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
132075      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
132076      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
132077      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
132078      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
132079      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
132080      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
132081      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
132082      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
132083      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
132084      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
132085      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
132086      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
132087      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
132088      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
132089      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
132090      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
132091      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
132092      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
132093      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
132094      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
132095      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
132096      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
132097      case SQLITE_CONSTRAINT_FOREIGNKEY:
132098                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
132099      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
132100      case SQLITE_CONSTRAINT_PRIMARYKEY:
132101                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
132102      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
132103      case SQLITE_CONSTRAINT_COMMITHOOK:
132104                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
132105      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
132106      case SQLITE_CONSTRAINT_FUNCTION:
132107                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
132108      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
132109      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
132110      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
132111      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
132112      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
132113      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
132114      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
132115      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
132116      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
132117      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
132118      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
132119      case SQLITE_NOTICE_RECOVER_ROLLBACK:
132120                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
132121      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
132122      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
132123      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
132124    }
132125  }
132126  if( zName==0 ){
132127    static char zBuf[50];
132128    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
132129    zName = zBuf;
132130  }
132131  return zName;
132132}
132133#endif
132134
132135/*
132136** Return a static string that describes the kind of error specified in the
132137** argument.
132138*/
132139SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
132140  static const char* const aMsg[] = {
132141    /* SQLITE_OK          */ "not an error",
132142    /* SQLITE_ERROR       */ "SQL logic error or missing database",
132143    /* SQLITE_INTERNAL    */ 0,
132144    /* SQLITE_PERM        */ "access permission denied",
132145    /* SQLITE_ABORT       */ "callback requested query abort",
132146    /* SQLITE_BUSY        */ "database is locked",
132147    /* SQLITE_LOCKED      */ "database table is locked",
132148    /* SQLITE_NOMEM       */ "out of memory",
132149    /* SQLITE_READONLY    */ "attempt to write a readonly database",
132150    /* SQLITE_INTERRUPT   */ "interrupted",
132151    /* SQLITE_IOERR       */ "disk I/O error",
132152    /* SQLITE_CORRUPT     */ "database disk image is malformed",
132153    /* SQLITE_NOTFOUND    */ "unknown operation",
132154    /* SQLITE_FULL        */ "database or disk is full",
132155    /* SQLITE_CANTOPEN    */ "unable to open database file",
132156    /* SQLITE_PROTOCOL    */ "locking protocol",
132157    /* SQLITE_EMPTY       */ "table contains no data",
132158    /* SQLITE_SCHEMA      */ "database schema has changed",
132159    /* SQLITE_TOOBIG      */ "string or blob too big",
132160    /* SQLITE_CONSTRAINT  */ "constraint failed",
132161    /* SQLITE_MISMATCH    */ "datatype mismatch",
132162    /* SQLITE_MISUSE      */ "library routine called out of sequence",
132163    /* SQLITE_NOLFS       */ "large file support is disabled",
132164    /* SQLITE_AUTH        */ "authorization denied",
132165    /* SQLITE_FORMAT      */ "auxiliary database format error",
132166    /* SQLITE_RANGE       */ "bind or column index out of range",
132167    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
132168  };
132169  const char *zErr = "unknown error";
132170  switch( rc ){
132171    case SQLITE_ABORT_ROLLBACK: {
132172      zErr = "abort due to ROLLBACK";
132173      break;
132174    }
132175    default: {
132176      rc &= 0xff;
132177      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
132178        zErr = aMsg[rc];
132179      }
132180      break;
132181    }
132182  }
132183  return zErr;
132184}
132185
132186/*
132187** This routine implements a busy callback that sleeps and tries
132188** again until a timeout value is reached.  The timeout value is
132189** an integer number of milliseconds passed in as the first
132190** argument.
132191*/
132192static int sqliteDefaultBusyCallback(
132193 void *ptr,               /* Database connection */
132194 int count                /* Number of times table has been busy */
132195){
132196#if SQLITE_OS_WIN || HAVE_USLEEP
132197  static const u8 delays[] =
132198     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
132199  static const u8 totals[] =
132200     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
132201# define NDELAY ArraySize(delays)
132202  sqlite3 *db = (sqlite3 *)ptr;
132203  int timeout = db->busyTimeout;
132204  int delay, prior;
132205
132206  assert( count>=0 );
132207  if( count < NDELAY ){
132208    delay = delays[count];
132209    prior = totals[count];
132210  }else{
132211    delay = delays[NDELAY-1];
132212    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
132213  }
132214  if( prior + delay > timeout ){
132215    delay = timeout - prior;
132216    if( delay<=0 ) return 0;
132217  }
132218  sqlite3OsSleep(db->pVfs, delay*1000);
132219  return 1;
132220#else
132221  sqlite3 *db = (sqlite3 *)ptr;
132222  int timeout = ((sqlite3 *)ptr)->busyTimeout;
132223  if( (count+1)*1000 > timeout ){
132224    return 0;
132225  }
132226  sqlite3OsSleep(db->pVfs, 1000000);
132227  return 1;
132228#endif
132229}
132230
132231/*
132232** Invoke the given busy handler.
132233**
132234** This routine is called when an operation failed with a lock.
132235** If this routine returns non-zero, the lock is retried.  If it
132236** returns 0, the operation aborts with an SQLITE_BUSY error.
132237*/
132238SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
132239  int rc;
132240  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
132241  rc = p->xFunc(p->pArg, p->nBusy);
132242  if( rc==0 ){
132243    p->nBusy = -1;
132244  }else{
132245    p->nBusy++;
132246  }
132247  return rc;
132248}
132249
132250/*
132251** This routine sets the busy callback for an Sqlite database to the
132252** given callback function with the given argument.
132253*/
132254SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
132255  sqlite3 *db,
132256  int (*xBusy)(void*,int),
132257  void *pArg
132258){
132259#ifdef SQLITE_ENABLE_API_ARMOR
132260  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132261#endif
132262  sqlite3_mutex_enter(db->mutex);
132263  db->busyHandler.xFunc = xBusy;
132264  db->busyHandler.pArg = pArg;
132265  db->busyHandler.nBusy = 0;
132266  db->busyTimeout = 0;
132267  sqlite3_mutex_leave(db->mutex);
132268  return SQLITE_OK;
132269}
132270
132271#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
132272/*
132273** This routine sets the progress callback for an Sqlite database to the
132274** given callback function with the given argument. The progress callback will
132275** be invoked every nOps opcodes.
132276*/
132277SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
132278  sqlite3 *db,
132279  int nOps,
132280  int (*xProgress)(void*),
132281  void *pArg
132282){
132283#ifdef SQLITE_ENABLE_API_ARMOR
132284  if( !sqlite3SafetyCheckOk(db) ){
132285    (void)SQLITE_MISUSE_BKPT;
132286    return;
132287  }
132288#endif
132289  sqlite3_mutex_enter(db->mutex);
132290  if( nOps>0 ){
132291    db->xProgress = xProgress;
132292    db->nProgressOps = (unsigned)nOps;
132293    db->pProgressArg = pArg;
132294  }else{
132295    db->xProgress = 0;
132296    db->nProgressOps = 0;
132297    db->pProgressArg = 0;
132298  }
132299  sqlite3_mutex_leave(db->mutex);
132300}
132301#endif
132302
132303
132304/*
132305** This routine installs a default busy handler that waits for the
132306** specified number of milliseconds before returning 0.
132307*/
132308SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
132309#ifdef SQLITE_ENABLE_API_ARMOR
132310  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132311#endif
132312  if( ms>0 ){
132313    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
132314    db->busyTimeout = ms;
132315  }else{
132316    sqlite3_busy_handler(db, 0, 0);
132317  }
132318  return SQLITE_OK;
132319}
132320
132321/*
132322** Cause any pending operation to stop at its earliest opportunity.
132323*/
132324SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
132325#ifdef SQLITE_ENABLE_API_ARMOR
132326  if( !sqlite3SafetyCheckOk(db) ){
132327    (void)SQLITE_MISUSE_BKPT;
132328    return;
132329  }
132330#endif
132331  db->u1.isInterrupted = 1;
132332}
132333
132334
132335/*
132336** This function is exactly the same as sqlite3_create_function(), except
132337** that it is designed to be called by internal code. The difference is
132338** that if a malloc() fails in sqlite3_create_function(), an error code
132339** is returned and the mallocFailed flag cleared.
132340*/
132341SQLITE_PRIVATE int sqlite3CreateFunc(
132342  sqlite3 *db,
132343  const char *zFunctionName,
132344  int nArg,
132345  int enc,
132346  void *pUserData,
132347  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132348  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132349  void (*xFinal)(sqlite3_context*),
132350  FuncDestructor *pDestructor
132351){
132352  FuncDef *p;
132353  int nName;
132354  int extraFlags;
132355
132356  assert( sqlite3_mutex_held(db->mutex) );
132357  if( zFunctionName==0 ||
132358      (xFunc && (xFinal || xStep)) ||
132359      (!xFunc && (xFinal && !xStep)) ||
132360      (!xFunc && (!xFinal && xStep)) ||
132361      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
132362      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
132363    return SQLITE_MISUSE_BKPT;
132364  }
132365
132366  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
132367  extraFlags = enc &  SQLITE_DETERMINISTIC;
132368  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
132369
132370#ifndef SQLITE_OMIT_UTF16
132371  /* If SQLITE_UTF16 is specified as the encoding type, transform this
132372  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
132373  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
132374  **
132375  ** If SQLITE_ANY is specified, add three versions of the function
132376  ** to the hash table.
132377  */
132378  if( enc==SQLITE_UTF16 ){
132379    enc = SQLITE_UTF16NATIVE;
132380  }else if( enc==SQLITE_ANY ){
132381    int rc;
132382    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
132383         pUserData, xFunc, xStep, xFinal, pDestructor);
132384    if( rc==SQLITE_OK ){
132385      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
132386          pUserData, xFunc, xStep, xFinal, pDestructor);
132387    }
132388    if( rc!=SQLITE_OK ){
132389      return rc;
132390    }
132391    enc = SQLITE_UTF16BE;
132392  }
132393#else
132394  enc = SQLITE_UTF8;
132395#endif
132396
132397  /* Check if an existing function is being overridden or deleted. If so,
132398  ** and there are active VMs, then return SQLITE_BUSY. If a function
132399  ** is being overridden/deleted but there are no active VMs, allow the
132400  ** operation to continue but invalidate all precompiled statements.
132401  */
132402  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
132403  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
132404    if( db->nVdbeActive ){
132405      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
132406        "unable to delete/modify user-function due to active statements");
132407      assert( !db->mallocFailed );
132408      return SQLITE_BUSY;
132409    }else{
132410      sqlite3ExpirePreparedStatements(db);
132411    }
132412  }
132413
132414  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
132415  assert(p || db->mallocFailed);
132416  if( !p ){
132417    return SQLITE_NOMEM;
132418  }
132419
132420  /* If an older version of the function with a configured destructor is
132421  ** being replaced invoke the destructor function here. */
132422  functionDestroy(db, p);
132423
132424  if( pDestructor ){
132425    pDestructor->nRef++;
132426  }
132427  p->pDestructor = pDestructor;
132428  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
132429  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
132430  p->xFunc = xFunc;
132431  p->xStep = xStep;
132432  p->xFinalize = xFinal;
132433  p->pUserData = pUserData;
132434  p->nArg = (u16)nArg;
132435  return SQLITE_OK;
132436}
132437
132438/*
132439** Create new user functions.
132440*/
132441SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
132442  sqlite3 *db,
132443  const char *zFunc,
132444  int nArg,
132445  int enc,
132446  void *p,
132447  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132448  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132449  void (*xFinal)(sqlite3_context*)
132450){
132451  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
132452                                    xFinal, 0);
132453}
132454
132455SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
132456  sqlite3 *db,
132457  const char *zFunc,
132458  int nArg,
132459  int enc,
132460  void *p,
132461  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132462  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132463  void (*xFinal)(sqlite3_context*),
132464  void (*xDestroy)(void *)
132465){
132466  int rc = SQLITE_ERROR;
132467  FuncDestructor *pArg = 0;
132468
132469#ifdef SQLITE_ENABLE_API_ARMOR
132470  if( !sqlite3SafetyCheckOk(db) ){
132471    return SQLITE_MISUSE_BKPT;
132472  }
132473#endif
132474  sqlite3_mutex_enter(db->mutex);
132475  if( xDestroy ){
132476    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
132477    if( !pArg ){
132478      xDestroy(p);
132479      goto out;
132480    }
132481    pArg->xDestroy = xDestroy;
132482    pArg->pUserData = p;
132483  }
132484  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
132485  if( pArg && pArg->nRef==0 ){
132486    assert( rc!=SQLITE_OK );
132487    xDestroy(p);
132488    sqlite3DbFree(db, pArg);
132489  }
132490
132491 out:
132492  rc = sqlite3ApiExit(db, rc);
132493  sqlite3_mutex_leave(db->mutex);
132494  return rc;
132495}
132496
132497#ifndef SQLITE_OMIT_UTF16
132498SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
132499  sqlite3 *db,
132500  const void *zFunctionName,
132501  int nArg,
132502  int eTextRep,
132503  void *p,
132504  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
132505  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
132506  void (*xFinal)(sqlite3_context*)
132507){
132508  int rc;
132509  char *zFunc8;
132510
132511#ifdef SQLITE_ENABLE_API_ARMOR
132512  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
132513#endif
132514  sqlite3_mutex_enter(db->mutex);
132515  assert( !db->mallocFailed );
132516  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
132517  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
132518  sqlite3DbFree(db, zFunc8);
132519  rc = sqlite3ApiExit(db, rc);
132520  sqlite3_mutex_leave(db->mutex);
132521  return rc;
132522}
132523#endif
132524
132525
132526/*
132527** Declare that a function has been overloaded by a virtual table.
132528**
132529** If the function already exists as a regular global function, then
132530** this routine is a no-op.  If the function does not exist, then create
132531** a new one that always throws a run-time error.
132532**
132533** When virtual tables intend to provide an overloaded function, they
132534** should call this routine to make sure the global function exists.
132535** A global function must exist in order for name resolution to work
132536** properly.
132537*/
132538SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
132539  sqlite3 *db,
132540  const char *zName,
132541  int nArg
132542){
132543  int nName = sqlite3Strlen30(zName);
132544  int rc = SQLITE_OK;
132545
132546#ifdef SQLITE_ENABLE_API_ARMOR
132547  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
132548    return SQLITE_MISUSE_BKPT;
132549  }
132550#endif
132551  sqlite3_mutex_enter(db->mutex);
132552  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
132553    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
132554                           0, sqlite3InvalidFunction, 0, 0, 0);
132555  }
132556  rc = sqlite3ApiExit(db, rc);
132557  sqlite3_mutex_leave(db->mutex);
132558  return rc;
132559}
132560
132561#ifndef SQLITE_OMIT_TRACE
132562/*
132563** Register a trace function.  The pArg from the previously registered trace
132564** is returned.
132565**
132566** A NULL trace function means that no tracing is executes.  A non-NULL
132567** trace is a pointer to a function that is invoked at the start of each
132568** SQL statement.
132569*/
132570SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
132571  void *pOld;
132572
132573#ifdef SQLITE_ENABLE_API_ARMOR
132574  if( !sqlite3SafetyCheckOk(db) ){
132575    (void)SQLITE_MISUSE_BKPT;
132576    return 0;
132577  }
132578#endif
132579  sqlite3_mutex_enter(db->mutex);
132580  pOld = db->pTraceArg;
132581  db->xTrace = xTrace;
132582  db->pTraceArg = pArg;
132583  sqlite3_mutex_leave(db->mutex);
132584  return pOld;
132585}
132586/*
132587** Register a profile function.  The pArg from the previously registered
132588** profile function is returned.
132589**
132590** A NULL profile function means that no profiling is executes.  A non-NULL
132591** profile is a pointer to a function that is invoked at the conclusion of
132592** each SQL statement that is run.
132593*/
132594SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
132595  sqlite3 *db,
132596  void (*xProfile)(void*,const char*,sqlite_uint64),
132597  void *pArg
132598){
132599  void *pOld;
132600
132601#ifdef SQLITE_ENABLE_API_ARMOR
132602  if( !sqlite3SafetyCheckOk(db) ){
132603    (void)SQLITE_MISUSE_BKPT;
132604    return 0;
132605  }
132606#endif
132607  sqlite3_mutex_enter(db->mutex);
132608  pOld = db->pProfileArg;
132609  db->xProfile = xProfile;
132610  db->pProfileArg = pArg;
132611  sqlite3_mutex_leave(db->mutex);
132612  return pOld;
132613}
132614#endif /* SQLITE_OMIT_TRACE */
132615
132616/*
132617** Register a function to be invoked when a transaction commits.
132618** If the invoked function returns non-zero, then the commit becomes a
132619** rollback.
132620*/
132621SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
132622  sqlite3 *db,              /* Attach the hook to this database */
132623  int (*xCallback)(void*),  /* Function to invoke on each commit */
132624  void *pArg                /* Argument to the function */
132625){
132626  void *pOld;
132627
132628#ifdef SQLITE_ENABLE_API_ARMOR
132629  if( !sqlite3SafetyCheckOk(db) ){
132630    (void)SQLITE_MISUSE_BKPT;
132631    return 0;
132632  }
132633#endif
132634  sqlite3_mutex_enter(db->mutex);
132635  pOld = db->pCommitArg;
132636  db->xCommitCallback = xCallback;
132637  db->pCommitArg = pArg;
132638  sqlite3_mutex_leave(db->mutex);
132639  return pOld;
132640}
132641
132642/*
132643** Register a callback to be invoked each time a row is updated,
132644** inserted or deleted using this database connection.
132645*/
132646SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
132647  sqlite3 *db,              /* Attach the hook to this database */
132648  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
132649  void *pArg                /* Argument to the function */
132650){
132651  void *pRet;
132652
132653#ifdef SQLITE_ENABLE_API_ARMOR
132654  if( !sqlite3SafetyCheckOk(db) ){
132655    (void)SQLITE_MISUSE_BKPT;
132656    return 0;
132657  }
132658#endif
132659  sqlite3_mutex_enter(db->mutex);
132660  pRet = db->pUpdateArg;
132661  db->xUpdateCallback = xCallback;
132662  db->pUpdateArg = pArg;
132663  sqlite3_mutex_leave(db->mutex);
132664  return pRet;
132665}
132666
132667/*
132668** Register a callback to be invoked each time a transaction is rolled
132669** back by this database connection.
132670*/
132671SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
132672  sqlite3 *db,              /* Attach the hook to this database */
132673  void (*xCallback)(void*), /* Callback function */
132674  void *pArg                /* Argument to the function */
132675){
132676  void *pRet;
132677
132678#ifdef SQLITE_ENABLE_API_ARMOR
132679  if( !sqlite3SafetyCheckOk(db) ){
132680    (void)SQLITE_MISUSE_BKPT;
132681    return 0;
132682  }
132683#endif
132684  sqlite3_mutex_enter(db->mutex);
132685  pRet = db->pRollbackArg;
132686  db->xRollbackCallback = xCallback;
132687  db->pRollbackArg = pArg;
132688  sqlite3_mutex_leave(db->mutex);
132689  return pRet;
132690}
132691
132692#ifndef SQLITE_OMIT_WAL
132693/*
132694** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
132695** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
132696** is greater than sqlite3.pWalArg cast to an integer (the value configured by
132697** wal_autocheckpoint()).
132698*/
132699SQLITE_PRIVATE int sqlite3WalDefaultHook(
132700  void *pClientData,     /* Argument */
132701  sqlite3 *db,           /* Connection */
132702  const char *zDb,       /* Database */
132703  int nFrame             /* Size of WAL */
132704){
132705  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
132706    sqlite3BeginBenignMalloc();
132707    sqlite3_wal_checkpoint(db, zDb);
132708    sqlite3EndBenignMalloc();
132709  }
132710  return SQLITE_OK;
132711}
132712#endif /* SQLITE_OMIT_WAL */
132713
132714/*
132715** Configure an sqlite3_wal_hook() callback to automatically checkpoint
132716** a database after committing a transaction if there are nFrame or
132717** more frames in the log file. Passing zero or a negative value as the
132718** nFrame parameter disables automatic checkpoints entirely.
132719**
132720** The callback registered by this function replaces any existing callback
132721** registered using sqlite3_wal_hook(). Likewise, registering a callback
132722** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
132723** configured by this function.
132724*/
132725SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
132726#ifdef SQLITE_OMIT_WAL
132727  UNUSED_PARAMETER(db);
132728  UNUSED_PARAMETER(nFrame);
132729#else
132730#ifdef SQLITE_ENABLE_API_ARMOR
132731  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132732#endif
132733  if( nFrame>0 ){
132734    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
132735  }else{
132736    sqlite3_wal_hook(db, 0, 0);
132737  }
132738#endif
132739  return SQLITE_OK;
132740}
132741
132742/*
132743** Register a callback to be invoked each time a transaction is written
132744** into the write-ahead-log by this database connection.
132745*/
132746SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
132747  sqlite3 *db,                    /* Attach the hook to this db handle */
132748  int(*xCallback)(void *, sqlite3*, const char*, int),
132749  void *pArg                      /* First argument passed to xCallback() */
132750){
132751#ifndef SQLITE_OMIT_WAL
132752  void *pRet;
132753#ifdef SQLITE_ENABLE_API_ARMOR
132754  if( !sqlite3SafetyCheckOk(db) ){
132755    (void)SQLITE_MISUSE_BKPT;
132756    return 0;
132757  }
132758#endif
132759  sqlite3_mutex_enter(db->mutex);
132760  pRet = db->pWalArg;
132761  db->xWalCallback = xCallback;
132762  db->pWalArg = pArg;
132763  sqlite3_mutex_leave(db->mutex);
132764  return pRet;
132765#else
132766  return 0;
132767#endif
132768}
132769
132770/*
132771** Checkpoint database zDb.
132772*/
132773SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
132774  sqlite3 *db,                    /* Database handle */
132775  const char *zDb,                /* Name of attached database (or NULL) */
132776  int eMode,                      /* SQLITE_CHECKPOINT_* value */
132777  int *pnLog,                     /* OUT: Size of WAL log in frames */
132778  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
132779){
132780#ifdef SQLITE_OMIT_WAL
132781  return SQLITE_OK;
132782#else
132783  int rc;                         /* Return code */
132784  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
132785
132786#ifdef SQLITE_ENABLE_API_ARMOR
132787  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132788#endif
132789
132790  /* Initialize the output variables to -1 in case an error occurs. */
132791  if( pnLog ) *pnLog = -1;
132792  if( pnCkpt ) *pnCkpt = -1;
132793
132794  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
132795  assert( SQLITE_CHECKPOINT_FULL==1 );
132796  assert( SQLITE_CHECKPOINT_RESTART==2 );
132797  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
132798  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
132799    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
132800    ** mode: */
132801    return SQLITE_MISUSE;
132802  }
132803
132804  sqlite3_mutex_enter(db->mutex);
132805  if( zDb && zDb[0] ){
132806    iDb = sqlite3FindDbName(db, zDb);
132807  }
132808  if( iDb<0 ){
132809    rc = SQLITE_ERROR;
132810    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
132811  }else{
132812    db->busyHandler.nBusy = 0;
132813    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
132814    sqlite3Error(db, rc);
132815  }
132816  rc = sqlite3ApiExit(db, rc);
132817  sqlite3_mutex_leave(db->mutex);
132818  return rc;
132819#endif
132820}
132821
132822
132823/*
132824** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
132825** to contains a zero-length string, all attached databases are
132826** checkpointed.
132827*/
132828SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
132829  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
132830  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
132831  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
132832}
132833
132834#ifndef SQLITE_OMIT_WAL
132835/*
132836** Run a checkpoint on database iDb. This is a no-op if database iDb is
132837** not currently open in WAL mode.
132838**
132839** If a transaction is open on the database being checkpointed, this
132840** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
132841** an error occurs while running the checkpoint, an SQLite error code is
132842** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
132843**
132844** The mutex on database handle db should be held by the caller. The mutex
132845** associated with the specific b-tree being checkpointed is taken by
132846** this function while the checkpoint is running.
132847**
132848** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
132849** checkpointed. If an error is encountered it is returned immediately -
132850** no attempt is made to checkpoint any remaining databases.
132851**
132852** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
132853*/
132854SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
132855  int rc = SQLITE_OK;             /* Return code */
132856  int i;                          /* Used to iterate through attached dbs */
132857  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
132858
132859  assert( sqlite3_mutex_held(db->mutex) );
132860  assert( !pnLog || *pnLog==-1 );
132861  assert( !pnCkpt || *pnCkpt==-1 );
132862
132863  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
132864    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
132865      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
132866      pnLog = 0;
132867      pnCkpt = 0;
132868      if( rc==SQLITE_BUSY ){
132869        bBusy = 1;
132870        rc = SQLITE_OK;
132871      }
132872    }
132873  }
132874
132875  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
132876}
132877#endif /* SQLITE_OMIT_WAL */
132878
132879/*
132880** This function returns true if main-memory should be used instead of
132881** a temporary file for transient pager files and statement journals.
132882** The value returned depends on the value of db->temp_store (runtime
132883** parameter) and the compile time value of SQLITE_TEMP_STORE. The
132884** following table describes the relationship between these two values
132885** and this functions return value.
132886**
132887**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
132888**   -----------------     --------------     ------------------------------
132889**   0                     any                file      (return 0)
132890**   1                     1                  file      (return 0)
132891**   1                     2                  memory    (return 1)
132892**   1                     0                  file      (return 0)
132893**   2                     1                  file      (return 0)
132894**   2                     2                  memory    (return 1)
132895**   2                     0                  memory    (return 1)
132896**   3                     any                memory    (return 1)
132897*/
132898SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
132899#if SQLITE_TEMP_STORE==1
132900  return ( db->temp_store==2 );
132901#endif
132902#if SQLITE_TEMP_STORE==2
132903  return ( db->temp_store!=1 );
132904#endif
132905#if SQLITE_TEMP_STORE==3
132906  UNUSED_PARAMETER(db);
132907  return 1;
132908#endif
132909#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
132910  UNUSED_PARAMETER(db);
132911  return 0;
132912#endif
132913}
132914
132915/*
132916** Return UTF-8 encoded English language explanation of the most recent
132917** error.
132918*/
132919SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
132920  const char *z;
132921  if( !db ){
132922    return sqlite3ErrStr(SQLITE_NOMEM);
132923  }
132924  if( !sqlite3SafetyCheckSickOrOk(db) ){
132925    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
132926  }
132927  sqlite3_mutex_enter(db->mutex);
132928  if( db->mallocFailed ){
132929    z = sqlite3ErrStr(SQLITE_NOMEM);
132930  }else{
132931    testcase( db->pErr==0 );
132932    z = (char*)sqlite3_value_text(db->pErr);
132933    assert( !db->mallocFailed );
132934    if( z==0 ){
132935      z = sqlite3ErrStr(db->errCode);
132936    }
132937  }
132938  sqlite3_mutex_leave(db->mutex);
132939  return z;
132940}
132941
132942#ifndef SQLITE_OMIT_UTF16
132943/*
132944** Return UTF-16 encoded English language explanation of the most recent
132945** error.
132946*/
132947SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
132948  static const u16 outOfMem[] = {
132949    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
132950  };
132951  static const u16 misuse[] = {
132952    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
132953    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
132954    'c', 'a', 'l', 'l', 'e', 'd', ' ',
132955    'o', 'u', 't', ' ',
132956    'o', 'f', ' ',
132957    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
132958  };
132959
132960  const void *z;
132961  if( !db ){
132962    return (void *)outOfMem;
132963  }
132964  if( !sqlite3SafetyCheckSickOrOk(db) ){
132965    return (void *)misuse;
132966  }
132967  sqlite3_mutex_enter(db->mutex);
132968  if( db->mallocFailed ){
132969    z = (void *)outOfMem;
132970  }else{
132971    z = sqlite3_value_text16(db->pErr);
132972    if( z==0 ){
132973      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
132974      z = sqlite3_value_text16(db->pErr);
132975    }
132976    /* A malloc() may have failed within the call to sqlite3_value_text16()
132977    ** above. If this is the case, then the db->mallocFailed flag needs to
132978    ** be cleared before returning. Do this directly, instead of via
132979    ** sqlite3ApiExit(), to avoid setting the database handle error message.
132980    */
132981    db->mallocFailed = 0;
132982  }
132983  sqlite3_mutex_leave(db->mutex);
132984  return z;
132985}
132986#endif /* SQLITE_OMIT_UTF16 */
132987
132988/*
132989** Return the most recent error code generated by an SQLite routine. If NULL is
132990** passed to this function, we assume a malloc() failed during sqlite3_open().
132991*/
132992SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
132993  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
132994    return SQLITE_MISUSE_BKPT;
132995  }
132996  if( !db || db->mallocFailed ){
132997    return SQLITE_NOMEM;
132998  }
132999  return db->errCode & db->errMask;
133000}
133001SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
133002  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
133003    return SQLITE_MISUSE_BKPT;
133004  }
133005  if( !db || db->mallocFailed ){
133006    return SQLITE_NOMEM;
133007  }
133008  return db->errCode;
133009}
133010
133011/*
133012** Return a string that describes the kind of error specified in the
133013** argument.  For now, this simply calls the internal sqlite3ErrStr()
133014** function.
133015*/
133016SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
133017  return sqlite3ErrStr(rc);
133018}
133019
133020/*
133021** Create a new collating function for database "db".  The name is zName
133022** and the encoding is enc.
133023*/
133024static int createCollation(
133025  sqlite3* db,
133026  const char *zName,
133027  u8 enc,
133028  void* pCtx,
133029  int(*xCompare)(void*,int,const void*,int,const void*),
133030  void(*xDel)(void*)
133031){
133032  CollSeq *pColl;
133033  int enc2;
133034
133035  assert( sqlite3_mutex_held(db->mutex) );
133036
133037  /* If SQLITE_UTF16 is specified as the encoding type, transform this
133038  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
133039  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
133040  */
133041  enc2 = enc;
133042  testcase( enc2==SQLITE_UTF16 );
133043  testcase( enc2==SQLITE_UTF16_ALIGNED );
133044  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
133045    enc2 = SQLITE_UTF16NATIVE;
133046  }
133047  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
133048    return SQLITE_MISUSE_BKPT;
133049  }
133050
133051  /* Check if this call is removing or replacing an existing collation
133052  ** sequence. If so, and there are active VMs, return busy. If there
133053  ** are no active VMs, invalidate any pre-compiled statements.
133054  */
133055  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
133056  if( pColl && pColl->xCmp ){
133057    if( db->nVdbeActive ){
133058      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
133059        "unable to delete/modify collation sequence due to active statements");
133060      return SQLITE_BUSY;
133061    }
133062    sqlite3ExpirePreparedStatements(db);
133063
133064    /* If collation sequence pColl was created directly by a call to
133065    ** sqlite3_create_collation, and not generated by synthCollSeq(),
133066    ** then any copies made by synthCollSeq() need to be invalidated.
133067    ** Also, collation destructor - CollSeq.xDel() - function may need
133068    ** to be called.
133069    */
133070    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
133071      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
133072      int j;
133073      for(j=0; j<3; j++){
133074        CollSeq *p = &aColl[j];
133075        if( p->enc==pColl->enc ){
133076          if( p->xDel ){
133077            p->xDel(p->pUser);
133078          }
133079          p->xCmp = 0;
133080        }
133081      }
133082    }
133083  }
133084
133085  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
133086  if( pColl==0 ) return SQLITE_NOMEM;
133087  pColl->xCmp = xCompare;
133088  pColl->pUser = pCtx;
133089  pColl->xDel = xDel;
133090  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
133091  sqlite3Error(db, SQLITE_OK);
133092  return SQLITE_OK;
133093}
133094
133095
133096/*
133097** This array defines hard upper bounds on limit values.  The
133098** initializer must be kept in sync with the SQLITE_LIMIT_*
133099** #defines in sqlite3.h.
133100*/
133101static const int aHardLimit[] = {
133102  SQLITE_MAX_LENGTH,
133103  SQLITE_MAX_SQL_LENGTH,
133104  SQLITE_MAX_COLUMN,
133105  SQLITE_MAX_EXPR_DEPTH,
133106  SQLITE_MAX_COMPOUND_SELECT,
133107  SQLITE_MAX_VDBE_OP,
133108  SQLITE_MAX_FUNCTION_ARG,
133109  SQLITE_MAX_ATTACHED,
133110  SQLITE_MAX_LIKE_PATTERN_LENGTH,
133111  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
133112  SQLITE_MAX_TRIGGER_DEPTH,
133113  SQLITE_MAX_WORKER_THREADS,
133114};
133115
133116/*
133117** Make sure the hard limits are set to reasonable values
133118*/
133119#if SQLITE_MAX_LENGTH<100
133120# error SQLITE_MAX_LENGTH must be at least 100
133121#endif
133122#if SQLITE_MAX_SQL_LENGTH<100
133123# error SQLITE_MAX_SQL_LENGTH must be at least 100
133124#endif
133125#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
133126# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
133127#endif
133128#if SQLITE_MAX_COMPOUND_SELECT<2
133129# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
133130#endif
133131#if SQLITE_MAX_VDBE_OP<40
133132# error SQLITE_MAX_VDBE_OP must be at least 40
133133#endif
133134#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
133135# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
133136#endif
133137#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
133138# error SQLITE_MAX_ATTACHED must be between 0 and 125
133139#endif
133140#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
133141# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
133142#endif
133143#if SQLITE_MAX_COLUMN>32767
133144# error SQLITE_MAX_COLUMN must not exceed 32767
133145#endif
133146#if SQLITE_MAX_TRIGGER_DEPTH<1
133147# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
133148#endif
133149#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
133150# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
133151#endif
133152
133153
133154/*
133155** Change the value of a limit.  Report the old value.
133156** If an invalid limit index is supplied, report -1.
133157** Make no changes but still report the old value if the
133158** new limit is negative.
133159**
133160** A new lower limit does not shrink existing constructs.
133161** It merely prevents new constructs that exceed the limit
133162** from forming.
133163*/
133164SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
133165  int oldLimit;
133166
133167#ifdef SQLITE_ENABLE_API_ARMOR
133168  if( !sqlite3SafetyCheckOk(db) ){
133169    (void)SQLITE_MISUSE_BKPT;
133170    return -1;
133171  }
133172#endif
133173
133174  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
133175  ** there is a hard upper bound set at compile-time by a C preprocessor
133176  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
133177  ** "_MAX_".)
133178  */
133179  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
133180  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
133181  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
133182  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
133183  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
133184  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
133185  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
133186  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
133187  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
133188                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
133189  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
133190  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
133191  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
133192  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
133193
133194
133195  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
133196    return -1;
133197  }
133198  oldLimit = db->aLimit[limitId];
133199  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
133200    if( newLimit>aHardLimit[limitId] ){
133201      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
133202    }
133203    db->aLimit[limitId] = newLimit;
133204  }
133205  return oldLimit;                     /* IMP: R-53341-35419 */
133206}
133207
133208/*
133209** This function is used to parse both URIs and non-URI filenames passed by the
133210** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
133211** URIs specified as part of ATTACH statements.
133212**
133213** The first argument to this function is the name of the VFS to use (or
133214** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
133215** query parameter. The second argument contains the URI (or non-URI filename)
133216** itself. When this function is called the *pFlags variable should contain
133217** the default flags to open the database handle with. The value stored in
133218** *pFlags may be updated before returning if the URI filename contains
133219** "cache=xxx" or "mode=xxx" query parameters.
133220**
133221** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
133222** the VFS that should be used to open the database file. *pzFile is set to
133223** point to a buffer containing the name of the file to open. It is the
133224** responsibility of the caller to eventually call sqlite3_free() to release
133225** this buffer.
133226**
133227** If an error occurs, then an SQLite error code is returned and *pzErrMsg
133228** may be set to point to a buffer containing an English language error
133229** message. It is the responsibility of the caller to eventually release
133230** this buffer by calling sqlite3_free().
133231*/
133232SQLITE_PRIVATE int sqlite3ParseUri(
133233  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
133234  const char *zUri,               /* Nul-terminated URI to parse */
133235  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
133236  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
133237  char **pzFile,                  /* OUT: Filename component of URI */
133238  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
133239){
133240  int rc = SQLITE_OK;
133241  unsigned int flags = *pFlags;
133242  const char *zVfs = zDefaultVfs;
133243  char *zFile;
133244  char c;
133245  int nUri = sqlite3Strlen30(zUri);
133246
133247  assert( *pzErrMsg==0 );
133248
133249  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
133250            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
133251   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
133252  ){
133253    char *zOpt;
133254    int eState;                   /* Parser state when parsing URI */
133255    int iIn;                      /* Input character index */
133256    int iOut = 0;                 /* Output character index */
133257    u64 nByte = nUri+2;           /* Bytes of space to allocate */
133258
133259    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
133260    ** method that there may be extra parameters following the file-name.  */
133261    flags |= SQLITE_OPEN_URI;
133262
133263    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
133264    zFile = sqlite3_malloc64(nByte);
133265    if( !zFile ) return SQLITE_NOMEM;
133266
133267    iIn = 5;
133268#ifdef SQLITE_ALLOW_URI_AUTHORITY
133269    if( strncmp(zUri+5, "///", 3)==0 ){
133270      iIn = 7;
133271      /* The following condition causes URIs with five leading / characters
133272      ** like file://///host/path to be converted into UNCs like //host/path.
133273      ** The correct URI for that UNC has only two or four leading / characters
133274      ** file://host/path or file:////host/path.  But 5 leading slashes is a
133275      ** common error, we are told, so we handle it as a special case. */
133276      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
133277    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
133278      iIn = 16;
133279    }
133280#else
133281    /* Discard the scheme and authority segments of the URI. */
133282    if( zUri[5]=='/' && zUri[6]=='/' ){
133283      iIn = 7;
133284      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
133285      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
133286        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
133287            iIn-7, &zUri[7]);
133288        rc = SQLITE_ERROR;
133289        goto parse_uri_out;
133290      }
133291    }
133292#endif
133293
133294    /* Copy the filename and any query parameters into the zFile buffer.
133295    ** Decode %HH escape codes along the way.
133296    **
133297    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
133298    ** on the parsing context. As follows:
133299    **
133300    **   0: Parsing file-name.
133301    **   1: Parsing name section of a name=value query parameter.
133302    **   2: Parsing value section of a name=value query parameter.
133303    */
133304    eState = 0;
133305    while( (c = zUri[iIn])!=0 && c!='#' ){
133306      iIn++;
133307      if( c=='%'
133308       && sqlite3Isxdigit(zUri[iIn])
133309       && sqlite3Isxdigit(zUri[iIn+1])
133310      ){
133311        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
133312        octet += sqlite3HexToInt(zUri[iIn++]);
133313
133314        assert( octet>=0 && octet<256 );
133315        if( octet==0 ){
133316          /* This branch is taken when "%00" appears within the URI. In this
133317          ** case we ignore all text in the remainder of the path, name or
133318          ** value currently being parsed. So ignore the current character
133319          ** and skip to the next "?", "=" or "&", as appropriate. */
133320          while( (c = zUri[iIn])!=0 && c!='#'
133321              && (eState!=0 || c!='?')
133322              && (eState!=1 || (c!='=' && c!='&'))
133323              && (eState!=2 || c!='&')
133324          ){
133325            iIn++;
133326          }
133327          continue;
133328        }
133329        c = octet;
133330      }else if( eState==1 && (c=='&' || c=='=') ){
133331        if( zFile[iOut-1]==0 ){
133332          /* An empty option name. Ignore this option altogether. */
133333          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
133334          continue;
133335        }
133336        if( c=='&' ){
133337          zFile[iOut++] = '\0';
133338        }else{
133339          eState = 2;
133340        }
133341        c = 0;
133342      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
133343        c = 0;
133344        eState = 1;
133345      }
133346      zFile[iOut++] = c;
133347    }
133348    if( eState==1 ) zFile[iOut++] = '\0';
133349    zFile[iOut++] = '\0';
133350    zFile[iOut++] = '\0';
133351
133352    /* Check if there were any options specified that should be interpreted
133353    ** here. Options that are interpreted here include "vfs" and those that
133354    ** correspond to flags that may be passed to the sqlite3_open_v2()
133355    ** method. */
133356    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
133357    while( zOpt[0] ){
133358      int nOpt = sqlite3Strlen30(zOpt);
133359      char *zVal = &zOpt[nOpt+1];
133360      int nVal = sqlite3Strlen30(zVal);
133361
133362      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
133363        zVfs = zVal;
133364      }else{
133365        struct OpenMode {
133366          const char *z;
133367          int mode;
133368        } *aMode = 0;
133369        char *zModeType = 0;
133370        int mask = 0;
133371        int limit = 0;
133372
133373        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
133374          static struct OpenMode aCacheMode[] = {
133375            { "shared",  SQLITE_OPEN_SHAREDCACHE },
133376            { "private", SQLITE_OPEN_PRIVATECACHE },
133377            { 0, 0 }
133378          };
133379
133380          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
133381          aMode = aCacheMode;
133382          limit = mask;
133383          zModeType = "cache";
133384        }
133385        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
133386          static struct OpenMode aOpenMode[] = {
133387            { "ro",  SQLITE_OPEN_READONLY },
133388            { "rw",  SQLITE_OPEN_READWRITE },
133389            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
133390            { "memory", SQLITE_OPEN_MEMORY },
133391            { 0, 0 }
133392          };
133393
133394          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
133395                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
133396          aMode = aOpenMode;
133397          limit = mask & flags;
133398          zModeType = "access";
133399        }
133400
133401        if( aMode ){
133402          int i;
133403          int mode = 0;
133404          for(i=0; aMode[i].z; i++){
133405            const char *z = aMode[i].z;
133406            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
133407              mode = aMode[i].mode;
133408              break;
133409            }
133410          }
133411          if( mode==0 ){
133412            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
133413            rc = SQLITE_ERROR;
133414            goto parse_uri_out;
133415          }
133416          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
133417            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
133418                                        zModeType, zVal);
133419            rc = SQLITE_PERM;
133420            goto parse_uri_out;
133421          }
133422          flags = (flags & ~mask) | mode;
133423        }
133424      }
133425
133426      zOpt = &zVal[nVal+1];
133427    }
133428
133429  }else{
133430    zFile = sqlite3_malloc64(nUri+2);
133431    if( !zFile ) return SQLITE_NOMEM;
133432    memcpy(zFile, zUri, nUri);
133433    zFile[nUri] = '\0';
133434    zFile[nUri+1] = '\0';
133435    flags &= ~SQLITE_OPEN_URI;
133436  }
133437
133438  *ppVfs = sqlite3_vfs_find(zVfs);
133439  if( *ppVfs==0 ){
133440    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
133441    rc = SQLITE_ERROR;
133442  }
133443 parse_uri_out:
133444  if( rc!=SQLITE_OK ){
133445    sqlite3_free(zFile);
133446    zFile = 0;
133447  }
133448  *pFlags = flags;
133449  *pzFile = zFile;
133450  return rc;
133451}
133452
133453
133454/*
133455** This routine does the work of opening a database on behalf of
133456** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
133457** is UTF-8 encoded.
133458*/
133459static int openDatabase(
133460  const char *zFilename, /* Database filename UTF-8 encoded */
133461  sqlite3 **ppDb,        /* OUT: Returned database handle */
133462  unsigned int flags,    /* Operational flags */
133463  const char *zVfs       /* Name of the VFS to use */
133464){
133465  sqlite3 *db;                    /* Store allocated handle here */
133466  int rc;                         /* Return code */
133467  int isThreadsafe;               /* True for threadsafe connections */
133468  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
133469  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
133470
133471#ifdef SQLITE_ENABLE_API_ARMOR
133472  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
133473#endif
133474  *ppDb = 0;
133475#ifndef SQLITE_OMIT_AUTOINIT
133476  rc = sqlite3_initialize();
133477  if( rc ) return rc;
133478#endif
133479
133480  /* Only allow sensible combinations of bits in the flags argument.
133481  ** Throw an error if any non-sense combination is used.  If we
133482  ** do not block illegal combinations here, it could trigger
133483  ** assert() statements in deeper layers.  Sensible combinations
133484  ** are:
133485  **
133486  **  1:  SQLITE_OPEN_READONLY
133487  **  2:  SQLITE_OPEN_READWRITE
133488  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
133489  */
133490  assert( SQLITE_OPEN_READONLY  == 0x01 );
133491  assert( SQLITE_OPEN_READWRITE == 0x02 );
133492  assert( SQLITE_OPEN_CREATE    == 0x04 );
133493  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
133494  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
133495  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
133496  if( ((1<<(flags&7)) & 0x46)==0 ){
133497    return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
133498  }
133499
133500  if( sqlite3GlobalConfig.bCoreMutex==0 ){
133501    isThreadsafe = 0;
133502  }else if( flags & SQLITE_OPEN_NOMUTEX ){
133503    isThreadsafe = 0;
133504  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
133505    isThreadsafe = 1;
133506  }else{
133507    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
133508  }
133509  if( flags & SQLITE_OPEN_PRIVATECACHE ){
133510    flags &= ~SQLITE_OPEN_SHAREDCACHE;
133511  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
133512    flags |= SQLITE_OPEN_SHAREDCACHE;
133513  }
133514
133515  /* Remove harmful bits from the flags parameter
133516  **
133517  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
133518  ** dealt with in the previous code block.  Besides these, the only
133519  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
133520  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
133521  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
133522  ** off all other flags.
133523  */
133524  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
133525               SQLITE_OPEN_EXCLUSIVE |
133526               SQLITE_OPEN_MAIN_DB |
133527               SQLITE_OPEN_TEMP_DB |
133528               SQLITE_OPEN_TRANSIENT_DB |
133529               SQLITE_OPEN_MAIN_JOURNAL |
133530               SQLITE_OPEN_TEMP_JOURNAL |
133531               SQLITE_OPEN_SUBJOURNAL |
133532               SQLITE_OPEN_MASTER_JOURNAL |
133533               SQLITE_OPEN_NOMUTEX |
133534               SQLITE_OPEN_FULLMUTEX |
133535               SQLITE_OPEN_WAL
133536             );
133537
133538  /* Allocate the sqlite data structure */
133539  db = sqlite3MallocZero( sizeof(sqlite3) );
133540  if( db==0 ) goto opendb_out;
133541  if( isThreadsafe ){
133542    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
133543    if( db->mutex==0 ){
133544      sqlite3_free(db);
133545      db = 0;
133546      goto opendb_out;
133547    }
133548  }
133549  sqlite3_mutex_enter(db->mutex);
133550  db->errMask = 0xff;
133551  db->nDb = 2;
133552  db->magic = SQLITE_MAGIC_BUSY;
133553  db->aDb = db->aDbStatic;
133554
133555  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
133556  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
133557  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
133558  db->autoCommit = 1;
133559  db->nextAutovac = -1;
133560  db->szMmap = sqlite3GlobalConfig.szMmap;
133561  db->nextPagesize = 0;
133562  db->nMaxSorterMmap = 0x7FFFFFFF;
133563  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
133564#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
133565                 | SQLITE_AutoIndex
133566#endif
133567#if SQLITE_DEFAULT_CKPTFULLFSYNC
133568                 | SQLITE_CkptFullFSync
133569#endif
133570#if SQLITE_DEFAULT_FILE_FORMAT<4
133571                 | SQLITE_LegacyFileFmt
133572#endif
133573#ifdef SQLITE_ENABLE_LOAD_EXTENSION
133574                 | SQLITE_LoadExtension
133575#endif
133576#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
133577                 | SQLITE_RecTriggers
133578#endif
133579#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
133580                 | SQLITE_ForeignKeys
133581#endif
133582#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
133583                 | SQLITE_ReverseOrder
133584#endif
133585#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
133586                 | SQLITE_CellSizeCk
133587#endif
133588      ;
133589  sqlite3HashInit(&db->aCollSeq);
133590#ifndef SQLITE_OMIT_VIRTUALTABLE
133591  sqlite3HashInit(&db->aModule);
133592#endif
133593
133594  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
133595  ** and UTF-16, so add a version for each to avoid any unnecessary
133596  ** conversions. The only error that can occur here is a malloc() failure.
133597  **
133598  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
133599  ** functions:
133600  */
133601  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
133602  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
133603  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
133604  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
133605  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
133606  if( db->mallocFailed ){
133607    goto opendb_out;
133608  }
133609  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
133610  ** strings is BINARY.
133611  */
133612  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
133613  assert( db->pDfltColl!=0 );
133614
133615  /* Parse the filename/URI argument. */
133616  db->openFlags = flags;
133617  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
133618  if( rc!=SQLITE_OK ){
133619    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
133620    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
133621    sqlite3_free(zErrMsg);
133622    goto opendb_out;
133623  }
133624
133625  /* Open the backend database driver */
133626  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
133627                        flags | SQLITE_OPEN_MAIN_DB);
133628  if( rc!=SQLITE_OK ){
133629    if( rc==SQLITE_IOERR_NOMEM ){
133630      rc = SQLITE_NOMEM;
133631    }
133632    sqlite3Error(db, rc);
133633    goto opendb_out;
133634  }
133635  sqlite3BtreeEnter(db->aDb[0].pBt);
133636  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
133637  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
133638  sqlite3BtreeLeave(db->aDb[0].pBt);
133639  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
133640
133641  /* The default safety_level for the main database is 'full'; for the temp
133642  ** database it is 'NONE'. This matches the pager layer defaults.
133643  */
133644  db->aDb[0].zName = "main";
133645  db->aDb[0].safety_level = 3;
133646  db->aDb[1].zName = "temp";
133647  db->aDb[1].safety_level = 1;
133648
133649  db->magic = SQLITE_MAGIC_OPEN;
133650  if( db->mallocFailed ){
133651    goto opendb_out;
133652  }
133653
133654  /* Register all built-in functions, but do not attempt to read the
133655  ** database schema yet. This is delayed until the first time the database
133656  ** is accessed.
133657  */
133658  sqlite3Error(db, SQLITE_OK);
133659  sqlite3RegisterBuiltinFunctions(db);
133660
133661  /* Load automatic extensions - extensions that have been registered
133662  ** using the sqlite3_automatic_extension() API.
133663  */
133664  rc = sqlite3_errcode(db);
133665  if( rc==SQLITE_OK ){
133666    sqlite3AutoLoadExtensions(db);
133667    rc = sqlite3_errcode(db);
133668    if( rc!=SQLITE_OK ){
133669      goto opendb_out;
133670    }
133671  }
133672
133673#ifdef SQLITE_ENABLE_FTS1
133674  if( !db->mallocFailed ){
133675    extern int sqlite3Fts1Init(sqlite3*);
133676    rc = sqlite3Fts1Init(db);
133677  }
133678#endif
133679
133680#ifdef SQLITE_ENABLE_FTS2
133681  if( !db->mallocFailed && rc==SQLITE_OK ){
133682    extern int sqlite3Fts2Init(sqlite3*);
133683    rc = sqlite3Fts2Init(db);
133684  }
133685#endif
133686
133687#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
133688  if( !db->mallocFailed && rc==SQLITE_OK ){
133689    rc = sqlite3Fts3Init(db);
133690  }
133691#endif
133692
133693#ifdef SQLITE_ENABLE_FTS5
133694  if( !db->mallocFailed && rc==SQLITE_OK ){
133695    rc = sqlite3Fts5Init(db);
133696  }
133697#endif
133698
133699#ifdef SQLITE_ENABLE_ICU
133700  if( !db->mallocFailed && rc==SQLITE_OK ){
133701    rc = sqlite3IcuInit(db);
133702  }
133703#endif
133704
133705#ifdef SQLITE_ENABLE_RTREE
133706  if( !db->mallocFailed && rc==SQLITE_OK){
133707    rc = sqlite3RtreeInit(db);
133708  }
133709#endif
133710
133711#ifdef SQLITE_ENABLE_DBSTAT_VTAB
133712  if( !db->mallocFailed && rc==SQLITE_OK){
133713    rc = sqlite3DbstatRegister(db);
133714  }
133715#endif
133716
133717#ifdef SQLITE_ENABLE_JSON1
133718  if( !db->mallocFailed && rc==SQLITE_OK){
133719    rc = sqlite3Json1Init(db);
133720  }
133721#endif
133722
133723  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
133724  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
133725  ** mode.  Doing nothing at all also makes NORMAL the default.
133726  */
133727#ifdef SQLITE_DEFAULT_LOCKING_MODE
133728  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
133729  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
133730                          SQLITE_DEFAULT_LOCKING_MODE);
133731#endif
133732
133733  if( rc ) sqlite3Error(db, rc);
133734
133735  /* Enable the lookaside-malloc subsystem */
133736  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
133737                        sqlite3GlobalConfig.nLookaside);
133738
133739  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
133740
133741opendb_out:
133742  sqlite3_free(zOpen);
133743  if( db ){
133744    assert( db->mutex!=0 || isThreadsafe==0
133745           || sqlite3GlobalConfig.bFullMutex==0 );
133746    sqlite3_mutex_leave(db->mutex);
133747  }
133748  rc = sqlite3_errcode(db);
133749  assert( db!=0 || rc==SQLITE_NOMEM );
133750  if( rc==SQLITE_NOMEM ){
133751    sqlite3_close(db);
133752    db = 0;
133753  }else if( rc!=SQLITE_OK ){
133754    db->magic = SQLITE_MAGIC_SICK;
133755  }
133756  *ppDb = db;
133757#ifdef SQLITE_ENABLE_SQLLOG
133758  if( sqlite3GlobalConfig.xSqllog ){
133759    /* Opening a db handle. Fourth parameter is passed 0. */
133760    void *pArg = sqlite3GlobalConfig.pSqllogArg;
133761    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
133762  }
133763#endif
133764  return rc & 0xff;
133765}
133766
133767/*
133768** Open a new database handle.
133769*/
133770SQLITE_API int SQLITE_STDCALL sqlite3_open(
133771  const char *zFilename,
133772  sqlite3 **ppDb
133773){
133774  return openDatabase(zFilename, ppDb,
133775                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
133776}
133777SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
133778  const char *filename,   /* Database filename (UTF-8) */
133779  sqlite3 **ppDb,         /* OUT: SQLite db handle */
133780  int flags,              /* Flags */
133781  const char *zVfs        /* Name of VFS module to use */
133782){
133783  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
133784}
133785
133786#ifndef SQLITE_OMIT_UTF16
133787/*
133788** Open a new database handle.
133789*/
133790SQLITE_API int SQLITE_STDCALL sqlite3_open16(
133791  const void *zFilename,
133792  sqlite3 **ppDb
133793){
133794  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
133795  sqlite3_value *pVal;
133796  int rc;
133797
133798#ifdef SQLITE_ENABLE_API_ARMOR
133799  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
133800#endif
133801  *ppDb = 0;
133802#ifndef SQLITE_OMIT_AUTOINIT
133803  rc = sqlite3_initialize();
133804  if( rc ) return rc;
133805#endif
133806  if( zFilename==0 ) zFilename = "\000\000";
133807  pVal = sqlite3ValueNew(0);
133808  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
133809  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
133810  if( zFilename8 ){
133811    rc = openDatabase(zFilename8, ppDb,
133812                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
133813    assert( *ppDb || rc==SQLITE_NOMEM );
133814    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
133815      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
133816    }
133817  }else{
133818    rc = SQLITE_NOMEM;
133819  }
133820  sqlite3ValueFree(pVal);
133821
133822  return rc & 0xff;
133823}
133824#endif /* SQLITE_OMIT_UTF16 */
133825
133826/*
133827** Register a new collation sequence with the database handle db.
133828*/
133829SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
133830  sqlite3* db,
133831  const char *zName,
133832  int enc,
133833  void* pCtx,
133834  int(*xCompare)(void*,int,const void*,int,const void*)
133835){
133836  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
133837}
133838
133839/*
133840** Register a new collation sequence with the database handle db.
133841*/
133842SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
133843  sqlite3* db,
133844  const char *zName,
133845  int enc,
133846  void* pCtx,
133847  int(*xCompare)(void*,int,const void*,int,const void*),
133848  void(*xDel)(void*)
133849){
133850  int rc;
133851
133852#ifdef SQLITE_ENABLE_API_ARMOR
133853  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
133854#endif
133855  sqlite3_mutex_enter(db->mutex);
133856  assert( !db->mallocFailed );
133857  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
133858  rc = sqlite3ApiExit(db, rc);
133859  sqlite3_mutex_leave(db->mutex);
133860  return rc;
133861}
133862
133863#ifndef SQLITE_OMIT_UTF16
133864/*
133865** Register a new collation sequence with the database handle db.
133866*/
133867SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
133868  sqlite3* db,
133869  const void *zName,
133870  int enc,
133871  void* pCtx,
133872  int(*xCompare)(void*,int,const void*,int,const void*)
133873){
133874  int rc = SQLITE_OK;
133875  char *zName8;
133876
133877#ifdef SQLITE_ENABLE_API_ARMOR
133878  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
133879#endif
133880  sqlite3_mutex_enter(db->mutex);
133881  assert( !db->mallocFailed );
133882  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
133883  if( zName8 ){
133884    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
133885    sqlite3DbFree(db, zName8);
133886  }
133887  rc = sqlite3ApiExit(db, rc);
133888  sqlite3_mutex_leave(db->mutex);
133889  return rc;
133890}
133891#endif /* SQLITE_OMIT_UTF16 */
133892
133893/*
133894** Register a collation sequence factory callback with the database handle
133895** db. Replace any previously installed collation sequence factory.
133896*/
133897SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
133898  sqlite3 *db,
133899  void *pCollNeededArg,
133900  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
133901){
133902#ifdef SQLITE_ENABLE_API_ARMOR
133903  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
133904#endif
133905  sqlite3_mutex_enter(db->mutex);
133906  db->xCollNeeded = xCollNeeded;
133907  db->xCollNeeded16 = 0;
133908  db->pCollNeededArg = pCollNeededArg;
133909  sqlite3_mutex_leave(db->mutex);
133910  return SQLITE_OK;
133911}
133912
133913#ifndef SQLITE_OMIT_UTF16
133914/*
133915** Register a collation sequence factory callback with the database handle
133916** db. Replace any previously installed collation sequence factory.
133917*/
133918SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
133919  sqlite3 *db,
133920  void *pCollNeededArg,
133921  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
133922){
133923#ifdef SQLITE_ENABLE_API_ARMOR
133924  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
133925#endif
133926  sqlite3_mutex_enter(db->mutex);
133927  db->xCollNeeded = 0;
133928  db->xCollNeeded16 = xCollNeeded16;
133929  db->pCollNeededArg = pCollNeededArg;
133930  sqlite3_mutex_leave(db->mutex);
133931  return SQLITE_OK;
133932}
133933#endif /* SQLITE_OMIT_UTF16 */
133934
133935#ifndef SQLITE_OMIT_DEPRECATED
133936/*
133937** This function is now an anachronism. It used to be used to recover from a
133938** malloc() failure, but SQLite now does this automatically.
133939*/
133940SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
133941  return SQLITE_OK;
133942}
133943#endif
133944
133945/*
133946** Test to see whether or not the database connection is in autocommit
133947** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
133948** by default.  Autocommit is disabled by a BEGIN statement and reenabled
133949** by the next COMMIT or ROLLBACK.
133950*/
133951SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
133952#ifdef SQLITE_ENABLE_API_ARMOR
133953  if( !sqlite3SafetyCheckOk(db) ){
133954    (void)SQLITE_MISUSE_BKPT;
133955    return 0;
133956  }
133957#endif
133958  return db->autoCommit;
133959}
133960
133961/*
133962** The following routines are substitutes for constants SQLITE_CORRUPT,
133963** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
133964** constants.  They serve two purposes:
133965**
133966**   1.  Serve as a convenient place to set a breakpoint in a debugger
133967**       to detect when version error conditions occurs.
133968**
133969**   2.  Invoke sqlite3_log() to provide the source code location where
133970**       a low-level error is first detected.
133971*/
133972SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
133973  testcase( sqlite3GlobalConfig.xLog!=0 );
133974  sqlite3_log(SQLITE_CORRUPT,
133975              "database corruption at line %d of [%.10s]",
133976              lineno, 20+sqlite3_sourceid());
133977  return SQLITE_CORRUPT;
133978}
133979SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
133980  testcase( sqlite3GlobalConfig.xLog!=0 );
133981  sqlite3_log(SQLITE_MISUSE,
133982              "misuse at line %d of [%.10s]",
133983              lineno, 20+sqlite3_sourceid());
133984  return SQLITE_MISUSE;
133985}
133986SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
133987  testcase( sqlite3GlobalConfig.xLog!=0 );
133988  sqlite3_log(SQLITE_CANTOPEN,
133989              "cannot open file at line %d of [%.10s]",
133990              lineno, 20+sqlite3_sourceid());
133991  return SQLITE_CANTOPEN;
133992}
133993
133994
133995#ifndef SQLITE_OMIT_DEPRECATED
133996/*
133997** This is a convenience routine that makes sure that all thread-specific
133998** data for this thread has been deallocated.
133999**
134000** SQLite no longer uses thread-specific data so this routine is now a
134001** no-op.  It is retained for historical compatibility.
134002*/
134003SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
134004}
134005#endif
134006
134007/*
134008** Return meta information about a specific column of a database table.
134009** See comment in sqlite3.h (sqlite.h.in) for details.
134010*/
134011SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
134012  sqlite3 *db,                /* Connection handle */
134013  const char *zDbName,        /* Database name or NULL */
134014  const char *zTableName,     /* Table name */
134015  const char *zColumnName,    /* Column name */
134016  char const **pzDataType,    /* OUTPUT: Declared data type */
134017  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
134018  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
134019  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
134020  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
134021){
134022  int rc;
134023  char *zErrMsg = 0;
134024  Table *pTab = 0;
134025  Column *pCol = 0;
134026  int iCol = 0;
134027  char const *zDataType = 0;
134028  char const *zCollSeq = 0;
134029  int notnull = 0;
134030  int primarykey = 0;
134031  int autoinc = 0;
134032
134033
134034#ifdef SQLITE_ENABLE_API_ARMOR
134035  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
134036    return SQLITE_MISUSE_BKPT;
134037  }
134038#endif
134039
134040  /* Ensure the database schema has been loaded */
134041  sqlite3_mutex_enter(db->mutex);
134042  sqlite3BtreeEnterAll(db);
134043  rc = sqlite3Init(db, &zErrMsg);
134044  if( SQLITE_OK!=rc ){
134045    goto error_out;
134046  }
134047
134048  /* Locate the table in question */
134049  pTab = sqlite3FindTable(db, zTableName, zDbName);
134050  if( !pTab || pTab->pSelect ){
134051    pTab = 0;
134052    goto error_out;
134053  }
134054
134055  /* Find the column for which info is requested */
134056  if( zColumnName==0 ){
134057    /* Query for existance of table only */
134058  }else{
134059    for(iCol=0; iCol<pTab->nCol; iCol++){
134060      pCol = &pTab->aCol[iCol];
134061      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
134062        break;
134063      }
134064    }
134065    if( iCol==pTab->nCol ){
134066      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
134067        iCol = pTab->iPKey;
134068        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
134069      }else{
134070        pTab = 0;
134071        goto error_out;
134072      }
134073    }
134074  }
134075
134076  /* The following block stores the meta information that will be returned
134077  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
134078  ** and autoinc. At this point there are two possibilities:
134079  **
134080  **     1. The specified column name was rowid", "oid" or "_rowid_"
134081  **        and there is no explicitly declared IPK column.
134082  **
134083  **     2. The table is not a view and the column name identified an
134084  **        explicitly declared column. Copy meta information from *pCol.
134085  */
134086  if( pCol ){
134087    zDataType = pCol->zType;
134088    zCollSeq = pCol->zColl;
134089    notnull = pCol->notNull!=0;
134090    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
134091    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
134092  }else{
134093    zDataType = "INTEGER";
134094    primarykey = 1;
134095  }
134096  if( !zCollSeq ){
134097    zCollSeq = "BINARY";
134098  }
134099
134100error_out:
134101  sqlite3BtreeLeaveAll(db);
134102
134103  /* Whether the function call succeeded or failed, set the output parameters
134104  ** to whatever their local counterparts contain. If an error did occur,
134105  ** this has the effect of zeroing all output parameters.
134106  */
134107  if( pzDataType ) *pzDataType = zDataType;
134108  if( pzCollSeq ) *pzCollSeq = zCollSeq;
134109  if( pNotNull ) *pNotNull = notnull;
134110  if( pPrimaryKey ) *pPrimaryKey = primarykey;
134111  if( pAutoinc ) *pAutoinc = autoinc;
134112
134113  if( SQLITE_OK==rc && !pTab ){
134114    sqlite3DbFree(db, zErrMsg);
134115    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
134116        zColumnName);
134117    rc = SQLITE_ERROR;
134118  }
134119  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
134120  sqlite3DbFree(db, zErrMsg);
134121  rc = sqlite3ApiExit(db, rc);
134122  sqlite3_mutex_leave(db->mutex);
134123  return rc;
134124}
134125
134126/*
134127** Sleep for a little while.  Return the amount of time slept.
134128*/
134129SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
134130  sqlite3_vfs *pVfs;
134131  int rc;
134132  pVfs = sqlite3_vfs_find(0);
134133  if( pVfs==0 ) return 0;
134134
134135  /* This function works in milliseconds, but the underlying OsSleep()
134136  ** API uses microseconds. Hence the 1000's.
134137  */
134138  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
134139  return rc;
134140}
134141
134142/*
134143** Enable or disable the extended result codes.
134144*/
134145SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
134146#ifdef SQLITE_ENABLE_API_ARMOR
134147  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
134148#endif
134149  sqlite3_mutex_enter(db->mutex);
134150  db->errMask = onoff ? 0xffffffff : 0xff;
134151  sqlite3_mutex_leave(db->mutex);
134152  return SQLITE_OK;
134153}
134154
134155/*
134156** Invoke the xFileControl method on a particular database.
134157*/
134158SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
134159  int rc = SQLITE_ERROR;
134160  Btree *pBtree;
134161
134162#ifdef SQLITE_ENABLE_API_ARMOR
134163  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
134164#endif
134165  sqlite3_mutex_enter(db->mutex);
134166  pBtree = sqlite3DbNameToBtree(db, zDbName);
134167  if( pBtree ){
134168    Pager *pPager;
134169    sqlite3_file *fd;
134170    sqlite3BtreeEnter(pBtree);
134171    pPager = sqlite3BtreePager(pBtree);
134172    assert( pPager!=0 );
134173    fd = sqlite3PagerFile(pPager);
134174    assert( fd!=0 );
134175    if( op==SQLITE_FCNTL_FILE_POINTER ){
134176      *(sqlite3_file**)pArg = fd;
134177      rc = SQLITE_OK;
134178    }else if( fd->pMethods ){
134179      rc = sqlite3OsFileControl(fd, op, pArg);
134180    }else{
134181      rc = SQLITE_NOTFOUND;
134182    }
134183    sqlite3BtreeLeave(pBtree);
134184  }
134185  sqlite3_mutex_leave(db->mutex);
134186  return rc;
134187}
134188
134189/*
134190** Interface to the testing logic.
134191*/
134192SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
134193  int rc = 0;
134194#ifdef SQLITE_OMIT_BUILTIN_TEST
134195  UNUSED_PARAMETER(op);
134196#else
134197  va_list ap;
134198  va_start(ap, op);
134199  switch( op ){
134200
134201    /*
134202    ** Save the current state of the PRNG.
134203    */
134204    case SQLITE_TESTCTRL_PRNG_SAVE: {
134205      sqlite3PrngSaveState();
134206      break;
134207    }
134208
134209    /*
134210    ** Restore the state of the PRNG to the last state saved using
134211    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
134212    ** this verb acts like PRNG_RESET.
134213    */
134214    case SQLITE_TESTCTRL_PRNG_RESTORE: {
134215      sqlite3PrngRestoreState();
134216      break;
134217    }
134218
134219    /*
134220    ** Reset the PRNG back to its uninitialized state.  The next call
134221    ** to sqlite3_randomness() will reseed the PRNG using a single call
134222    ** to the xRandomness method of the default VFS.
134223    */
134224    case SQLITE_TESTCTRL_PRNG_RESET: {
134225      sqlite3_randomness(0,0);
134226      break;
134227    }
134228
134229    /*
134230    **  sqlite3_test_control(BITVEC_TEST, size, program)
134231    **
134232    ** Run a test against a Bitvec object of size.  The program argument
134233    ** is an array of integers that defines the test.  Return -1 on a
134234    ** memory allocation error, 0 on success, or non-zero for an error.
134235    ** See the sqlite3BitvecBuiltinTest() for additional information.
134236    */
134237    case SQLITE_TESTCTRL_BITVEC_TEST: {
134238      int sz = va_arg(ap, int);
134239      int *aProg = va_arg(ap, int*);
134240      rc = sqlite3BitvecBuiltinTest(sz, aProg);
134241      break;
134242    }
134243
134244    /*
134245    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
134246    **
134247    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
134248    ** if xCallback is not NULL.
134249    **
134250    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
134251    ** is called immediately after installing the new callback and the return
134252    ** value from sqlite3FaultSim(0) becomes the return from
134253    ** sqlite3_test_control().
134254    */
134255    case SQLITE_TESTCTRL_FAULT_INSTALL: {
134256      /* MSVC is picky about pulling func ptrs from va lists.
134257      ** http://support.microsoft.com/kb/47961
134258      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
134259      */
134260      typedef int(*TESTCALLBACKFUNC_t)(int);
134261      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
134262      rc = sqlite3FaultSim(0);
134263      break;
134264    }
134265
134266    /*
134267    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
134268    **
134269    ** Register hooks to call to indicate which malloc() failures
134270    ** are benign.
134271    */
134272    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
134273      typedef void (*void_function)(void);
134274      void_function xBenignBegin;
134275      void_function xBenignEnd;
134276      xBenignBegin = va_arg(ap, void_function);
134277      xBenignEnd = va_arg(ap, void_function);
134278      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
134279      break;
134280    }
134281
134282    /*
134283    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
134284    **
134285    ** Set the PENDING byte to the value in the argument, if X>0.
134286    ** Make no changes if X==0.  Return the value of the pending byte
134287    ** as it existing before this routine was called.
134288    **
134289    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
134290    ** an incompatible database file format.  Changing the PENDING byte
134291    ** while any database connection is open results in undefined and
134292    ** deleterious behavior.
134293    */
134294    case SQLITE_TESTCTRL_PENDING_BYTE: {
134295      rc = PENDING_BYTE;
134296#ifndef SQLITE_OMIT_WSD
134297      {
134298        unsigned int newVal = va_arg(ap, unsigned int);
134299        if( newVal ) sqlite3PendingByte = newVal;
134300      }
134301#endif
134302      break;
134303    }
134304
134305    /*
134306    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
134307    **
134308    ** This action provides a run-time test to see whether or not
134309    ** assert() was enabled at compile-time.  If X is true and assert()
134310    ** is enabled, then the return value is true.  If X is true and
134311    ** assert() is disabled, then the return value is zero.  If X is
134312    ** false and assert() is enabled, then the assertion fires and the
134313    ** process aborts.  If X is false and assert() is disabled, then the
134314    ** return value is zero.
134315    */
134316    case SQLITE_TESTCTRL_ASSERT: {
134317      volatile int x = 0;
134318      assert( (x = va_arg(ap,int))!=0 );
134319      rc = x;
134320      break;
134321    }
134322
134323
134324    /*
134325    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
134326    **
134327    ** This action provides a run-time test to see how the ALWAYS and
134328    ** NEVER macros were defined at compile-time.
134329    **
134330    ** The return value is ALWAYS(X).
134331    **
134332    ** The recommended test is X==2.  If the return value is 2, that means
134333    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
134334    ** default setting.  If the return value is 1, then ALWAYS() is either
134335    ** hard-coded to true or else it asserts if its argument is false.
134336    ** The first behavior (hard-coded to true) is the case if
134337    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
134338    ** behavior (assert if the argument to ALWAYS() is false) is the case if
134339    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
134340    **
134341    ** The run-time test procedure might look something like this:
134342    **
134343    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
134344    **      // ALWAYS() and NEVER() are no-op pass-through macros
134345    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
134346    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
134347    **    }else{
134348    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
134349    **    }
134350    */
134351    case SQLITE_TESTCTRL_ALWAYS: {
134352      int x = va_arg(ap,int);
134353      rc = ALWAYS(x);
134354      break;
134355    }
134356
134357    /*
134358    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
134359    **
134360    ** The integer returned reveals the byte-order of the computer on which
134361    ** SQLite is running:
134362    **
134363    **       1     big-endian,    determined at run-time
134364    **      10     little-endian, determined at run-time
134365    **  432101     big-endian,    determined at compile-time
134366    **  123410     little-endian, determined at compile-time
134367    */
134368    case SQLITE_TESTCTRL_BYTEORDER: {
134369      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
134370      break;
134371    }
134372
134373    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
134374    **
134375    ** Set the nReserve size to N for the main database on the database
134376    ** connection db.
134377    */
134378    case SQLITE_TESTCTRL_RESERVE: {
134379      sqlite3 *db = va_arg(ap, sqlite3*);
134380      int x = va_arg(ap,int);
134381      sqlite3_mutex_enter(db->mutex);
134382      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
134383      sqlite3_mutex_leave(db->mutex);
134384      break;
134385    }
134386
134387    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
134388    **
134389    ** Enable or disable various optimizations for testing purposes.  The
134390    ** argument N is a bitmask of optimizations to be disabled.  For normal
134391    ** operation N should be 0.  The idea is that a test program (like the
134392    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
134393    ** with various optimizations disabled to verify that the same answer
134394    ** is obtained in every case.
134395    */
134396    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
134397      sqlite3 *db = va_arg(ap, sqlite3*);
134398      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
134399      break;
134400    }
134401
134402#ifdef SQLITE_N_KEYWORD
134403    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
134404    **
134405    ** If zWord is a keyword recognized by the parser, then return the
134406    ** number of keywords.  Or if zWord is not a keyword, return 0.
134407    **
134408    ** This test feature is only available in the amalgamation since
134409    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
134410    ** is built using separate source files.
134411    */
134412    case SQLITE_TESTCTRL_ISKEYWORD: {
134413      const char *zWord = va_arg(ap, const char*);
134414      int n = sqlite3Strlen30(zWord);
134415      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
134416      break;
134417    }
134418#endif
134419
134420    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
134421    **
134422    ** Pass pFree into sqlite3ScratchFree().
134423    ** If sz>0 then allocate a scratch buffer into pNew.
134424    */
134425    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
134426      void *pFree, **ppNew;
134427      int sz;
134428      sz = va_arg(ap, int);
134429      ppNew = va_arg(ap, void**);
134430      pFree = va_arg(ap, void*);
134431      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
134432      sqlite3ScratchFree(pFree);
134433      break;
134434    }
134435
134436    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
134437    **
134438    ** If parameter onoff is non-zero, configure the wrappers so that all
134439    ** subsequent calls to localtime() and variants fail. If onoff is zero,
134440    ** undo this setting.
134441    */
134442    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
134443      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
134444      break;
134445    }
134446
134447    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
134448    **
134449    ** Set or clear a flag that indicates that the database file is always well-
134450    ** formed and never corrupt.  This flag is clear by default, indicating that
134451    ** database files might have arbitrary corruption.  Setting the flag during
134452    ** testing causes certain assert() statements in the code to be activated
134453    ** that demonstrat invariants on well-formed database files.
134454    */
134455    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
134456      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
134457      break;
134458    }
134459
134460
134461    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
134462    **
134463    ** Set the VDBE coverage callback function to xCallback with context
134464    ** pointer ptr.
134465    */
134466    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
134467#ifdef SQLITE_VDBE_COVERAGE
134468      typedef void (*branch_callback)(void*,int,u8,u8);
134469      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
134470      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
134471#endif
134472      break;
134473    }
134474
134475    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
134476    case SQLITE_TESTCTRL_SORTER_MMAP: {
134477      sqlite3 *db = va_arg(ap, sqlite3*);
134478      db->nMaxSorterMmap = va_arg(ap, int);
134479      break;
134480    }
134481
134482    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
134483    **
134484    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
134485    ** not.
134486    */
134487    case SQLITE_TESTCTRL_ISINIT: {
134488      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
134489      break;
134490    }
134491
134492    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
134493    **
134494    ** This test control is used to create imposter tables.  "db" is a pointer
134495    ** to the database connection.  dbName is the database name (ex: "main" or
134496    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
134497    ** or off.  "tnum" is the root page of the b-tree to which the imposter
134498    ** table should connect.
134499    **
134500    ** Enable imposter mode only when the schema has already been parsed.  Then
134501    ** run a single CREATE TABLE statement to construct the imposter table in
134502    ** the parsed schema.  Then turn imposter mode back off again.
134503    **
134504    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
134505    ** the schema to be reparsed the next time it is needed.  This has the
134506    ** effect of erasing all imposter tables.
134507    */
134508    case SQLITE_TESTCTRL_IMPOSTER: {
134509      sqlite3 *db = va_arg(ap, sqlite3*);
134510      sqlite3_mutex_enter(db->mutex);
134511      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
134512      db->init.busy = db->init.imposterTable = va_arg(ap,int);
134513      db->init.newTnum = va_arg(ap,int);
134514      if( db->init.busy==0 && db->init.newTnum>0 ){
134515        sqlite3ResetAllSchemasOfConnection(db);
134516      }
134517      sqlite3_mutex_leave(db->mutex);
134518      break;
134519    }
134520  }
134521  va_end(ap);
134522#endif /* SQLITE_OMIT_BUILTIN_TEST */
134523  return rc;
134524}
134525
134526/*
134527** This is a utility routine, useful to VFS implementations, that checks
134528** to see if a database file was a URI that contained a specific query
134529** parameter, and if so obtains the value of the query parameter.
134530**
134531** The zFilename argument is the filename pointer passed into the xOpen()
134532** method of a VFS implementation.  The zParam argument is the name of the
134533** query parameter we seek.  This routine returns the value of the zParam
134534** parameter if it exists.  If the parameter does not exist, this routine
134535** returns a NULL pointer.
134536*/
134537SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
134538  if( zFilename==0 || zParam==0 ) return 0;
134539  zFilename += sqlite3Strlen30(zFilename) + 1;
134540  while( zFilename[0] ){
134541    int x = strcmp(zFilename, zParam);
134542    zFilename += sqlite3Strlen30(zFilename) + 1;
134543    if( x==0 ) return zFilename;
134544    zFilename += sqlite3Strlen30(zFilename) + 1;
134545  }
134546  return 0;
134547}
134548
134549/*
134550** Return a boolean value for a query parameter.
134551*/
134552SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
134553  const char *z = sqlite3_uri_parameter(zFilename, zParam);
134554  bDflt = bDflt!=0;
134555  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
134556}
134557
134558/*
134559** Return a 64-bit integer value for a query parameter.
134560*/
134561SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
134562  const char *zFilename,    /* Filename as passed to xOpen */
134563  const char *zParam,       /* URI parameter sought */
134564  sqlite3_int64 bDflt       /* return if parameter is missing */
134565){
134566  const char *z = sqlite3_uri_parameter(zFilename, zParam);
134567  sqlite3_int64 v;
134568  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
134569    bDflt = v;
134570  }
134571  return bDflt;
134572}
134573
134574/*
134575** Return the Btree pointer identified by zDbName.  Return NULL if not found.
134576*/
134577SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
134578  int i;
134579  for(i=0; i<db->nDb; i++){
134580    if( db->aDb[i].pBt
134581     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
134582    ){
134583      return db->aDb[i].pBt;
134584    }
134585  }
134586  return 0;
134587}
134588
134589/*
134590** Return the filename of the database associated with a database
134591** connection.
134592*/
134593SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
134594  Btree *pBt;
134595#ifdef SQLITE_ENABLE_API_ARMOR
134596  if( !sqlite3SafetyCheckOk(db) ){
134597    (void)SQLITE_MISUSE_BKPT;
134598    return 0;
134599  }
134600#endif
134601  pBt = sqlite3DbNameToBtree(db, zDbName);
134602  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
134603}
134604
134605/*
134606** Return 1 if database is read-only or 0 if read/write.  Return -1 if
134607** no such database exists.
134608*/
134609SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
134610  Btree *pBt;
134611#ifdef SQLITE_ENABLE_API_ARMOR
134612  if( !sqlite3SafetyCheckOk(db) ){
134613    (void)SQLITE_MISUSE_BKPT;
134614    return -1;
134615  }
134616#endif
134617  pBt = sqlite3DbNameToBtree(db, zDbName);
134618  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
134619}
134620
134621/************** End of main.c ************************************************/
134622/************** Begin file notify.c ******************************************/
134623/*
134624** 2009 March 3
134625**
134626** The author disclaims copyright to this source code.  In place of
134627** a legal notice, here is a blessing:
134628**
134629**    May you do good and not evil.
134630**    May you find forgiveness for yourself and forgive others.
134631**    May you share freely, never taking more than you give.
134632**
134633*************************************************************************
134634**
134635** This file contains the implementation of the sqlite3_unlock_notify()
134636** API method and its associated functionality.
134637*/
134638/* #include "sqliteInt.h" */
134639/* #include "btreeInt.h" */
134640
134641/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
134642#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
134643
134644/*
134645** Public interfaces:
134646**
134647**   sqlite3ConnectionBlocked()
134648**   sqlite3ConnectionUnlocked()
134649**   sqlite3ConnectionClosed()
134650**   sqlite3_unlock_notify()
134651*/
134652
134653#define assertMutexHeld() \
134654  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
134655
134656/*
134657** Head of a linked list of all sqlite3 objects created by this process
134658** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
134659** is not NULL. This variable may only accessed while the STATIC_MASTER
134660** mutex is held.
134661*/
134662static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
134663
134664#ifndef NDEBUG
134665/*
134666** This function is a complex assert() that verifies the following
134667** properties of the blocked connections list:
134668**
134669**   1) Each entry in the list has a non-NULL value for either
134670**      pUnlockConnection or pBlockingConnection, or both.
134671**
134672**   2) All entries in the list that share a common value for
134673**      xUnlockNotify are grouped together.
134674**
134675**   3) If the argument db is not NULL, then none of the entries in the
134676**      blocked connections list have pUnlockConnection or pBlockingConnection
134677**      set to db. This is used when closing connection db.
134678*/
134679static void checkListProperties(sqlite3 *db){
134680  sqlite3 *p;
134681  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
134682    int seen = 0;
134683    sqlite3 *p2;
134684
134685    /* Verify property (1) */
134686    assert( p->pUnlockConnection || p->pBlockingConnection );
134687
134688    /* Verify property (2) */
134689    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
134690      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
134691      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
134692      assert( db==0 || p->pUnlockConnection!=db );
134693      assert( db==0 || p->pBlockingConnection!=db );
134694    }
134695  }
134696}
134697#else
134698# define checkListProperties(x)
134699#endif
134700
134701/*
134702** Remove connection db from the blocked connections list. If connection
134703** db is not currently a part of the list, this function is a no-op.
134704*/
134705static void removeFromBlockedList(sqlite3 *db){
134706  sqlite3 **pp;
134707  assertMutexHeld();
134708  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
134709    if( *pp==db ){
134710      *pp = (*pp)->pNextBlocked;
134711      break;
134712    }
134713  }
134714}
134715
134716/*
134717** Add connection db to the blocked connections list. It is assumed
134718** that it is not already a part of the list.
134719*/
134720static void addToBlockedList(sqlite3 *db){
134721  sqlite3 **pp;
134722  assertMutexHeld();
134723  for(
134724    pp=&sqlite3BlockedList;
134725    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
134726    pp=&(*pp)->pNextBlocked
134727  );
134728  db->pNextBlocked = *pp;
134729  *pp = db;
134730}
134731
134732/*
134733** Obtain the STATIC_MASTER mutex.
134734*/
134735static void enterMutex(void){
134736  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
134737  checkListProperties(0);
134738}
134739
134740/*
134741** Release the STATIC_MASTER mutex.
134742*/
134743static void leaveMutex(void){
134744  assertMutexHeld();
134745  checkListProperties(0);
134746  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
134747}
134748
134749/*
134750** Register an unlock-notify callback.
134751**
134752** This is called after connection "db" has attempted some operation
134753** but has received an SQLITE_LOCKED error because another connection
134754** (call it pOther) in the same process was busy using the same shared
134755** cache.  pOther is found by looking at db->pBlockingConnection.
134756**
134757** If there is no blocking connection, the callback is invoked immediately,
134758** before this routine returns.
134759**
134760** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
134761** a deadlock.
134762**
134763** Otherwise, make arrangements to invoke xNotify when pOther drops
134764** its locks.
134765**
134766** Each call to this routine overrides any prior callbacks registered
134767** on the same "db".  If xNotify==0 then any prior callbacks are immediately
134768** cancelled.
134769*/
134770SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
134771  sqlite3 *db,
134772  void (*xNotify)(void **, int),
134773  void *pArg
134774){
134775  int rc = SQLITE_OK;
134776
134777  sqlite3_mutex_enter(db->mutex);
134778  enterMutex();
134779
134780  if( xNotify==0 ){
134781    removeFromBlockedList(db);
134782    db->pBlockingConnection = 0;
134783    db->pUnlockConnection = 0;
134784    db->xUnlockNotify = 0;
134785    db->pUnlockArg = 0;
134786  }else if( 0==db->pBlockingConnection ){
134787    /* The blocking transaction has been concluded. Or there never was a
134788    ** blocking transaction. In either case, invoke the notify callback
134789    ** immediately.
134790    */
134791    xNotify(&pArg, 1);
134792  }else{
134793    sqlite3 *p;
134794
134795    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
134796    if( p ){
134797      rc = SQLITE_LOCKED;              /* Deadlock detected. */
134798    }else{
134799      db->pUnlockConnection = db->pBlockingConnection;
134800      db->xUnlockNotify = xNotify;
134801      db->pUnlockArg = pArg;
134802      removeFromBlockedList(db);
134803      addToBlockedList(db);
134804    }
134805  }
134806
134807  leaveMutex();
134808  assert( !db->mallocFailed );
134809  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
134810  sqlite3_mutex_leave(db->mutex);
134811  return rc;
134812}
134813
134814/*
134815** This function is called while stepping or preparing a statement
134816** associated with connection db. The operation will return SQLITE_LOCKED
134817** to the user because it requires a lock that will not be available
134818** until connection pBlocker concludes its current transaction.
134819*/
134820SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
134821  enterMutex();
134822  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
134823    addToBlockedList(db);
134824  }
134825  db->pBlockingConnection = pBlocker;
134826  leaveMutex();
134827}
134828
134829/*
134830** This function is called when
134831** the transaction opened by database db has just finished. Locks held
134832** by database connection db have been released.
134833**
134834** This function loops through each entry in the blocked connections
134835** list and does the following:
134836**
134837**   1) If the sqlite3.pBlockingConnection member of a list entry is
134838**      set to db, then set pBlockingConnection=0.
134839**
134840**   2) If the sqlite3.pUnlockConnection member of a list entry is
134841**      set to db, then invoke the configured unlock-notify callback and
134842**      set pUnlockConnection=0.
134843**
134844**   3) If the two steps above mean that pBlockingConnection==0 and
134845**      pUnlockConnection==0, remove the entry from the blocked connections
134846**      list.
134847*/
134848SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
134849  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
134850  int nArg = 0;                            /* Number of entries in aArg[] */
134851  sqlite3 **pp;                            /* Iterator variable */
134852  void **aArg;               /* Arguments to the unlock callback */
134853  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
134854  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
134855
134856  aArg = aStatic;
134857  enterMutex();         /* Enter STATIC_MASTER mutex */
134858
134859  /* This loop runs once for each entry in the blocked-connections list. */
134860  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
134861    sqlite3 *p = *pp;
134862
134863    /* Step 1. */
134864    if( p->pBlockingConnection==db ){
134865      p->pBlockingConnection = 0;
134866    }
134867
134868    /* Step 2. */
134869    if( p->pUnlockConnection==db ){
134870      assert( p->xUnlockNotify );
134871      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
134872        xUnlockNotify(aArg, nArg);
134873        nArg = 0;
134874      }
134875
134876      sqlite3BeginBenignMalloc();
134877      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
134878      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
134879      if( (!aDyn && nArg==(int)ArraySize(aStatic))
134880       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
134881      ){
134882        /* The aArg[] array needs to grow. */
134883        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
134884        if( pNew ){
134885          memcpy(pNew, aArg, nArg*sizeof(void *));
134886          sqlite3_free(aDyn);
134887          aDyn = aArg = pNew;
134888        }else{
134889          /* This occurs when the array of context pointers that need to
134890          ** be passed to the unlock-notify callback is larger than the
134891          ** aStatic[] array allocated on the stack and the attempt to
134892          ** allocate a larger array from the heap has failed.
134893          **
134894          ** This is a difficult situation to handle. Returning an error
134895          ** code to the caller is insufficient, as even if an error code
134896          ** is returned the transaction on connection db will still be
134897          ** closed and the unlock-notify callbacks on blocked connections
134898          ** will go unissued. This might cause the application to wait
134899          ** indefinitely for an unlock-notify callback that will never
134900          ** arrive.
134901          **
134902          ** Instead, invoke the unlock-notify callback with the context
134903          ** array already accumulated. We can then clear the array and
134904          ** begin accumulating any further context pointers without
134905          ** requiring any dynamic allocation. This is sub-optimal because
134906          ** it means that instead of one callback with a large array of
134907          ** context pointers the application will receive two or more
134908          ** callbacks with smaller arrays of context pointers, which will
134909          ** reduce the applications ability to prioritize multiple
134910          ** connections. But it is the best that can be done under the
134911          ** circumstances.
134912          */
134913          xUnlockNotify(aArg, nArg);
134914          nArg = 0;
134915        }
134916      }
134917      sqlite3EndBenignMalloc();
134918
134919      aArg[nArg++] = p->pUnlockArg;
134920      xUnlockNotify = p->xUnlockNotify;
134921      p->pUnlockConnection = 0;
134922      p->xUnlockNotify = 0;
134923      p->pUnlockArg = 0;
134924    }
134925
134926    /* Step 3. */
134927    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
134928      /* Remove connection p from the blocked connections list. */
134929      *pp = p->pNextBlocked;
134930      p->pNextBlocked = 0;
134931    }else{
134932      pp = &p->pNextBlocked;
134933    }
134934  }
134935
134936  if( nArg!=0 ){
134937    xUnlockNotify(aArg, nArg);
134938  }
134939  sqlite3_free(aDyn);
134940  leaveMutex();         /* Leave STATIC_MASTER mutex */
134941}
134942
134943/*
134944** This is called when the database connection passed as an argument is
134945** being closed. The connection is removed from the blocked list.
134946*/
134947SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
134948  sqlite3ConnectionUnlocked(db);
134949  enterMutex();
134950  removeFromBlockedList(db);
134951  checkListProperties(db);
134952  leaveMutex();
134953}
134954#endif
134955
134956/************** End of notify.c **********************************************/
134957/************** Begin file fts3.c ********************************************/
134958/*
134959** 2006 Oct 10
134960**
134961** The author disclaims copyright to this source code.  In place of
134962** a legal notice, here is a blessing:
134963**
134964**    May you do good and not evil.
134965**    May you find forgiveness for yourself and forgive others.
134966**    May you share freely, never taking more than you give.
134967**
134968******************************************************************************
134969**
134970** This is an SQLite module implementing full-text search.
134971*/
134972
134973/*
134974** The code in this file is only compiled if:
134975**
134976**     * The FTS3 module is being built as an extension
134977**       (in which case SQLITE_CORE is not defined), or
134978**
134979**     * The FTS3 module is being built into the core of
134980**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
134981*/
134982
134983/* The full-text index is stored in a series of b+tree (-like)
134984** structures called segments which map terms to doclists.  The
134985** structures are like b+trees in layout, but are constructed from the
134986** bottom up in optimal fashion and are not updatable.  Since trees
134987** are built from the bottom up, things will be described from the
134988** bottom up.
134989**
134990**
134991**** Varints ****
134992** The basic unit of encoding is a variable-length integer called a
134993** varint.  We encode variable-length integers in little-endian order
134994** using seven bits * per byte as follows:
134995**
134996** KEY:
134997**         A = 0xxxxxxx    7 bits of data and one flag bit
134998**         B = 1xxxxxxx    7 bits of data and one flag bit
134999**
135000**  7 bits - A
135001** 14 bits - BA
135002** 21 bits - BBA
135003** and so on.
135004**
135005** This is similar in concept to how sqlite encodes "varints" but
135006** the encoding is not the same.  SQLite varints are big-endian
135007** are are limited to 9 bytes in length whereas FTS3 varints are
135008** little-endian and can be up to 10 bytes in length (in theory).
135009**
135010** Example encodings:
135011**
135012**     1:    0x01
135013**   127:    0x7f
135014**   128:    0x81 0x00
135015**
135016**
135017**** Document lists ****
135018** A doclist (document list) holds a docid-sorted list of hits for a
135019** given term.  Doclists hold docids and associated token positions.
135020** A docid is the unique integer identifier for a single document.
135021** A position is the index of a word within the document.  The first
135022** word of the document has a position of 0.
135023**
135024** FTS3 used to optionally store character offsets using a compile-time
135025** option.  But that functionality is no longer supported.
135026**
135027** A doclist is stored like this:
135028**
135029** array {
135030**   varint docid;          (delta from previous doclist)
135031**   array {                (position list for column 0)
135032**     varint position;     (2 more than the delta from previous position)
135033**   }
135034**   array {
135035**     varint POS_COLUMN;   (marks start of position list for new column)
135036**     varint column;       (index of new column)
135037**     array {
135038**       varint position;   (2 more than the delta from previous position)
135039**     }
135040**   }
135041**   varint POS_END;        (marks end of positions for this document.
135042** }
135043**
135044** Here, array { X } means zero or more occurrences of X, adjacent in
135045** memory.  A "position" is an index of a token in the token stream
135046** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
135047** in the same logical place as the position element, and act as sentinals
135048** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
135049** The positions numbers are not stored literally but rather as two more
135050** than the difference from the prior position, or the just the position plus
135051** 2 for the first position.  Example:
135052**
135053**   label:       A B C D E  F  G H   I  J K
135054**   value:     123 5 9 1 1 14 35 0 234 72 0
135055**
135056** The 123 value is the first docid.  For column zero in this document
135057** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
135058** at D signals the start of a new column; the 1 at E indicates that the
135059** new column is column number 1.  There are two positions at 12 and 45
135060** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
135061** 234 at I is the delta to next docid (357).  It has one position 70
135062** (72-2) and then terminates with the 0 at K.
135063**
135064** A "position-list" is the list of positions for multiple columns for
135065** a single docid.  A "column-list" is the set of positions for a single
135066** column.  Hence, a position-list consists of one or more column-lists,
135067** a document record consists of a docid followed by a position-list and
135068** a doclist consists of one or more document records.
135069**
135070** A bare doclist omits the position information, becoming an
135071** array of varint-encoded docids.
135072**
135073**** Segment leaf nodes ****
135074** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
135075** nodes are written using LeafWriter, and read using LeafReader (to
135076** iterate through a single leaf node's data) and LeavesReader (to
135077** iterate through a segment's entire leaf layer).  Leaf nodes have
135078** the format:
135079**
135080** varint iHeight;             (height from leaf level, always 0)
135081** varint nTerm;               (length of first term)
135082** char pTerm[nTerm];          (content of first term)
135083** varint nDoclist;            (length of term's associated doclist)
135084** char pDoclist[nDoclist];    (content of doclist)
135085** array {
135086**                             (further terms are delta-encoded)
135087**   varint nPrefix;           (length of prefix shared with previous term)
135088**   varint nSuffix;           (length of unshared suffix)
135089**   char pTermSuffix[nSuffix];(unshared suffix of next term)
135090**   varint nDoclist;          (length of term's associated doclist)
135091**   char pDoclist[nDoclist];  (content of doclist)
135092** }
135093**
135094** Here, array { X } means zero or more occurrences of X, adjacent in
135095** memory.
135096**
135097** Leaf nodes are broken into blocks which are stored contiguously in
135098** the %_segments table in sorted order.  This means that when the end
135099** of a node is reached, the next term is in the node with the next
135100** greater node id.
135101**
135102** New data is spilled to a new leaf node when the current node
135103** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
135104** larger than STANDALONE_MIN (default 1024) is placed in a standalone
135105** node (a leaf node with a single term and doclist).  The goal of
135106** these settings is to pack together groups of small doclists while
135107** making it efficient to directly access large doclists.  The
135108** assumption is that large doclists represent terms which are more
135109** likely to be query targets.
135110**
135111** TODO(shess) It may be useful for blocking decisions to be more
135112** dynamic.  For instance, it may make more sense to have a 2.5k leaf
135113** node rather than splitting into 2k and .5k nodes.  My intuition is
135114** that this might extend through 2x or 4x the pagesize.
135115**
135116**
135117**** Segment interior nodes ****
135118** Segment interior nodes store blockids for subtree nodes and terms
135119** to describe what data is stored by the each subtree.  Interior
135120** nodes are written using InteriorWriter, and read using
135121** InteriorReader.  InteriorWriters are created as needed when
135122** SegmentWriter creates new leaf nodes, or when an interior node
135123** itself grows too big and must be split.  The format of interior
135124** nodes:
135125**
135126** varint iHeight;           (height from leaf level, always >0)
135127** varint iBlockid;          (block id of node's leftmost subtree)
135128** optional {
135129**   varint nTerm;           (length of first term)
135130**   char pTerm[nTerm];      (content of first term)
135131**   array {
135132**                                (further terms are delta-encoded)
135133**     varint nPrefix;            (length of shared prefix with previous term)
135134**     varint nSuffix;            (length of unshared suffix)
135135**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
135136**   }
135137** }
135138**
135139** Here, optional { X } means an optional element, while array { X }
135140** means zero or more occurrences of X, adjacent in memory.
135141**
135142** An interior node encodes n terms separating n+1 subtrees.  The
135143** subtree blocks are contiguous, so only the first subtree's blockid
135144** is encoded.  The subtree at iBlockid will contain all terms less
135145** than the first term encoded (or all terms if no term is encoded).
135146** Otherwise, for terms greater than or equal to pTerm[i] but less
135147** than pTerm[i+1], the subtree for that term will be rooted at
135148** iBlockid+i.  Interior nodes only store enough term data to
135149** distinguish adjacent children (if the rightmost term of the left
135150** child is "something", and the leftmost term of the right child is
135151** "wicked", only "w" is stored).
135152**
135153** New data is spilled to a new interior node at the same height when
135154** the current node exceeds INTERIOR_MAX bytes (default 2048).
135155** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
135156** interior nodes and making the tree too skinny.  The interior nodes
135157** at a given height are naturally tracked by interior nodes at
135158** height+1, and so on.
135159**
135160**
135161**** Segment directory ****
135162** The segment directory in table %_segdir stores meta-information for
135163** merging and deleting segments, and also the root node of the
135164** segment's tree.
135165**
135166** The root node is the top node of the segment's tree after encoding
135167** the entire segment, restricted to ROOT_MAX bytes (default 1024).
135168** This could be either a leaf node or an interior node.  If the top
135169** node requires more than ROOT_MAX bytes, it is flushed to %_segments
135170** and a new root interior node is generated (which should always fit
135171** within ROOT_MAX because it only needs space for 2 varints, the
135172** height and the blockid of the previous root).
135173**
135174** The meta-information in the segment directory is:
135175**   level               - segment level (see below)
135176**   idx                 - index within level
135177**                       - (level,idx uniquely identify a segment)
135178**   start_block         - first leaf node
135179**   leaves_end_block    - last leaf node
135180**   end_block           - last block (including interior nodes)
135181**   root                - contents of root node
135182**
135183** If the root node is a leaf node, then start_block,
135184** leaves_end_block, and end_block are all 0.
135185**
135186**
135187**** Segment merging ****
135188** To amortize update costs, segments are grouped into levels and
135189** merged in batches.  Each increase in level represents exponentially
135190** more documents.
135191**
135192** New documents (actually, document updates) are tokenized and
135193** written individually (using LeafWriter) to a level 0 segment, with
135194** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
135195** level 0 segments are merged into a single level 1 segment.  Level 1
135196** is populated like level 0, and eventually MERGE_COUNT level 1
135197** segments are merged to a single level 2 segment (representing
135198** MERGE_COUNT^2 updates), and so on.
135199**
135200** A segment merge traverses all segments at a given level in
135201** parallel, performing a straightforward sorted merge.  Since segment
135202** leaf nodes are written in to the %_segments table in order, this
135203** merge traverses the underlying sqlite disk structures efficiently.
135204** After the merge, all segment blocks from the merged level are
135205** deleted.
135206**
135207** MERGE_COUNT controls how often we merge segments.  16 seems to be
135208** somewhat of a sweet spot for insertion performance.  32 and 64 show
135209** very similar performance numbers to 16 on insertion, though they're
135210** a tiny bit slower (perhaps due to more overhead in merge-time
135211** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
135212** 16, 2 about 66% slower than 16.
135213**
135214** At query time, high MERGE_COUNT increases the number of segments
135215** which need to be scanned and merged.  For instance, with 100k docs
135216** inserted:
135217**
135218**    MERGE_COUNT   segments
135219**       16           25
135220**        8           12
135221**        4           10
135222**        2            6
135223**
135224** This appears to have only a moderate impact on queries for very
135225** frequent terms (which are somewhat dominated by segment merge
135226** costs), and infrequent and non-existent terms still seem to be fast
135227** even with many segments.
135228**
135229** TODO(shess) That said, it would be nice to have a better query-side
135230** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
135231** optimizations to things like doclist merging will swing the sweet
135232** spot around.
135233**
135234**
135235**
135236**** Handling of deletions and updates ****
135237** Since we're using a segmented structure, with no docid-oriented
135238** index into the term index, we clearly cannot simply update the term
135239** index when a document is deleted or updated.  For deletions, we
135240** write an empty doclist (varint(docid) varint(POS_END)), for updates
135241** we simply write the new doclist.  Segment merges overwrite older
135242** data for a particular docid with newer data, so deletes or updates
135243** will eventually overtake the earlier data and knock it out.  The
135244** query logic likewise merges doclists so that newer data knocks out
135245** older data.
135246*/
135247
135248/************** Include fts3Int.h in the middle of fts3.c ********************/
135249/************** Begin file fts3Int.h *****************************************/
135250/*
135251** 2009 Nov 12
135252**
135253** The author disclaims copyright to this source code.  In place of
135254** a legal notice, here is a blessing:
135255**
135256**    May you do good and not evil.
135257**    May you find forgiveness for yourself and forgive others.
135258**    May you share freely, never taking more than you give.
135259**
135260******************************************************************************
135261**
135262*/
135263#ifndef _FTSINT_H
135264#define _FTSINT_H
135265
135266#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
135267# define NDEBUG 1
135268#endif
135269
135270/*
135271** FTS4 is really an extension for FTS3.  It is enabled using the
135272** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
135273** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
135274*/
135275#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
135276# define SQLITE_ENABLE_FTS3
135277#endif
135278
135279#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135280
135281/* If not building as part of the core, include sqlite3ext.h. */
135282#ifndef SQLITE_CORE
135283/* # include "sqlite3ext.h"  */
135284SQLITE_EXTENSION_INIT3
135285#endif
135286
135287/* #include "sqlite3.h" */
135288/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
135289/************** Begin file fts3_tokenizer.h **********************************/
135290/*
135291** 2006 July 10
135292**
135293** The author disclaims copyright to this source code.
135294**
135295*************************************************************************
135296** Defines the interface to tokenizers used by fulltext-search.  There
135297** are three basic components:
135298**
135299** sqlite3_tokenizer_module is a singleton defining the tokenizer
135300** interface functions.  This is essentially the class structure for
135301** tokenizers.
135302**
135303** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
135304** including customization information defined at creation time.
135305**
135306** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
135307** tokens from a particular input.
135308*/
135309#ifndef _FTS3_TOKENIZER_H_
135310#define _FTS3_TOKENIZER_H_
135311
135312/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
135313** If tokenizers are to be allowed to call sqlite3_*() functions, then
135314** we will need a way to register the API consistently.
135315*/
135316/* #include "sqlite3.h" */
135317
135318/*
135319** Structures used by the tokenizer interface. When a new tokenizer
135320** implementation is registered, the caller provides a pointer to
135321** an sqlite3_tokenizer_module containing pointers to the callback
135322** functions that make up an implementation.
135323**
135324** When an fts3 table is created, it passes any arguments passed to
135325** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
135326** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
135327** implementation. The xCreate() function in turn returns an
135328** sqlite3_tokenizer structure representing the specific tokenizer to
135329** be used for the fts3 table (customized by the tokenizer clause arguments).
135330**
135331** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
135332** method is called. It returns an sqlite3_tokenizer_cursor object
135333** that may be used to tokenize a specific input buffer based on
135334** the tokenization rules supplied by a specific sqlite3_tokenizer
135335** object.
135336*/
135337typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
135338typedef struct sqlite3_tokenizer sqlite3_tokenizer;
135339typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
135340
135341struct sqlite3_tokenizer_module {
135342
135343  /*
135344  ** Structure version. Should always be set to 0 or 1.
135345  */
135346  int iVersion;
135347
135348  /*
135349  ** Create a new tokenizer. The values in the argv[] array are the
135350  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
135351  ** TABLE statement that created the fts3 table. For example, if
135352  ** the following SQL is executed:
135353  **
135354  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
135355  **
135356  ** then argc is set to 2, and the argv[] array contains pointers
135357  ** to the strings "arg1" and "arg2".
135358  **
135359  ** This method should return either SQLITE_OK (0), or an SQLite error
135360  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
135361  ** to point at the newly created tokenizer structure. The generic
135362  ** sqlite3_tokenizer.pModule variable should not be initialized by
135363  ** this callback. The caller will do so.
135364  */
135365  int (*xCreate)(
135366    int argc,                           /* Size of argv array */
135367    const char *const*argv,             /* Tokenizer argument strings */
135368    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
135369  );
135370
135371  /*
135372  ** Destroy an existing tokenizer. The fts3 module calls this method
135373  ** exactly once for each successful call to xCreate().
135374  */
135375  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
135376
135377  /*
135378  ** Create a tokenizer cursor to tokenize an input buffer. The caller
135379  ** is responsible for ensuring that the input buffer remains valid
135380  ** until the cursor is closed (using the xClose() method).
135381  */
135382  int (*xOpen)(
135383    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
135384    const char *pInput, int nBytes,      /* Input buffer */
135385    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
135386  );
135387
135388  /*
135389  ** Destroy an existing tokenizer cursor. The fts3 module calls this
135390  ** method exactly once for each successful call to xOpen().
135391  */
135392  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
135393
135394  /*
135395  ** Retrieve the next token from the tokenizer cursor pCursor. This
135396  ** method should either return SQLITE_OK and set the values of the
135397  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
135398  ** the end of the buffer has been reached, or an SQLite error code.
135399  **
135400  ** *ppToken should be set to point at a buffer containing the
135401  ** normalized version of the token (i.e. after any case-folding and/or
135402  ** stemming has been performed). *pnBytes should be set to the length
135403  ** of this buffer in bytes. The input text that generated the token is
135404  ** identified by the byte offsets returned in *piStartOffset and
135405  ** *piEndOffset. *piStartOffset should be set to the index of the first
135406  ** byte of the token in the input buffer. *piEndOffset should be set
135407  ** to the index of the first byte just past the end of the token in
135408  ** the input buffer.
135409  **
135410  ** The buffer *ppToken is set to point at is managed by the tokenizer
135411  ** implementation. It is only required to be valid until the next call
135412  ** to xNext() or xClose().
135413  */
135414  /* TODO(shess) current implementation requires pInput to be
135415  ** nul-terminated.  This should either be fixed, or pInput/nBytes
135416  ** should be converted to zInput.
135417  */
135418  int (*xNext)(
135419    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
135420    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
135421    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
135422    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
135423    int *piPosition      /* OUT: Number of tokens returned before this one */
135424  );
135425
135426  /***********************************************************************
135427  ** Methods below this point are only available if iVersion>=1.
135428  */
135429
135430  /*
135431  ** Configure the language id of a tokenizer cursor.
135432  */
135433  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
135434};
135435
135436struct sqlite3_tokenizer {
135437  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
135438  /* Tokenizer implementations will typically add additional fields */
135439};
135440
135441struct sqlite3_tokenizer_cursor {
135442  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
135443  /* Tokenizer implementations will typically add additional fields */
135444};
135445
135446int fts3_global_term_cnt(int iTerm, int iCol);
135447int fts3_term_cnt(int iTerm, int iCol);
135448
135449
135450#endif /* _FTS3_TOKENIZER_H_ */
135451
135452/************** End of fts3_tokenizer.h **************************************/
135453/************** Continuing where we left off in fts3Int.h ********************/
135454/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
135455/************** Begin file fts3_hash.h ***************************************/
135456/*
135457** 2001 September 22
135458**
135459** The author disclaims copyright to this source code.  In place of
135460** a legal notice, here is a blessing:
135461**
135462**    May you do good and not evil.
135463**    May you find forgiveness for yourself and forgive others.
135464**    May you share freely, never taking more than you give.
135465**
135466*************************************************************************
135467** This is the header file for the generic hash-table implementation
135468** used in SQLite.  We've modified it slightly to serve as a standalone
135469** hash table implementation for the full-text indexing module.
135470**
135471*/
135472#ifndef _FTS3_HASH_H_
135473#define _FTS3_HASH_H_
135474
135475/* Forward declarations of structures. */
135476typedef struct Fts3Hash Fts3Hash;
135477typedef struct Fts3HashElem Fts3HashElem;
135478
135479/* A complete hash table is an instance of the following structure.
135480** The internals of this structure are intended to be opaque -- client
135481** code should not attempt to access or modify the fields of this structure
135482** directly.  Change this structure only by using the routines below.
135483** However, many of the "procedures" and "functions" for modifying and
135484** accessing this structure are really macros, so we can't really make
135485** this structure opaque.
135486*/
135487struct Fts3Hash {
135488  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
135489  char copyKey;           /* True if copy of key made on insert */
135490  int count;              /* Number of entries in this table */
135491  Fts3HashElem *first;    /* The first element of the array */
135492  int htsize;             /* Number of buckets in the hash table */
135493  struct _fts3ht {        /* the hash table */
135494    int count;               /* Number of entries with this hash */
135495    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
135496  } *ht;
135497};
135498
135499/* Each element in the hash table is an instance of the following
135500** structure.  All elements are stored on a single doubly-linked list.
135501**
135502** Again, this structure is intended to be opaque, but it can't really
135503** be opaque because it is used by macros.
135504*/
135505struct Fts3HashElem {
135506  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
135507  void *data;                /* Data associated with this element */
135508  void *pKey; int nKey;      /* Key associated with this element */
135509};
135510
135511/*
135512** There are 2 different modes of operation for a hash table:
135513**
135514**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
135515**                           (including the null-terminator, if any).  Case
135516**                           is respected in comparisons.
135517**
135518**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
135519**                           memcmp() is used to compare keys.
135520**
135521** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
135522*/
135523#define FTS3_HASH_STRING    1
135524#define FTS3_HASH_BINARY    2
135525
135526/*
135527** Access routines.  To delete, insert a NULL pointer.
135528*/
135529SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
135530SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
135531SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
135532SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
135533SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
135534
135535/*
135536** Shorthand for the functions above
135537*/
135538#define fts3HashInit     sqlite3Fts3HashInit
135539#define fts3HashInsert   sqlite3Fts3HashInsert
135540#define fts3HashFind     sqlite3Fts3HashFind
135541#define fts3HashClear    sqlite3Fts3HashClear
135542#define fts3HashFindElem sqlite3Fts3HashFindElem
135543
135544/*
135545** Macros for looping over all elements of a hash table.  The idiom is
135546** like this:
135547**
135548**   Fts3Hash h;
135549**   Fts3HashElem *p;
135550**   ...
135551**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
135552**     SomeStructure *pData = fts3HashData(p);
135553**     // do something with pData
135554**   }
135555*/
135556#define fts3HashFirst(H)  ((H)->first)
135557#define fts3HashNext(E)   ((E)->next)
135558#define fts3HashData(E)   ((E)->data)
135559#define fts3HashKey(E)    ((E)->pKey)
135560#define fts3HashKeysize(E) ((E)->nKey)
135561
135562/*
135563** Number of entries in a hash table
135564*/
135565#define fts3HashCount(H)  ((H)->count)
135566
135567#endif /* _FTS3_HASH_H_ */
135568
135569/************** End of fts3_hash.h *******************************************/
135570/************** Continuing where we left off in fts3Int.h ********************/
135571
135572/*
135573** This constant determines the maximum depth of an FTS expression tree
135574** that the library will create and use. FTS uses recursion to perform
135575** various operations on the query tree, so the disadvantage of a large
135576** limit is that it may allow very large queries to use large amounts
135577** of stack space (perhaps causing a stack overflow).
135578*/
135579#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
135580# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
135581#endif
135582
135583
135584/*
135585** This constant controls how often segments are merged. Once there are
135586** FTS3_MERGE_COUNT segments of level N, they are merged into a single
135587** segment of level N+1.
135588*/
135589#define FTS3_MERGE_COUNT 16
135590
135591/*
135592** This is the maximum amount of data (in bytes) to store in the
135593** Fts3Table.pendingTerms hash table. Normally, the hash table is
135594** populated as documents are inserted/updated/deleted in a transaction
135595** and used to create a new segment when the transaction is committed.
135596** However if this limit is reached midway through a transaction, a new
135597** segment is created and the hash table cleared immediately.
135598*/
135599#define FTS3_MAX_PENDING_DATA (1*1024*1024)
135600
135601/*
135602** Macro to return the number of elements in an array. SQLite has a
135603** similar macro called ArraySize(). Use a different name to avoid
135604** a collision when building an amalgamation with built-in FTS3.
135605*/
135606#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
135607
135608
135609#ifndef MIN
135610# define MIN(x,y) ((x)<(y)?(x):(y))
135611#endif
135612#ifndef MAX
135613# define MAX(x,y) ((x)>(y)?(x):(y))
135614#endif
135615
135616/*
135617** Maximum length of a varint encoded integer. The varint format is different
135618** from that used by SQLite, so the maximum length is 10, not 9.
135619*/
135620#define FTS3_VARINT_MAX 10
135621
135622/*
135623** FTS4 virtual tables may maintain multiple indexes - one index of all terms
135624** in the document set and zero or more prefix indexes. All indexes are stored
135625** as one or more b+-trees in the %_segments and %_segdir tables.
135626**
135627** It is possible to determine which index a b+-tree belongs to based on the
135628** value stored in the "%_segdir.level" column. Given this value L, the index
135629** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
135630** level values between 0 and 1023 (inclusive) belong to index 0, all levels
135631** between 1024 and 2047 to index 1, and so on.
135632**
135633** It is considered impossible for an index to use more than 1024 levels. In
135634** theory though this may happen, but only after at least
135635** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
135636*/
135637#define FTS3_SEGDIR_MAXLEVEL      1024
135638#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
135639
135640/*
135641** The testcase() macro is only used by the amalgamation.  If undefined,
135642** make it a no-op.
135643*/
135644#ifndef testcase
135645# define testcase(X)
135646#endif
135647
135648/*
135649** Terminator values for position-lists and column-lists.
135650*/
135651#define POS_COLUMN  (1)     /* Column-list terminator */
135652#define POS_END     (0)     /* Position-list terminator */
135653
135654/*
135655** This section provides definitions to allow the
135656** FTS3 extension to be compiled outside of the
135657** amalgamation.
135658*/
135659#ifndef SQLITE_AMALGAMATION
135660/*
135661** Macros indicating that conditional expressions are always true or
135662** false.
135663*/
135664#ifdef SQLITE_COVERAGE_TEST
135665# define ALWAYS(x) (1)
135666# define NEVER(X)  (0)
135667#elif defined(SQLITE_DEBUG)
135668# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
135669# define NEVER(x) sqlite3Fts3Never((x)!=0)
135670SQLITE_PRIVATE int sqlite3Fts3Always(int b);
135671SQLITE_PRIVATE int sqlite3Fts3Never(int b);
135672#else
135673# define ALWAYS(x) (x)
135674# define NEVER(x)  (x)
135675#endif
135676
135677/*
135678** Internal types used by SQLite.
135679*/
135680typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
135681typedef short int i16;            /* 2-byte (or larger) signed integer */
135682typedef unsigned int u32;         /* 4-byte unsigned integer */
135683typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
135684typedef sqlite3_int64 i64;        /* 8-byte signed integer */
135685
135686/*
135687** Macro used to suppress compiler warnings for unused parameters.
135688*/
135689#define UNUSED_PARAMETER(x) (void)(x)
135690
135691/*
135692** Activate assert() only if SQLITE_TEST is enabled.
135693*/
135694#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
135695# define NDEBUG 1
135696#endif
135697
135698/*
135699** The TESTONLY macro is used to enclose variable declarations or
135700** other bits of code that are needed to support the arguments
135701** within testcase() and assert() macros.
135702*/
135703#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
135704# define TESTONLY(X)  X
135705#else
135706# define TESTONLY(X)
135707#endif
135708
135709#endif /* SQLITE_AMALGAMATION */
135710
135711#ifdef SQLITE_DEBUG
135712SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
135713# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
135714#else
135715# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
135716#endif
135717
135718typedef struct Fts3Table Fts3Table;
135719typedef struct Fts3Cursor Fts3Cursor;
135720typedef struct Fts3Expr Fts3Expr;
135721typedef struct Fts3Phrase Fts3Phrase;
135722typedef struct Fts3PhraseToken Fts3PhraseToken;
135723
135724typedef struct Fts3Doclist Fts3Doclist;
135725typedef struct Fts3SegFilter Fts3SegFilter;
135726typedef struct Fts3DeferredToken Fts3DeferredToken;
135727typedef struct Fts3SegReader Fts3SegReader;
135728typedef struct Fts3MultiSegReader Fts3MultiSegReader;
135729
135730typedef struct MatchinfoBuffer MatchinfoBuffer;
135731
135732/*
135733** A connection to a fulltext index is an instance of the following
135734** structure. The xCreate and xConnect methods create an instance
135735** of this structure and xDestroy and xDisconnect free that instance.
135736** All other methods receive a pointer to the structure as one of their
135737** arguments.
135738*/
135739struct Fts3Table {
135740  sqlite3_vtab base;              /* Base class used by SQLite core */
135741  sqlite3 *db;                    /* The database connection */
135742  const char *zDb;                /* logical database name */
135743  const char *zName;              /* virtual table name */
135744  int nColumn;                    /* number of named columns in virtual table */
135745  char **azColumn;                /* column names.  malloced */
135746  u8 *abNotindexed;               /* True for 'notindexed' columns */
135747  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
135748  char *zContentTbl;              /* content=xxx option, or NULL */
135749  char *zLanguageid;              /* languageid=xxx option, or NULL */
135750  int nAutoincrmerge;             /* Value configured by 'automerge' */
135751  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
135752
135753  /* Precompiled statements used by the implementation. Each of these
135754  ** statements is run and reset within a single virtual table API call.
135755  */
135756  sqlite3_stmt *aStmt[40];
135757
135758  char *zReadExprlist;
135759  char *zWriteExprlist;
135760
135761  int nNodeSize;                  /* Soft limit for node size */
135762  u8 bFts4;                       /* True for FTS4, false for FTS3 */
135763  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
135764  u8 bHasDocsize;                 /* True if %_docsize table exists */
135765  u8 bDescIdx;                    /* True if doclists are in reverse order */
135766  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
135767  int nPgsz;                      /* Page size for host database */
135768  char *zSegmentsTbl;             /* Name of %_segments table */
135769  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
135770
135771  /*
135772  ** The following array of hash tables is used to buffer pending index
135773  ** updates during transactions. All pending updates buffered at any one
135774  ** time must share a common language-id (see the FTS4 langid= feature).
135775  ** The current language id is stored in variable iPrevLangid.
135776  **
135777  ** A single FTS4 table may have multiple full-text indexes. For each index
135778  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
135779  ** terms that appear in the document set. Each subsequent index in aIndex[]
135780  ** is an index of prefixes of a specific length.
135781  **
135782  ** Variable nPendingData contains an estimate the memory consumed by the
135783  ** pending data structures, including hash table overhead, but not including
135784  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
135785  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
135786  ** recently inserted record.
135787  */
135788  int nIndex;                     /* Size of aIndex[] */
135789  struct Fts3Index {
135790    int nPrefix;                  /* Prefix length (0 for main terms index) */
135791    Fts3Hash hPending;            /* Pending terms table for this index */
135792  } *aIndex;
135793  int nMaxPendingData;            /* Max pending data before flush to disk */
135794  int nPendingData;               /* Current bytes of pending data */
135795  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
135796  int iPrevLangid;                /* Langid of recently inserted document */
135797  int bPrevDelete;                /* True if last operation was a delete */
135798
135799#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
135800  /* State variables used for validating that the transaction control
135801  ** methods of the virtual table are called at appropriate times.  These
135802  ** values do not contribute to FTS functionality; they are used for
135803  ** verifying the operation of the SQLite core.
135804  */
135805  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
135806  int mxSavepoint;       /* Largest valid xSavepoint integer */
135807#endif
135808
135809#ifdef SQLITE_TEST
135810  /* True to disable the incremental doclist optimization. This is controled
135811  ** by special insert command 'test-no-incr-doclist'.  */
135812  int bNoIncrDoclist;
135813#endif
135814};
135815
135816/*
135817** When the core wants to read from the virtual table, it creates a
135818** virtual table cursor (an instance of the following structure) using
135819** the xOpen method. Cursors are destroyed using the xClose method.
135820*/
135821struct Fts3Cursor {
135822  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
135823  i16 eSearch;                    /* Search strategy (see below) */
135824  u8 isEof;                       /* True if at End Of Results */
135825  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
135826  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
135827  Fts3Expr *pExpr;                /* Parsed MATCH query string */
135828  int iLangid;                    /* Language being queried for */
135829  int nPhrase;                    /* Number of matchable phrases in query */
135830  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
135831  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
135832  char *pNextId;                  /* Pointer into the body of aDoclist */
135833  char *aDoclist;                 /* List of docids for full-text queries */
135834  int nDoclist;                   /* Size of buffer at aDoclist */
135835  u8 bDesc;                       /* True to sort in descending order */
135836  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
135837  int nRowAvg;                    /* Average size of database rows, in pages */
135838  sqlite3_int64 nDoc;             /* Documents in table */
135839  i64 iMinDocid;                  /* Minimum docid to return */
135840  i64 iMaxDocid;                  /* Maximum docid to return */
135841  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
135842  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
135843};
135844
135845#define FTS3_EVAL_FILTER    0
135846#define FTS3_EVAL_NEXT      1
135847#define FTS3_EVAL_MATCHINFO 2
135848
135849/*
135850** The Fts3Cursor.eSearch member is always set to one of the following.
135851** Actualy, Fts3Cursor.eSearch can be greater than or equal to
135852** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
135853** of the column to be searched.  For example, in
135854**
135855**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
135856**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
135857**
135858** Because the LHS of the MATCH operator is 2nd column "b",
135859** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
135860** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
135861** indicating that all columns should be searched,
135862** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
135863*/
135864#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
135865#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
135866#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
135867
135868/*
135869** The lower 16-bits of the sqlite3_index_info.idxNum value set by
135870** the xBestIndex() method contains the Fts3Cursor.eSearch value described
135871** above. The upper 16-bits contain a combination of the following
135872** bits, used to describe extra constraints on full-text searches.
135873*/
135874#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
135875#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
135876#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
135877
135878struct Fts3Doclist {
135879  char *aAll;                    /* Array containing doclist (or NULL) */
135880  int nAll;                      /* Size of a[] in bytes */
135881  char *pNextDocid;              /* Pointer to next docid */
135882
135883  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
135884  int bFreeList;                 /* True if pList should be sqlite3_free()d */
135885  char *pList;                   /* Pointer to position list following iDocid */
135886  int nList;                     /* Length of position list */
135887};
135888
135889/*
135890** A "phrase" is a sequence of one or more tokens that must match in
135891** sequence.  A single token is the base case and the most common case.
135892** For a sequence of tokens contained in double-quotes (i.e. "one two three")
135893** nToken will be the number of tokens in the string.
135894*/
135895struct Fts3PhraseToken {
135896  char *z;                        /* Text of the token */
135897  int n;                          /* Number of bytes in buffer z */
135898  int isPrefix;                   /* True if token ends with a "*" character */
135899  int bFirst;                     /* True if token must appear at position 0 */
135900
135901  /* Variables above this point are populated when the expression is
135902  ** parsed (by code in fts3_expr.c). Below this point the variables are
135903  ** used when evaluating the expression. */
135904  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
135905  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
135906};
135907
135908struct Fts3Phrase {
135909  /* Cache of doclist for this phrase. */
135910  Fts3Doclist doclist;
135911  int bIncr;                 /* True if doclist is loaded incrementally */
135912  int iDoclistToken;
135913
135914  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
135915  ** OR condition.  */
135916  char *pOrPoslist;
135917  i64 iOrDocid;
135918
135919  /* Variables below this point are populated by fts3_expr.c when parsing
135920  ** a MATCH expression. Everything above is part of the evaluation phase.
135921  */
135922  int nToken;                /* Number of tokens in the phrase */
135923  int iColumn;               /* Index of column this phrase must match */
135924  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
135925};
135926
135927/*
135928** A tree of these objects forms the RHS of a MATCH operator.
135929**
135930** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
135931** points to a malloced buffer, size nDoclist bytes, containing the results
135932** of this phrase query in FTS3 doclist format. As usual, the initial
135933** "Length" field found in doclists stored on disk is omitted from this
135934** buffer.
135935**
135936** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
135937** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
135938** where nCol is the number of columns in the queried FTS table. The array
135939** is populated as follows:
135940**
135941**   aMI[iCol*3 + 0] = Undefined
135942**   aMI[iCol*3 + 1] = Number of occurrences
135943**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
135944**
135945** The aMI array is allocated using sqlite3_malloc(). It should be freed
135946** when the expression node is.
135947*/
135948struct Fts3Expr {
135949  int eType;                 /* One of the FTSQUERY_XXX values defined below */
135950  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
135951  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
135952  Fts3Expr *pLeft;           /* Left operand */
135953  Fts3Expr *pRight;          /* Right operand */
135954  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
135955
135956  /* The following are used by the fts3_eval.c module. */
135957  sqlite3_int64 iDocid;      /* Current docid */
135958  u8 bEof;                   /* True this expression is at EOF already */
135959  u8 bStart;                 /* True if iDocid is valid */
135960  u8 bDeferred;              /* True if this expression is entirely deferred */
135961
135962  /* The following are used by the fts3_snippet.c module. */
135963  int iPhrase;               /* Index of this phrase in matchinfo() results */
135964  u32 *aMI;                  /* See above */
135965};
135966
135967/*
135968** Candidate values for Fts3Query.eType. Note that the order of the first
135969** four values is in order of precedence when parsing expressions. For
135970** example, the following:
135971**
135972**   "a OR b AND c NOT d NEAR e"
135973**
135974** is equivalent to:
135975**
135976**   "a OR (b AND (c NOT (d NEAR e)))"
135977*/
135978#define FTSQUERY_NEAR   1
135979#define FTSQUERY_NOT    2
135980#define FTSQUERY_AND    3
135981#define FTSQUERY_OR     4
135982#define FTSQUERY_PHRASE 5
135983
135984
135985/* fts3_write.c */
135986SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
135987SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
135988SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
135989SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
135990SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
135991  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
135992SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
135993  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
135994SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
135995SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
135996SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
135997
135998SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
135999SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
136000
136001#ifndef SQLITE_DISABLE_FTS4_DEFERRED
136002SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
136003SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
136004SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
136005SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
136006SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
136007#else
136008# define sqlite3Fts3FreeDeferredTokens(x)
136009# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
136010# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
136011# define sqlite3Fts3FreeDeferredDoclists(x)
136012# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
136013#endif
136014
136015SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
136016SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
136017
136018/* Special values interpreted by sqlite3SegReaderCursor() */
136019#define FTS3_SEGCURSOR_PENDING        -1
136020#define FTS3_SEGCURSOR_ALL            -2
136021
136022SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
136023SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
136024SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
136025
136026SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
136027    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
136028
136029/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
136030#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
136031#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
136032#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
136033#define FTS3_SEGMENT_PREFIX        0x00000008
136034#define FTS3_SEGMENT_SCAN          0x00000010
136035#define FTS3_SEGMENT_FIRST         0x00000020
136036
136037/* Type passed as 4th argument to SegmentReaderIterate() */
136038struct Fts3SegFilter {
136039  const char *zTerm;
136040  int nTerm;
136041  int iCol;
136042  int flags;
136043};
136044
136045struct Fts3MultiSegReader {
136046  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
136047  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
136048  int nSegment;                   /* Size of apSegment array */
136049  int nAdvance;                   /* How many seg-readers to advance */
136050  Fts3SegFilter *pFilter;         /* Pointer to filter object */
136051  char *aBuffer;                  /* Buffer to merge doclists in */
136052  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
136053
136054  int iColFilter;                 /* If >=0, filter for this column */
136055  int bRestart;
136056
136057  /* Used by fts3.c only. */
136058  int nCost;                      /* Cost of running iterator */
136059  int bLookup;                    /* True if a lookup of a single entry. */
136060
136061  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
136062  char *zTerm;                    /* Pointer to term buffer */
136063  int nTerm;                      /* Size of zTerm in bytes */
136064  char *aDoclist;                 /* Pointer to doclist buffer */
136065  int nDoclist;                   /* Size of aDoclist[] in bytes */
136066};
136067
136068SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
136069
136070#define fts3GetVarint32(p, piVal) (                                           \
136071  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
136072)
136073
136074/* fts3.c */
136075SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
136076SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
136077SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
136078SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
136079SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
136080SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
136081SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
136082SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
136083SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
136084SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
136085SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
136086
136087/* fts3_tokenizer.c */
136088SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
136089SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
136090SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
136091    sqlite3_tokenizer **, char **
136092);
136093SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
136094
136095/* fts3_snippet.c */
136096SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
136097SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
136098  const char *, const char *, int, int
136099);
136100SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
136101SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
136102
136103/* fts3_expr.c */
136104SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
136105  char **, int, int, int, const char *, int, Fts3Expr **, char **
136106);
136107SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
136108#ifdef SQLITE_TEST
136109SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
136110SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
136111#endif
136112
136113SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
136114  sqlite3_tokenizer_cursor **
136115);
136116
136117/* fts3_aux.c */
136118SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
136119
136120SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
136121
136122SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
136123    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
136124SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
136125    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
136126SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
136127SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
136128SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
136129
136130/* fts3_tokenize_vtab.c */
136131SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
136132
136133/* fts3_unicode2.c (functions generated by parsing unicode text files) */
136134#ifndef SQLITE_DISABLE_FTS3_UNICODE
136135SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
136136SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
136137SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
136138#endif
136139
136140#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
136141#endif /* _FTSINT_H */
136142
136143/************** End of fts3Int.h *********************************************/
136144/************** Continuing where we left off in fts3.c ***********************/
136145#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
136146
136147#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
136148# define SQLITE_CORE 1
136149#endif
136150
136151/* #include <assert.h> */
136152/* #include <stdlib.h> */
136153/* #include <stddef.h> */
136154/* #include <stdio.h> */
136155/* #include <string.h> */
136156/* #include <stdarg.h> */
136157
136158/* #include "fts3.h" */
136159#ifndef SQLITE_CORE
136160/* # include "sqlite3ext.h" */
136161  SQLITE_EXTENSION_INIT1
136162#endif
136163
136164static int fts3EvalNext(Fts3Cursor *pCsr);
136165static int fts3EvalStart(Fts3Cursor *pCsr);
136166static int fts3TermSegReaderCursor(
136167    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
136168
136169#ifndef SQLITE_AMALGAMATION
136170# if defined(SQLITE_DEBUG)
136171SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
136172SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
136173# endif
136174#endif
136175
136176/*
136177** Write a 64-bit variable-length integer to memory starting at p[0].
136178** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
136179** The number of bytes written is returned.
136180*/
136181SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
136182  unsigned char *q = (unsigned char *) p;
136183  sqlite_uint64 vu = v;
136184  do{
136185    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
136186    vu >>= 7;
136187  }while( vu!=0 );
136188  q[-1] &= 0x7f;  /* turn off high bit in final byte */
136189  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
136190  return (int) (q - (unsigned char *)p);
136191}
136192
136193#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
136194  v = (v & mask1) | ( (*ptr++) << shift );                    \
136195  if( (v & mask2)==0 ){ var = v; return ret; }
136196#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
136197  v = (*ptr++);                                               \
136198  if( (v & mask2)==0 ){ var = v; return ret; }
136199
136200/*
136201** Read a 64-bit variable-length integer from memory starting at p[0].
136202** Return the number of bytes read, or 0 on error.
136203** The value is stored in *v.
136204*/
136205SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
136206  const char *pStart = p;
136207  u32 a;
136208  u64 b;
136209  int shift;
136210
136211  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
136212  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
136213  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
136214  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
136215  b = (a & 0x0FFFFFFF );
136216
136217  for(shift=28; shift<=63; shift+=7){
136218    u64 c = *p++;
136219    b += (c&0x7F) << shift;
136220    if( (c & 0x80)==0 ) break;
136221  }
136222  *v = b;
136223  return (int)(p - pStart);
136224}
136225
136226/*
136227** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
136228** 32-bit integer before it is returned.
136229*/
136230SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
136231  u32 a;
136232
136233#ifndef fts3GetVarint32
136234  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
136235#else
136236  a = (*p++);
136237  assert( a & 0x80 );
136238#endif
136239
136240  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
136241  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
136242  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
136243  a = (a & 0x0FFFFFFF );
136244  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
136245  return 5;
136246}
136247
136248/*
136249** Return the number of bytes required to encode v as a varint
136250*/
136251SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
136252  int i = 0;
136253  do{
136254    i++;
136255    v >>= 7;
136256  }while( v!=0 );
136257  return i;
136258}
136259
136260/*
136261** Convert an SQL-style quoted string into a normal string by removing
136262** the quote characters.  The conversion is done in-place.  If the
136263** input does not begin with a quote character, then this routine
136264** is a no-op.
136265**
136266** Examples:
136267**
136268**     "abc"   becomes   abc
136269**     'xyz'   becomes   xyz
136270**     [pqr]   becomes   pqr
136271**     `mno`   becomes   mno
136272**
136273*/
136274SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
136275  char quote;                     /* Quote character (if any ) */
136276
136277  quote = z[0];
136278  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
136279    int iIn = 1;                  /* Index of next byte to read from input */
136280    int iOut = 0;                 /* Index of next byte to write to output */
136281
136282    /* If the first byte was a '[', then the close-quote character is a ']' */
136283    if( quote=='[' ) quote = ']';
136284
136285    while( z[iIn] ){
136286      if( z[iIn]==quote ){
136287        if( z[iIn+1]!=quote ) break;
136288        z[iOut++] = quote;
136289        iIn += 2;
136290      }else{
136291        z[iOut++] = z[iIn++];
136292      }
136293    }
136294    z[iOut] = '\0';
136295  }
136296}
136297
136298/*
136299** Read a single varint from the doclist at *pp and advance *pp to point
136300** to the first byte past the end of the varint.  Add the value of the varint
136301** to *pVal.
136302*/
136303static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
136304  sqlite3_int64 iVal;
136305  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
136306  *pVal += iVal;
136307}
136308
136309/*
136310** When this function is called, *pp points to the first byte following a
136311** varint that is part of a doclist (or position-list, or any other list
136312** of varints). This function moves *pp to point to the start of that varint,
136313** and sets *pVal by the varint value.
136314**
136315** Argument pStart points to the first byte of the doclist that the
136316** varint is part of.
136317*/
136318static void fts3GetReverseVarint(
136319  char **pp,
136320  char *pStart,
136321  sqlite3_int64 *pVal
136322){
136323  sqlite3_int64 iVal;
136324  char *p;
136325
136326  /* Pointer p now points at the first byte past the varint we are
136327  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
136328  ** clear on character p[-1]. */
136329  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
136330  p++;
136331  *pp = p;
136332
136333  sqlite3Fts3GetVarint(p, &iVal);
136334  *pVal = iVal;
136335}
136336
136337/*
136338** The xDisconnect() virtual table method.
136339*/
136340static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
136341  Fts3Table *p = (Fts3Table *)pVtab;
136342  int i;
136343
136344  assert( p->nPendingData==0 );
136345  assert( p->pSegments==0 );
136346
136347  /* Free any prepared statements held */
136348  for(i=0; i<SizeofArray(p->aStmt); i++){
136349    sqlite3_finalize(p->aStmt[i]);
136350  }
136351  sqlite3_free(p->zSegmentsTbl);
136352  sqlite3_free(p->zReadExprlist);
136353  sqlite3_free(p->zWriteExprlist);
136354  sqlite3_free(p->zContentTbl);
136355  sqlite3_free(p->zLanguageid);
136356
136357  /* Invoke the tokenizer destructor to free the tokenizer. */
136358  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
136359
136360  sqlite3_free(p);
136361  return SQLITE_OK;
136362}
136363
136364/*
136365** Write an error message into *pzErr
136366*/
136367SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
136368  va_list ap;
136369  sqlite3_free(*pzErr);
136370  va_start(ap, zFormat);
136371  *pzErr = sqlite3_vmprintf(zFormat, ap);
136372  va_end(ap);
136373}
136374
136375/*
136376** Construct one or more SQL statements from the format string given
136377** and then evaluate those statements. The success code is written
136378** into *pRc.
136379**
136380** If *pRc is initially non-zero then this routine is a no-op.
136381*/
136382static void fts3DbExec(
136383  int *pRc,              /* Success code */
136384  sqlite3 *db,           /* Database in which to run SQL */
136385  const char *zFormat,   /* Format string for SQL */
136386  ...                    /* Arguments to the format string */
136387){
136388  va_list ap;
136389  char *zSql;
136390  if( *pRc ) return;
136391  va_start(ap, zFormat);
136392  zSql = sqlite3_vmprintf(zFormat, ap);
136393  va_end(ap);
136394  if( zSql==0 ){
136395    *pRc = SQLITE_NOMEM;
136396  }else{
136397    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
136398    sqlite3_free(zSql);
136399  }
136400}
136401
136402/*
136403** The xDestroy() virtual table method.
136404*/
136405static int fts3DestroyMethod(sqlite3_vtab *pVtab){
136406  Fts3Table *p = (Fts3Table *)pVtab;
136407  int rc = SQLITE_OK;              /* Return code */
136408  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
136409  sqlite3 *db = p->db;             /* Database handle */
136410
136411  /* Drop the shadow tables */
136412  if( p->zContentTbl==0 ){
136413    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
136414  }
136415  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
136416  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
136417  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
136418  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
136419
136420  /* If everything has worked, invoke fts3DisconnectMethod() to free the
136421  ** memory associated with the Fts3Table structure and return SQLITE_OK.
136422  ** Otherwise, return an SQLite error code.
136423  */
136424  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
136425}
136426
136427
136428/*
136429** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
136430** passed as the first argument. This is done as part of the xConnect()
136431** and xCreate() methods.
136432**
136433** If *pRc is non-zero when this function is called, it is a no-op.
136434** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
136435** before returning.
136436*/
136437static void fts3DeclareVtab(int *pRc, Fts3Table *p){
136438  if( *pRc==SQLITE_OK ){
136439    int i;                        /* Iterator variable */
136440    int rc;                       /* Return code */
136441    char *zSql;                   /* SQL statement passed to declare_vtab() */
136442    char *zCols;                  /* List of user defined columns */
136443    const char *zLanguageid;
136444
136445    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
136446    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
136447
136448    /* Create a list of user columns for the virtual table */
136449    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
136450    for(i=1; zCols && i<p->nColumn; i++){
136451      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
136452    }
136453
136454    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
136455    zSql = sqlite3_mprintf(
136456        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
136457        zCols, p->zName, zLanguageid
136458    );
136459    if( !zCols || !zSql ){
136460      rc = SQLITE_NOMEM;
136461    }else{
136462      rc = sqlite3_declare_vtab(p->db, zSql);
136463    }
136464
136465    sqlite3_free(zSql);
136466    sqlite3_free(zCols);
136467    *pRc = rc;
136468  }
136469}
136470
136471/*
136472** Create the %_stat table if it does not already exist.
136473*/
136474SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
136475  fts3DbExec(pRc, p->db,
136476      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
136477          "(id INTEGER PRIMARY KEY, value BLOB);",
136478      p->zDb, p->zName
136479  );
136480  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
136481}
136482
136483/*
136484** Create the backing store tables (%_content, %_segments and %_segdir)
136485** required by the FTS3 table passed as the only argument. This is done
136486** as part of the vtab xCreate() method.
136487**
136488** If the p->bHasDocsize boolean is true (indicating that this is an
136489** FTS4 table, not an FTS3 table) then also create the %_docsize and
136490** %_stat tables required by FTS4.
136491*/
136492static int fts3CreateTables(Fts3Table *p){
136493  int rc = SQLITE_OK;             /* Return code */
136494  int i;                          /* Iterator variable */
136495  sqlite3 *db = p->db;            /* The database connection */
136496
136497  if( p->zContentTbl==0 ){
136498    const char *zLanguageid = p->zLanguageid;
136499    char *zContentCols;           /* Columns of %_content table */
136500
136501    /* Create a list of user columns for the content table */
136502    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
136503    for(i=0; zContentCols && i<p->nColumn; i++){
136504      char *z = p->azColumn[i];
136505      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
136506    }
136507    if( zLanguageid && zContentCols ){
136508      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
136509    }
136510    if( zContentCols==0 ) rc = SQLITE_NOMEM;
136511
136512    /* Create the content table */
136513    fts3DbExec(&rc, db,
136514       "CREATE TABLE %Q.'%q_content'(%s)",
136515       p->zDb, p->zName, zContentCols
136516    );
136517    sqlite3_free(zContentCols);
136518  }
136519
136520  /* Create other tables */
136521  fts3DbExec(&rc, db,
136522      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
136523      p->zDb, p->zName
136524  );
136525  fts3DbExec(&rc, db,
136526      "CREATE TABLE %Q.'%q_segdir'("
136527        "level INTEGER,"
136528        "idx INTEGER,"
136529        "start_block INTEGER,"
136530        "leaves_end_block INTEGER,"
136531        "end_block INTEGER,"
136532        "root BLOB,"
136533        "PRIMARY KEY(level, idx)"
136534      ");",
136535      p->zDb, p->zName
136536  );
136537  if( p->bHasDocsize ){
136538    fts3DbExec(&rc, db,
136539        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
136540        p->zDb, p->zName
136541    );
136542  }
136543  assert( p->bHasStat==p->bFts4 );
136544  if( p->bHasStat ){
136545    sqlite3Fts3CreateStatTable(&rc, p);
136546  }
136547  return rc;
136548}
136549
136550/*
136551** Store the current database page-size in bytes in p->nPgsz.
136552**
136553** If *pRc is non-zero when this function is called, it is a no-op.
136554** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
136555** before returning.
136556*/
136557static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
136558  if( *pRc==SQLITE_OK ){
136559    int rc;                       /* Return code */
136560    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
136561    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
136562
136563    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
136564    if( !zSql ){
136565      rc = SQLITE_NOMEM;
136566    }else{
136567      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
136568      if( rc==SQLITE_OK ){
136569        sqlite3_step(pStmt);
136570        p->nPgsz = sqlite3_column_int(pStmt, 0);
136571        rc = sqlite3_finalize(pStmt);
136572      }else if( rc==SQLITE_AUTH ){
136573        p->nPgsz = 1024;
136574        rc = SQLITE_OK;
136575      }
136576    }
136577    assert( p->nPgsz>0 || rc!=SQLITE_OK );
136578    sqlite3_free(zSql);
136579    *pRc = rc;
136580  }
136581}
136582
136583/*
136584** "Special" FTS4 arguments are column specifications of the following form:
136585**
136586**   <key> = <value>
136587**
136588** There may not be whitespace surrounding the "=" character. The <value>
136589** term may be quoted, but the <key> may not.
136590*/
136591static int fts3IsSpecialColumn(
136592  const char *z,
136593  int *pnKey,
136594  char **pzValue
136595){
136596  char *zValue;
136597  const char *zCsr = z;
136598
136599  while( *zCsr!='=' ){
136600    if( *zCsr=='\0' ) return 0;
136601    zCsr++;
136602  }
136603
136604  *pnKey = (int)(zCsr-z);
136605  zValue = sqlite3_mprintf("%s", &zCsr[1]);
136606  if( zValue ){
136607    sqlite3Fts3Dequote(zValue);
136608  }
136609  *pzValue = zValue;
136610  return 1;
136611}
136612
136613/*
136614** Append the output of a printf() style formatting to an existing string.
136615*/
136616static void fts3Appendf(
136617  int *pRc,                       /* IN/OUT: Error code */
136618  char **pz,                      /* IN/OUT: Pointer to string buffer */
136619  const char *zFormat,            /* Printf format string to append */
136620  ...                             /* Arguments for printf format string */
136621){
136622  if( *pRc==SQLITE_OK ){
136623    va_list ap;
136624    char *z;
136625    va_start(ap, zFormat);
136626    z = sqlite3_vmprintf(zFormat, ap);
136627    va_end(ap);
136628    if( z && *pz ){
136629      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
136630      sqlite3_free(z);
136631      z = z2;
136632    }
136633    if( z==0 ) *pRc = SQLITE_NOMEM;
136634    sqlite3_free(*pz);
136635    *pz = z;
136636  }
136637}
136638
136639/*
136640** Return a copy of input string zInput enclosed in double-quotes (") and
136641** with all double quote characters escaped. For example:
136642**
136643**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
136644**
136645** The pointer returned points to memory obtained from sqlite3_malloc(). It
136646** is the callers responsibility to call sqlite3_free() to release this
136647** memory.
136648*/
136649static char *fts3QuoteId(char const *zInput){
136650  int nRet;
136651  char *zRet;
136652  nRet = 2 + (int)strlen(zInput)*2 + 1;
136653  zRet = sqlite3_malloc(nRet);
136654  if( zRet ){
136655    int i;
136656    char *z = zRet;
136657    *(z++) = '"';
136658    for(i=0; zInput[i]; i++){
136659      if( zInput[i]=='"' ) *(z++) = '"';
136660      *(z++) = zInput[i];
136661    }
136662    *(z++) = '"';
136663    *(z++) = '\0';
136664  }
136665  return zRet;
136666}
136667
136668/*
136669** Return a list of comma separated SQL expressions and a FROM clause that
136670** could be used in a SELECT statement such as the following:
136671**
136672**     SELECT <list of expressions> FROM %_content AS x ...
136673**
136674** to return the docid, followed by each column of text data in order
136675** from left to write. If parameter zFunc is not NULL, then instead of
136676** being returned directly each column of text data is passed to an SQL
136677** function named zFunc first. For example, if zFunc is "unzip" and the
136678** table has the three user-defined columns "a", "b", and "c", the following
136679** string is returned:
136680**
136681**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
136682**
136683** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
136684** is the responsibility of the caller to eventually free it.
136685**
136686** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
136687** a NULL pointer is returned). Otherwise, if an OOM error is encountered
136688** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
136689** no error occurs, *pRc is left unmodified.
136690*/
136691static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
136692  char *zRet = 0;
136693  char *zFree = 0;
136694  char *zFunction;
136695  int i;
136696
136697  if( p->zContentTbl==0 ){
136698    if( !zFunc ){
136699      zFunction = "";
136700    }else{
136701      zFree = zFunction = fts3QuoteId(zFunc);
136702    }
136703    fts3Appendf(pRc, &zRet, "docid");
136704    for(i=0; i<p->nColumn; i++){
136705      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
136706    }
136707    if( p->zLanguageid ){
136708      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
136709    }
136710    sqlite3_free(zFree);
136711  }else{
136712    fts3Appendf(pRc, &zRet, "rowid");
136713    for(i=0; i<p->nColumn; i++){
136714      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
136715    }
136716    if( p->zLanguageid ){
136717      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
136718    }
136719  }
136720  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
136721      p->zDb,
136722      (p->zContentTbl ? p->zContentTbl : p->zName),
136723      (p->zContentTbl ? "" : "_content")
136724  );
136725  return zRet;
136726}
136727
136728/*
136729** Return a list of N comma separated question marks, where N is the number
136730** of columns in the %_content table (one for the docid plus one for each
136731** user-defined text column).
136732**
136733** If argument zFunc is not NULL, then all but the first question mark
136734** is preceded by zFunc and an open bracket, and followed by a closed
136735** bracket. For example, if zFunc is "zip" and the FTS3 table has three
136736** user-defined text columns, the following string is returned:
136737**
136738**     "?, zip(?), zip(?), zip(?)"
136739**
136740** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
136741** is the responsibility of the caller to eventually free it.
136742**
136743** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
136744** a NULL pointer is returned). Otherwise, if an OOM error is encountered
136745** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
136746** no error occurs, *pRc is left unmodified.
136747*/
136748static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
136749  char *zRet = 0;
136750  char *zFree = 0;
136751  char *zFunction;
136752  int i;
136753
136754  if( !zFunc ){
136755    zFunction = "";
136756  }else{
136757    zFree = zFunction = fts3QuoteId(zFunc);
136758  }
136759  fts3Appendf(pRc, &zRet, "?");
136760  for(i=0; i<p->nColumn; i++){
136761    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
136762  }
136763  if( p->zLanguageid ){
136764    fts3Appendf(pRc, &zRet, ", ?");
136765  }
136766  sqlite3_free(zFree);
136767  return zRet;
136768}
136769
136770/*
136771** This function interprets the string at (*pp) as a non-negative integer
136772** value. It reads the integer and sets *pnOut to the value read, then
136773** sets *pp to point to the byte immediately following the last byte of
136774** the integer value.
136775**
136776** Only decimal digits ('0'..'9') may be part of an integer value.
136777**
136778** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
136779** the output value undefined. Otherwise SQLITE_OK is returned.
136780**
136781** This function is used when parsing the "prefix=" FTS4 parameter.
136782*/
136783static int fts3GobbleInt(const char **pp, int *pnOut){
136784  const int MAX_NPREFIX = 10000000;
136785  const char *p;                  /* Iterator pointer */
136786  int nInt = 0;                   /* Output value */
136787
136788  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
136789    nInt = nInt * 10 + (p[0] - '0');
136790    if( nInt>MAX_NPREFIX ){
136791      nInt = 0;
136792      break;
136793    }
136794  }
136795  if( p==*pp ) return SQLITE_ERROR;
136796  *pnOut = nInt;
136797  *pp = p;
136798  return SQLITE_OK;
136799}
136800
136801/*
136802** This function is called to allocate an array of Fts3Index structures
136803** representing the indexes maintained by the current FTS table. FTS tables
136804** always maintain the main "terms" index, but may also maintain one or
136805** more "prefix" indexes, depending on the value of the "prefix=" parameter
136806** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
136807**
136808** Argument zParam is passed the value of the "prefix=" option if one was
136809** specified, or NULL otherwise.
136810**
136811** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
136812** the allocated array. *pnIndex is set to the number of elements in the
136813** array. If an error does occur, an SQLite error code is returned.
136814**
136815** Regardless of whether or not an error is returned, it is the responsibility
136816** of the caller to call sqlite3_free() on the output array to free it.
136817*/
136818static int fts3PrefixParameter(
136819  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
136820  int *pnIndex,                   /* OUT: size of *apIndex[] array */
136821  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
136822){
136823  struct Fts3Index *aIndex;       /* Allocated array */
136824  int nIndex = 1;                 /* Number of entries in array */
136825
136826  if( zParam && zParam[0] ){
136827    const char *p;
136828    nIndex++;
136829    for(p=zParam; *p; p++){
136830      if( *p==',' ) nIndex++;
136831    }
136832  }
136833
136834  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
136835  *apIndex = aIndex;
136836  if( !aIndex ){
136837    return SQLITE_NOMEM;
136838  }
136839
136840  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
136841  if( zParam ){
136842    const char *p = zParam;
136843    int i;
136844    for(i=1; i<nIndex; i++){
136845      int nPrefix = 0;
136846      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
136847      assert( nPrefix>=0 );
136848      if( nPrefix==0 ){
136849        nIndex--;
136850        i--;
136851      }else{
136852        aIndex[i].nPrefix = nPrefix;
136853      }
136854      p++;
136855    }
136856  }
136857
136858  *pnIndex = nIndex;
136859  return SQLITE_OK;
136860}
136861
136862/*
136863** This function is called when initializing an FTS4 table that uses the
136864** content=xxx option. It determines the number of and names of the columns
136865** of the new FTS4 table.
136866**
136867** The third argument passed to this function is the value passed to the
136868** config=xxx option (i.e. "xxx"). This function queries the database for
136869** a table of that name. If found, the output variables are populated
136870** as follows:
136871**
136872**   *pnCol:   Set to the number of columns table xxx has,
136873**
136874**   *pnStr:   Set to the total amount of space required to store a copy
136875**             of each columns name, including the nul-terminator.
136876**
136877**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
136878**             the name of the corresponding column in table xxx. The array
136879**             and its contents are allocated using a single allocation. It
136880**             is the responsibility of the caller to free this allocation
136881**             by eventually passing the *pazCol value to sqlite3_free().
136882**
136883** If the table cannot be found, an error code is returned and the output
136884** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
136885** returned (and the output variables are undefined).
136886*/
136887static int fts3ContentColumns(
136888  sqlite3 *db,                    /* Database handle */
136889  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
136890  const char *zTbl,               /* Name of content table */
136891  const char ***pazCol,           /* OUT: Malloc'd array of column names */
136892  int *pnCol,                     /* OUT: Size of array *pazCol */
136893  int *pnStr,                     /* OUT: Bytes of string content */
136894  char **pzErr                    /* OUT: error message */
136895){
136896  int rc = SQLITE_OK;             /* Return code */
136897  char *zSql;                     /* "SELECT *" statement on zTbl */
136898  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
136899
136900  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
136901  if( !zSql ){
136902    rc = SQLITE_NOMEM;
136903  }else{
136904    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
136905    if( rc!=SQLITE_OK ){
136906      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
136907    }
136908  }
136909  sqlite3_free(zSql);
136910
136911  if( rc==SQLITE_OK ){
136912    const char **azCol;           /* Output array */
136913    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
136914    int nCol;                     /* Number of table columns */
136915    int i;                        /* Used to iterate through columns */
136916
136917    /* Loop through the returned columns. Set nStr to the number of bytes of
136918    ** space required to store a copy of each column name, including the
136919    ** nul-terminator byte.  */
136920    nCol = sqlite3_column_count(pStmt);
136921    for(i=0; i<nCol; i++){
136922      const char *zCol = sqlite3_column_name(pStmt, i);
136923      nStr += (int)strlen(zCol) + 1;
136924    }
136925
136926    /* Allocate and populate the array to return. */
136927    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
136928    if( azCol==0 ){
136929      rc = SQLITE_NOMEM;
136930    }else{
136931      char *p = (char *)&azCol[nCol];
136932      for(i=0; i<nCol; i++){
136933        const char *zCol = sqlite3_column_name(pStmt, i);
136934        int n = (int)strlen(zCol)+1;
136935        memcpy(p, zCol, n);
136936        azCol[i] = p;
136937        p += n;
136938      }
136939    }
136940    sqlite3_finalize(pStmt);
136941
136942    /* Set the output variables. */
136943    *pnCol = nCol;
136944    *pnStr = nStr;
136945    *pazCol = azCol;
136946  }
136947
136948  return rc;
136949}
136950
136951/*
136952** This function is the implementation of both the xConnect and xCreate
136953** methods of the FTS3 virtual table.
136954**
136955** The argv[] array contains the following:
136956**
136957**   argv[0]   -> module name  ("fts3" or "fts4")
136958**   argv[1]   -> database name
136959**   argv[2]   -> table name
136960**   argv[...] -> "column name" and other module argument fields.
136961*/
136962static int fts3InitVtab(
136963  int isCreate,                   /* True for xCreate, false for xConnect */
136964  sqlite3 *db,                    /* The SQLite database connection */
136965  void *pAux,                     /* Hash table containing tokenizers */
136966  int argc,                       /* Number of elements in argv array */
136967  const char * const *argv,       /* xCreate/xConnect argument array */
136968  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
136969  char **pzErr                    /* Write any error message here */
136970){
136971  Fts3Hash *pHash = (Fts3Hash *)pAux;
136972  Fts3Table *p = 0;               /* Pointer to allocated vtab */
136973  int rc = SQLITE_OK;             /* Return code */
136974  int i;                          /* Iterator variable */
136975  int nByte;                      /* Size of allocation used for *p */
136976  int iCol;                       /* Column index */
136977  int nString = 0;                /* Bytes required to hold all column names */
136978  int nCol = 0;                   /* Number of columns in the FTS table */
136979  char *zCsr;                     /* Space for holding column names */
136980  int nDb;                        /* Bytes required to hold database name */
136981  int nName;                      /* Bytes required to hold table name */
136982  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
136983  const char **aCol;              /* Array of column names */
136984  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
136985
136986  int nIndex = 0;                 /* Size of aIndex[] array */
136987  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
136988
136989  /* The results of parsing supported FTS4 key=value options: */
136990  int bNoDocsize = 0;             /* True to omit %_docsize table */
136991  int bDescIdx = 0;               /* True to store descending indexes */
136992  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
136993  char *zCompress = 0;            /* compress=? parameter (or NULL) */
136994  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
136995  char *zContent = 0;             /* content=? parameter (or NULL) */
136996  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
136997  char **azNotindexed = 0;        /* The set of notindexed= columns */
136998  int nNotindexed = 0;            /* Size of azNotindexed[] array */
136999
137000  assert( strlen(argv[0])==4 );
137001  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
137002       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
137003  );
137004
137005  nDb = (int)strlen(argv[1]) + 1;
137006  nName = (int)strlen(argv[2]) + 1;
137007
137008  nByte = sizeof(const char *) * (argc-2);
137009  aCol = (const char **)sqlite3_malloc(nByte);
137010  if( aCol ){
137011    memset((void*)aCol, 0, nByte);
137012    azNotindexed = (char **)sqlite3_malloc(nByte);
137013  }
137014  if( azNotindexed ){
137015    memset(azNotindexed, 0, nByte);
137016  }
137017  if( !aCol || !azNotindexed ){
137018    rc = SQLITE_NOMEM;
137019    goto fts3_init_out;
137020  }
137021
137022  /* Loop through all of the arguments passed by the user to the FTS3/4
137023  ** module (i.e. all the column names and special arguments). This loop
137024  ** does the following:
137025  **
137026  **   + Figures out the number of columns the FTSX table will have, and
137027  **     the number of bytes of space that must be allocated to store copies
137028  **     of the column names.
137029  **
137030  **   + If there is a tokenizer specification included in the arguments,
137031  **     initializes the tokenizer pTokenizer.
137032  */
137033  for(i=3; rc==SQLITE_OK && i<argc; i++){
137034    char const *z = argv[i];
137035    int nKey;
137036    char *zVal;
137037
137038    /* Check if this is a tokenizer specification */
137039    if( !pTokenizer
137040     && strlen(z)>8
137041     && 0==sqlite3_strnicmp(z, "tokenize", 8)
137042     && 0==sqlite3Fts3IsIdChar(z[8])
137043    ){
137044      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
137045    }
137046
137047    /* Check if it is an FTS4 special argument. */
137048    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
137049      struct Fts4Option {
137050        const char *zOpt;
137051        int nOpt;
137052      } aFts4Opt[] = {
137053        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
137054        { "prefix",      6 },     /* 1 -> PREFIX */
137055        { "compress",    8 },     /* 2 -> COMPRESS */
137056        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
137057        { "order",       5 },     /* 4 -> ORDER */
137058        { "content",     7 },     /* 5 -> CONTENT */
137059        { "languageid", 10 },     /* 6 -> LANGUAGEID */
137060        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
137061      };
137062
137063      int iOpt;
137064      if( !zVal ){
137065        rc = SQLITE_NOMEM;
137066      }else{
137067        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
137068          struct Fts4Option *pOp = &aFts4Opt[iOpt];
137069          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
137070            break;
137071          }
137072        }
137073        if( iOpt==SizeofArray(aFts4Opt) ){
137074          sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
137075          rc = SQLITE_ERROR;
137076        }else{
137077          switch( iOpt ){
137078            case 0:               /* MATCHINFO */
137079              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
137080                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
137081                rc = SQLITE_ERROR;
137082              }
137083              bNoDocsize = 1;
137084              break;
137085
137086            case 1:               /* PREFIX */
137087              sqlite3_free(zPrefix);
137088              zPrefix = zVal;
137089              zVal = 0;
137090              break;
137091
137092            case 2:               /* COMPRESS */
137093              sqlite3_free(zCompress);
137094              zCompress = zVal;
137095              zVal = 0;
137096              break;
137097
137098            case 3:               /* UNCOMPRESS */
137099              sqlite3_free(zUncompress);
137100              zUncompress = zVal;
137101              zVal = 0;
137102              break;
137103
137104            case 4:               /* ORDER */
137105              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
137106               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
137107              ){
137108                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
137109                rc = SQLITE_ERROR;
137110              }
137111              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
137112              break;
137113
137114            case 5:              /* CONTENT */
137115              sqlite3_free(zContent);
137116              zContent = zVal;
137117              zVal = 0;
137118              break;
137119
137120            case 6:              /* LANGUAGEID */
137121              assert( iOpt==6 );
137122              sqlite3_free(zLanguageid);
137123              zLanguageid = zVal;
137124              zVal = 0;
137125              break;
137126
137127            case 7:              /* NOTINDEXED */
137128              azNotindexed[nNotindexed++] = zVal;
137129              zVal = 0;
137130              break;
137131          }
137132        }
137133        sqlite3_free(zVal);
137134      }
137135    }
137136
137137    /* Otherwise, the argument is a column name. */
137138    else {
137139      nString += (int)(strlen(z) + 1);
137140      aCol[nCol++] = z;
137141    }
137142  }
137143
137144  /* If a content=xxx option was specified, the following:
137145  **
137146  **   1. Ignore any compress= and uncompress= options.
137147  **
137148  **   2. If no column names were specified as part of the CREATE VIRTUAL
137149  **      TABLE statement, use all columns from the content table.
137150  */
137151  if( rc==SQLITE_OK && zContent ){
137152    sqlite3_free(zCompress);
137153    sqlite3_free(zUncompress);
137154    zCompress = 0;
137155    zUncompress = 0;
137156    if( nCol==0 ){
137157      sqlite3_free((void*)aCol);
137158      aCol = 0;
137159      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
137160
137161      /* If a languageid= option was specified, remove the language id
137162      ** column from the aCol[] array. */
137163      if( rc==SQLITE_OK && zLanguageid ){
137164        int j;
137165        for(j=0; j<nCol; j++){
137166          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
137167            int k;
137168            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
137169            nCol--;
137170            break;
137171          }
137172        }
137173      }
137174    }
137175  }
137176  if( rc!=SQLITE_OK ) goto fts3_init_out;
137177
137178  if( nCol==0 ){
137179    assert( nString==0 );
137180    aCol[0] = "content";
137181    nString = 8;
137182    nCol = 1;
137183  }
137184
137185  if( pTokenizer==0 ){
137186    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
137187    if( rc!=SQLITE_OK ) goto fts3_init_out;
137188  }
137189  assert( pTokenizer );
137190
137191  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
137192  if( rc==SQLITE_ERROR ){
137193    assert( zPrefix );
137194    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
137195  }
137196  if( rc!=SQLITE_OK ) goto fts3_init_out;
137197
137198  /* Allocate and populate the Fts3Table structure. */
137199  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
137200          nCol * sizeof(char *) +              /* azColumn */
137201          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
137202          nCol * sizeof(u8) +                  /* abNotindexed */
137203          nName +                              /* zName */
137204          nDb +                                /* zDb */
137205          nString;                             /* Space for azColumn strings */
137206  p = (Fts3Table*)sqlite3_malloc(nByte);
137207  if( p==0 ){
137208    rc = SQLITE_NOMEM;
137209    goto fts3_init_out;
137210  }
137211  memset(p, 0, nByte);
137212  p->db = db;
137213  p->nColumn = nCol;
137214  p->nPendingData = 0;
137215  p->azColumn = (char **)&p[1];
137216  p->pTokenizer = pTokenizer;
137217  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
137218  p->bHasDocsize = (isFts4 && bNoDocsize==0);
137219  p->bHasStat = isFts4;
137220  p->bFts4 = isFts4;
137221  p->bDescIdx = bDescIdx;
137222  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
137223  p->zContentTbl = zContent;
137224  p->zLanguageid = zLanguageid;
137225  zContent = 0;
137226  zLanguageid = 0;
137227  TESTONLY( p->inTransaction = -1 );
137228  TESTONLY( p->mxSavepoint = -1 );
137229
137230  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
137231  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
137232  p->nIndex = nIndex;
137233  for(i=0; i<nIndex; i++){
137234    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
137235  }
137236  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
137237
137238  /* Fill in the zName and zDb fields of the vtab structure. */
137239  zCsr = (char *)&p->abNotindexed[nCol];
137240  p->zName = zCsr;
137241  memcpy(zCsr, argv[2], nName);
137242  zCsr += nName;
137243  p->zDb = zCsr;
137244  memcpy(zCsr, argv[1], nDb);
137245  zCsr += nDb;
137246
137247  /* Fill in the azColumn array */
137248  for(iCol=0; iCol<nCol; iCol++){
137249    char *z;
137250    int n = 0;
137251    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
137252    memcpy(zCsr, z, n);
137253    zCsr[n] = '\0';
137254    sqlite3Fts3Dequote(zCsr);
137255    p->azColumn[iCol] = zCsr;
137256    zCsr += n+1;
137257    assert( zCsr <= &((char *)p)[nByte] );
137258  }
137259
137260  /* Fill in the abNotindexed array */
137261  for(iCol=0; iCol<nCol; iCol++){
137262    int n = (int)strlen(p->azColumn[iCol]);
137263    for(i=0; i<nNotindexed; i++){
137264      char *zNot = azNotindexed[i];
137265      if( zNot && n==(int)strlen(zNot)
137266       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
137267      ){
137268        p->abNotindexed[iCol] = 1;
137269        sqlite3_free(zNot);
137270        azNotindexed[i] = 0;
137271      }
137272    }
137273  }
137274  for(i=0; i<nNotindexed; i++){
137275    if( azNotindexed[i] ){
137276      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
137277      rc = SQLITE_ERROR;
137278    }
137279  }
137280
137281  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
137282    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
137283    rc = SQLITE_ERROR;
137284    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
137285  }
137286  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
137287  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
137288  if( rc!=SQLITE_OK ) goto fts3_init_out;
137289
137290  /* If this is an xCreate call, create the underlying tables in the
137291  ** database. TODO: For xConnect(), it could verify that said tables exist.
137292  */
137293  if( isCreate ){
137294    rc = fts3CreateTables(p);
137295  }
137296
137297  /* Check to see if a legacy fts3 table has been "upgraded" by the
137298  ** addition of a %_stat table so that it can use incremental merge.
137299  */
137300  if( !isFts4 && !isCreate ){
137301    p->bHasStat = 2;
137302  }
137303
137304  /* Figure out the page-size for the database. This is required in order to
137305  ** estimate the cost of loading large doclists from the database.  */
137306  fts3DatabasePageSize(&rc, p);
137307  p->nNodeSize = p->nPgsz-35;
137308
137309  /* Declare the table schema to SQLite. */
137310  fts3DeclareVtab(&rc, p);
137311
137312fts3_init_out:
137313  sqlite3_free(zPrefix);
137314  sqlite3_free(aIndex);
137315  sqlite3_free(zCompress);
137316  sqlite3_free(zUncompress);
137317  sqlite3_free(zContent);
137318  sqlite3_free(zLanguageid);
137319  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
137320  sqlite3_free((void *)aCol);
137321  sqlite3_free((void *)azNotindexed);
137322  if( rc!=SQLITE_OK ){
137323    if( p ){
137324      fts3DisconnectMethod((sqlite3_vtab *)p);
137325    }else if( pTokenizer ){
137326      pTokenizer->pModule->xDestroy(pTokenizer);
137327    }
137328  }else{
137329    assert( p->pSegments==0 );
137330    *ppVTab = &p->base;
137331  }
137332  return rc;
137333}
137334
137335/*
137336** The xConnect() and xCreate() methods for the virtual table. All the
137337** work is done in function fts3InitVtab().
137338*/
137339static int fts3ConnectMethod(
137340  sqlite3 *db,                    /* Database connection */
137341  void *pAux,                     /* Pointer to tokenizer hash table */
137342  int argc,                       /* Number of elements in argv array */
137343  const char * const *argv,       /* xCreate/xConnect argument array */
137344  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
137345  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
137346){
137347  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
137348}
137349static int fts3CreateMethod(
137350  sqlite3 *db,                    /* Database connection */
137351  void *pAux,                     /* Pointer to tokenizer hash table */
137352  int argc,                       /* Number of elements in argv array */
137353  const char * const *argv,       /* xCreate/xConnect argument array */
137354  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
137355  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
137356){
137357  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
137358}
137359
137360/*
137361** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
137362** extension is currently being used by a version of SQLite too old to
137363** support estimatedRows. In that case this function is a no-op.
137364*/
137365static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
137366#if SQLITE_VERSION_NUMBER>=3008002
137367  if( sqlite3_libversion_number()>=3008002 ){
137368    pIdxInfo->estimatedRows = nRow;
137369  }
137370#endif
137371}
137372
137373/*
137374** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
137375** extension is currently being used by a version of SQLite too old to
137376** support index-info flags. In that case this function is a no-op.
137377*/
137378static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
137379#if SQLITE_VERSION_NUMBER>=3008012
137380  if( sqlite3_libversion_number()>=3008012 ){
137381    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
137382  }
137383#endif
137384}
137385
137386/*
137387** Implementation of the xBestIndex method for FTS3 tables. There
137388** are three possible strategies, in order of preference:
137389**
137390**   1. Direct lookup by rowid or docid.
137391**   2. Full-text search using a MATCH operator on a non-docid column.
137392**   3. Linear scan of %_content table.
137393*/
137394static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
137395  Fts3Table *p = (Fts3Table *)pVTab;
137396  int i;                          /* Iterator variable */
137397  int iCons = -1;                 /* Index of constraint to use */
137398
137399  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
137400  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
137401  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
137402  int iIdx;
137403
137404  /* By default use a full table scan. This is an expensive option,
137405  ** so search through the constraints to see if a more efficient
137406  ** strategy is possible.
137407  */
137408  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
137409  pInfo->estimatedCost = 5000000;
137410  for(i=0; i<pInfo->nConstraint; i++){
137411    int bDocid;                 /* True if this constraint is on docid */
137412    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
137413    if( pCons->usable==0 ){
137414      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
137415        /* There exists an unusable MATCH constraint. This means that if
137416        ** the planner does elect to use the results of this call as part
137417        ** of the overall query plan the user will see an "unable to use
137418        ** function MATCH in the requested context" error. To discourage
137419        ** this, return a very high cost here.  */
137420        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
137421        pInfo->estimatedCost = 1e50;
137422        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
137423        return SQLITE_OK;
137424      }
137425      continue;
137426    }
137427
137428    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
137429
137430    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
137431    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
137432      pInfo->idxNum = FTS3_DOCID_SEARCH;
137433      pInfo->estimatedCost = 1.0;
137434      iCons = i;
137435    }
137436
137437    /* A MATCH constraint. Use a full-text search.
137438    **
137439    ** If there is more than one MATCH constraint available, use the first
137440    ** one encountered. If there is both a MATCH constraint and a direct
137441    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
137442    ** though the rowid/docid lookup is faster than a MATCH query, selecting
137443    ** it would lead to an "unable to use function MATCH in the requested
137444    ** context" error.
137445    */
137446    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
137447     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
137448    ){
137449      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
137450      pInfo->estimatedCost = 2.0;
137451      iCons = i;
137452    }
137453
137454    /* Equality constraint on the langid column */
137455    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
137456     && pCons->iColumn==p->nColumn + 2
137457    ){
137458      iLangidCons = i;
137459    }
137460
137461    if( bDocid ){
137462      switch( pCons->op ){
137463        case SQLITE_INDEX_CONSTRAINT_GE:
137464        case SQLITE_INDEX_CONSTRAINT_GT:
137465          iDocidGe = i;
137466          break;
137467
137468        case SQLITE_INDEX_CONSTRAINT_LE:
137469        case SQLITE_INDEX_CONSTRAINT_LT:
137470          iDocidLe = i;
137471          break;
137472      }
137473    }
137474  }
137475
137476  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
137477  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
137478
137479  iIdx = 1;
137480  if( iCons>=0 ){
137481    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
137482    pInfo->aConstraintUsage[iCons].omit = 1;
137483  }
137484  if( iLangidCons>=0 ){
137485    pInfo->idxNum |= FTS3_HAVE_LANGID;
137486    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
137487  }
137488  if( iDocidGe>=0 ){
137489    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
137490    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
137491  }
137492  if( iDocidLe>=0 ){
137493    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
137494    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
137495  }
137496
137497  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
137498  ** docid) order. Both ascending and descending are possible.
137499  */
137500  if( pInfo->nOrderBy==1 ){
137501    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
137502    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
137503      if( pOrder->desc ){
137504        pInfo->idxStr = "DESC";
137505      }else{
137506        pInfo->idxStr = "ASC";
137507      }
137508      pInfo->orderByConsumed = 1;
137509    }
137510  }
137511
137512  assert( p->pSegments==0 );
137513  return SQLITE_OK;
137514}
137515
137516/*
137517** Implementation of xOpen method.
137518*/
137519static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
137520  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
137521
137522  UNUSED_PARAMETER(pVTab);
137523
137524  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
137525  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
137526  ** if the allocation fails, return SQLITE_NOMEM.
137527  */
137528  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
137529  if( !pCsr ){
137530    return SQLITE_NOMEM;
137531  }
137532  memset(pCsr, 0, sizeof(Fts3Cursor));
137533  return SQLITE_OK;
137534}
137535
137536/*
137537** Close the cursor.  For additional information see the documentation
137538** on the xClose method of the virtual table interface.
137539*/
137540static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
137541  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
137542  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
137543  sqlite3_finalize(pCsr->pStmt);
137544  sqlite3Fts3ExprFree(pCsr->pExpr);
137545  sqlite3Fts3FreeDeferredTokens(pCsr);
137546  sqlite3_free(pCsr->aDoclist);
137547  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
137548  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
137549  sqlite3_free(pCsr);
137550  return SQLITE_OK;
137551}
137552
137553/*
137554** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
137555** compose and prepare an SQL statement of the form:
137556**
137557**    "SELECT <columns> FROM %_content WHERE rowid = ?"
137558**
137559** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
137560** it. If an error occurs, return an SQLite error code.
137561**
137562** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
137563*/
137564static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
137565  int rc = SQLITE_OK;
137566  if( pCsr->pStmt==0 ){
137567    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
137568    char *zSql;
137569    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
137570    if( !zSql ) return SQLITE_NOMEM;
137571    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
137572    sqlite3_free(zSql);
137573  }
137574  *ppStmt = pCsr->pStmt;
137575  return rc;
137576}
137577
137578/*
137579** Position the pCsr->pStmt statement so that it is on the row
137580** of the %_content table that contains the last match.  Return
137581** SQLITE_OK on success.
137582*/
137583static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
137584  int rc = SQLITE_OK;
137585  if( pCsr->isRequireSeek ){
137586    sqlite3_stmt *pStmt = 0;
137587
137588    rc = fts3CursorSeekStmt(pCsr, &pStmt);
137589    if( rc==SQLITE_OK ){
137590      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
137591      pCsr->isRequireSeek = 0;
137592      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
137593        return SQLITE_OK;
137594      }else{
137595        rc = sqlite3_reset(pCsr->pStmt);
137596        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
137597          /* If no row was found and no error has occurred, then the %_content
137598          ** table is missing a row that is present in the full-text index.
137599          ** The data structures are corrupt.  */
137600          rc = FTS_CORRUPT_VTAB;
137601          pCsr->isEof = 1;
137602        }
137603      }
137604    }
137605  }
137606
137607  if( rc!=SQLITE_OK && pContext ){
137608    sqlite3_result_error_code(pContext, rc);
137609  }
137610  return rc;
137611}
137612
137613/*
137614** This function is used to process a single interior node when searching
137615** a b-tree for a term or term prefix. The node data is passed to this
137616** function via the zNode/nNode parameters. The term to search for is
137617** passed in zTerm/nTerm.
137618**
137619** If piFirst is not NULL, then this function sets *piFirst to the blockid
137620** of the child node that heads the sub-tree that may contain the term.
137621**
137622** If piLast is not NULL, then *piLast is set to the right-most child node
137623** that heads a sub-tree that may contain a term for which zTerm/nTerm is
137624** a prefix.
137625**
137626** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
137627*/
137628static int fts3ScanInteriorNode(
137629  const char *zTerm,              /* Term to select leaves for */
137630  int nTerm,                      /* Size of term zTerm in bytes */
137631  const char *zNode,              /* Buffer containing segment interior node */
137632  int nNode,                      /* Size of buffer at zNode */
137633  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
137634  sqlite3_int64 *piLast           /* OUT: Selected child node */
137635){
137636  int rc = SQLITE_OK;             /* Return code */
137637  const char *zCsr = zNode;       /* Cursor to iterate through node */
137638  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
137639  char *zBuffer = 0;              /* Buffer to load terms into */
137640  int nAlloc = 0;                 /* Size of allocated buffer */
137641  int isFirstTerm = 1;            /* True when processing first term on page */
137642  sqlite3_int64 iChild;           /* Block id of child node to descend to */
137643
137644  /* Skip over the 'height' varint that occurs at the start of every
137645  ** interior node. Then load the blockid of the left-child of the b-tree
137646  ** node into variable iChild.
137647  **
137648  ** Even if the data structure on disk is corrupted, this (reading two
137649  ** varints from the buffer) does not risk an overread. If zNode is a
137650  ** root node, then the buffer comes from a SELECT statement. SQLite does
137651  ** not make this guarantee explicitly, but in practice there are always
137652  ** either more than 20 bytes of allocated space following the nNode bytes of
137653  ** contents, or two zero bytes. Or, if the node is read from the %_segments
137654  ** table, then there are always 20 bytes of zeroed padding following the
137655  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
137656  */
137657  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
137658  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
137659  if( zCsr>zEnd ){
137660    return FTS_CORRUPT_VTAB;
137661  }
137662
137663  while( zCsr<zEnd && (piFirst || piLast) ){
137664    int cmp;                      /* memcmp() result */
137665    int nSuffix;                  /* Size of term suffix */
137666    int nPrefix = 0;              /* Size of term prefix */
137667    int nBuffer;                  /* Total term size */
137668
137669    /* Load the next term on the node into zBuffer. Use realloc() to expand
137670    ** the size of zBuffer if required.  */
137671    if( !isFirstTerm ){
137672      zCsr += fts3GetVarint32(zCsr, &nPrefix);
137673    }
137674    isFirstTerm = 0;
137675    zCsr += fts3GetVarint32(zCsr, &nSuffix);
137676
137677    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
137678      rc = FTS_CORRUPT_VTAB;
137679      goto finish_scan;
137680    }
137681    if( nPrefix+nSuffix>nAlloc ){
137682      char *zNew;
137683      nAlloc = (nPrefix+nSuffix) * 2;
137684      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
137685      if( !zNew ){
137686        rc = SQLITE_NOMEM;
137687        goto finish_scan;
137688      }
137689      zBuffer = zNew;
137690    }
137691    assert( zBuffer );
137692    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
137693    nBuffer = nPrefix + nSuffix;
137694    zCsr += nSuffix;
137695
137696    /* Compare the term we are searching for with the term just loaded from
137697    ** the interior node. If the specified term is greater than or equal
137698    ** to the term from the interior node, then all terms on the sub-tree
137699    ** headed by node iChild are smaller than zTerm. No need to search
137700    ** iChild.
137701    **
137702    ** If the interior node term is larger than the specified term, then
137703    ** the tree headed by iChild may contain the specified term.
137704    */
137705    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
137706    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
137707      *piFirst = iChild;
137708      piFirst = 0;
137709    }
137710
137711    if( piLast && cmp<0 ){
137712      *piLast = iChild;
137713      piLast = 0;
137714    }
137715
137716    iChild++;
137717  };
137718
137719  if( piFirst ) *piFirst = iChild;
137720  if( piLast ) *piLast = iChild;
137721
137722 finish_scan:
137723  sqlite3_free(zBuffer);
137724  return rc;
137725}
137726
137727
137728/*
137729** The buffer pointed to by argument zNode (size nNode bytes) contains an
137730** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
137731** contains a term. This function searches the sub-tree headed by the zNode
137732** node for the range of leaf nodes that may contain the specified term
137733** or terms for which the specified term is a prefix.
137734**
137735** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
137736** left-most leaf node in the tree that may contain the specified term.
137737** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
137738** right-most leaf node that may contain a term for which the specified
137739** term is a prefix.
137740**
137741** It is possible that the range of returned leaf nodes does not contain
137742** the specified term or any terms for which it is a prefix. However, if the
137743** segment does contain any such terms, they are stored within the identified
137744** range. Because this function only inspects interior segment nodes (and
137745** never loads leaf nodes into memory), it is not possible to be sure.
137746**
137747** If an error occurs, an error code other than SQLITE_OK is returned.
137748*/
137749static int fts3SelectLeaf(
137750  Fts3Table *p,                   /* Virtual table handle */
137751  const char *zTerm,              /* Term to select leaves for */
137752  int nTerm,                      /* Size of term zTerm in bytes */
137753  const char *zNode,              /* Buffer containing segment interior node */
137754  int nNode,                      /* Size of buffer at zNode */
137755  sqlite3_int64 *piLeaf,          /* Selected leaf node */
137756  sqlite3_int64 *piLeaf2          /* Selected leaf node */
137757){
137758  int rc = SQLITE_OK;             /* Return code */
137759  int iHeight;                    /* Height of this node in tree */
137760
137761  assert( piLeaf || piLeaf2 );
137762
137763  fts3GetVarint32(zNode, &iHeight);
137764  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
137765  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
137766
137767  if( rc==SQLITE_OK && iHeight>1 ){
137768    char *zBlob = 0;              /* Blob read from %_segments table */
137769    int nBlob = 0;                /* Size of zBlob in bytes */
137770
137771    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
137772      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
137773      if( rc==SQLITE_OK ){
137774        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
137775      }
137776      sqlite3_free(zBlob);
137777      piLeaf = 0;
137778      zBlob = 0;
137779    }
137780
137781    if( rc==SQLITE_OK ){
137782      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
137783    }
137784    if( rc==SQLITE_OK ){
137785      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
137786    }
137787    sqlite3_free(zBlob);
137788  }
137789
137790  return rc;
137791}
137792
137793/*
137794** This function is used to create delta-encoded serialized lists of FTS3
137795** varints. Each call to this function appends a single varint to a list.
137796*/
137797static void fts3PutDeltaVarint(
137798  char **pp,                      /* IN/OUT: Output pointer */
137799  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
137800  sqlite3_int64 iVal              /* Write this value to the list */
137801){
137802  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
137803  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
137804  *piPrev = iVal;
137805}
137806
137807/*
137808** When this function is called, *ppPoslist is assumed to point to the
137809** start of a position-list. After it returns, *ppPoslist points to the
137810** first byte after the position-list.
137811**
137812** A position list is list of positions (delta encoded) and columns for
137813** a single document record of a doclist.  So, in other words, this
137814** routine advances *ppPoslist so that it points to the next docid in
137815** the doclist, or to the first byte past the end of the doclist.
137816**
137817** If pp is not NULL, then the contents of the position list are copied
137818** to *pp. *pp is set to point to the first byte past the last byte copied
137819** before this function returns.
137820*/
137821static void fts3PoslistCopy(char **pp, char **ppPoslist){
137822  char *pEnd = *ppPoslist;
137823  char c = 0;
137824
137825  /* The end of a position list is marked by a zero encoded as an FTS3
137826  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
137827  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
137828  ** of some other, multi-byte, value.
137829  **
137830  ** The following while-loop moves pEnd to point to the first byte that is not
137831  ** immediately preceded by a byte with the 0x80 bit set. Then increments
137832  ** pEnd once more so that it points to the byte immediately following the
137833  ** last byte in the position-list.
137834  */
137835  while( *pEnd | c ){
137836    c = *pEnd++ & 0x80;
137837    testcase( c!=0 && (*pEnd)==0 );
137838  }
137839  pEnd++;  /* Advance past the POS_END terminator byte */
137840
137841  if( pp ){
137842    int n = (int)(pEnd - *ppPoslist);
137843    char *p = *pp;
137844    memcpy(p, *ppPoslist, n);
137845    p += n;
137846    *pp = p;
137847  }
137848  *ppPoslist = pEnd;
137849}
137850
137851/*
137852** When this function is called, *ppPoslist is assumed to point to the
137853** start of a column-list. After it returns, *ppPoslist points to the
137854** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
137855**
137856** A column-list is list of delta-encoded positions for a single column
137857** within a single document within a doclist.
137858**
137859** The column-list is terminated either by a POS_COLUMN varint (1) or
137860** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
137861** the POS_COLUMN or POS_END that terminates the column-list.
137862**
137863** If pp is not NULL, then the contents of the column-list are copied
137864** to *pp. *pp is set to point to the first byte past the last byte copied
137865** before this function returns.  The POS_COLUMN or POS_END terminator
137866** is not copied into *pp.
137867*/
137868static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
137869  char *pEnd = *ppPoslist;
137870  char c = 0;
137871
137872  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
137873  ** not part of a multi-byte varint.
137874  */
137875  while( 0xFE & (*pEnd | c) ){
137876    c = *pEnd++ & 0x80;
137877    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
137878  }
137879  if( pp ){
137880    int n = (int)(pEnd - *ppPoslist);
137881    char *p = *pp;
137882    memcpy(p, *ppPoslist, n);
137883    p += n;
137884    *pp = p;
137885  }
137886  *ppPoslist = pEnd;
137887}
137888
137889/*
137890** Value used to signify the end of an position-list. This is safe because
137891** it is not possible to have a document with 2^31 terms.
137892*/
137893#define POSITION_LIST_END 0x7fffffff
137894
137895/*
137896** This function is used to help parse position-lists. When this function is
137897** called, *pp may point to the start of the next varint in the position-list
137898** being parsed, or it may point to 1 byte past the end of the position-list
137899** (in which case **pp will be a terminator bytes POS_END (0) or
137900** (1)).
137901**
137902** If *pp points past the end of the current position-list, set *pi to
137903** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
137904** increment the current value of *pi by the value read, and set *pp to
137905** point to the next value before returning.
137906**
137907** Before calling this routine *pi must be initialized to the value of
137908** the previous position, or zero if we are reading the first position
137909** in the position-list.  Because positions are delta-encoded, the value
137910** of the previous position is needed in order to compute the value of
137911** the next position.
137912*/
137913static void fts3ReadNextPos(
137914  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
137915  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
137916){
137917  if( (**pp)&0xFE ){
137918    fts3GetDeltaVarint(pp, pi);
137919    *pi -= 2;
137920  }else{
137921    *pi = POSITION_LIST_END;
137922  }
137923}
137924
137925/*
137926** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
137927** the value of iCol encoded as a varint to *pp.   This will start a new
137928** column list.
137929**
137930** Set *pp to point to the byte just after the last byte written before
137931** returning (do not modify it if iCol==0). Return the total number of bytes
137932** written (0 if iCol==0).
137933*/
137934static int fts3PutColNumber(char **pp, int iCol){
137935  int n = 0;                      /* Number of bytes written */
137936  if( iCol ){
137937    char *p = *pp;                /* Output pointer */
137938    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
137939    *p = 0x01;
137940    *pp = &p[n];
137941  }
137942  return n;
137943}
137944
137945/*
137946** Compute the union of two position lists.  The output written
137947** into *pp contains all positions of both *pp1 and *pp2 in sorted
137948** order and with any duplicates removed.  All pointers are
137949** updated appropriately.   The caller is responsible for insuring
137950** that there is enough space in *pp to hold the complete output.
137951*/
137952static void fts3PoslistMerge(
137953  char **pp,                      /* Output buffer */
137954  char **pp1,                     /* Left input list */
137955  char **pp2                      /* Right input list */
137956){
137957  char *p = *pp;
137958  char *p1 = *pp1;
137959  char *p2 = *pp2;
137960
137961  while( *p1 || *p2 ){
137962    int iCol1;         /* The current column index in pp1 */
137963    int iCol2;         /* The current column index in pp2 */
137964
137965    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
137966    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
137967    else iCol1 = 0;
137968
137969    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
137970    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
137971    else iCol2 = 0;
137972
137973    if( iCol1==iCol2 ){
137974      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
137975      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
137976      sqlite3_int64 iPrev = 0;
137977      int n = fts3PutColNumber(&p, iCol1);
137978      p1 += n;
137979      p2 += n;
137980
137981      /* At this point, both p1 and p2 point to the start of column-lists
137982      ** for the same column (the column with index iCol1 and iCol2).
137983      ** A column-list is a list of non-negative delta-encoded varints, each
137984      ** incremented by 2 before being stored. Each list is terminated by a
137985      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
137986      ** and writes the results to buffer p. p is left pointing to the byte
137987      ** after the list written. No terminator (POS_END or POS_COLUMN) is
137988      ** written to the output.
137989      */
137990      fts3GetDeltaVarint(&p1, &i1);
137991      fts3GetDeltaVarint(&p2, &i2);
137992      do {
137993        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
137994        iPrev -= 2;
137995        if( i1==i2 ){
137996          fts3ReadNextPos(&p1, &i1);
137997          fts3ReadNextPos(&p2, &i2);
137998        }else if( i1<i2 ){
137999          fts3ReadNextPos(&p1, &i1);
138000        }else{
138001          fts3ReadNextPos(&p2, &i2);
138002        }
138003      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
138004    }else if( iCol1<iCol2 ){
138005      p1 += fts3PutColNumber(&p, iCol1);
138006      fts3ColumnlistCopy(&p, &p1);
138007    }else{
138008      p2 += fts3PutColNumber(&p, iCol2);
138009      fts3ColumnlistCopy(&p, &p2);
138010    }
138011  }
138012
138013  *p++ = POS_END;
138014  *pp = p;
138015  *pp1 = p1 + 1;
138016  *pp2 = p2 + 1;
138017}
138018
138019/*
138020** This function is used to merge two position lists into one. When it is
138021** called, *pp1 and *pp2 must both point to position lists. A position-list is
138022** the part of a doclist that follows each document id. For example, if a row
138023** contains:
138024**
138025**     'a b c'|'x y z'|'a b b a'
138026**
138027** Then the position list for this row for token 'b' would consist of:
138028**
138029**     0x02 0x01 0x02 0x03 0x03 0x00
138030**
138031** When this function returns, both *pp1 and *pp2 are left pointing to the
138032** byte following the 0x00 terminator of their respective position lists.
138033**
138034** If isSaveLeft is 0, an entry is added to the output position list for
138035** each position in *pp2 for which there exists one or more positions in
138036** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
138037** when the *pp1 token appears before the *pp2 token, but not more than nToken
138038** slots before it.
138039**
138040** e.g. nToken==1 searches for adjacent positions.
138041*/
138042static int fts3PoslistPhraseMerge(
138043  char **pp,                      /* IN/OUT: Preallocated output buffer */
138044  int nToken,                     /* Maximum difference in token positions */
138045  int isSaveLeft,                 /* Save the left position */
138046  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
138047  char **pp1,                     /* IN/OUT: Left input list */
138048  char **pp2                      /* IN/OUT: Right input list */
138049){
138050  char *p = *pp;
138051  char *p1 = *pp1;
138052  char *p2 = *pp2;
138053  int iCol1 = 0;
138054  int iCol2 = 0;
138055
138056  /* Never set both isSaveLeft and isExact for the same invocation. */
138057  assert( isSaveLeft==0 || isExact==0 );
138058
138059  assert( p!=0 && *p1!=0 && *p2!=0 );
138060  if( *p1==POS_COLUMN ){
138061    p1++;
138062    p1 += fts3GetVarint32(p1, &iCol1);
138063  }
138064  if( *p2==POS_COLUMN ){
138065    p2++;
138066    p2 += fts3GetVarint32(p2, &iCol2);
138067  }
138068
138069  while( 1 ){
138070    if( iCol1==iCol2 ){
138071      char *pSave = p;
138072      sqlite3_int64 iPrev = 0;
138073      sqlite3_int64 iPos1 = 0;
138074      sqlite3_int64 iPos2 = 0;
138075
138076      if( iCol1 ){
138077        *p++ = POS_COLUMN;
138078        p += sqlite3Fts3PutVarint(p, iCol1);
138079      }
138080
138081      assert( *p1!=POS_END && *p1!=POS_COLUMN );
138082      assert( *p2!=POS_END && *p2!=POS_COLUMN );
138083      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
138084      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
138085
138086      while( 1 ){
138087        if( iPos2==iPos1+nToken
138088         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
138089        ){
138090          sqlite3_int64 iSave;
138091          iSave = isSaveLeft ? iPos1 : iPos2;
138092          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
138093          pSave = 0;
138094          assert( p );
138095        }
138096        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
138097          if( (*p2&0xFE)==0 ) break;
138098          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
138099        }else{
138100          if( (*p1&0xFE)==0 ) break;
138101          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
138102        }
138103      }
138104
138105      if( pSave ){
138106        assert( pp && p );
138107        p = pSave;
138108      }
138109
138110      fts3ColumnlistCopy(0, &p1);
138111      fts3ColumnlistCopy(0, &p2);
138112      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
138113      if( 0==*p1 || 0==*p2 ) break;
138114
138115      p1++;
138116      p1 += fts3GetVarint32(p1, &iCol1);
138117      p2++;
138118      p2 += fts3GetVarint32(p2, &iCol2);
138119    }
138120
138121    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
138122    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
138123    ** end of the position list, or the 0x01 that precedes the next
138124    ** column-number in the position list.
138125    */
138126    else if( iCol1<iCol2 ){
138127      fts3ColumnlistCopy(0, &p1);
138128      if( 0==*p1 ) break;
138129      p1++;
138130      p1 += fts3GetVarint32(p1, &iCol1);
138131    }else{
138132      fts3ColumnlistCopy(0, &p2);
138133      if( 0==*p2 ) break;
138134      p2++;
138135      p2 += fts3GetVarint32(p2, &iCol2);
138136    }
138137  }
138138
138139  fts3PoslistCopy(0, &p2);
138140  fts3PoslistCopy(0, &p1);
138141  *pp1 = p1;
138142  *pp2 = p2;
138143  if( *pp==p ){
138144    return 0;
138145  }
138146  *p++ = 0x00;
138147  *pp = p;
138148  return 1;
138149}
138150
138151/*
138152** Merge two position-lists as required by the NEAR operator. The argument
138153** position lists correspond to the left and right phrases of an expression
138154** like:
138155**
138156**     "phrase 1" NEAR "phrase number 2"
138157**
138158** Position list *pp1 corresponds to the left-hand side of the NEAR
138159** expression and *pp2 to the right. As usual, the indexes in the position
138160** lists are the offsets of the last token in each phrase (tokens "1" and "2"
138161** in the example above).
138162**
138163** The output position list - written to *pp - is a copy of *pp2 with those
138164** entries that are not sufficiently NEAR entries in *pp1 removed.
138165*/
138166static int fts3PoslistNearMerge(
138167  char **pp,                      /* Output buffer */
138168  char *aTmp,                     /* Temporary buffer space */
138169  int nRight,                     /* Maximum difference in token positions */
138170  int nLeft,                      /* Maximum difference in token positions */
138171  char **pp1,                     /* IN/OUT: Left input list */
138172  char **pp2                      /* IN/OUT: Right input list */
138173){
138174  char *p1 = *pp1;
138175  char *p2 = *pp2;
138176
138177  char *pTmp1 = aTmp;
138178  char *pTmp2;
138179  char *aTmp2;
138180  int res = 1;
138181
138182  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
138183  aTmp2 = pTmp2 = pTmp1;
138184  *pp1 = p1;
138185  *pp2 = p2;
138186  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
138187  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
138188    fts3PoslistMerge(pp, &aTmp, &aTmp2);
138189  }else if( pTmp1!=aTmp ){
138190    fts3PoslistCopy(pp, &aTmp);
138191  }else if( pTmp2!=aTmp2 ){
138192    fts3PoslistCopy(pp, &aTmp2);
138193  }else{
138194    res = 0;
138195  }
138196
138197  return res;
138198}
138199
138200/*
138201** An instance of this function is used to merge together the (potentially
138202** large number of) doclists for each term that matches a prefix query.
138203** See function fts3TermSelectMerge() for details.
138204*/
138205typedef struct TermSelect TermSelect;
138206struct TermSelect {
138207  char *aaOutput[16];             /* Malloc'd output buffers */
138208  int anOutput[16];               /* Size each output buffer in bytes */
138209};
138210
138211/*
138212** This function is used to read a single varint from a buffer. Parameter
138213** pEnd points 1 byte past the end of the buffer. When this function is
138214** called, if *pp points to pEnd or greater, then the end of the buffer
138215** has been reached. In this case *pp is set to 0 and the function returns.
138216**
138217** If *pp does not point to or past pEnd, then a single varint is read
138218** from *pp. *pp is then set to point 1 byte past the end of the read varint.
138219**
138220** If bDescIdx is false, the value read is added to *pVal before returning.
138221** If it is true, the value read is subtracted from *pVal before this
138222** function returns.
138223*/
138224static void fts3GetDeltaVarint3(
138225  char **pp,                      /* IN/OUT: Point to read varint from */
138226  char *pEnd,                     /* End of buffer */
138227  int bDescIdx,                   /* True if docids are descending */
138228  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
138229){
138230  if( *pp>=pEnd ){
138231    *pp = 0;
138232  }else{
138233    sqlite3_int64 iVal;
138234    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
138235    if( bDescIdx ){
138236      *pVal -= iVal;
138237    }else{
138238      *pVal += iVal;
138239    }
138240  }
138241}
138242
138243/*
138244** This function is used to write a single varint to a buffer. The varint
138245** is written to *pp. Before returning, *pp is set to point 1 byte past the
138246** end of the value written.
138247**
138248** If *pbFirst is zero when this function is called, the value written to
138249** the buffer is that of parameter iVal.
138250**
138251** If *pbFirst is non-zero when this function is called, then the value
138252** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
138253** (if bDescIdx is non-zero).
138254**
138255** Before returning, this function always sets *pbFirst to 1 and *piPrev
138256** to the value of parameter iVal.
138257*/
138258static void fts3PutDeltaVarint3(
138259  char **pp,                      /* IN/OUT: Output pointer */
138260  int bDescIdx,                   /* True for descending docids */
138261  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
138262  int *pbFirst,                   /* IN/OUT: True after first int written */
138263  sqlite3_int64 iVal              /* Write this value to the list */
138264){
138265  sqlite3_int64 iWrite;
138266  if( bDescIdx==0 || *pbFirst==0 ){
138267    iWrite = iVal - *piPrev;
138268  }else{
138269    iWrite = *piPrev - iVal;
138270  }
138271  assert( *pbFirst || *piPrev==0 );
138272  assert( *pbFirst==0 || iWrite>0 );
138273  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
138274  *piPrev = iVal;
138275  *pbFirst = 1;
138276}
138277
138278
138279/*
138280** This macro is used by various functions that merge doclists. The two
138281** arguments are 64-bit docid values. If the value of the stack variable
138282** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
138283** Otherwise, (i2-i1).
138284**
138285** Using this makes it easier to write code that can merge doclists that are
138286** sorted in either ascending or descending order.
138287*/
138288#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
138289
138290/*
138291** This function does an "OR" merge of two doclists (output contains all
138292** positions contained in either argument doclist). If the docids in the
138293** input doclists are sorted in ascending order, parameter bDescDoclist
138294** should be false. If they are sorted in ascending order, it should be
138295** passed a non-zero value.
138296**
138297** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
138298** containing the output doclist and SQLITE_OK is returned. In this case
138299** *pnOut is set to the number of bytes in the output doclist.
138300**
138301** If an error occurs, an SQLite error code is returned. The output values
138302** are undefined in this case.
138303*/
138304static int fts3DoclistOrMerge(
138305  int bDescDoclist,               /* True if arguments are desc */
138306  char *a1, int n1,               /* First doclist */
138307  char *a2, int n2,               /* Second doclist */
138308  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
138309){
138310  sqlite3_int64 i1 = 0;
138311  sqlite3_int64 i2 = 0;
138312  sqlite3_int64 iPrev = 0;
138313  char *pEnd1 = &a1[n1];
138314  char *pEnd2 = &a2[n2];
138315  char *p1 = a1;
138316  char *p2 = a2;
138317  char *p;
138318  char *aOut;
138319  int bFirstOut = 0;
138320
138321  *paOut = 0;
138322  *pnOut = 0;
138323
138324  /* Allocate space for the output. Both the input and output doclists
138325  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
138326  ** then the first docid in each list is simply encoded as a varint. For
138327  ** each subsequent docid, the varint stored is the difference between the
138328  ** current and previous docid (a positive number - since the list is in
138329  ** ascending order).
138330  **
138331  ** The first docid written to the output is therefore encoded using the
138332  ** same number of bytes as it is in whichever of the input lists it is
138333  ** read from. And each subsequent docid read from the same input list
138334  ** consumes either the same or less bytes as it did in the input (since
138335  ** the difference between it and the previous value in the output must
138336  ** be a positive value less than or equal to the delta value read from
138337  ** the input list). The same argument applies to all but the first docid
138338  ** read from the 'other' list. And to the contents of all position lists
138339  ** that will be copied and merged from the input to the output.
138340  **
138341  ** However, if the first docid copied to the output is a negative number,
138342  ** then the encoding of the first docid from the 'other' input list may
138343  ** be larger in the output than it was in the input (since the delta value
138344  ** may be a larger positive integer than the actual docid).
138345  **
138346  ** The space required to store the output is therefore the sum of the
138347  ** sizes of the two inputs, plus enough space for exactly one of the input
138348  ** docids to grow.
138349  **
138350  ** A symetric argument may be made if the doclists are in descending
138351  ** order.
138352  */
138353  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
138354  if( !aOut ) return SQLITE_NOMEM;
138355
138356  p = aOut;
138357  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
138358  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
138359  while( p1 || p2 ){
138360    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
138361
138362    if( p2 && p1 && iDiff==0 ){
138363      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138364      fts3PoslistMerge(&p, &p1, &p2);
138365      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138366      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138367    }else if( !p2 || (p1 && iDiff<0) ){
138368      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138369      fts3PoslistCopy(&p, &p1);
138370      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138371    }else{
138372      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
138373      fts3PoslistCopy(&p, &p2);
138374      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138375    }
138376  }
138377
138378  *paOut = aOut;
138379  *pnOut = (int)(p-aOut);
138380  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
138381  return SQLITE_OK;
138382}
138383
138384/*
138385** This function does a "phrase" merge of two doclists. In a phrase merge,
138386** the output contains a copy of each position from the right-hand input
138387** doclist for which there is a position in the left-hand input doclist
138388** exactly nDist tokens before it.
138389**
138390** If the docids in the input doclists are sorted in ascending order,
138391** parameter bDescDoclist should be false. If they are sorted in ascending
138392** order, it should be passed a non-zero value.
138393**
138394** The right-hand input doclist is overwritten by this function.
138395*/
138396static int fts3DoclistPhraseMerge(
138397  int bDescDoclist,               /* True if arguments are desc */
138398  int nDist,                      /* Distance from left to right (1=adjacent) */
138399  char *aLeft, int nLeft,         /* Left doclist */
138400  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
138401){
138402  sqlite3_int64 i1 = 0;
138403  sqlite3_int64 i2 = 0;
138404  sqlite3_int64 iPrev = 0;
138405  char *aRight = *paRight;
138406  char *pEnd1 = &aLeft[nLeft];
138407  char *pEnd2 = &aRight[*pnRight];
138408  char *p1 = aLeft;
138409  char *p2 = aRight;
138410  char *p;
138411  int bFirstOut = 0;
138412  char *aOut;
138413
138414  assert( nDist>0 );
138415  if( bDescDoclist ){
138416    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
138417    if( aOut==0 ) return SQLITE_NOMEM;
138418  }else{
138419    aOut = aRight;
138420  }
138421  p = aOut;
138422
138423  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
138424  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
138425
138426  while( p1 && p2 ){
138427    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
138428    if( iDiff==0 ){
138429      char *pSave = p;
138430      sqlite3_int64 iPrevSave = iPrev;
138431      int bFirstOutSave = bFirstOut;
138432
138433      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138434      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
138435        p = pSave;
138436        iPrev = iPrevSave;
138437        bFirstOut = bFirstOutSave;
138438      }
138439      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138440      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138441    }else if( iDiff<0 ){
138442      fts3PoslistCopy(0, &p1);
138443      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138444    }else{
138445      fts3PoslistCopy(0, &p2);
138446      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138447    }
138448  }
138449
138450  *pnRight = (int)(p - aOut);
138451  if( bDescDoclist ){
138452    sqlite3_free(aRight);
138453    *paRight = aOut;
138454  }
138455
138456  return SQLITE_OK;
138457}
138458
138459/*
138460** Argument pList points to a position list nList bytes in size. This
138461** function checks to see if the position list contains any entries for
138462** a token in position 0 (of any column). If so, it writes argument iDelta
138463** to the output buffer pOut, followed by a position list consisting only
138464** of the entries from pList at position 0, and terminated by an 0x00 byte.
138465** The value returned is the number of bytes written to pOut (if any).
138466*/
138467SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
138468  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
138469  char *pList,                    /* Position list (no 0x00 term) */
138470  int nList,                      /* Size of pList in bytes */
138471  char *pOut                      /* Write output here */
138472){
138473  int nOut = 0;
138474  int bWritten = 0;               /* True once iDelta has been written */
138475  char *p = pList;
138476  char *pEnd = &pList[nList];
138477
138478  if( *p!=0x01 ){
138479    if( *p==0x02 ){
138480      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
138481      pOut[nOut++] = 0x02;
138482      bWritten = 1;
138483    }
138484    fts3ColumnlistCopy(0, &p);
138485  }
138486
138487  while( p<pEnd && *p==0x01 ){
138488    sqlite3_int64 iCol;
138489    p++;
138490    p += sqlite3Fts3GetVarint(p, &iCol);
138491    if( *p==0x02 ){
138492      if( bWritten==0 ){
138493        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
138494        bWritten = 1;
138495      }
138496      pOut[nOut++] = 0x01;
138497      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
138498      pOut[nOut++] = 0x02;
138499    }
138500    fts3ColumnlistCopy(0, &p);
138501  }
138502  if( bWritten ){
138503    pOut[nOut++] = 0x00;
138504  }
138505
138506  return nOut;
138507}
138508
138509
138510/*
138511** Merge all doclists in the TermSelect.aaOutput[] array into a single
138512** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
138513** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
138514**
138515** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
138516** the responsibility of the caller to free any doclists left in the
138517** TermSelect.aaOutput[] array.
138518*/
138519static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
138520  char *aOut = 0;
138521  int nOut = 0;
138522  int i;
138523
138524  /* Loop through the doclists in the aaOutput[] array. Merge them all
138525  ** into a single doclist.
138526  */
138527  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
138528    if( pTS->aaOutput[i] ){
138529      if( !aOut ){
138530        aOut = pTS->aaOutput[i];
138531        nOut = pTS->anOutput[i];
138532        pTS->aaOutput[i] = 0;
138533      }else{
138534        int nNew;
138535        char *aNew;
138536
138537        int rc = fts3DoclistOrMerge(p->bDescIdx,
138538            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
138539        );
138540        if( rc!=SQLITE_OK ){
138541          sqlite3_free(aOut);
138542          return rc;
138543        }
138544
138545        sqlite3_free(pTS->aaOutput[i]);
138546        sqlite3_free(aOut);
138547        pTS->aaOutput[i] = 0;
138548        aOut = aNew;
138549        nOut = nNew;
138550      }
138551    }
138552  }
138553
138554  pTS->aaOutput[0] = aOut;
138555  pTS->anOutput[0] = nOut;
138556  return SQLITE_OK;
138557}
138558
138559/*
138560** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
138561** as the first argument. The merge is an "OR" merge (see function
138562** fts3DoclistOrMerge() for details).
138563**
138564** This function is called with the doclist for each term that matches
138565** a queried prefix. It merges all these doclists into one, the doclist
138566** for the specified prefix. Since there can be a very large number of
138567** doclists to merge, the merging is done pair-wise using the TermSelect
138568** object.
138569**
138570** This function returns SQLITE_OK if the merge is successful, or an
138571** SQLite error code (SQLITE_NOMEM) if an error occurs.
138572*/
138573static int fts3TermSelectMerge(
138574  Fts3Table *p,                   /* FTS table handle */
138575  TermSelect *pTS,                /* TermSelect object to merge into */
138576  char *aDoclist,                 /* Pointer to doclist */
138577  int nDoclist                    /* Size of aDoclist in bytes */
138578){
138579  if( pTS->aaOutput[0]==0 ){
138580    /* If this is the first term selected, copy the doclist to the output
138581    ** buffer using memcpy().
138582    **
138583    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
138584    ** allocation. This is so as to ensure that the buffer is big enough
138585    ** to hold the current doclist AND'd with any other doclist. If the
138586    ** doclists are stored in order=ASC order, this padding would not be
138587    ** required (since the size of [doclistA AND doclistB] is always less
138588    ** than or equal to the size of [doclistA] in that case). But this is
138589    ** not true for order=DESC. For example, a doclist containing (1, -1)
138590    ** may be smaller than (-1), as in the first example the -1 may be stored
138591    ** as a single-byte delta, whereas in the second it must be stored as a
138592    ** FTS3_VARINT_MAX byte varint.
138593    **
138594    ** Similar padding is added in the fts3DoclistOrMerge() function.
138595    */
138596    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
138597    pTS->anOutput[0] = nDoclist;
138598    if( pTS->aaOutput[0] ){
138599      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
138600    }else{
138601      return SQLITE_NOMEM;
138602    }
138603  }else{
138604    char *aMerge = aDoclist;
138605    int nMerge = nDoclist;
138606    int iOut;
138607
138608    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
138609      if( pTS->aaOutput[iOut]==0 ){
138610        assert( iOut>0 );
138611        pTS->aaOutput[iOut] = aMerge;
138612        pTS->anOutput[iOut] = nMerge;
138613        break;
138614      }else{
138615        char *aNew;
138616        int nNew;
138617
138618        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
138619            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
138620        );
138621        if( rc!=SQLITE_OK ){
138622          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
138623          return rc;
138624        }
138625
138626        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
138627        sqlite3_free(pTS->aaOutput[iOut]);
138628        pTS->aaOutput[iOut] = 0;
138629
138630        aMerge = aNew;
138631        nMerge = nNew;
138632        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
138633          pTS->aaOutput[iOut] = aMerge;
138634          pTS->anOutput[iOut] = nMerge;
138635        }
138636      }
138637    }
138638  }
138639  return SQLITE_OK;
138640}
138641
138642/*
138643** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
138644*/
138645static int fts3SegReaderCursorAppend(
138646  Fts3MultiSegReader *pCsr,
138647  Fts3SegReader *pNew
138648){
138649  if( (pCsr->nSegment%16)==0 ){
138650    Fts3SegReader **apNew;
138651    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
138652    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
138653    if( !apNew ){
138654      sqlite3Fts3SegReaderFree(pNew);
138655      return SQLITE_NOMEM;
138656    }
138657    pCsr->apSegment = apNew;
138658  }
138659  pCsr->apSegment[pCsr->nSegment++] = pNew;
138660  return SQLITE_OK;
138661}
138662
138663/*
138664** Add seg-reader objects to the Fts3MultiSegReader object passed as the
138665** 8th argument.
138666**
138667** This function returns SQLITE_OK if successful, or an SQLite error code
138668** otherwise.
138669*/
138670static int fts3SegReaderCursor(
138671  Fts3Table *p,                   /* FTS3 table handle */
138672  int iLangid,                    /* Language id */
138673  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
138674  int iLevel,                     /* Level of segments to scan */
138675  const char *zTerm,              /* Term to query for */
138676  int nTerm,                      /* Size of zTerm in bytes */
138677  int isPrefix,                   /* True for a prefix search */
138678  int isScan,                     /* True to scan from zTerm to EOF */
138679  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
138680){
138681  int rc = SQLITE_OK;             /* Error code */
138682  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
138683  int rc2;                        /* Result of sqlite3_reset() */
138684
138685  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
138686  ** for the pending-terms. If this is a scan, then this call must be being
138687  ** made by an fts4aux module, not an FTS table. In this case calling
138688  ** Fts3SegReaderPending might segfault, as the data structures used by
138689  ** fts4aux are not completely populated. So it's easiest to filter these
138690  ** calls out here.  */
138691  if( iLevel<0 && p->aIndex ){
138692    Fts3SegReader *pSeg = 0;
138693    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
138694    if( rc==SQLITE_OK && pSeg ){
138695      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
138696    }
138697  }
138698
138699  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
138700    if( rc==SQLITE_OK ){
138701      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
138702    }
138703
138704    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
138705      Fts3SegReader *pSeg = 0;
138706
138707      /* Read the values returned by the SELECT into local variables. */
138708      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
138709      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
138710      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
138711      int nRoot = sqlite3_column_bytes(pStmt, 4);
138712      char const *zRoot = sqlite3_column_blob(pStmt, 4);
138713
138714      /* If zTerm is not NULL, and this segment is not stored entirely on its
138715      ** root node, the range of leaves scanned can be reduced. Do this. */
138716      if( iStartBlock && zTerm ){
138717        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
138718        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
138719        if( rc!=SQLITE_OK ) goto finished;
138720        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
138721      }
138722
138723      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
138724          (isPrefix==0 && isScan==0),
138725          iStartBlock, iLeavesEndBlock,
138726          iEndBlock, zRoot, nRoot, &pSeg
138727      );
138728      if( rc!=SQLITE_OK ) goto finished;
138729      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
138730    }
138731  }
138732
138733 finished:
138734  rc2 = sqlite3_reset(pStmt);
138735  if( rc==SQLITE_DONE ) rc = rc2;
138736
138737  return rc;
138738}
138739
138740/*
138741** Set up a cursor object for iterating through a full-text index or a
138742** single level therein.
138743*/
138744SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
138745  Fts3Table *p,                   /* FTS3 table handle */
138746  int iLangid,                    /* Language-id to search */
138747  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
138748  int iLevel,                     /* Level of segments to scan */
138749  const char *zTerm,              /* Term to query for */
138750  int nTerm,                      /* Size of zTerm in bytes */
138751  int isPrefix,                   /* True for a prefix search */
138752  int isScan,                     /* True to scan from zTerm to EOF */
138753  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
138754){
138755  assert( iIndex>=0 && iIndex<p->nIndex );
138756  assert( iLevel==FTS3_SEGCURSOR_ALL
138757      ||  iLevel==FTS3_SEGCURSOR_PENDING
138758      ||  iLevel>=0
138759  );
138760  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
138761  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
138762  assert( isPrefix==0 || isScan==0 );
138763
138764  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
138765  return fts3SegReaderCursor(
138766      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
138767  );
138768}
138769
138770/*
138771** In addition to its current configuration, have the Fts3MultiSegReader
138772** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
138773**
138774** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
138775*/
138776static int fts3SegReaderCursorAddZero(
138777  Fts3Table *p,                   /* FTS virtual table handle */
138778  int iLangid,
138779  const char *zTerm,              /* Term to scan doclist of */
138780  int nTerm,                      /* Number of bytes in zTerm */
138781  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
138782){
138783  return fts3SegReaderCursor(p,
138784      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
138785  );
138786}
138787
138788/*
138789** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
138790** if isPrefix is true, to scan the doclist for all terms for which
138791** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
138792** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
138793** an SQLite error code.
138794**
138795** It is the responsibility of the caller to free this object by eventually
138796** passing it to fts3SegReaderCursorFree()
138797**
138798** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
138799** Output parameter *ppSegcsr is set to 0 if an error occurs.
138800*/
138801static int fts3TermSegReaderCursor(
138802  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
138803  const char *zTerm,              /* Term to query for */
138804  int nTerm,                      /* Size of zTerm in bytes */
138805  int isPrefix,                   /* True for a prefix search */
138806  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
138807){
138808  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
138809  int rc = SQLITE_NOMEM;          /* Return code */
138810
138811  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
138812  if( pSegcsr ){
138813    int i;
138814    int bFound = 0;               /* True once an index has been found */
138815    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
138816
138817    if( isPrefix ){
138818      for(i=1; bFound==0 && i<p->nIndex; i++){
138819        if( p->aIndex[i].nPrefix==nTerm ){
138820          bFound = 1;
138821          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138822              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
138823          );
138824          pSegcsr->bLookup = 1;
138825        }
138826      }
138827
138828      for(i=1; bFound==0 && i<p->nIndex; i++){
138829        if( p->aIndex[i].nPrefix==nTerm+1 ){
138830          bFound = 1;
138831          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138832              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
138833          );
138834          if( rc==SQLITE_OK ){
138835            rc = fts3SegReaderCursorAddZero(
138836                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
138837            );
138838          }
138839        }
138840      }
138841    }
138842
138843    if( bFound==0 ){
138844      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138845          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
138846      );
138847      pSegcsr->bLookup = !isPrefix;
138848    }
138849  }
138850
138851  *ppSegcsr = pSegcsr;
138852  return rc;
138853}
138854
138855/*
138856** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
138857*/
138858static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
138859  sqlite3Fts3SegReaderFinish(pSegcsr);
138860  sqlite3_free(pSegcsr);
138861}
138862
138863/*
138864** This function retrieves the doclist for the specified term (or term
138865** prefix) from the database.
138866*/
138867static int fts3TermSelect(
138868  Fts3Table *p,                   /* Virtual table handle */
138869  Fts3PhraseToken *pTok,          /* Token to query for */
138870  int iColumn,                    /* Column to query (or -ve for all columns) */
138871  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
138872  char **ppOut                    /* OUT: Malloced result buffer */
138873){
138874  int rc;                         /* Return code */
138875  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
138876  TermSelect tsc;                 /* Object for pair-wise doclist merging */
138877  Fts3SegFilter filter;           /* Segment term filter configuration */
138878
138879  pSegcsr = pTok->pSegcsr;
138880  memset(&tsc, 0, sizeof(TermSelect));
138881
138882  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
138883        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
138884        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
138885        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
138886  filter.iCol = iColumn;
138887  filter.zTerm = pTok->z;
138888  filter.nTerm = pTok->n;
138889
138890  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
138891  while( SQLITE_OK==rc
138892      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
138893  ){
138894    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
138895  }
138896
138897  if( rc==SQLITE_OK ){
138898    rc = fts3TermSelectFinishMerge(p, &tsc);
138899  }
138900  if( rc==SQLITE_OK ){
138901    *ppOut = tsc.aaOutput[0];
138902    *pnOut = tsc.anOutput[0];
138903  }else{
138904    int i;
138905    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
138906      sqlite3_free(tsc.aaOutput[i]);
138907    }
138908  }
138909
138910  fts3SegReaderCursorFree(pSegcsr);
138911  pTok->pSegcsr = 0;
138912  return rc;
138913}
138914
138915/*
138916** This function counts the total number of docids in the doclist stored
138917** in buffer aList[], size nList bytes.
138918**
138919** If the isPoslist argument is true, then it is assumed that the doclist
138920** contains a position-list following each docid. Otherwise, it is assumed
138921** that the doclist is simply a list of docids stored as delta encoded
138922** varints.
138923*/
138924static int fts3DoclistCountDocids(char *aList, int nList){
138925  int nDoc = 0;                   /* Return value */
138926  if( aList ){
138927    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
138928    char *p = aList;              /* Cursor */
138929    while( p<aEnd ){
138930      nDoc++;
138931      while( (*p++)&0x80 );     /* Skip docid varint */
138932      fts3PoslistCopy(0, &p);   /* Skip over position list */
138933    }
138934  }
138935
138936  return nDoc;
138937}
138938
138939/*
138940** Advance the cursor to the next row in the %_content table that
138941** matches the search criteria.  For a MATCH search, this will be
138942** the next row that matches. For a full-table scan, this will be
138943** simply the next row in the %_content table.  For a docid lookup,
138944** this routine simply sets the EOF flag.
138945**
138946** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
138947** even if we reach end-of-file.  The fts3EofMethod() will be called
138948** subsequently to determine whether or not an EOF was hit.
138949*/
138950static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
138951  int rc;
138952  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
138953  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
138954    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
138955      pCsr->isEof = 1;
138956      rc = sqlite3_reset(pCsr->pStmt);
138957    }else{
138958      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
138959      rc = SQLITE_OK;
138960    }
138961  }else{
138962    rc = fts3EvalNext((Fts3Cursor *)pCursor);
138963  }
138964  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
138965  return rc;
138966}
138967
138968/*
138969** The following are copied from sqliteInt.h.
138970**
138971** Constants for the largest and smallest possible 64-bit signed integers.
138972** These macros are designed to work correctly on both 32-bit and 64-bit
138973** compilers.
138974*/
138975#ifndef SQLITE_AMALGAMATION
138976# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
138977# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
138978#endif
138979
138980/*
138981** If the numeric type of argument pVal is "integer", then return it
138982** converted to a 64-bit signed integer. Otherwise, return a copy of
138983** the second parameter, iDefault.
138984*/
138985static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
138986  if( pVal ){
138987    int eType = sqlite3_value_numeric_type(pVal);
138988    if( eType==SQLITE_INTEGER ){
138989      return sqlite3_value_int64(pVal);
138990    }
138991  }
138992  return iDefault;
138993}
138994
138995/*
138996** This is the xFilter interface for the virtual table.  See
138997** the virtual table xFilter method documentation for additional
138998** information.
138999**
139000** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
139001** the %_content table.
139002**
139003** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
139004** in the %_content table.
139005**
139006** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
139007** column on the left-hand side of the MATCH operator is column
139008** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
139009** side of the MATCH operator.
139010*/
139011static int fts3FilterMethod(
139012  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
139013  int idxNum,                     /* Strategy index */
139014  const char *idxStr,             /* Unused */
139015  int nVal,                       /* Number of elements in apVal */
139016  sqlite3_value **apVal           /* Arguments for the indexing scheme */
139017){
139018  int rc = SQLITE_OK;
139019  char *zSql;                     /* SQL statement used to access %_content */
139020  int eSearch;
139021  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
139022  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
139023
139024  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
139025  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
139026  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
139027  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
139028  int iIdx;
139029
139030  UNUSED_PARAMETER(idxStr);
139031  UNUSED_PARAMETER(nVal);
139032
139033  eSearch = (idxNum & 0x0000FFFF);
139034  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
139035  assert( p->pSegments==0 );
139036
139037  /* Collect arguments into local variables */
139038  iIdx = 0;
139039  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
139040  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
139041  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
139042  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
139043  assert( iIdx==nVal );
139044
139045  /* In case the cursor has been used before, clear it now. */
139046  sqlite3_finalize(pCsr->pStmt);
139047  sqlite3_free(pCsr->aDoclist);
139048  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
139049  sqlite3Fts3ExprFree(pCsr->pExpr);
139050  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
139051
139052  /* Set the lower and upper bounds on docids to return */
139053  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
139054  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
139055
139056  if( idxStr ){
139057    pCsr->bDesc = (idxStr[0]=='D');
139058  }else{
139059    pCsr->bDesc = p->bDescIdx;
139060  }
139061  pCsr->eSearch = (i16)eSearch;
139062
139063  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
139064    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
139065    const char *zQuery = (const char *)sqlite3_value_text(pCons);
139066
139067    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
139068      return SQLITE_NOMEM;
139069    }
139070
139071    pCsr->iLangid = 0;
139072    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
139073
139074    assert( p->base.zErrMsg==0 );
139075    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
139076        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
139077        &p->base.zErrMsg
139078    );
139079    if( rc!=SQLITE_OK ){
139080      return rc;
139081    }
139082
139083    rc = fts3EvalStart(pCsr);
139084    sqlite3Fts3SegmentsClose(p);
139085    if( rc!=SQLITE_OK ) return rc;
139086    pCsr->pNextId = pCsr->aDoclist;
139087    pCsr->iPrevId = 0;
139088  }
139089
139090  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
139091  ** statement loops through all rows of the %_content table. For a
139092  ** full-text query or docid lookup, the statement retrieves a single
139093  ** row by docid.
139094  */
139095  if( eSearch==FTS3_FULLSCAN_SEARCH ){
139096    if( pDocidGe || pDocidLe ){
139097      zSql = sqlite3_mprintf(
139098          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
139099          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
139100          (pCsr->bDesc ? "DESC" : "ASC")
139101      );
139102    }else{
139103      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
139104          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
139105      );
139106    }
139107    if( zSql ){
139108      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
139109      sqlite3_free(zSql);
139110    }else{
139111      rc = SQLITE_NOMEM;
139112    }
139113  }else if( eSearch==FTS3_DOCID_SEARCH ){
139114    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
139115    if( rc==SQLITE_OK ){
139116      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
139117    }
139118  }
139119  if( rc!=SQLITE_OK ) return rc;
139120
139121  return fts3NextMethod(pCursor);
139122}
139123
139124/*
139125** This is the xEof method of the virtual table. SQLite calls this
139126** routine to find out if it has reached the end of a result set.
139127*/
139128static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
139129  return ((Fts3Cursor *)pCursor)->isEof;
139130}
139131
139132/*
139133** This is the xRowid method. The SQLite core calls this routine to
139134** retrieve the rowid for the current row of the result set. fts3
139135** exposes %_content.docid as the rowid for the virtual table. The
139136** rowid should be written to *pRowid.
139137*/
139138static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
139139  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
139140  *pRowid = pCsr->iPrevId;
139141  return SQLITE_OK;
139142}
139143
139144/*
139145** This is the xColumn method, called by SQLite to request a value from
139146** the row that the supplied cursor currently points to.
139147**
139148** If:
139149**
139150**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
139151**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
139152**   (iCol == p->nColumn+1) -> Docid column
139153**   (iCol == p->nColumn+2) -> Langid column
139154*/
139155static int fts3ColumnMethod(
139156  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139157  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
139158  int iCol                        /* Index of column to read value from */
139159){
139160  int rc = SQLITE_OK;             /* Return Code */
139161  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
139162  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
139163
139164  /* The column value supplied by SQLite must be in range. */
139165  assert( iCol>=0 && iCol<=p->nColumn+2 );
139166
139167  if( iCol==p->nColumn+1 ){
139168    /* This call is a request for the "docid" column. Since "docid" is an
139169    ** alias for "rowid", use the xRowid() method to obtain the value.
139170    */
139171    sqlite3_result_int64(pCtx, pCsr->iPrevId);
139172  }else if( iCol==p->nColumn ){
139173    /* The extra column whose name is the same as the table.
139174    ** Return a blob which is a pointer to the cursor.  */
139175    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
139176  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
139177    sqlite3_result_int64(pCtx, pCsr->iLangid);
139178  }else{
139179    /* The requested column is either a user column (one that contains
139180    ** indexed data), or the language-id column.  */
139181    rc = fts3CursorSeek(0, pCsr);
139182
139183    if( rc==SQLITE_OK ){
139184      if( iCol==p->nColumn+2 ){
139185        int iLangid = 0;
139186        if( p->zLanguageid ){
139187          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
139188        }
139189        sqlite3_result_int(pCtx, iLangid);
139190      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
139191        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
139192      }
139193    }
139194  }
139195
139196  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
139197  return rc;
139198}
139199
139200/*
139201** This function is the implementation of the xUpdate callback used by
139202** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
139203** inserted, updated or deleted.
139204*/
139205static int fts3UpdateMethod(
139206  sqlite3_vtab *pVtab,            /* Virtual table handle */
139207  int nArg,                       /* Size of argument array */
139208  sqlite3_value **apVal,          /* Array of arguments */
139209  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
139210){
139211  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
139212}
139213
139214/*
139215** Implementation of xSync() method. Flush the contents of the pending-terms
139216** hash-table to the database.
139217*/
139218static int fts3SyncMethod(sqlite3_vtab *pVtab){
139219
139220  /* Following an incremental-merge operation, assuming that the input
139221  ** segments are not completely consumed (the usual case), they are updated
139222  ** in place to remove the entries that have already been merged. This
139223  ** involves updating the leaf block that contains the smallest unmerged
139224  ** entry and each block (if any) between the leaf and the root node. So
139225  ** if the height of the input segment b-trees is N, and input segments
139226  ** are merged eight at a time, updating the input segments at the end
139227  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
139228  ** small - often between 0 and 2. So the overhead of the incremental
139229  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
139230  ** dwarfing the actual productive work accomplished, the incremental merge
139231  ** is only attempted if it will write at least 64 leaf blocks. Hence
139232  ** nMinMerge.
139233  **
139234  ** Of course, updating the input segments also involves deleting a bunch
139235  ** of blocks from the segments table. But this is not considered overhead
139236  ** as it would also be required by a crisis-merge that used the same input
139237  ** segments.
139238  */
139239  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
139240
139241  Fts3Table *p = (Fts3Table*)pVtab;
139242  int rc = sqlite3Fts3PendingTermsFlush(p);
139243
139244  if( rc==SQLITE_OK
139245   && p->nLeafAdd>(nMinMerge/16)
139246   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
139247  ){
139248    int mxLevel = 0;              /* Maximum relative level value in db */
139249    int A;                        /* Incr-merge parameter A */
139250
139251    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
139252    assert( rc==SQLITE_OK || mxLevel==0 );
139253    A = p->nLeafAdd * mxLevel;
139254    A += (A/2);
139255    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
139256  }
139257  sqlite3Fts3SegmentsClose(p);
139258  return rc;
139259}
139260
139261/*
139262** If it is currently unknown whether or not the FTS table has an %_stat
139263** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
139264** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
139265** if an error occurs.
139266*/
139267static int fts3SetHasStat(Fts3Table *p){
139268  int rc = SQLITE_OK;
139269  if( p->bHasStat==2 ){
139270    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
139271    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
139272    if( zSql ){
139273      sqlite3_stmt *pStmt = 0;
139274      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
139275      if( rc==SQLITE_OK ){
139276        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
139277        rc = sqlite3_finalize(pStmt);
139278        if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
139279      }
139280      sqlite3_free(zSql);
139281    }else{
139282      rc = SQLITE_NOMEM;
139283    }
139284  }
139285  return rc;
139286}
139287
139288/*
139289** Implementation of xBegin() method.
139290*/
139291static int fts3BeginMethod(sqlite3_vtab *pVtab){
139292  Fts3Table *p = (Fts3Table*)pVtab;
139293  UNUSED_PARAMETER(pVtab);
139294  assert( p->pSegments==0 );
139295  assert( p->nPendingData==0 );
139296  assert( p->inTransaction!=1 );
139297  TESTONLY( p->inTransaction = 1 );
139298  TESTONLY( p->mxSavepoint = -1; );
139299  p->nLeafAdd = 0;
139300  return fts3SetHasStat(p);
139301}
139302
139303/*
139304** Implementation of xCommit() method. This is a no-op. The contents of
139305** the pending-terms hash-table have already been flushed into the database
139306** by fts3SyncMethod().
139307*/
139308static int fts3CommitMethod(sqlite3_vtab *pVtab){
139309  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
139310  UNUSED_PARAMETER(pVtab);
139311  assert( p->nPendingData==0 );
139312  assert( p->inTransaction!=0 );
139313  assert( p->pSegments==0 );
139314  TESTONLY( p->inTransaction = 0 );
139315  TESTONLY( p->mxSavepoint = -1; );
139316  return SQLITE_OK;
139317}
139318
139319/*
139320** Implementation of xRollback(). Discard the contents of the pending-terms
139321** hash-table. Any changes made to the database are reverted by SQLite.
139322*/
139323static int fts3RollbackMethod(sqlite3_vtab *pVtab){
139324  Fts3Table *p = (Fts3Table*)pVtab;
139325  sqlite3Fts3PendingTermsClear(p);
139326  assert( p->inTransaction!=0 );
139327  TESTONLY( p->inTransaction = 0 );
139328  TESTONLY( p->mxSavepoint = -1; );
139329  return SQLITE_OK;
139330}
139331
139332/*
139333** When called, *ppPoslist must point to the byte immediately following the
139334** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
139335** moves *ppPoslist so that it instead points to the first byte of the
139336** same position list.
139337*/
139338static void fts3ReversePoslist(char *pStart, char **ppPoslist){
139339  char *p = &(*ppPoslist)[-2];
139340  char c = 0;
139341
139342  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
139343  while( p>pStart && (c=*p--)==0 );
139344
139345  /* Search backwards for a varint with value zero (the end of the previous
139346  ** poslist). This is an 0x00 byte preceded by some byte that does not
139347  ** have the 0x80 bit set.  */
139348  while( p>pStart && (*p & 0x80) | c ){
139349    c = *p--;
139350  }
139351  assert( p==pStart || c==0 );
139352
139353  /* At this point p points to that preceding byte without the 0x80 bit
139354  ** set. So to find the start of the poslist, skip forward 2 bytes then
139355  ** over a varint.
139356  **
139357  ** Normally. The other case is that p==pStart and the poslist to return
139358  ** is the first in the doclist. In this case do not skip forward 2 bytes.
139359  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
139360  ** is required for cases where the first byte of a doclist and the
139361  ** doclist is empty. For example, if the first docid is 10, a doclist
139362  ** that begins with:
139363  **
139364  **   0x0A 0x00 <next docid delta varint>
139365  */
139366  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
139367  while( *p++&0x80 );
139368  *ppPoslist = p;
139369}
139370
139371/*
139372** Helper function used by the implementation of the overloaded snippet(),
139373** offsets() and optimize() SQL functions.
139374**
139375** If the value passed as the third argument is a blob of size
139376** sizeof(Fts3Cursor*), then the blob contents are copied to the
139377** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
139378** message is written to context pContext and SQLITE_ERROR returned. The
139379** string passed via zFunc is used as part of the error message.
139380*/
139381static int fts3FunctionArg(
139382  sqlite3_context *pContext,      /* SQL function call context */
139383  const char *zFunc,              /* Function name */
139384  sqlite3_value *pVal,            /* argv[0] passed to function */
139385  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
139386){
139387  Fts3Cursor *pRet;
139388  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
139389   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
139390  ){
139391    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
139392    sqlite3_result_error(pContext, zErr, -1);
139393    sqlite3_free(zErr);
139394    return SQLITE_ERROR;
139395  }
139396  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
139397  *ppCsr = pRet;
139398  return SQLITE_OK;
139399}
139400
139401/*
139402** Implementation of the snippet() function for FTS3
139403*/
139404static void fts3SnippetFunc(
139405  sqlite3_context *pContext,      /* SQLite function call context */
139406  int nVal,                       /* Size of apVal[] array */
139407  sqlite3_value **apVal           /* Array of arguments */
139408){
139409  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139410  const char *zStart = "<b>";
139411  const char *zEnd = "</b>";
139412  const char *zEllipsis = "<b>...</b>";
139413  int iCol = -1;
139414  int nToken = 15;                /* Default number of tokens in snippet */
139415
139416  /* There must be at least one argument passed to this function (otherwise
139417  ** the non-overloaded version would have been called instead of this one).
139418  */
139419  assert( nVal>=1 );
139420
139421  if( nVal>6 ){
139422    sqlite3_result_error(pContext,
139423        "wrong number of arguments to function snippet()", -1);
139424    return;
139425  }
139426  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
139427
139428  switch( nVal ){
139429    case 6: nToken = sqlite3_value_int(apVal[5]);
139430    case 5: iCol = sqlite3_value_int(apVal[4]);
139431    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
139432    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
139433    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
139434  }
139435  if( !zEllipsis || !zEnd || !zStart ){
139436    sqlite3_result_error_nomem(pContext);
139437  }else if( nToken==0 ){
139438    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
139439  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
139440    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
139441  }
139442}
139443
139444/*
139445** Implementation of the offsets() function for FTS3
139446*/
139447static void fts3OffsetsFunc(
139448  sqlite3_context *pContext,      /* SQLite function call context */
139449  int nVal,                       /* Size of argument array */
139450  sqlite3_value **apVal           /* Array of arguments */
139451){
139452  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139453
139454  UNUSED_PARAMETER(nVal);
139455
139456  assert( nVal==1 );
139457  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
139458  assert( pCsr );
139459  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
139460    sqlite3Fts3Offsets(pContext, pCsr);
139461  }
139462}
139463
139464/*
139465** Implementation of the special optimize() function for FTS3. This
139466** function merges all segments in the database to a single segment.
139467** Example usage is:
139468**
139469**   SELECT optimize(t) FROM t LIMIT 1;
139470**
139471** where 't' is the name of an FTS3 table.
139472*/
139473static void fts3OptimizeFunc(
139474  sqlite3_context *pContext,      /* SQLite function call context */
139475  int nVal,                       /* Size of argument array */
139476  sqlite3_value **apVal           /* Array of arguments */
139477){
139478  int rc;                         /* Return code */
139479  Fts3Table *p;                   /* Virtual table handle */
139480  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
139481
139482  UNUSED_PARAMETER(nVal);
139483
139484  assert( nVal==1 );
139485  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
139486  p = (Fts3Table *)pCursor->base.pVtab;
139487  assert( p );
139488
139489  rc = sqlite3Fts3Optimize(p);
139490
139491  switch( rc ){
139492    case SQLITE_OK:
139493      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
139494      break;
139495    case SQLITE_DONE:
139496      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
139497      break;
139498    default:
139499      sqlite3_result_error_code(pContext, rc);
139500      break;
139501  }
139502}
139503
139504/*
139505** Implementation of the matchinfo() function for FTS3
139506*/
139507static void fts3MatchinfoFunc(
139508  sqlite3_context *pContext,      /* SQLite function call context */
139509  int nVal,                       /* Size of argument array */
139510  sqlite3_value **apVal           /* Array of arguments */
139511){
139512  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139513  assert( nVal==1 || nVal==2 );
139514  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
139515    const char *zArg = 0;
139516    if( nVal>1 ){
139517      zArg = (const char *)sqlite3_value_text(apVal[1]);
139518    }
139519    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
139520  }
139521}
139522
139523/*
139524** This routine implements the xFindFunction method for the FTS3
139525** virtual table.
139526*/
139527static int fts3FindFunctionMethod(
139528  sqlite3_vtab *pVtab,            /* Virtual table handle */
139529  int nArg,                       /* Number of SQL function arguments */
139530  const char *zName,              /* Name of SQL function */
139531  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
139532  void **ppArg                    /* Unused */
139533){
139534  struct Overloaded {
139535    const char *zName;
139536    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
139537  } aOverload[] = {
139538    { "snippet", fts3SnippetFunc },
139539    { "offsets", fts3OffsetsFunc },
139540    { "optimize", fts3OptimizeFunc },
139541    { "matchinfo", fts3MatchinfoFunc },
139542  };
139543  int i;                          /* Iterator variable */
139544
139545  UNUSED_PARAMETER(pVtab);
139546  UNUSED_PARAMETER(nArg);
139547  UNUSED_PARAMETER(ppArg);
139548
139549  for(i=0; i<SizeofArray(aOverload); i++){
139550    if( strcmp(zName, aOverload[i].zName)==0 ){
139551      *pxFunc = aOverload[i].xFunc;
139552      return 1;
139553    }
139554  }
139555
139556  /* No function of the specified name was found. Return 0. */
139557  return 0;
139558}
139559
139560/*
139561** Implementation of FTS3 xRename method. Rename an fts3 table.
139562*/
139563static int fts3RenameMethod(
139564  sqlite3_vtab *pVtab,            /* Virtual table handle */
139565  const char *zName               /* New name of table */
139566){
139567  Fts3Table *p = (Fts3Table *)pVtab;
139568  sqlite3 *db = p->db;            /* Database connection */
139569  int rc;                         /* Return Code */
139570
139571  /* At this point it must be known if the %_stat table exists or not.
139572  ** So bHasStat may not be 2.  */
139573  rc = fts3SetHasStat(p);
139574
139575  /* As it happens, the pending terms table is always empty here. This is
139576  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
139577  ** always opens a savepoint transaction. And the xSavepoint() method
139578  ** flushes the pending terms table. But leave the (no-op) call to
139579  ** PendingTermsFlush() in in case that changes.
139580  */
139581  assert( p->nPendingData==0 );
139582  if( rc==SQLITE_OK ){
139583    rc = sqlite3Fts3PendingTermsFlush(p);
139584  }
139585
139586  if( p->zContentTbl==0 ){
139587    fts3DbExec(&rc, db,
139588      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
139589      p->zDb, p->zName, zName
139590    );
139591  }
139592
139593  if( p->bHasDocsize ){
139594    fts3DbExec(&rc, db,
139595      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
139596      p->zDb, p->zName, zName
139597    );
139598  }
139599  if( p->bHasStat ){
139600    fts3DbExec(&rc, db,
139601      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
139602      p->zDb, p->zName, zName
139603    );
139604  }
139605  fts3DbExec(&rc, db,
139606    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
139607    p->zDb, p->zName, zName
139608  );
139609  fts3DbExec(&rc, db,
139610    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
139611    p->zDb, p->zName, zName
139612  );
139613  return rc;
139614}
139615
139616/*
139617** The xSavepoint() method.
139618**
139619** Flush the contents of the pending-terms table to disk.
139620*/
139621static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
139622  int rc = SQLITE_OK;
139623  UNUSED_PARAMETER(iSavepoint);
139624  assert( ((Fts3Table *)pVtab)->inTransaction );
139625  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
139626  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
139627  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
139628    rc = fts3SyncMethod(pVtab);
139629  }
139630  return rc;
139631}
139632
139633/*
139634** The xRelease() method.
139635**
139636** This is a no-op.
139637*/
139638static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
139639  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
139640  UNUSED_PARAMETER(iSavepoint);
139641  UNUSED_PARAMETER(pVtab);
139642  assert( p->inTransaction );
139643  assert( p->mxSavepoint >= iSavepoint );
139644  TESTONLY( p->mxSavepoint = iSavepoint-1 );
139645  return SQLITE_OK;
139646}
139647
139648/*
139649** The xRollbackTo() method.
139650**
139651** Discard the contents of the pending terms table.
139652*/
139653static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
139654  Fts3Table *p = (Fts3Table*)pVtab;
139655  UNUSED_PARAMETER(iSavepoint);
139656  assert( p->inTransaction );
139657  assert( p->mxSavepoint >= iSavepoint );
139658  TESTONLY( p->mxSavepoint = iSavepoint );
139659  sqlite3Fts3PendingTermsClear(p);
139660  return SQLITE_OK;
139661}
139662
139663static const sqlite3_module fts3Module = {
139664  /* iVersion      */ 2,
139665  /* xCreate       */ fts3CreateMethod,
139666  /* xConnect      */ fts3ConnectMethod,
139667  /* xBestIndex    */ fts3BestIndexMethod,
139668  /* xDisconnect   */ fts3DisconnectMethod,
139669  /* xDestroy      */ fts3DestroyMethod,
139670  /* xOpen         */ fts3OpenMethod,
139671  /* xClose        */ fts3CloseMethod,
139672  /* xFilter       */ fts3FilterMethod,
139673  /* xNext         */ fts3NextMethod,
139674  /* xEof          */ fts3EofMethod,
139675  /* xColumn       */ fts3ColumnMethod,
139676  /* xRowid        */ fts3RowidMethod,
139677  /* xUpdate       */ fts3UpdateMethod,
139678  /* xBegin        */ fts3BeginMethod,
139679  /* xSync         */ fts3SyncMethod,
139680  /* xCommit       */ fts3CommitMethod,
139681  /* xRollback     */ fts3RollbackMethod,
139682  /* xFindFunction */ fts3FindFunctionMethod,
139683  /* xRename */       fts3RenameMethod,
139684  /* xSavepoint    */ fts3SavepointMethod,
139685  /* xRelease      */ fts3ReleaseMethod,
139686  /* xRollbackTo   */ fts3RollbackToMethod,
139687};
139688
139689/*
139690** This function is registered as the module destructor (called when an
139691** FTS3 enabled database connection is closed). It frees the memory
139692** allocated for the tokenizer hash table.
139693*/
139694static void hashDestroy(void *p){
139695  Fts3Hash *pHash = (Fts3Hash *)p;
139696  sqlite3Fts3HashClear(pHash);
139697  sqlite3_free(pHash);
139698}
139699
139700/*
139701** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
139702** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
139703** respectively. The following three forward declarations are for functions
139704** declared in these files used to retrieve the respective implementations.
139705**
139706** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
139707** to by the argument to point to the "simple" tokenizer implementation.
139708** And so on.
139709*/
139710SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139711SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139712#ifndef SQLITE_DISABLE_FTS3_UNICODE
139713SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
139714#endif
139715#ifdef SQLITE_ENABLE_ICU
139716SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139717#endif
139718
139719/*
139720** Initialize the fts3 extension. If this extension is built as part
139721** of the sqlite library, then this function is called directly by
139722** SQLite. If fts3 is built as a dynamically loadable extension, this
139723** function is called by the sqlite3_extension_init() entry point.
139724*/
139725SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
139726  int rc = SQLITE_OK;
139727  Fts3Hash *pHash = 0;
139728  const sqlite3_tokenizer_module *pSimple = 0;
139729  const sqlite3_tokenizer_module *pPorter = 0;
139730#ifndef SQLITE_DISABLE_FTS3_UNICODE
139731  const sqlite3_tokenizer_module *pUnicode = 0;
139732#endif
139733
139734#ifdef SQLITE_ENABLE_ICU
139735  const sqlite3_tokenizer_module *pIcu = 0;
139736  sqlite3Fts3IcuTokenizerModule(&pIcu);
139737#endif
139738
139739#ifndef SQLITE_DISABLE_FTS3_UNICODE
139740  sqlite3Fts3UnicodeTokenizer(&pUnicode);
139741#endif
139742
139743#ifdef SQLITE_TEST
139744  rc = sqlite3Fts3InitTerm(db);
139745  if( rc!=SQLITE_OK ) return rc;
139746#endif
139747
139748  rc = sqlite3Fts3InitAux(db);
139749  if( rc!=SQLITE_OK ) return rc;
139750
139751  sqlite3Fts3SimpleTokenizerModule(&pSimple);
139752  sqlite3Fts3PorterTokenizerModule(&pPorter);
139753
139754  /* Allocate and initialize the hash-table used to store tokenizers. */
139755  pHash = sqlite3_malloc(sizeof(Fts3Hash));
139756  if( !pHash ){
139757    rc = SQLITE_NOMEM;
139758  }else{
139759    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
139760  }
139761
139762  /* Load the built-in tokenizers into the hash table */
139763  if( rc==SQLITE_OK ){
139764    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
139765     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
139766
139767#ifndef SQLITE_DISABLE_FTS3_UNICODE
139768     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
139769#endif
139770#ifdef SQLITE_ENABLE_ICU
139771     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
139772#endif
139773    ){
139774      rc = SQLITE_NOMEM;
139775    }
139776  }
139777
139778#ifdef SQLITE_TEST
139779  if( rc==SQLITE_OK ){
139780    rc = sqlite3Fts3ExprInitTestInterface(db);
139781  }
139782#endif
139783
139784  /* Create the virtual table wrapper around the hash-table and overload
139785  ** the two scalar functions. If this is successful, register the
139786  ** module with sqlite.
139787  */
139788  if( SQLITE_OK==rc
139789   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
139790   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
139791   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
139792   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
139793   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
139794   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
139795  ){
139796    rc = sqlite3_create_module_v2(
139797        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
139798    );
139799    if( rc==SQLITE_OK ){
139800      rc = sqlite3_create_module_v2(
139801          db, "fts4", &fts3Module, (void *)pHash, 0
139802      );
139803    }
139804    if( rc==SQLITE_OK ){
139805      rc = sqlite3Fts3InitTok(db, (void *)pHash);
139806    }
139807    return rc;
139808  }
139809
139810
139811  /* An error has occurred. Delete the hash table and return the error code. */
139812  assert( rc!=SQLITE_OK );
139813  if( pHash ){
139814    sqlite3Fts3HashClear(pHash);
139815    sqlite3_free(pHash);
139816  }
139817  return rc;
139818}
139819
139820/*
139821** Allocate an Fts3MultiSegReader for each token in the expression headed
139822** by pExpr.
139823**
139824** An Fts3SegReader object is a cursor that can seek or scan a range of
139825** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
139826** Fts3SegReader objects internally to provide an interface to seek or scan
139827** within the union of all segments of a b-tree. Hence the name.
139828**
139829** If the allocated Fts3MultiSegReader just seeks to a single entry in a
139830** segment b-tree (if the term is not a prefix or it is a prefix for which
139831** there exists prefix b-tree of the right length) then it may be traversed
139832** and merged incrementally. Otherwise, it has to be merged into an in-memory
139833** doclist and then traversed.
139834*/
139835static void fts3EvalAllocateReaders(
139836  Fts3Cursor *pCsr,               /* FTS cursor handle */
139837  Fts3Expr *pExpr,                /* Allocate readers for this expression */
139838  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
139839  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
139840  int *pRc                        /* IN/OUT: Error code */
139841){
139842  if( pExpr && SQLITE_OK==*pRc ){
139843    if( pExpr->eType==FTSQUERY_PHRASE ){
139844      int i;
139845      int nToken = pExpr->pPhrase->nToken;
139846      *pnToken += nToken;
139847      for(i=0; i<nToken; i++){
139848        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
139849        int rc = fts3TermSegReaderCursor(pCsr,
139850            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
139851        );
139852        if( rc!=SQLITE_OK ){
139853          *pRc = rc;
139854          return;
139855        }
139856      }
139857      assert( pExpr->pPhrase->iDoclistToken==0 );
139858      pExpr->pPhrase->iDoclistToken = -1;
139859    }else{
139860      *pnOr += (pExpr->eType==FTSQUERY_OR);
139861      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
139862      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
139863    }
139864  }
139865}
139866
139867/*
139868** Arguments pList/nList contain the doclist for token iToken of phrase p.
139869** It is merged into the main doclist stored in p->doclist.aAll/nAll.
139870**
139871** This function assumes that pList points to a buffer allocated using
139872** sqlite3_malloc(). This function takes responsibility for eventually
139873** freeing the buffer.
139874**
139875** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
139876*/
139877static int fts3EvalPhraseMergeToken(
139878  Fts3Table *pTab,                /* FTS Table pointer */
139879  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
139880  int iToken,                     /* Token pList/nList corresponds to */
139881  char *pList,                    /* Pointer to doclist */
139882  int nList                       /* Number of bytes in pList */
139883){
139884  int rc = SQLITE_OK;
139885  assert( iToken!=p->iDoclistToken );
139886
139887  if( pList==0 ){
139888    sqlite3_free(p->doclist.aAll);
139889    p->doclist.aAll = 0;
139890    p->doclist.nAll = 0;
139891  }
139892
139893  else if( p->iDoclistToken<0 ){
139894    p->doclist.aAll = pList;
139895    p->doclist.nAll = nList;
139896  }
139897
139898  else if( p->doclist.aAll==0 ){
139899    sqlite3_free(pList);
139900  }
139901
139902  else {
139903    char *pLeft;
139904    char *pRight;
139905    int nLeft;
139906    int nRight;
139907    int nDiff;
139908
139909    if( p->iDoclistToken<iToken ){
139910      pLeft = p->doclist.aAll;
139911      nLeft = p->doclist.nAll;
139912      pRight = pList;
139913      nRight = nList;
139914      nDiff = iToken - p->iDoclistToken;
139915    }else{
139916      pRight = p->doclist.aAll;
139917      nRight = p->doclist.nAll;
139918      pLeft = pList;
139919      nLeft = nList;
139920      nDiff = p->iDoclistToken - iToken;
139921    }
139922
139923    rc = fts3DoclistPhraseMerge(
139924        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
139925    );
139926    sqlite3_free(pLeft);
139927    p->doclist.aAll = pRight;
139928    p->doclist.nAll = nRight;
139929  }
139930
139931  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
139932  return rc;
139933}
139934
139935/*
139936** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
139937** does not take deferred tokens into account.
139938**
139939** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
139940*/
139941static int fts3EvalPhraseLoad(
139942  Fts3Cursor *pCsr,               /* FTS Cursor handle */
139943  Fts3Phrase *p                   /* Phrase object */
139944){
139945  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
139946  int iToken;
139947  int rc = SQLITE_OK;
139948
139949  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
139950    Fts3PhraseToken *pToken = &p->aToken[iToken];
139951    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
139952
139953    if( pToken->pSegcsr ){
139954      int nThis = 0;
139955      char *pThis = 0;
139956      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
139957      if( rc==SQLITE_OK ){
139958        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
139959      }
139960    }
139961    assert( pToken->pSegcsr==0 );
139962  }
139963
139964  return rc;
139965}
139966
139967/*
139968** This function is called on each phrase after the position lists for
139969** any deferred tokens have been loaded into memory. It updates the phrases
139970** current position list to include only those positions that are really
139971** instances of the phrase (after considering deferred tokens). If this
139972** means that the phrase does not appear in the current row, doclist.pList
139973** and doclist.nList are both zeroed.
139974**
139975** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
139976*/
139977static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
139978  int iToken;                     /* Used to iterate through phrase tokens */
139979  char *aPoslist = 0;             /* Position list for deferred tokens */
139980  int nPoslist = 0;               /* Number of bytes in aPoslist */
139981  int iPrev = -1;                 /* Token number of previous deferred token */
139982
139983  assert( pPhrase->doclist.bFreeList==0 );
139984
139985  for(iToken=0; iToken<pPhrase->nToken; iToken++){
139986    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
139987    Fts3DeferredToken *pDeferred = pToken->pDeferred;
139988
139989    if( pDeferred ){
139990      char *pList;
139991      int nList;
139992      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
139993      if( rc!=SQLITE_OK ) return rc;
139994
139995      if( pList==0 ){
139996        sqlite3_free(aPoslist);
139997        pPhrase->doclist.pList = 0;
139998        pPhrase->doclist.nList = 0;
139999        return SQLITE_OK;
140000
140001      }else if( aPoslist==0 ){
140002        aPoslist = pList;
140003        nPoslist = nList;
140004
140005      }else{
140006        char *aOut = pList;
140007        char *p1 = aPoslist;
140008        char *p2 = aOut;
140009
140010        assert( iPrev>=0 );
140011        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
140012        sqlite3_free(aPoslist);
140013        aPoslist = pList;
140014        nPoslist = (int)(aOut - aPoslist);
140015        if( nPoslist==0 ){
140016          sqlite3_free(aPoslist);
140017          pPhrase->doclist.pList = 0;
140018          pPhrase->doclist.nList = 0;
140019          return SQLITE_OK;
140020        }
140021      }
140022      iPrev = iToken;
140023    }
140024  }
140025
140026  if( iPrev>=0 ){
140027    int nMaxUndeferred = pPhrase->iDoclistToken;
140028    if( nMaxUndeferred<0 ){
140029      pPhrase->doclist.pList = aPoslist;
140030      pPhrase->doclist.nList = nPoslist;
140031      pPhrase->doclist.iDocid = pCsr->iPrevId;
140032      pPhrase->doclist.bFreeList = 1;
140033    }else{
140034      int nDistance;
140035      char *p1;
140036      char *p2;
140037      char *aOut;
140038
140039      if( nMaxUndeferred>iPrev ){
140040        p1 = aPoslist;
140041        p2 = pPhrase->doclist.pList;
140042        nDistance = nMaxUndeferred - iPrev;
140043      }else{
140044        p1 = pPhrase->doclist.pList;
140045        p2 = aPoslist;
140046        nDistance = iPrev - nMaxUndeferred;
140047      }
140048
140049      aOut = (char *)sqlite3_malloc(nPoslist+8);
140050      if( !aOut ){
140051        sqlite3_free(aPoslist);
140052        return SQLITE_NOMEM;
140053      }
140054
140055      pPhrase->doclist.pList = aOut;
140056      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
140057        pPhrase->doclist.bFreeList = 1;
140058        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
140059      }else{
140060        sqlite3_free(aOut);
140061        pPhrase->doclist.pList = 0;
140062        pPhrase->doclist.nList = 0;
140063      }
140064      sqlite3_free(aPoslist);
140065    }
140066  }
140067
140068  return SQLITE_OK;
140069}
140070
140071/*
140072** Maximum number of tokens a phrase may have to be considered for the
140073** incremental doclists strategy.
140074*/
140075#define MAX_INCR_PHRASE_TOKENS 4
140076
140077/*
140078** This function is called for each Fts3Phrase in a full-text query
140079** expression to initialize the mechanism for returning rows. Once this
140080** function has been called successfully on an Fts3Phrase, it may be
140081** used with fts3EvalPhraseNext() to iterate through the matching docids.
140082**
140083** If parameter bOptOk is true, then the phrase may (or may not) use the
140084** incremental loading strategy. Otherwise, the entire doclist is loaded into
140085** memory within this call.
140086**
140087** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
140088*/
140089static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
140090  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140091  int rc = SQLITE_OK;             /* Error code */
140092  int i;
140093
140094  /* Determine if doclists may be loaded from disk incrementally. This is
140095  ** possible if the bOptOk argument is true, the FTS doclists will be
140096  ** scanned in forward order, and the phrase consists of
140097  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
140098  ** tokens or prefix tokens that cannot use a prefix-index.  */
140099  int bHaveIncr = 0;
140100  int bIncrOk = (bOptOk
140101   && pCsr->bDesc==pTab->bDescIdx
140102   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
140103#ifdef SQLITE_TEST
140104   && pTab->bNoIncrDoclist==0
140105#endif
140106  );
140107  for(i=0; bIncrOk==1 && i<p->nToken; i++){
140108    Fts3PhraseToken *pToken = &p->aToken[i];
140109    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
140110      bIncrOk = 0;
140111    }
140112    if( pToken->pSegcsr ) bHaveIncr = 1;
140113  }
140114
140115  if( bIncrOk && bHaveIncr ){
140116    /* Use the incremental approach. */
140117    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
140118    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
140119      Fts3PhraseToken *pToken = &p->aToken[i];
140120      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
140121      if( pSegcsr ){
140122        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
140123      }
140124    }
140125    p->bIncr = 1;
140126  }else{
140127    /* Load the full doclist for the phrase into memory. */
140128    rc = fts3EvalPhraseLoad(pCsr, p);
140129    p->bIncr = 0;
140130  }
140131
140132  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
140133  return rc;
140134}
140135
140136/*
140137** This function is used to iterate backwards (from the end to start)
140138** through doclists. It is used by this module to iterate through phrase
140139** doclists in reverse and by the fts3_write.c module to iterate through
140140** pending-terms lists when writing to databases with "order=desc".
140141**
140142** The doclist may be sorted in ascending (parameter bDescIdx==0) or
140143** descending (parameter bDescIdx==1) order of docid. Regardless, this
140144** function iterates from the end of the doclist to the beginning.
140145*/
140146SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
140147  int bDescIdx,                   /* True if the doclist is desc */
140148  char *aDoclist,                 /* Pointer to entire doclist */
140149  int nDoclist,                   /* Length of aDoclist in bytes */
140150  char **ppIter,                  /* IN/OUT: Iterator pointer */
140151  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
140152  int *pnList,                    /* OUT: List length pointer */
140153  u8 *pbEof                       /* OUT: End-of-file flag */
140154){
140155  char *p = *ppIter;
140156
140157  assert( nDoclist>0 );
140158  assert( *pbEof==0 );
140159  assert( p || *piDocid==0 );
140160  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
140161
140162  if( p==0 ){
140163    sqlite3_int64 iDocid = 0;
140164    char *pNext = 0;
140165    char *pDocid = aDoclist;
140166    char *pEnd = &aDoclist[nDoclist];
140167    int iMul = 1;
140168
140169    while( pDocid<pEnd ){
140170      sqlite3_int64 iDelta;
140171      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
140172      iDocid += (iMul * iDelta);
140173      pNext = pDocid;
140174      fts3PoslistCopy(0, &pDocid);
140175      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
140176      iMul = (bDescIdx ? -1 : 1);
140177    }
140178
140179    *pnList = (int)(pEnd - pNext);
140180    *ppIter = pNext;
140181    *piDocid = iDocid;
140182  }else{
140183    int iMul = (bDescIdx ? -1 : 1);
140184    sqlite3_int64 iDelta;
140185    fts3GetReverseVarint(&p, aDoclist, &iDelta);
140186    *piDocid -= (iMul * iDelta);
140187
140188    if( p==aDoclist ){
140189      *pbEof = 1;
140190    }else{
140191      char *pSave = p;
140192      fts3ReversePoslist(aDoclist, &p);
140193      *pnList = (int)(pSave - p);
140194    }
140195    *ppIter = p;
140196  }
140197}
140198
140199/*
140200** Iterate forwards through a doclist.
140201*/
140202SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
140203  int bDescIdx,                   /* True if the doclist is desc */
140204  char *aDoclist,                 /* Pointer to entire doclist */
140205  int nDoclist,                   /* Length of aDoclist in bytes */
140206  char **ppIter,                  /* IN/OUT: Iterator pointer */
140207  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
140208  u8 *pbEof                       /* OUT: End-of-file flag */
140209){
140210  char *p = *ppIter;
140211
140212  assert( nDoclist>0 );
140213  assert( *pbEof==0 );
140214  assert( p || *piDocid==0 );
140215  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
140216
140217  if( p==0 ){
140218    p = aDoclist;
140219    p += sqlite3Fts3GetVarint(p, piDocid);
140220  }else{
140221    fts3PoslistCopy(0, &p);
140222    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
140223    if( p>=&aDoclist[nDoclist] ){
140224      *pbEof = 1;
140225    }else{
140226      sqlite3_int64 iVar;
140227      p += sqlite3Fts3GetVarint(p, &iVar);
140228      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
140229    }
140230  }
140231
140232  *ppIter = p;
140233}
140234
140235/*
140236** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
140237** to true if EOF is reached.
140238*/
140239static void fts3EvalDlPhraseNext(
140240  Fts3Table *pTab,
140241  Fts3Doclist *pDL,
140242  u8 *pbEof
140243){
140244  char *pIter;                            /* Used to iterate through aAll */
140245  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
140246
140247  if( pDL->pNextDocid ){
140248    pIter = pDL->pNextDocid;
140249  }else{
140250    pIter = pDL->aAll;
140251  }
140252
140253  if( pIter>=pEnd ){
140254    /* We have already reached the end of this doclist. EOF. */
140255    *pbEof = 1;
140256  }else{
140257    sqlite3_int64 iDelta;
140258    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
140259    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
140260      pDL->iDocid += iDelta;
140261    }else{
140262      pDL->iDocid -= iDelta;
140263    }
140264    pDL->pList = pIter;
140265    fts3PoslistCopy(0, &pIter);
140266    pDL->nList = (int)(pIter - pDL->pList);
140267
140268    /* pIter now points just past the 0x00 that terminates the position-
140269    ** list for document pDL->iDocid. However, if this position-list was
140270    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
140271    ** point to the start of the next docid value. The following line deals
140272    ** with this case by advancing pIter past the zero-padding added by
140273    ** fts3EvalNearTrim().  */
140274    while( pIter<pEnd && *pIter==0 ) pIter++;
140275
140276    pDL->pNextDocid = pIter;
140277    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
140278    *pbEof = 0;
140279  }
140280}
140281
140282/*
140283** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
140284*/
140285typedef struct TokenDoclist TokenDoclist;
140286struct TokenDoclist {
140287  int bIgnore;
140288  sqlite3_int64 iDocid;
140289  char *pList;
140290  int nList;
140291};
140292
140293/*
140294** Token pToken is an incrementally loaded token that is part of a
140295** multi-token phrase. Advance it to the next matching document in the
140296** database and populate output variable *p with the details of the new
140297** entry. Or, if the iterator has reached EOF, set *pbEof to true.
140298**
140299** If an error occurs, return an SQLite error code. Otherwise, return
140300** SQLITE_OK.
140301*/
140302static int incrPhraseTokenNext(
140303  Fts3Table *pTab,                /* Virtual table handle */
140304  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
140305  int iToken,                     /* Specific token to advance */
140306  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
140307  u8 *pbEof                       /* OUT: True if iterator is at EOF */
140308){
140309  int rc = SQLITE_OK;
140310
140311  if( pPhrase->iDoclistToken==iToken ){
140312    assert( p->bIgnore==0 );
140313    assert( pPhrase->aToken[iToken].pSegcsr==0 );
140314    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
140315    p->pList = pPhrase->doclist.pList;
140316    p->nList = pPhrase->doclist.nList;
140317    p->iDocid = pPhrase->doclist.iDocid;
140318  }else{
140319    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
140320    assert( pToken->pDeferred==0 );
140321    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
140322    if( pToken->pSegcsr ){
140323      assert( p->bIgnore==0 );
140324      rc = sqlite3Fts3MsrIncrNext(
140325          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
140326      );
140327      if( p->pList==0 ) *pbEof = 1;
140328    }else{
140329      p->bIgnore = 1;
140330    }
140331  }
140332
140333  return rc;
140334}
140335
140336
140337/*
140338** The phrase iterator passed as the second argument:
140339**
140340**   * features at least one token that uses an incremental doclist, and
140341**
140342**   * does not contain any deferred tokens.
140343**
140344** Advance it to the next matching documnent in the database and populate
140345** the Fts3Doclist.pList and nList fields.
140346**
140347** If there is no "next" entry and no error occurs, then *pbEof is set to
140348** 1 before returning. Otherwise, if no error occurs and the iterator is
140349** successfully advanced, *pbEof is set to 0.
140350**
140351** If an error occurs, return an SQLite error code. Otherwise, return
140352** SQLITE_OK.
140353*/
140354static int fts3EvalIncrPhraseNext(
140355  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140356  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
140357  u8 *pbEof                       /* OUT: Set to 1 if EOF */
140358){
140359  int rc = SQLITE_OK;
140360  Fts3Doclist *pDL = &p->doclist;
140361  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140362  u8 bEof = 0;
140363
140364  /* This is only called if it is guaranteed that the phrase has at least
140365  ** one incremental token. In which case the bIncr flag is set. */
140366  assert( p->bIncr==1 );
140367
140368  if( p->nToken==1 && p->bIncr ){
140369    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
140370        &pDL->iDocid, &pDL->pList, &pDL->nList
140371    );
140372    if( pDL->pList==0 ) bEof = 1;
140373  }else{
140374    int bDescDoclist = pCsr->bDesc;
140375    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
140376
140377    memset(a, 0, sizeof(a));
140378    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
140379    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
140380
140381    while( bEof==0 ){
140382      int bMaxSet = 0;
140383      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
140384      int i;                      /* Used to iterate through tokens */
140385
140386      /* Advance the iterator for each token in the phrase once. */
140387      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
140388        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
140389        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
140390          iMax = a[i].iDocid;
140391          bMaxSet = 1;
140392        }
140393      }
140394      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
140395      assert( rc!=SQLITE_OK || bMaxSet );
140396
140397      /* Keep advancing iterators until they all point to the same document */
140398      for(i=0; i<p->nToken; i++){
140399        while( rc==SQLITE_OK && bEof==0
140400            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
140401        ){
140402          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
140403          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
140404            iMax = a[i].iDocid;
140405            i = 0;
140406          }
140407        }
140408      }
140409
140410      /* Check if the current entries really are a phrase match */
140411      if( bEof==0 ){
140412        int nList = 0;
140413        int nByte = a[p->nToken-1].nList;
140414        char *aDoclist = sqlite3_malloc(nByte+1);
140415        if( !aDoclist ) return SQLITE_NOMEM;
140416        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
140417
140418        for(i=0; i<(p->nToken-1); i++){
140419          if( a[i].bIgnore==0 ){
140420            char *pL = a[i].pList;
140421            char *pR = aDoclist;
140422            char *pOut = aDoclist;
140423            int nDist = p->nToken-1-i;
140424            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
140425            if( res==0 ) break;
140426            nList = (int)(pOut - aDoclist);
140427          }
140428        }
140429        if( i==(p->nToken-1) ){
140430          pDL->iDocid = iMax;
140431          pDL->pList = aDoclist;
140432          pDL->nList = nList;
140433          pDL->bFreeList = 1;
140434          break;
140435        }
140436        sqlite3_free(aDoclist);
140437      }
140438    }
140439  }
140440
140441  *pbEof = bEof;
140442  return rc;
140443}
140444
140445/*
140446** Attempt to move the phrase iterator to point to the next matching docid.
140447** If an error occurs, return an SQLite error code. Otherwise, return
140448** SQLITE_OK.
140449**
140450** If there is no "next" entry and no error occurs, then *pbEof is set to
140451** 1 before returning. Otherwise, if no error occurs and the iterator is
140452** successfully advanced, *pbEof is set to 0.
140453*/
140454static int fts3EvalPhraseNext(
140455  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140456  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
140457  u8 *pbEof                       /* OUT: Set to 1 if EOF */
140458){
140459  int rc = SQLITE_OK;
140460  Fts3Doclist *pDL = &p->doclist;
140461  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140462
140463  if( p->bIncr ){
140464    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
140465  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
140466    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
140467        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
140468    );
140469    pDL->pList = pDL->pNextDocid;
140470  }else{
140471    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
140472  }
140473
140474  return rc;
140475}
140476
140477/*
140478**
140479** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
140480** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
140481** expression. Also the Fts3Expr.bDeferred variable is set to true for any
140482** expressions for which all descendent tokens are deferred.
140483**
140484** If parameter bOptOk is zero, then it is guaranteed that the
140485** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
140486** each phrase in the expression (subject to deferred token processing).
140487** Or, if bOptOk is non-zero, then one or more tokens within the expression
140488** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
140489**
140490** If an error occurs within this function, *pRc is set to an SQLite error
140491** code before returning.
140492*/
140493static void fts3EvalStartReaders(
140494  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140495  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
140496  int *pRc                        /* IN/OUT: Error code */
140497){
140498  if( pExpr && SQLITE_OK==*pRc ){
140499    if( pExpr->eType==FTSQUERY_PHRASE ){
140500      int nToken = pExpr->pPhrase->nToken;
140501      if( nToken ){
140502        int i;
140503        for(i=0; i<nToken; i++){
140504          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
140505        }
140506        pExpr->bDeferred = (i==nToken);
140507      }
140508      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
140509    }else{
140510      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
140511      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
140512      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
140513    }
140514  }
140515}
140516
140517/*
140518** An array of the following structures is assembled as part of the process
140519** of selecting tokens to defer before the query starts executing (as part
140520** of the xFilter() method). There is one element in the array for each
140521** token in the FTS expression.
140522**
140523** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
140524** to phrases that are connected only by AND and NEAR operators (not OR or
140525** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
140526** separately. The root of a tokens AND/NEAR cluster is stored in
140527** Fts3TokenAndCost.pRoot.
140528*/
140529typedef struct Fts3TokenAndCost Fts3TokenAndCost;
140530struct Fts3TokenAndCost {
140531  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
140532  int iToken;                     /* Position of token in phrase */
140533  Fts3PhraseToken *pToken;        /* The token itself */
140534  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
140535  int nOvfl;                      /* Number of overflow pages to load doclist */
140536  int iCol;                       /* The column the token must match */
140537};
140538
140539/*
140540** This function is used to populate an allocated Fts3TokenAndCost array.
140541**
140542** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
140543** Otherwise, if an error occurs during execution, *pRc is set to an
140544** SQLite error code.
140545*/
140546static void fts3EvalTokenCosts(
140547  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140548  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
140549  Fts3Expr *pExpr,                /* Expression to consider */
140550  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
140551  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
140552  int *pRc                        /* IN/OUT: Error code */
140553){
140554  if( *pRc==SQLITE_OK ){
140555    if( pExpr->eType==FTSQUERY_PHRASE ){
140556      Fts3Phrase *pPhrase = pExpr->pPhrase;
140557      int i;
140558      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
140559        Fts3TokenAndCost *pTC = (*ppTC)++;
140560        pTC->pPhrase = pPhrase;
140561        pTC->iToken = i;
140562        pTC->pRoot = pRoot;
140563        pTC->pToken = &pPhrase->aToken[i];
140564        pTC->iCol = pPhrase->iColumn;
140565        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
140566      }
140567    }else if( pExpr->eType!=FTSQUERY_NOT ){
140568      assert( pExpr->eType==FTSQUERY_OR
140569           || pExpr->eType==FTSQUERY_AND
140570           || pExpr->eType==FTSQUERY_NEAR
140571      );
140572      assert( pExpr->pLeft && pExpr->pRight );
140573      if( pExpr->eType==FTSQUERY_OR ){
140574        pRoot = pExpr->pLeft;
140575        **ppOr = pRoot;
140576        (*ppOr)++;
140577      }
140578      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
140579      if( pExpr->eType==FTSQUERY_OR ){
140580        pRoot = pExpr->pRight;
140581        **ppOr = pRoot;
140582        (*ppOr)++;
140583      }
140584      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
140585    }
140586  }
140587}
140588
140589/*
140590** Determine the average document (row) size in pages. If successful,
140591** write this value to *pnPage and return SQLITE_OK. Otherwise, return
140592** an SQLite error code.
140593**
140594** The average document size in pages is calculated by first calculating
140595** determining the average size in bytes, B. If B is less than the amount
140596** of data that will fit on a single leaf page of an intkey table in
140597** this database, then the average docsize is 1. Otherwise, it is 1 plus
140598** the number of overflow pages consumed by a record B bytes in size.
140599*/
140600static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
140601  if( pCsr->nRowAvg==0 ){
140602    /* The average document size, which is required to calculate the cost
140603    ** of each doclist, has not yet been determined. Read the required
140604    ** data from the %_stat table to calculate it.
140605    **
140606    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
140607    ** varints, where nCol is the number of columns in the FTS3 table.
140608    ** The first varint is the number of documents currently stored in
140609    ** the table. The following nCol varints contain the total amount of
140610    ** data stored in all rows of each column of the table, from left
140611    ** to right.
140612    */
140613    int rc;
140614    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
140615    sqlite3_stmt *pStmt;
140616    sqlite3_int64 nDoc = 0;
140617    sqlite3_int64 nByte = 0;
140618    const char *pEnd;
140619    const char *a;
140620
140621    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
140622    if( rc!=SQLITE_OK ) return rc;
140623    a = sqlite3_column_blob(pStmt, 0);
140624    assert( a );
140625
140626    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
140627    a += sqlite3Fts3GetVarint(a, &nDoc);
140628    while( a<pEnd ){
140629      a += sqlite3Fts3GetVarint(a, &nByte);
140630    }
140631    if( nDoc==0 || nByte==0 ){
140632      sqlite3_reset(pStmt);
140633      return FTS_CORRUPT_VTAB;
140634    }
140635
140636    pCsr->nDoc = nDoc;
140637    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
140638    assert( pCsr->nRowAvg>0 );
140639    rc = sqlite3_reset(pStmt);
140640    if( rc!=SQLITE_OK ) return rc;
140641  }
140642
140643  *pnPage = pCsr->nRowAvg;
140644  return SQLITE_OK;
140645}
140646
140647/*
140648** This function is called to select the tokens (if any) that will be
140649** deferred. The array aTC[] has already been populated when this is
140650** called.
140651**
140652** This function is called once for each AND/NEAR cluster in the
140653** expression. Each invocation determines which tokens to defer within
140654** the cluster with root node pRoot. See comments above the definition
140655** of struct Fts3TokenAndCost for more details.
140656**
140657** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
140658** called on each token to defer. Otherwise, an SQLite error code is
140659** returned.
140660*/
140661static int fts3EvalSelectDeferred(
140662  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140663  Fts3Expr *pRoot,                /* Consider tokens with this root node */
140664  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
140665  int nTC                         /* Number of entries in aTC[] */
140666){
140667  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140668  int nDocSize = 0;               /* Number of pages per doc loaded */
140669  int rc = SQLITE_OK;             /* Return code */
140670  int ii;                         /* Iterator variable for various purposes */
140671  int nOvfl = 0;                  /* Total overflow pages used by doclists */
140672  int nToken = 0;                 /* Total number of tokens in cluster */
140673
140674  int nMinEst = 0;                /* The minimum count for any phrase so far. */
140675  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
140676
140677  /* Tokens are never deferred for FTS tables created using the content=xxx
140678  ** option. The reason being that it is not guaranteed that the content
140679  ** table actually contains the same data as the index. To prevent this from
140680  ** causing any problems, the deferred token optimization is completely
140681  ** disabled for content=xxx tables. */
140682  if( pTab->zContentTbl ){
140683    return SQLITE_OK;
140684  }
140685
140686  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
140687  ** associated with the tokens spill onto overflow pages, or if there is
140688  ** only 1 token, exit early. No tokens to defer in this case. */
140689  for(ii=0; ii<nTC; ii++){
140690    if( aTC[ii].pRoot==pRoot ){
140691      nOvfl += aTC[ii].nOvfl;
140692      nToken++;
140693    }
140694  }
140695  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
140696
140697  /* Obtain the average docsize (in pages). */
140698  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
140699  assert( rc!=SQLITE_OK || nDocSize>0 );
140700
140701
140702  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
140703  ** of the number of overflow pages that will be loaded by the pager layer
140704  ** to retrieve the entire doclist for the token from the full-text index.
140705  ** Load the doclists for tokens that are either:
140706  **
140707  **   a. The cheapest token in the entire query (i.e. the one visited by the
140708  **      first iteration of this loop), or
140709  **
140710  **   b. Part of a multi-token phrase.
140711  **
140712  ** After each token doclist is loaded, merge it with the others from the
140713  ** same phrase and count the number of documents that the merged doclist
140714  ** contains. Set variable "nMinEst" to the smallest number of documents in
140715  ** any phrase doclist for which 1 or more token doclists have been loaded.
140716  ** Let nOther be the number of other phrases for which it is certain that
140717  ** one or more tokens will not be deferred.
140718  **
140719  ** Then, for each token, defer it if loading the doclist would result in
140720  ** loading N or more overflow pages into memory, where N is computed as:
140721  **
140722  **    (nMinEst + 4^nOther - 1) / (4^nOther)
140723  */
140724  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
140725    int iTC;                      /* Used to iterate through aTC[] array. */
140726    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
140727
140728    /* Set pTC to point to the cheapest remaining token. */
140729    for(iTC=0; iTC<nTC; iTC++){
140730      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
140731       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
140732      ){
140733        pTC = &aTC[iTC];
140734      }
140735    }
140736    assert( pTC );
140737
140738    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
140739      /* The number of overflow pages to load for this (and therefore all
140740      ** subsequent) tokens is greater than the estimated number of pages
140741      ** that will be loaded if all subsequent tokens are deferred.
140742      */
140743      Fts3PhraseToken *pToken = pTC->pToken;
140744      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
140745      fts3SegReaderCursorFree(pToken->pSegcsr);
140746      pToken->pSegcsr = 0;
140747    }else{
140748      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
140749      ** for-loop. Except, limit the value to 2^24 to prevent it from
140750      ** overflowing the 32-bit integer it is stored in. */
140751      if( ii<12 ) nLoad4 = nLoad4*4;
140752
140753      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
140754        /* Either this is the cheapest token in the entire query, or it is
140755        ** part of a multi-token phrase. Either way, the entire doclist will
140756        ** (eventually) be loaded into memory. It may as well be now. */
140757        Fts3PhraseToken *pToken = pTC->pToken;
140758        int nList = 0;
140759        char *pList = 0;
140760        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
140761        assert( rc==SQLITE_OK || pList==0 );
140762        if( rc==SQLITE_OK ){
140763          rc = fts3EvalPhraseMergeToken(
140764              pTab, pTC->pPhrase, pTC->iToken,pList,nList
140765          );
140766        }
140767        if( rc==SQLITE_OK ){
140768          int nCount;
140769          nCount = fts3DoclistCountDocids(
140770              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
140771          );
140772          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
140773        }
140774      }
140775    }
140776    pTC->pToken = 0;
140777  }
140778
140779  return rc;
140780}
140781
140782/*
140783** This function is called from within the xFilter method. It initializes
140784** the full-text query currently stored in pCsr->pExpr. To iterate through
140785** the results of a query, the caller does:
140786**
140787**    fts3EvalStart(pCsr);
140788**    while( 1 ){
140789**      fts3EvalNext(pCsr);
140790**      if( pCsr->bEof ) break;
140791**      ... return row pCsr->iPrevId to the caller ...
140792**    }
140793*/
140794static int fts3EvalStart(Fts3Cursor *pCsr){
140795  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140796  int rc = SQLITE_OK;
140797  int nToken = 0;
140798  int nOr = 0;
140799
140800  /* Allocate a MultiSegReader for each token in the expression. */
140801  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
140802
140803  /* Determine which, if any, tokens in the expression should be deferred. */
140804#ifndef SQLITE_DISABLE_FTS4_DEFERRED
140805  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
140806    Fts3TokenAndCost *aTC;
140807    Fts3Expr **apOr;
140808    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
140809        sizeof(Fts3TokenAndCost) * nToken
140810      + sizeof(Fts3Expr *) * nOr * 2
140811    );
140812    apOr = (Fts3Expr **)&aTC[nToken];
140813
140814    if( !aTC ){
140815      rc = SQLITE_NOMEM;
140816    }else{
140817      int ii;
140818      Fts3TokenAndCost *pTC = aTC;
140819      Fts3Expr **ppOr = apOr;
140820
140821      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
140822      nToken = (int)(pTC-aTC);
140823      nOr = (int)(ppOr-apOr);
140824
140825      if( rc==SQLITE_OK ){
140826        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
140827        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
140828          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
140829        }
140830      }
140831
140832      sqlite3_free(aTC);
140833    }
140834  }
140835#endif
140836
140837  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
140838  return rc;
140839}
140840
140841/*
140842** Invalidate the current position list for phrase pPhrase.
140843*/
140844static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
140845  if( pPhrase->doclist.bFreeList ){
140846    sqlite3_free(pPhrase->doclist.pList);
140847  }
140848  pPhrase->doclist.pList = 0;
140849  pPhrase->doclist.nList = 0;
140850  pPhrase->doclist.bFreeList = 0;
140851}
140852
140853/*
140854** This function is called to edit the position list associated with
140855** the phrase object passed as the fifth argument according to a NEAR
140856** condition. For example:
140857**
140858**     abc NEAR/5 "def ghi"
140859**
140860** Parameter nNear is passed the NEAR distance of the expression (5 in
140861** the example above). When this function is called, *paPoslist points to
140862** the position list, and *pnToken is the number of phrase tokens in, the
140863** phrase on the other side of the NEAR operator to pPhrase. For example,
140864** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
140865** the position list associated with phrase "abc".
140866**
140867** All positions in the pPhrase position list that are not sufficiently
140868** close to a position in the *paPoslist position list are removed. If this
140869** leaves 0 positions, zero is returned. Otherwise, non-zero.
140870**
140871** Before returning, *paPoslist is set to point to the position lsit
140872** associated with pPhrase. And *pnToken is set to the number of tokens in
140873** pPhrase.
140874*/
140875static int fts3EvalNearTrim(
140876  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
140877  char *aTmp,                     /* Temporary space to use */
140878  char **paPoslist,               /* IN/OUT: Position list */
140879  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
140880  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
140881){
140882  int nParam1 = nNear + pPhrase->nToken;
140883  int nParam2 = nNear + *pnToken;
140884  int nNew;
140885  char *p2;
140886  char *pOut;
140887  int res;
140888
140889  assert( pPhrase->doclist.pList );
140890
140891  p2 = pOut = pPhrase->doclist.pList;
140892  res = fts3PoslistNearMerge(
140893    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
140894  );
140895  if( res ){
140896    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
140897    assert( pPhrase->doclist.pList[nNew]=='\0' );
140898    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
140899    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
140900    pPhrase->doclist.nList = nNew;
140901    *paPoslist = pPhrase->doclist.pList;
140902    *pnToken = pPhrase->nToken;
140903  }
140904
140905  return res;
140906}
140907
140908/*
140909** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
140910** Otherwise, it advances the expression passed as the second argument to
140911** point to the next matching row in the database. Expressions iterate through
140912** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
140913** or descending if it is non-zero.
140914**
140915** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
140916** successful, the following variables in pExpr are set:
140917**
140918**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
140919**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
140920**
140921** If the expression is of type FTSQUERY_PHRASE, and the expression is not
140922** at EOF, then the following variables are populated with the position list
140923** for the phrase for the visited row:
140924**
140925**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
140926**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
140927**
140928** It says above that this function advances the expression to the next
140929** matching row. This is usually true, but there are the following exceptions:
140930**
140931**   1. Deferred tokens are not taken into account. If a phrase consists
140932**      entirely of deferred tokens, it is assumed to match every row in
140933**      the db. In this case the position-list is not populated at all.
140934**
140935**      Or, if a phrase contains one or more deferred tokens and one or
140936**      more non-deferred tokens, then the expression is advanced to the
140937**      next possible match, considering only non-deferred tokens. In other
140938**      words, if the phrase is "A B C", and "B" is deferred, the expression
140939**      is advanced to the next row that contains an instance of "A * C",
140940**      where "*" may match any single token. The position list in this case
140941**      is populated as for "A * C" before returning.
140942**
140943**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
140944**      advanced to point to the next row that matches "x AND y".
140945**
140946** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
140947** really a match, taking into account deferred tokens and NEAR operators.
140948*/
140949static void fts3EvalNextRow(
140950  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140951  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
140952  int *pRc                        /* IN/OUT: Error code */
140953){
140954  if( *pRc==SQLITE_OK ){
140955    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
140956    assert( pExpr->bEof==0 );
140957    pExpr->bStart = 1;
140958
140959    switch( pExpr->eType ){
140960      case FTSQUERY_NEAR:
140961      case FTSQUERY_AND: {
140962        Fts3Expr *pLeft = pExpr->pLeft;
140963        Fts3Expr *pRight = pExpr->pRight;
140964        assert( !pLeft->bDeferred || !pRight->bDeferred );
140965
140966        if( pLeft->bDeferred ){
140967          /* LHS is entirely deferred. So we assume it matches every row.
140968          ** Advance the RHS iterator to find the next row visited. */
140969          fts3EvalNextRow(pCsr, pRight, pRc);
140970          pExpr->iDocid = pRight->iDocid;
140971          pExpr->bEof = pRight->bEof;
140972        }else if( pRight->bDeferred ){
140973          /* RHS is entirely deferred. So we assume it matches every row.
140974          ** Advance the LHS iterator to find the next row visited. */
140975          fts3EvalNextRow(pCsr, pLeft, pRc);
140976          pExpr->iDocid = pLeft->iDocid;
140977          pExpr->bEof = pLeft->bEof;
140978        }else{
140979          /* Neither the RHS or LHS are deferred. */
140980          fts3EvalNextRow(pCsr, pLeft, pRc);
140981          fts3EvalNextRow(pCsr, pRight, pRc);
140982          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
140983            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
140984            if( iDiff==0 ) break;
140985            if( iDiff<0 ){
140986              fts3EvalNextRow(pCsr, pLeft, pRc);
140987            }else{
140988              fts3EvalNextRow(pCsr, pRight, pRc);
140989            }
140990          }
140991          pExpr->iDocid = pLeft->iDocid;
140992          pExpr->bEof = (pLeft->bEof || pRight->bEof);
140993          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
140994            if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
140995              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
140996              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
140997                memset(pDl->pList, 0, pDl->nList);
140998                fts3EvalNextRow(pCsr, pRight, pRc);
140999              }
141000            }
141001            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
141002              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
141003              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
141004                memset(pDl->pList, 0, pDl->nList);
141005                fts3EvalNextRow(pCsr, pLeft, pRc);
141006              }
141007            }
141008          }
141009        }
141010        break;
141011      }
141012
141013      case FTSQUERY_OR: {
141014        Fts3Expr *pLeft = pExpr->pLeft;
141015        Fts3Expr *pRight = pExpr->pRight;
141016        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
141017
141018        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
141019        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
141020
141021        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
141022          fts3EvalNextRow(pCsr, pLeft, pRc);
141023        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
141024          fts3EvalNextRow(pCsr, pRight, pRc);
141025        }else{
141026          fts3EvalNextRow(pCsr, pLeft, pRc);
141027          fts3EvalNextRow(pCsr, pRight, pRc);
141028        }
141029
141030        pExpr->bEof = (pLeft->bEof && pRight->bEof);
141031        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
141032        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
141033          pExpr->iDocid = pLeft->iDocid;
141034        }else{
141035          pExpr->iDocid = pRight->iDocid;
141036        }
141037
141038        break;
141039      }
141040
141041      case FTSQUERY_NOT: {
141042        Fts3Expr *pLeft = pExpr->pLeft;
141043        Fts3Expr *pRight = pExpr->pRight;
141044
141045        if( pRight->bStart==0 ){
141046          fts3EvalNextRow(pCsr, pRight, pRc);
141047          assert( *pRc!=SQLITE_OK || pRight->bStart );
141048        }
141049
141050        fts3EvalNextRow(pCsr, pLeft, pRc);
141051        if( pLeft->bEof==0 ){
141052          while( !*pRc
141053              && !pRight->bEof
141054              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
141055          ){
141056            fts3EvalNextRow(pCsr, pRight, pRc);
141057          }
141058        }
141059        pExpr->iDocid = pLeft->iDocid;
141060        pExpr->bEof = pLeft->bEof;
141061        break;
141062      }
141063
141064      default: {
141065        Fts3Phrase *pPhrase = pExpr->pPhrase;
141066        fts3EvalInvalidatePoslist(pPhrase);
141067        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
141068        pExpr->iDocid = pPhrase->doclist.iDocid;
141069        break;
141070      }
141071    }
141072  }
141073}
141074
141075/*
141076** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
141077** cluster, then this function returns 1 immediately.
141078**
141079** Otherwise, it checks if the current row really does match the NEAR
141080** expression, using the data currently stored in the position lists
141081** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
141082**
141083** If the current row is a match, the position list associated with each
141084** phrase in the NEAR expression is edited in place to contain only those
141085** phrase instances sufficiently close to their peers to satisfy all NEAR
141086** constraints. In this case it returns 1. If the NEAR expression does not
141087** match the current row, 0 is returned. The position lists may or may not
141088** be edited if 0 is returned.
141089*/
141090static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
141091  int res = 1;
141092
141093  /* The following block runs if pExpr is the root of a NEAR query.
141094  ** For example, the query:
141095  **
141096  **         "w" NEAR "x" NEAR "y" NEAR "z"
141097  **
141098  ** which is represented in tree form as:
141099  **
141100  **                               |
141101  **                          +--NEAR--+      <-- root of NEAR query
141102  **                          |        |
141103  **                     +--NEAR--+   "z"
141104  **                     |        |
141105  **                +--NEAR--+   "y"
141106  **                |        |
141107  **               "w"      "x"
141108  **
141109  ** The right-hand child of a NEAR node is always a phrase. The
141110  ** left-hand child may be either a phrase or a NEAR node. There are
141111  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
141112  */
141113  if( *pRc==SQLITE_OK
141114   && pExpr->eType==FTSQUERY_NEAR
141115   && pExpr->bEof==0
141116   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
141117  ){
141118    Fts3Expr *p;
141119    int nTmp = 0;                 /* Bytes of temp space */
141120    char *aTmp;                   /* Temp space for PoslistNearMerge() */
141121
141122    /* Allocate temporary working space. */
141123    for(p=pExpr; p->pLeft; p=p->pLeft){
141124      nTmp += p->pRight->pPhrase->doclist.nList;
141125    }
141126    nTmp += p->pPhrase->doclist.nList;
141127    if( nTmp==0 ){
141128      res = 0;
141129    }else{
141130      aTmp = sqlite3_malloc(nTmp*2);
141131      if( !aTmp ){
141132        *pRc = SQLITE_NOMEM;
141133        res = 0;
141134      }else{
141135        char *aPoslist = p->pPhrase->doclist.pList;
141136        int nToken = p->pPhrase->nToken;
141137
141138        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
141139          Fts3Phrase *pPhrase = p->pRight->pPhrase;
141140          int nNear = p->nNear;
141141          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
141142        }
141143
141144        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
141145        nToken = pExpr->pRight->pPhrase->nToken;
141146        for(p=pExpr->pLeft; p && res; p=p->pLeft){
141147          int nNear;
141148          Fts3Phrase *pPhrase;
141149          assert( p->pParent && p->pParent->pLeft==p );
141150          nNear = p->pParent->nNear;
141151          pPhrase = (
141152              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
141153              );
141154          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
141155        }
141156      }
141157
141158      sqlite3_free(aTmp);
141159    }
141160  }
141161
141162  return res;
141163}
141164
141165/*
141166** This function is a helper function for sqlite3Fts3EvalTestDeferred().
141167** Assuming no error occurs or has occurred, It returns non-zero if the
141168** expression passed as the second argument matches the row that pCsr
141169** currently points to, or zero if it does not.
141170**
141171** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
141172** If an error occurs during execution of this function, *pRc is set to
141173** the appropriate SQLite error code. In this case the returned value is
141174** undefined.
141175*/
141176static int fts3EvalTestExpr(
141177  Fts3Cursor *pCsr,               /* FTS cursor handle */
141178  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
141179  int *pRc                        /* IN/OUT: Error code */
141180){
141181  int bHit = 1;                   /* Return value */
141182  if( *pRc==SQLITE_OK ){
141183    switch( pExpr->eType ){
141184      case FTSQUERY_NEAR:
141185      case FTSQUERY_AND:
141186        bHit = (
141187            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
141188         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
141189         && fts3EvalNearTest(pExpr, pRc)
141190        );
141191
141192        /* If the NEAR expression does not match any rows, zero the doclist for
141193        ** all phrases involved in the NEAR. This is because the snippet(),
141194        ** offsets() and matchinfo() functions are not supposed to recognize
141195        ** any instances of phrases that are part of unmatched NEAR queries.
141196        ** For example if this expression:
141197        **
141198        **    ... MATCH 'a OR (b NEAR c)'
141199        **
141200        ** is matched against a row containing:
141201        **
141202        **        'a b d e'
141203        **
141204        ** then any snippet() should ony highlight the "a" term, not the "b"
141205        ** (as "b" is part of a non-matching NEAR clause).
141206        */
141207        if( bHit==0
141208         && pExpr->eType==FTSQUERY_NEAR
141209         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
141210        ){
141211          Fts3Expr *p;
141212          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
141213            if( p->pRight->iDocid==pCsr->iPrevId ){
141214              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
141215            }
141216          }
141217          if( p->iDocid==pCsr->iPrevId ){
141218            fts3EvalInvalidatePoslist(p->pPhrase);
141219          }
141220        }
141221
141222        break;
141223
141224      case FTSQUERY_OR: {
141225        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
141226        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
141227        bHit = bHit1 || bHit2;
141228        break;
141229      }
141230
141231      case FTSQUERY_NOT:
141232        bHit = (
141233            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
141234         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
141235        );
141236        break;
141237
141238      default: {
141239#ifndef SQLITE_DISABLE_FTS4_DEFERRED
141240        if( pCsr->pDeferred
141241         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
141242        ){
141243          Fts3Phrase *pPhrase = pExpr->pPhrase;
141244          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
141245          if( pExpr->bDeferred ){
141246            fts3EvalInvalidatePoslist(pPhrase);
141247          }
141248          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
141249          bHit = (pPhrase->doclist.pList!=0);
141250          pExpr->iDocid = pCsr->iPrevId;
141251        }else
141252#endif
141253        {
141254          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
141255        }
141256        break;
141257      }
141258    }
141259  }
141260  return bHit;
141261}
141262
141263/*
141264** This function is called as the second part of each xNext operation when
141265** iterating through the results of a full-text query. At this point the
141266** cursor points to a row that matches the query expression, with the
141267** following caveats:
141268**
141269**   * Up until this point, "NEAR" operators in the expression have been
141270**     treated as "AND".
141271**
141272**   * Deferred tokens have not yet been considered.
141273**
141274** If *pRc is not SQLITE_OK when this function is called, it immediately
141275** returns 0. Otherwise, it tests whether or not after considering NEAR
141276** operators and deferred tokens the current row is still a match for the
141277** expression. It returns 1 if both of the following are true:
141278**
141279**   1. *pRc is SQLITE_OK when this function returns, and
141280**
141281**   2. After scanning the current FTS table row for the deferred tokens,
141282**      it is determined that the row does *not* match the query.
141283**
141284** Or, if no error occurs and it seems the current row does match the FTS
141285** query, return 0.
141286*/
141287SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
141288  int rc = *pRc;
141289  int bMiss = 0;
141290  if( rc==SQLITE_OK ){
141291
141292    /* If there are one or more deferred tokens, load the current row into
141293    ** memory and scan it to determine the position list for each deferred
141294    ** token. Then, see if this row is really a match, considering deferred
141295    ** tokens and NEAR operators (neither of which were taken into account
141296    ** earlier, by fts3EvalNextRow()).
141297    */
141298    if( pCsr->pDeferred ){
141299      rc = fts3CursorSeek(0, pCsr);
141300      if( rc==SQLITE_OK ){
141301        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
141302      }
141303    }
141304    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
141305
141306    /* Free the position-lists accumulated for each deferred token above. */
141307    sqlite3Fts3FreeDeferredDoclists(pCsr);
141308    *pRc = rc;
141309  }
141310  return (rc==SQLITE_OK && bMiss);
141311}
141312
141313/*
141314** Advance to the next document that matches the FTS expression in
141315** Fts3Cursor.pExpr.
141316*/
141317static int fts3EvalNext(Fts3Cursor *pCsr){
141318  int rc = SQLITE_OK;             /* Return Code */
141319  Fts3Expr *pExpr = pCsr->pExpr;
141320  assert( pCsr->isEof==0 );
141321  if( pExpr==0 ){
141322    pCsr->isEof = 1;
141323  }else{
141324    do {
141325      if( pCsr->isRequireSeek==0 ){
141326        sqlite3_reset(pCsr->pStmt);
141327      }
141328      assert( sqlite3_data_count(pCsr->pStmt)==0 );
141329      fts3EvalNextRow(pCsr, pExpr, &rc);
141330      pCsr->isEof = pExpr->bEof;
141331      pCsr->isRequireSeek = 1;
141332      pCsr->isMatchinfoNeeded = 1;
141333      pCsr->iPrevId = pExpr->iDocid;
141334    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
141335  }
141336
141337  /* Check if the cursor is past the end of the docid range specified
141338  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
141339  if( rc==SQLITE_OK && (
141340        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
141341     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
141342  )){
141343    pCsr->isEof = 1;
141344  }
141345
141346  return rc;
141347}
141348
141349/*
141350** Restart interation for expression pExpr so that the next call to
141351** fts3EvalNext() visits the first row. Do not allow incremental
141352** loading or merging of phrase doclists for this iteration.
141353**
141354** If *pRc is other than SQLITE_OK when this function is called, it is
141355** a no-op. If an error occurs within this function, *pRc is set to an
141356** SQLite error code before returning.
141357*/
141358static void fts3EvalRestart(
141359  Fts3Cursor *pCsr,
141360  Fts3Expr *pExpr,
141361  int *pRc
141362){
141363  if( pExpr && *pRc==SQLITE_OK ){
141364    Fts3Phrase *pPhrase = pExpr->pPhrase;
141365
141366    if( pPhrase ){
141367      fts3EvalInvalidatePoslist(pPhrase);
141368      if( pPhrase->bIncr ){
141369        int i;
141370        for(i=0; i<pPhrase->nToken; i++){
141371          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
141372          assert( pToken->pDeferred==0 );
141373          if( pToken->pSegcsr ){
141374            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
141375          }
141376        }
141377        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
141378      }
141379      pPhrase->doclist.pNextDocid = 0;
141380      pPhrase->doclist.iDocid = 0;
141381      pPhrase->pOrPoslist = 0;
141382    }
141383
141384    pExpr->iDocid = 0;
141385    pExpr->bEof = 0;
141386    pExpr->bStart = 0;
141387
141388    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
141389    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
141390  }
141391}
141392
141393/*
141394** After allocating the Fts3Expr.aMI[] array for each phrase in the
141395** expression rooted at pExpr, the cursor iterates through all rows matched
141396** by pExpr, calling this function for each row. This function increments
141397** the values in Fts3Expr.aMI[] according to the position-list currently
141398** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
141399** expression nodes.
141400*/
141401static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
141402  if( pExpr ){
141403    Fts3Phrase *pPhrase = pExpr->pPhrase;
141404    if( pPhrase && pPhrase->doclist.pList ){
141405      int iCol = 0;
141406      char *p = pPhrase->doclist.pList;
141407
141408      assert( *p );
141409      while( 1 ){
141410        u8 c = 0;
141411        int iCnt = 0;
141412        while( 0xFE & (*p | c) ){
141413          if( (c&0x80)==0 ) iCnt++;
141414          c = *p++ & 0x80;
141415        }
141416
141417        /* aMI[iCol*3 + 1] = Number of occurrences
141418        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
141419        */
141420        pExpr->aMI[iCol*3 + 1] += iCnt;
141421        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
141422        if( *p==0x00 ) break;
141423        p++;
141424        p += fts3GetVarint32(p, &iCol);
141425      }
141426    }
141427
141428    fts3EvalUpdateCounts(pExpr->pLeft);
141429    fts3EvalUpdateCounts(pExpr->pRight);
141430  }
141431}
141432
141433/*
141434** Expression pExpr must be of type FTSQUERY_PHRASE.
141435**
141436** If it is not already allocated and populated, this function allocates and
141437** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
141438** of a NEAR expression, then it also allocates and populates the same array
141439** for all other phrases that are part of the NEAR expression.
141440**
141441** SQLITE_OK is returned if the aMI[] array is successfully allocated and
141442** populated. Otherwise, if an error occurs, an SQLite error code is returned.
141443*/
141444static int fts3EvalGatherStats(
141445  Fts3Cursor *pCsr,               /* Cursor object */
141446  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
141447){
141448  int rc = SQLITE_OK;             /* Return code */
141449
141450  assert( pExpr->eType==FTSQUERY_PHRASE );
141451  if( pExpr->aMI==0 ){
141452    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141453    Fts3Expr *pRoot;                /* Root of NEAR expression */
141454    Fts3Expr *p;                    /* Iterator used for several purposes */
141455
141456    sqlite3_int64 iPrevId = pCsr->iPrevId;
141457    sqlite3_int64 iDocid;
141458    u8 bEof;
141459
141460    /* Find the root of the NEAR expression */
141461    pRoot = pExpr;
141462    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
141463      pRoot = pRoot->pParent;
141464    }
141465    iDocid = pRoot->iDocid;
141466    bEof = pRoot->bEof;
141467    assert( pRoot->bStart );
141468
141469    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
141470    for(p=pRoot; p; p=p->pLeft){
141471      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
141472      assert( pE->aMI==0 );
141473      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
141474      if( !pE->aMI ) return SQLITE_NOMEM;
141475      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
141476    }
141477
141478    fts3EvalRestart(pCsr, pRoot, &rc);
141479
141480    while( pCsr->isEof==0 && rc==SQLITE_OK ){
141481
141482      do {
141483        /* Ensure the %_content statement is reset. */
141484        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
141485        assert( sqlite3_data_count(pCsr->pStmt)==0 );
141486
141487        /* Advance to the next document */
141488        fts3EvalNextRow(pCsr, pRoot, &rc);
141489        pCsr->isEof = pRoot->bEof;
141490        pCsr->isRequireSeek = 1;
141491        pCsr->isMatchinfoNeeded = 1;
141492        pCsr->iPrevId = pRoot->iDocid;
141493      }while( pCsr->isEof==0
141494           && pRoot->eType==FTSQUERY_NEAR
141495           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
141496      );
141497
141498      if( rc==SQLITE_OK && pCsr->isEof==0 ){
141499        fts3EvalUpdateCounts(pRoot);
141500      }
141501    }
141502
141503    pCsr->isEof = 0;
141504    pCsr->iPrevId = iPrevId;
141505
141506    if( bEof ){
141507      pRoot->bEof = bEof;
141508    }else{
141509      /* Caution: pRoot may iterate through docids in ascending or descending
141510      ** order. For this reason, even though it seems more defensive, the
141511      ** do loop can not be written:
141512      **
141513      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
141514      */
141515      fts3EvalRestart(pCsr, pRoot, &rc);
141516      do {
141517        fts3EvalNextRow(pCsr, pRoot, &rc);
141518        assert( pRoot->bEof==0 );
141519      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
141520    }
141521  }
141522  return rc;
141523}
141524
141525/*
141526** This function is used by the matchinfo() module to query a phrase
141527** expression node for the following information:
141528**
141529**   1. The total number of occurrences of the phrase in each column of
141530**      the FTS table (considering all rows), and
141531**
141532**   2. For each column, the number of rows in the table for which the
141533**      column contains at least one instance of the phrase.
141534**
141535** If no error occurs, SQLITE_OK is returned and the values for each column
141536** written into the array aiOut as follows:
141537**
141538**   aiOut[iCol*3 + 1] = Number of occurrences
141539**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
141540**
141541** Caveats:
141542**
141543**   * If a phrase consists entirely of deferred tokens, then all output
141544**     values are set to the number of documents in the table. In other
141545**     words we assume that very common tokens occur exactly once in each
141546**     column of each row of the table.
141547**
141548**   * If a phrase contains some deferred tokens (and some non-deferred
141549**     tokens), count the potential occurrence identified by considering
141550**     the non-deferred tokens instead of actual phrase occurrences.
141551**
141552**   * If the phrase is part of a NEAR expression, then only phrase instances
141553**     that meet the NEAR constraint are included in the counts.
141554*/
141555SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
141556  Fts3Cursor *pCsr,               /* FTS cursor handle */
141557  Fts3Expr *pExpr,                /* Phrase expression */
141558  u32 *aiOut                      /* Array to write results into (see above) */
141559){
141560  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141561  int rc = SQLITE_OK;
141562  int iCol;
141563
141564  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
141565    assert( pCsr->nDoc>0 );
141566    for(iCol=0; iCol<pTab->nColumn; iCol++){
141567      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
141568      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
141569    }
141570  }else{
141571    rc = fts3EvalGatherStats(pCsr, pExpr);
141572    if( rc==SQLITE_OK ){
141573      assert( pExpr->aMI );
141574      for(iCol=0; iCol<pTab->nColumn; iCol++){
141575        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
141576        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
141577      }
141578    }
141579  }
141580
141581  return rc;
141582}
141583
141584/*
141585** The expression pExpr passed as the second argument to this function
141586** must be of type FTSQUERY_PHRASE.
141587**
141588** The returned value is either NULL or a pointer to a buffer containing
141589** a position-list indicating the occurrences of the phrase in column iCol
141590** of the current row.
141591**
141592** More specifically, the returned buffer contains 1 varint for each
141593** occurrence of the phrase in the column, stored using the normal (delta+2)
141594** compression and is terminated by either an 0x01 or 0x00 byte. For example,
141595** if the requested column contains "a b X c d X X" and the position-list
141596** for 'X' is requested, the buffer returned may contain:
141597**
141598**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
141599**
141600** This function works regardless of whether or not the phrase is deferred,
141601** incremental, or neither.
141602*/
141603SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
141604  Fts3Cursor *pCsr,               /* FTS3 cursor object */
141605  Fts3Expr *pExpr,                /* Phrase to return doclist for */
141606  int iCol,                       /* Column to return position list for */
141607  char **ppOut                    /* OUT: Pointer to position list */
141608){
141609  Fts3Phrase *pPhrase = pExpr->pPhrase;
141610  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141611  char *pIter;
141612  int iThis;
141613  sqlite3_int64 iDocid;
141614
141615  /* If this phrase is applies specifically to some column other than
141616  ** column iCol, return a NULL pointer.  */
141617  *ppOut = 0;
141618  assert( iCol>=0 && iCol<pTab->nColumn );
141619  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
141620    return SQLITE_OK;
141621  }
141622
141623  iDocid = pExpr->iDocid;
141624  pIter = pPhrase->doclist.pList;
141625  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
141626    int rc = SQLITE_OK;
141627    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
141628    int bOr = 0;
141629    u8 bTreeEof = 0;
141630    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
141631    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
141632    int bMatch;
141633
141634    /* Check if this phrase descends from an OR expression node. If not,
141635    ** return NULL. Otherwise, the entry that corresponds to docid
141636    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
141637    ** tree that the node is part of has been marked as EOF, but the node
141638    ** itself is not EOF, then it may point to an earlier entry. */
141639    pNear = pExpr;
141640    for(p=pExpr->pParent; p; p=p->pParent){
141641      if( p->eType==FTSQUERY_OR ) bOr = 1;
141642      if( p->eType==FTSQUERY_NEAR ) pNear = p;
141643      if( p->bEof ) bTreeEof = 1;
141644    }
141645    if( bOr==0 ) return SQLITE_OK;
141646
141647    /* This is the descendent of an OR node. In this case we cannot use
141648    ** an incremental phrase. Load the entire doclist for the phrase
141649    ** into memory in this case.  */
141650    if( pPhrase->bIncr ){
141651      int bEofSave = pNear->bEof;
141652      fts3EvalRestart(pCsr, pNear, &rc);
141653      while( rc==SQLITE_OK && !pNear->bEof ){
141654        fts3EvalNextRow(pCsr, pNear, &rc);
141655        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
141656      }
141657      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
141658    }
141659    if( bTreeEof ){
141660      while( rc==SQLITE_OK && !pNear->bEof ){
141661        fts3EvalNextRow(pCsr, pNear, &rc);
141662      }
141663    }
141664    if( rc!=SQLITE_OK ) return rc;
141665
141666    bMatch = 1;
141667    for(p=pNear; p; p=p->pLeft){
141668      u8 bEof = 0;
141669      Fts3Expr *pTest = p;
141670      Fts3Phrase *pPh;
141671      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
141672      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
141673      assert( pTest->eType==FTSQUERY_PHRASE );
141674      pPh = pTest->pPhrase;
141675
141676      pIter = pPh->pOrPoslist;
141677      iDocid = pPh->iOrDocid;
141678      if( pCsr->bDesc==bDescDoclist ){
141679        bEof = !pPh->doclist.nAll ||
141680          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
141681        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
141682          sqlite3Fts3DoclistNext(
141683              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
141684              &pIter, &iDocid, &bEof
141685          );
141686        }
141687      }else{
141688        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
141689        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
141690          int dummy;
141691          sqlite3Fts3DoclistPrev(
141692              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
141693              &pIter, &iDocid, &dummy, &bEof
141694              );
141695        }
141696      }
141697      pPh->pOrPoslist = pIter;
141698      pPh->iOrDocid = iDocid;
141699      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
141700    }
141701
141702    if( bMatch ){
141703      pIter = pPhrase->pOrPoslist;
141704    }else{
141705      pIter = 0;
141706    }
141707  }
141708  if( pIter==0 ) return SQLITE_OK;
141709
141710  if( *pIter==0x01 ){
141711    pIter++;
141712    pIter += fts3GetVarint32(pIter, &iThis);
141713  }else{
141714    iThis = 0;
141715  }
141716  while( iThis<iCol ){
141717    fts3ColumnlistCopy(0, &pIter);
141718    if( *pIter==0x00 ) return SQLITE_OK;
141719    pIter++;
141720    pIter += fts3GetVarint32(pIter, &iThis);
141721  }
141722  if( *pIter==0x00 ){
141723    pIter = 0;
141724  }
141725
141726  *ppOut = ((iCol==iThis)?pIter:0);
141727  return SQLITE_OK;
141728}
141729
141730/*
141731** Free all components of the Fts3Phrase structure that were allocated by
141732** the eval module. Specifically, this means to free:
141733**
141734**   * the contents of pPhrase->doclist, and
141735**   * any Fts3MultiSegReader objects held by phrase tokens.
141736*/
141737SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
141738  if( pPhrase ){
141739    int i;
141740    sqlite3_free(pPhrase->doclist.aAll);
141741    fts3EvalInvalidatePoslist(pPhrase);
141742    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
141743    for(i=0; i<pPhrase->nToken; i++){
141744      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
141745      pPhrase->aToken[i].pSegcsr = 0;
141746    }
141747  }
141748}
141749
141750
141751/*
141752** Return SQLITE_CORRUPT_VTAB.
141753*/
141754#ifdef SQLITE_DEBUG
141755SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
141756  return SQLITE_CORRUPT_VTAB;
141757}
141758#endif
141759
141760#if !SQLITE_CORE
141761/*
141762** Initialize API pointer table, if required.
141763*/
141764#ifdef _WIN32
141765__declspec(dllexport)
141766#endif
141767SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
141768  sqlite3 *db,
141769  char **pzErrMsg,
141770  const sqlite3_api_routines *pApi
141771){
141772  SQLITE_EXTENSION_INIT2(pApi)
141773  return sqlite3Fts3Init(db);
141774}
141775#endif
141776
141777#endif
141778
141779/************** End of fts3.c ************************************************/
141780/************** Begin file fts3_aux.c ****************************************/
141781/*
141782** 2011 Jan 27
141783**
141784** The author disclaims copyright to this source code.  In place of
141785** a legal notice, here is a blessing:
141786**
141787**    May you do good and not evil.
141788**    May you find forgiveness for yourself and forgive others.
141789**    May you share freely, never taking more than you give.
141790**
141791******************************************************************************
141792**
141793*/
141794/* #include "fts3Int.h" */
141795#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141796
141797/* #include <string.h> */
141798/* #include <assert.h> */
141799
141800typedef struct Fts3auxTable Fts3auxTable;
141801typedef struct Fts3auxCursor Fts3auxCursor;
141802
141803struct Fts3auxTable {
141804  sqlite3_vtab base;              /* Base class used by SQLite core */
141805  Fts3Table *pFts3Tab;
141806};
141807
141808struct Fts3auxCursor {
141809  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
141810  Fts3MultiSegReader csr;        /* Must be right after "base" */
141811  Fts3SegFilter filter;
141812  char *zStop;
141813  int nStop;                      /* Byte-length of string zStop */
141814  int iLangid;                    /* Language id to query */
141815  int isEof;                      /* True if cursor is at EOF */
141816  sqlite3_int64 iRowid;           /* Current rowid */
141817
141818  int iCol;                       /* Current value of 'col' column */
141819  int nStat;                      /* Size of aStat[] array */
141820  struct Fts3auxColstats {
141821    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
141822    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
141823  } *aStat;
141824};
141825
141826/*
141827** Schema of the terms table.
141828*/
141829#define FTS3_AUX_SCHEMA \
141830  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
141831
141832/*
141833** This function does all the work for both the xConnect and xCreate methods.
141834** These tables have no persistent representation of their own, so xConnect
141835** and xCreate are identical operations.
141836*/
141837static int fts3auxConnectMethod(
141838  sqlite3 *db,                    /* Database connection */
141839  void *pUnused,                  /* Unused */
141840  int argc,                       /* Number of elements in argv array */
141841  const char * const *argv,       /* xCreate/xConnect argument array */
141842  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
141843  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
141844){
141845  char const *zDb;                /* Name of database (e.g. "main") */
141846  char const *zFts3;              /* Name of fts3 table */
141847  int nDb;                        /* Result of strlen(zDb) */
141848  int nFts3;                      /* Result of strlen(zFts3) */
141849  int nByte;                      /* Bytes of space to allocate here */
141850  int rc;                         /* value returned by declare_vtab() */
141851  Fts3auxTable *p;                /* Virtual table object to return */
141852
141853  UNUSED_PARAMETER(pUnused);
141854
141855  /* The user should invoke this in one of two forms:
141856  **
141857  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
141858  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
141859  */
141860  if( argc!=4 && argc!=5 ) goto bad_args;
141861
141862  zDb = argv[1];
141863  nDb = (int)strlen(zDb);
141864  if( argc==5 ){
141865    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
141866      zDb = argv[3];
141867      nDb = (int)strlen(zDb);
141868      zFts3 = argv[4];
141869    }else{
141870      goto bad_args;
141871    }
141872  }else{
141873    zFts3 = argv[3];
141874  }
141875  nFts3 = (int)strlen(zFts3);
141876
141877  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
141878  if( rc!=SQLITE_OK ) return rc;
141879
141880  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
141881  p = (Fts3auxTable *)sqlite3_malloc(nByte);
141882  if( !p ) return SQLITE_NOMEM;
141883  memset(p, 0, nByte);
141884
141885  p->pFts3Tab = (Fts3Table *)&p[1];
141886  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
141887  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
141888  p->pFts3Tab->db = db;
141889  p->pFts3Tab->nIndex = 1;
141890
141891  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
141892  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
141893  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
141894
141895  *ppVtab = (sqlite3_vtab *)p;
141896  return SQLITE_OK;
141897
141898 bad_args:
141899  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
141900  return SQLITE_ERROR;
141901}
141902
141903/*
141904** This function does the work for both the xDisconnect and xDestroy methods.
141905** These tables have no persistent representation of their own, so xDisconnect
141906** and xDestroy are identical operations.
141907*/
141908static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
141909  Fts3auxTable *p = (Fts3auxTable *)pVtab;
141910  Fts3Table *pFts3 = p->pFts3Tab;
141911  int i;
141912
141913  /* Free any prepared statements held */
141914  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
141915    sqlite3_finalize(pFts3->aStmt[i]);
141916  }
141917  sqlite3_free(pFts3->zSegmentsTbl);
141918  sqlite3_free(p);
141919  return SQLITE_OK;
141920}
141921
141922#define FTS4AUX_EQ_CONSTRAINT 1
141923#define FTS4AUX_GE_CONSTRAINT 2
141924#define FTS4AUX_LE_CONSTRAINT 4
141925
141926/*
141927** xBestIndex - Analyze a WHERE and ORDER BY clause.
141928*/
141929static int fts3auxBestIndexMethod(
141930  sqlite3_vtab *pVTab,
141931  sqlite3_index_info *pInfo
141932){
141933  int i;
141934  int iEq = -1;
141935  int iGe = -1;
141936  int iLe = -1;
141937  int iLangid = -1;
141938  int iNext = 1;                  /* Next free argvIndex value */
141939
141940  UNUSED_PARAMETER(pVTab);
141941
141942  /* This vtab delivers always results in "ORDER BY term ASC" order. */
141943  if( pInfo->nOrderBy==1
141944   && pInfo->aOrderBy[0].iColumn==0
141945   && pInfo->aOrderBy[0].desc==0
141946  ){
141947    pInfo->orderByConsumed = 1;
141948  }
141949
141950  /* Search for equality and range constraints on the "term" column.
141951  ** And equality constraints on the hidden "languageid" column. */
141952  for(i=0; i<pInfo->nConstraint; i++){
141953    if( pInfo->aConstraint[i].usable ){
141954      int op = pInfo->aConstraint[i].op;
141955      int iCol = pInfo->aConstraint[i].iColumn;
141956
141957      if( iCol==0 ){
141958        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
141959        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
141960        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
141961        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
141962        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
141963      }
141964      if( iCol==4 ){
141965        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
141966      }
141967    }
141968  }
141969
141970  if( iEq>=0 ){
141971    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
141972    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
141973    pInfo->estimatedCost = 5;
141974  }else{
141975    pInfo->idxNum = 0;
141976    pInfo->estimatedCost = 20000;
141977    if( iGe>=0 ){
141978      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
141979      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
141980      pInfo->estimatedCost /= 2;
141981    }
141982    if( iLe>=0 ){
141983      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
141984      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
141985      pInfo->estimatedCost /= 2;
141986    }
141987  }
141988  if( iLangid>=0 ){
141989    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
141990    pInfo->estimatedCost--;
141991  }
141992
141993  return SQLITE_OK;
141994}
141995
141996/*
141997** xOpen - Open a cursor.
141998*/
141999static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
142000  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
142001
142002  UNUSED_PARAMETER(pVTab);
142003
142004  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
142005  if( !pCsr ) return SQLITE_NOMEM;
142006  memset(pCsr, 0, sizeof(Fts3auxCursor));
142007
142008  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
142009  return SQLITE_OK;
142010}
142011
142012/*
142013** xClose - Close a cursor.
142014*/
142015static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
142016  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142017  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142018
142019  sqlite3Fts3SegmentsClose(pFts3);
142020  sqlite3Fts3SegReaderFinish(&pCsr->csr);
142021  sqlite3_free((void *)pCsr->filter.zTerm);
142022  sqlite3_free(pCsr->zStop);
142023  sqlite3_free(pCsr->aStat);
142024  sqlite3_free(pCsr);
142025  return SQLITE_OK;
142026}
142027
142028static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
142029  if( nSize>pCsr->nStat ){
142030    struct Fts3auxColstats *aNew;
142031    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
142032        sizeof(struct Fts3auxColstats) * nSize
142033    );
142034    if( aNew==0 ) return SQLITE_NOMEM;
142035    memset(&aNew[pCsr->nStat], 0,
142036        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
142037    );
142038    pCsr->aStat = aNew;
142039    pCsr->nStat = nSize;
142040  }
142041  return SQLITE_OK;
142042}
142043
142044/*
142045** xNext - Advance the cursor to the next row, if any.
142046*/
142047static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
142048  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142049  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142050  int rc;
142051
142052  /* Increment our pretend rowid value. */
142053  pCsr->iRowid++;
142054
142055  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
142056    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
142057  }
142058
142059  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
142060  if( rc==SQLITE_ROW ){
142061    int i = 0;
142062    int nDoclist = pCsr->csr.nDoclist;
142063    char *aDoclist = pCsr->csr.aDoclist;
142064    int iCol;
142065
142066    int eState = 0;
142067
142068    if( pCsr->zStop ){
142069      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
142070      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
142071      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
142072        pCsr->isEof = 1;
142073        return SQLITE_OK;
142074      }
142075    }
142076
142077    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
142078    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
142079    iCol = 0;
142080
142081    while( i<nDoclist ){
142082      sqlite3_int64 v = 0;
142083
142084      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
142085      switch( eState ){
142086        /* State 0. In this state the integer just read was a docid. */
142087        case 0:
142088          pCsr->aStat[0].nDoc++;
142089          eState = 1;
142090          iCol = 0;
142091          break;
142092
142093        /* State 1. In this state we are expecting either a 1, indicating
142094        ** that the following integer will be a column number, or the
142095        ** start of a position list for column 0.
142096        **
142097        ** The only difference between state 1 and state 2 is that if the
142098        ** integer encountered in state 1 is not 0 or 1, then we need to
142099        ** increment the column 0 "nDoc" count for this term.
142100        */
142101        case 1:
142102          assert( iCol==0 );
142103          if( v>1 ){
142104            pCsr->aStat[1].nDoc++;
142105          }
142106          eState = 2;
142107          /* fall through */
142108
142109        case 2:
142110          if( v==0 ){       /* 0x00. Next integer will be a docid. */
142111            eState = 0;
142112          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
142113            eState = 3;
142114          }else{            /* 2 or greater. A position. */
142115            pCsr->aStat[iCol+1].nOcc++;
142116            pCsr->aStat[0].nOcc++;
142117          }
142118          break;
142119
142120        /* State 3. The integer just read is a column number. */
142121        default: assert( eState==3 );
142122          iCol = (int)v;
142123          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
142124          pCsr->aStat[iCol+1].nDoc++;
142125          eState = 2;
142126          break;
142127      }
142128    }
142129
142130    pCsr->iCol = 0;
142131    rc = SQLITE_OK;
142132  }else{
142133    pCsr->isEof = 1;
142134  }
142135  return rc;
142136}
142137
142138/*
142139** xFilter - Initialize a cursor to point at the start of its data.
142140*/
142141static int fts3auxFilterMethod(
142142  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
142143  int idxNum,                     /* Strategy index */
142144  const char *idxStr,             /* Unused */
142145  int nVal,                       /* Number of elements in apVal */
142146  sqlite3_value **apVal           /* Arguments for the indexing scheme */
142147){
142148  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142149  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142150  int rc;
142151  int isScan = 0;
142152  int iLangVal = 0;               /* Language id to query */
142153
142154  int iEq = -1;                   /* Index of term=? value in apVal */
142155  int iGe = -1;                   /* Index of term>=? value in apVal */
142156  int iLe = -1;                   /* Index of term<=? value in apVal */
142157  int iLangid = -1;               /* Index of languageid=? value in apVal */
142158  int iNext = 0;
142159
142160  UNUSED_PARAMETER(nVal);
142161  UNUSED_PARAMETER(idxStr);
142162
142163  assert( idxStr==0 );
142164  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
142165       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
142166       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
142167  );
142168
142169  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
142170    iEq = iNext++;
142171  }else{
142172    isScan = 1;
142173    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
142174      iGe = iNext++;
142175    }
142176    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
142177      iLe = iNext++;
142178    }
142179  }
142180  if( iNext<nVal ){
142181    iLangid = iNext++;
142182  }
142183
142184  /* In case this cursor is being reused, close and zero it. */
142185  testcase(pCsr->filter.zTerm);
142186  sqlite3Fts3SegReaderFinish(&pCsr->csr);
142187  sqlite3_free((void *)pCsr->filter.zTerm);
142188  sqlite3_free(pCsr->aStat);
142189  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
142190
142191  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
142192  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
142193
142194  if( iEq>=0 || iGe>=0 ){
142195    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
142196    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
142197    if( zStr ){
142198      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
142199      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
142200      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
142201    }
142202  }
142203
142204  if( iLe>=0 ){
142205    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
142206    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
142207    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
142208  }
142209
142210  if( iLangid>=0 ){
142211    iLangVal = sqlite3_value_int(apVal[iLangid]);
142212
142213    /* If the user specified a negative value for the languageid, use zero
142214    ** instead. This works, as the "languageid=?" constraint will also
142215    ** be tested by the VDBE layer. The test will always be false (since
142216    ** this module will not return a row with a negative languageid), and
142217    ** so the overall query will return zero rows.  */
142218    if( iLangVal<0 ) iLangVal = 0;
142219  }
142220  pCsr->iLangid = iLangVal;
142221
142222  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
142223      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
142224  );
142225  if( rc==SQLITE_OK ){
142226    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
142227  }
142228
142229  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
142230  return rc;
142231}
142232
142233/*
142234** xEof - Return true if the cursor is at EOF, or false otherwise.
142235*/
142236static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
142237  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142238  return pCsr->isEof;
142239}
142240
142241/*
142242** xColumn - Return a column value.
142243*/
142244static int fts3auxColumnMethod(
142245  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142246  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
142247  int iCol                        /* Index of column to read value from */
142248){
142249  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
142250
142251  assert( p->isEof==0 );
142252  switch( iCol ){
142253    case 0: /* term */
142254      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
142255      break;
142256
142257    case 1: /* col */
142258      if( p->iCol ){
142259        sqlite3_result_int(pCtx, p->iCol-1);
142260      }else{
142261        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
142262      }
142263      break;
142264
142265    case 2: /* documents */
142266      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
142267      break;
142268
142269    case 3: /* occurrences */
142270      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
142271      break;
142272
142273    default: /* languageid */
142274      assert( iCol==4 );
142275      sqlite3_result_int(pCtx, p->iLangid);
142276      break;
142277  }
142278
142279  return SQLITE_OK;
142280}
142281
142282/*
142283** xRowid - Return the current rowid for the cursor.
142284*/
142285static int fts3auxRowidMethod(
142286  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142287  sqlite_int64 *pRowid            /* OUT: Rowid value */
142288){
142289  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142290  *pRowid = pCsr->iRowid;
142291  return SQLITE_OK;
142292}
142293
142294/*
142295** Register the fts3aux module with database connection db. Return SQLITE_OK
142296** if successful or an error code if sqlite3_create_module() fails.
142297*/
142298SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
142299  static const sqlite3_module fts3aux_module = {
142300     0,                           /* iVersion      */
142301     fts3auxConnectMethod,        /* xCreate       */
142302     fts3auxConnectMethod,        /* xConnect      */
142303     fts3auxBestIndexMethod,      /* xBestIndex    */
142304     fts3auxDisconnectMethod,     /* xDisconnect   */
142305     fts3auxDisconnectMethod,     /* xDestroy      */
142306     fts3auxOpenMethod,           /* xOpen         */
142307     fts3auxCloseMethod,          /* xClose        */
142308     fts3auxFilterMethod,         /* xFilter       */
142309     fts3auxNextMethod,           /* xNext         */
142310     fts3auxEofMethod,            /* xEof          */
142311     fts3auxColumnMethod,         /* xColumn       */
142312     fts3auxRowidMethod,          /* xRowid        */
142313     0,                           /* xUpdate       */
142314     0,                           /* xBegin        */
142315     0,                           /* xSync         */
142316     0,                           /* xCommit       */
142317     0,                           /* xRollback     */
142318     0,                           /* xFindFunction */
142319     0,                           /* xRename       */
142320     0,                           /* xSavepoint    */
142321     0,                           /* xRelease      */
142322     0                            /* xRollbackTo   */
142323  };
142324  int rc;                         /* Return code */
142325
142326  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
142327  return rc;
142328}
142329
142330#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142331
142332/************** End of fts3_aux.c ********************************************/
142333/************** Begin file fts3_expr.c ***************************************/
142334/*
142335** 2008 Nov 28
142336**
142337** The author disclaims copyright to this source code.  In place of
142338** a legal notice, here is a blessing:
142339**
142340**    May you do good and not evil.
142341**    May you find forgiveness for yourself and forgive others.
142342**    May you share freely, never taking more than you give.
142343**
142344******************************************************************************
142345**
142346** This module contains code that implements a parser for fts3 query strings
142347** (the right-hand argument to the MATCH operator). Because the supported
142348** syntax is relatively simple, the whole tokenizer/parser system is
142349** hand-coded.
142350*/
142351/* #include "fts3Int.h" */
142352#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142353
142354/*
142355** By default, this module parses the legacy syntax that has been
142356** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
142357** is defined, then it uses the new syntax. The differences between
142358** the new and the old syntaxes are:
142359**
142360**  a) The new syntax supports parenthesis. The old does not.
142361**
142362**  b) The new syntax supports the AND and NOT operators. The old does not.
142363**
142364**  c) The old syntax supports the "-" token qualifier. This is not
142365**     supported by the new syntax (it is replaced by the NOT operator).
142366**
142367**  d) When using the old syntax, the OR operator has a greater precedence
142368**     than an implicit AND. When using the new, both implicity and explicit
142369**     AND operators have a higher precedence than OR.
142370**
142371** If compiled with SQLITE_TEST defined, then this module exports the
142372** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
142373** to zero causes the module to use the old syntax. If it is set to
142374** non-zero the new syntax is activated. This is so both syntaxes can
142375** be tested using a single build of testfixture.
142376**
142377** The following describes the syntax supported by the fts3 MATCH
142378** operator in a similar format to that used by the lemon parser
142379** generator. This module does not use actually lemon, it uses a
142380** custom parser.
142381**
142382**   query ::= andexpr (OR andexpr)*.
142383**
142384**   andexpr ::= notexpr (AND? notexpr)*.
142385**
142386**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
142387**   notexpr ::= LP query RP.
142388**
142389**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
142390**
142391**   distance_opt ::= .
142392**   distance_opt ::= / INTEGER.
142393**
142394**   phrase ::= TOKEN.
142395**   phrase ::= COLUMN:TOKEN.
142396**   phrase ::= "TOKEN TOKEN TOKEN...".
142397*/
142398
142399#ifdef SQLITE_TEST
142400SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
142401#else
142402# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
142403#  define sqlite3_fts3_enable_parentheses 1
142404# else
142405#  define sqlite3_fts3_enable_parentheses 0
142406# endif
142407#endif
142408
142409/*
142410** Default span for NEAR operators.
142411*/
142412#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
142413
142414/* #include <string.h> */
142415/* #include <assert.h> */
142416
142417/*
142418** isNot:
142419**   This variable is used by function getNextNode(). When getNextNode() is
142420**   called, it sets ParseContext.isNot to true if the 'next node' is a
142421**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
142422**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
142423**   zero.
142424*/
142425typedef struct ParseContext ParseContext;
142426struct ParseContext {
142427  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
142428  int iLangid;                        /* Language id used with tokenizer */
142429  const char **azCol;                 /* Array of column names for fts3 table */
142430  int bFts4;                          /* True to allow FTS4-only syntax */
142431  int nCol;                           /* Number of entries in azCol[] */
142432  int iDefaultCol;                    /* Default column to query */
142433  int isNot;                          /* True if getNextNode() sees a unary - */
142434  sqlite3_context *pCtx;              /* Write error message here */
142435  int nNest;                          /* Number of nested brackets */
142436};
142437
142438/*
142439** This function is equivalent to the standard isspace() function.
142440**
142441** The standard isspace() can be awkward to use safely, because although it
142442** is defined to accept an argument of type int, its behavior when passed
142443** an integer that falls outside of the range of the unsigned char type
142444** is undefined (and sometimes, "undefined" means segfault). This wrapper
142445** is defined to accept an argument of type char, and always returns 0 for
142446** any values that fall outside of the range of the unsigned char type (i.e.
142447** negative values).
142448*/
142449static int fts3isspace(char c){
142450  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
142451}
142452
142453/*
142454** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
142455** zero the memory before returning a pointer to it. If unsuccessful,
142456** return NULL.
142457*/
142458static void *fts3MallocZero(int nByte){
142459  void *pRet = sqlite3_malloc(nByte);
142460  if( pRet ) memset(pRet, 0, nByte);
142461  return pRet;
142462}
142463
142464SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
142465  sqlite3_tokenizer *pTokenizer,
142466  int iLangid,
142467  const char *z,
142468  int n,
142469  sqlite3_tokenizer_cursor **ppCsr
142470){
142471  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142472  sqlite3_tokenizer_cursor *pCsr = 0;
142473  int rc;
142474
142475  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
142476  assert( rc==SQLITE_OK || pCsr==0 );
142477  if( rc==SQLITE_OK ){
142478    pCsr->pTokenizer = pTokenizer;
142479    if( pModule->iVersion>=1 ){
142480      rc = pModule->xLanguageid(pCsr, iLangid);
142481      if( rc!=SQLITE_OK ){
142482        pModule->xClose(pCsr);
142483        pCsr = 0;
142484      }
142485    }
142486  }
142487  *ppCsr = pCsr;
142488  return rc;
142489}
142490
142491/*
142492** Function getNextNode(), which is called by fts3ExprParse(), may itself
142493** call fts3ExprParse(). So this forward declaration is required.
142494*/
142495static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
142496
142497/*
142498** Extract the next token from buffer z (length n) using the tokenizer
142499** and other information (column names etc.) in pParse. Create an Fts3Expr
142500** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
142501** single token and set *ppExpr to point to it. If the end of the buffer is
142502** reached before a token is found, set *ppExpr to zero. It is the
142503** responsibility of the caller to eventually deallocate the allocated
142504** Fts3Expr structure (if any) by passing it to sqlite3_free().
142505**
142506** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
142507** fails.
142508*/
142509static int getNextToken(
142510  ParseContext *pParse,                   /* fts3 query parse context */
142511  int iCol,                               /* Value for Fts3Phrase.iColumn */
142512  const char *z, int n,                   /* Input string */
142513  Fts3Expr **ppExpr,                      /* OUT: expression */
142514  int *pnConsumed                         /* OUT: Number of bytes consumed */
142515){
142516  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
142517  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142518  int rc;
142519  sqlite3_tokenizer_cursor *pCursor;
142520  Fts3Expr *pRet = 0;
142521  int i = 0;
142522
142523  /* Set variable i to the maximum number of bytes of input to tokenize. */
142524  for(i=0; i<n; i++){
142525    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
142526    if( z[i]=='"' ) break;
142527  }
142528
142529  *pnConsumed = i;
142530  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
142531  if( rc==SQLITE_OK ){
142532    const char *zToken;
142533    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
142534    int nByte;                               /* total space to allocate */
142535
142536    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
142537    if( rc==SQLITE_OK ){
142538      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
142539      pRet = (Fts3Expr *)fts3MallocZero(nByte);
142540      if( !pRet ){
142541        rc = SQLITE_NOMEM;
142542      }else{
142543        pRet->eType = FTSQUERY_PHRASE;
142544        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
142545        pRet->pPhrase->nToken = 1;
142546        pRet->pPhrase->iColumn = iCol;
142547        pRet->pPhrase->aToken[0].n = nToken;
142548        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
142549        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
142550
142551        if( iEnd<n && z[iEnd]=='*' ){
142552          pRet->pPhrase->aToken[0].isPrefix = 1;
142553          iEnd++;
142554        }
142555
142556        while( 1 ){
142557          if( !sqlite3_fts3_enable_parentheses
142558           && iStart>0 && z[iStart-1]=='-'
142559          ){
142560            pParse->isNot = 1;
142561            iStart--;
142562          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
142563            pRet->pPhrase->aToken[0].bFirst = 1;
142564            iStart--;
142565          }else{
142566            break;
142567          }
142568        }
142569
142570      }
142571      *pnConsumed = iEnd;
142572    }else if( i && rc==SQLITE_DONE ){
142573      rc = SQLITE_OK;
142574    }
142575
142576    pModule->xClose(pCursor);
142577  }
142578
142579  *ppExpr = pRet;
142580  return rc;
142581}
142582
142583
142584/*
142585** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
142586** then free the old allocation.
142587*/
142588static void *fts3ReallocOrFree(void *pOrig, int nNew){
142589  void *pRet = sqlite3_realloc(pOrig, nNew);
142590  if( !pRet ){
142591    sqlite3_free(pOrig);
142592  }
142593  return pRet;
142594}
142595
142596/*
142597** Buffer zInput, length nInput, contains the contents of a quoted string
142598** that appeared as part of an fts3 query expression. Neither quote character
142599** is included in the buffer. This function attempts to tokenize the entire
142600** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
142601** containing the results.
142602**
142603** If successful, SQLITE_OK is returned and *ppExpr set to point at the
142604** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
142605** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
142606** to 0.
142607*/
142608static int getNextString(
142609  ParseContext *pParse,                   /* fts3 query parse context */
142610  const char *zInput, int nInput,         /* Input string */
142611  Fts3Expr **ppExpr                       /* OUT: expression */
142612){
142613  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
142614  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142615  int rc;
142616  Fts3Expr *p = 0;
142617  sqlite3_tokenizer_cursor *pCursor = 0;
142618  char *zTemp = 0;
142619  int nTemp = 0;
142620
142621  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
142622  int nToken = 0;
142623
142624  /* The final Fts3Expr data structure, including the Fts3Phrase,
142625  ** Fts3PhraseToken structures token buffers are all stored as a single
142626  ** allocation so that the expression can be freed with a single call to
142627  ** sqlite3_free(). Setting this up requires a two pass approach.
142628  **
142629  ** The first pass, in the block below, uses a tokenizer cursor to iterate
142630  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
142631  ** to assemble data in two dynamic buffers:
142632  **
142633  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
142634  **             structure, followed by the array of Fts3PhraseToken
142635  **             structures. This pass only populates the Fts3PhraseToken array.
142636  **
142637  **   Buffer zTemp: Contains copies of all tokens.
142638  **
142639  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
142640  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
142641  ** structures.
142642  */
142643  rc = sqlite3Fts3OpenTokenizer(
142644      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
142645  if( rc==SQLITE_OK ){
142646    int ii;
142647    for(ii=0; rc==SQLITE_OK; ii++){
142648      const char *zByte;
142649      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
142650      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
142651      if( rc==SQLITE_OK ){
142652        Fts3PhraseToken *pToken;
142653
142654        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
142655        if( !p ) goto no_mem;
142656
142657        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
142658        if( !zTemp ) goto no_mem;
142659
142660        assert( nToken==ii );
142661        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
142662        memset(pToken, 0, sizeof(Fts3PhraseToken));
142663
142664        memcpy(&zTemp[nTemp], zByte, nByte);
142665        nTemp += nByte;
142666
142667        pToken->n = nByte;
142668        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
142669        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
142670        nToken = ii+1;
142671      }
142672    }
142673
142674    pModule->xClose(pCursor);
142675    pCursor = 0;
142676  }
142677
142678  if( rc==SQLITE_DONE ){
142679    int jj;
142680    char *zBuf = 0;
142681
142682    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
142683    if( !p ) goto no_mem;
142684    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
142685    p->eType = FTSQUERY_PHRASE;
142686    p->pPhrase = (Fts3Phrase *)&p[1];
142687    p->pPhrase->iColumn = pParse->iDefaultCol;
142688    p->pPhrase->nToken = nToken;
142689
142690    zBuf = (char *)&p->pPhrase->aToken[nToken];
142691    if( zTemp ){
142692      memcpy(zBuf, zTemp, nTemp);
142693      sqlite3_free(zTemp);
142694    }else{
142695      assert( nTemp==0 );
142696    }
142697
142698    for(jj=0; jj<p->pPhrase->nToken; jj++){
142699      p->pPhrase->aToken[jj].z = zBuf;
142700      zBuf += p->pPhrase->aToken[jj].n;
142701    }
142702    rc = SQLITE_OK;
142703  }
142704
142705  *ppExpr = p;
142706  return rc;
142707no_mem:
142708
142709  if( pCursor ){
142710    pModule->xClose(pCursor);
142711  }
142712  sqlite3_free(zTemp);
142713  sqlite3_free(p);
142714  *ppExpr = 0;
142715  return SQLITE_NOMEM;
142716}
142717
142718/*
142719** The output variable *ppExpr is populated with an allocated Fts3Expr
142720** structure, or set to 0 if the end of the input buffer is reached.
142721**
142722** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
142723** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
142724** If SQLITE_ERROR is returned, pContext is populated with an error message.
142725*/
142726static int getNextNode(
142727  ParseContext *pParse,                   /* fts3 query parse context */
142728  const char *z, int n,                   /* Input string */
142729  Fts3Expr **ppExpr,                      /* OUT: expression */
142730  int *pnConsumed                         /* OUT: Number of bytes consumed */
142731){
142732  static const struct Fts3Keyword {
142733    char *z;                              /* Keyword text */
142734    unsigned char n;                      /* Length of the keyword */
142735    unsigned char parenOnly;              /* Only valid in paren mode */
142736    unsigned char eType;                  /* Keyword code */
142737  } aKeyword[] = {
142738    { "OR" ,  2, 0, FTSQUERY_OR   },
142739    { "AND",  3, 1, FTSQUERY_AND  },
142740    { "NOT",  3, 1, FTSQUERY_NOT  },
142741    { "NEAR", 4, 0, FTSQUERY_NEAR }
142742  };
142743  int ii;
142744  int iCol;
142745  int iColLen;
142746  int rc;
142747  Fts3Expr *pRet = 0;
142748
142749  const char *zInput = z;
142750  int nInput = n;
142751
142752  pParse->isNot = 0;
142753
142754  /* Skip over any whitespace before checking for a keyword, an open or
142755  ** close bracket, or a quoted string.
142756  */
142757  while( nInput>0 && fts3isspace(*zInput) ){
142758    nInput--;
142759    zInput++;
142760  }
142761  if( nInput==0 ){
142762    return SQLITE_DONE;
142763  }
142764
142765  /* See if we are dealing with a keyword. */
142766  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
142767    const struct Fts3Keyword *pKey = &aKeyword[ii];
142768
142769    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
142770      continue;
142771    }
142772
142773    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
142774      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
142775      int nKey = pKey->n;
142776      char cNext;
142777
142778      /* If this is a "NEAR" keyword, check for an explicit nearness. */
142779      if( pKey->eType==FTSQUERY_NEAR ){
142780        assert( nKey==4 );
142781        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
142782          nNear = 0;
142783          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
142784            nNear = nNear * 10 + (zInput[nKey] - '0');
142785          }
142786        }
142787      }
142788
142789      /* At this point this is probably a keyword. But for that to be true,
142790      ** the next byte must contain either whitespace, an open or close
142791      ** parenthesis, a quote character, or EOF.
142792      */
142793      cNext = zInput[nKey];
142794      if( fts3isspace(cNext)
142795       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
142796      ){
142797        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
142798        if( !pRet ){
142799          return SQLITE_NOMEM;
142800        }
142801        pRet->eType = pKey->eType;
142802        pRet->nNear = nNear;
142803        *ppExpr = pRet;
142804        *pnConsumed = (int)((zInput - z) + nKey);
142805        return SQLITE_OK;
142806      }
142807
142808      /* Turns out that wasn't a keyword after all. This happens if the
142809      ** user has supplied a token such as "ORacle". Continue.
142810      */
142811    }
142812  }
142813
142814  /* See if we are dealing with a quoted phrase. If this is the case, then
142815  ** search for the closing quote and pass the whole string to getNextString()
142816  ** for processing. This is easy to do, as fts3 has no syntax for escaping
142817  ** a quote character embedded in a string.
142818  */
142819  if( *zInput=='"' ){
142820    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
142821    *pnConsumed = (int)((zInput - z) + ii + 1);
142822    if( ii==nInput ){
142823      return SQLITE_ERROR;
142824    }
142825    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
142826  }
142827
142828  if( sqlite3_fts3_enable_parentheses ){
142829    if( *zInput=='(' ){
142830      int nConsumed = 0;
142831      pParse->nNest++;
142832      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
142833      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
142834      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
142835      return rc;
142836    }else if( *zInput==')' ){
142837      pParse->nNest--;
142838      *pnConsumed = (int)((zInput - z) + 1);
142839      *ppExpr = 0;
142840      return SQLITE_DONE;
142841    }
142842  }
142843
142844  /* If control flows to this point, this must be a regular token, or
142845  ** the end of the input. Read a regular token using the sqlite3_tokenizer
142846  ** interface. Before doing so, figure out if there is an explicit
142847  ** column specifier for the token.
142848  **
142849  ** TODO: Strangely, it is not possible to associate a column specifier
142850  ** with a quoted phrase, only with a single token. Not sure if this was
142851  ** an implementation artifact or an intentional decision when fts3 was
142852  ** first implemented. Whichever it was, this module duplicates the
142853  ** limitation.
142854  */
142855  iCol = pParse->iDefaultCol;
142856  iColLen = 0;
142857  for(ii=0; ii<pParse->nCol; ii++){
142858    const char *zStr = pParse->azCol[ii];
142859    int nStr = (int)strlen(zStr);
142860    if( nInput>nStr && zInput[nStr]==':'
142861     && sqlite3_strnicmp(zStr, zInput, nStr)==0
142862    ){
142863      iCol = ii;
142864      iColLen = (int)((zInput - z) + nStr + 1);
142865      break;
142866    }
142867  }
142868  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
142869  *pnConsumed += iColLen;
142870  return rc;
142871}
142872
142873/*
142874** The argument is an Fts3Expr structure for a binary operator (any type
142875** except an FTSQUERY_PHRASE). Return an integer value representing the
142876** precedence of the operator. Lower values have a higher precedence (i.e.
142877** group more tightly). For example, in the C language, the == operator
142878** groups more tightly than ||, and would therefore have a higher precedence.
142879**
142880** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
142881** is defined), the order of the operators in precedence from highest to
142882** lowest is:
142883**
142884**   NEAR
142885**   NOT
142886**   AND (including implicit ANDs)
142887**   OR
142888**
142889** Note that when using the old query syntax, the OR operator has a higher
142890** precedence than the AND operator.
142891*/
142892static int opPrecedence(Fts3Expr *p){
142893  assert( p->eType!=FTSQUERY_PHRASE );
142894  if( sqlite3_fts3_enable_parentheses ){
142895    return p->eType;
142896  }else if( p->eType==FTSQUERY_NEAR ){
142897    return 1;
142898  }else if( p->eType==FTSQUERY_OR ){
142899    return 2;
142900  }
142901  assert( p->eType==FTSQUERY_AND );
142902  return 3;
142903}
142904
142905/*
142906** Argument ppHead contains a pointer to the current head of a query
142907** expression tree being parsed. pPrev is the expression node most recently
142908** inserted into the tree. This function adds pNew, which is always a binary
142909** operator node, into the expression tree based on the relative precedence
142910** of pNew and the existing nodes of the tree. This may result in the head
142911** of the tree changing, in which case *ppHead is set to the new root node.
142912*/
142913static void insertBinaryOperator(
142914  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
142915  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
142916  Fts3Expr *pNew           /* New binary node to insert into expression tree */
142917){
142918  Fts3Expr *pSplit = pPrev;
142919  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
142920    pSplit = pSplit->pParent;
142921  }
142922
142923  if( pSplit->pParent ){
142924    assert( pSplit->pParent->pRight==pSplit );
142925    pSplit->pParent->pRight = pNew;
142926    pNew->pParent = pSplit->pParent;
142927  }else{
142928    *ppHead = pNew;
142929  }
142930  pNew->pLeft = pSplit;
142931  pSplit->pParent = pNew;
142932}
142933
142934/*
142935** Parse the fts3 query expression found in buffer z, length n. This function
142936** returns either when the end of the buffer is reached or an unmatched
142937** closing bracket - ')' - is encountered.
142938**
142939** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
142940** parsed form of the expression and *pnConsumed is set to the number of
142941** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
142942** (out of memory error) or SQLITE_ERROR (parse error) is returned.
142943*/
142944static int fts3ExprParse(
142945  ParseContext *pParse,                   /* fts3 query parse context */
142946  const char *z, int n,                   /* Text of MATCH query */
142947  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
142948  int *pnConsumed                         /* OUT: Number of bytes consumed */
142949){
142950  Fts3Expr *pRet = 0;
142951  Fts3Expr *pPrev = 0;
142952  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
142953  int nIn = n;
142954  const char *zIn = z;
142955  int rc = SQLITE_OK;
142956  int isRequirePhrase = 1;
142957
142958  while( rc==SQLITE_OK ){
142959    Fts3Expr *p = 0;
142960    int nByte = 0;
142961
142962    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
142963    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
142964    if( rc==SQLITE_OK ){
142965      if( p ){
142966        int isPhrase;
142967
142968        if( !sqlite3_fts3_enable_parentheses
142969            && p->eType==FTSQUERY_PHRASE && pParse->isNot
142970        ){
142971          /* Create an implicit NOT operator. */
142972          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
142973          if( !pNot ){
142974            sqlite3Fts3ExprFree(p);
142975            rc = SQLITE_NOMEM;
142976            goto exprparse_out;
142977          }
142978          pNot->eType = FTSQUERY_NOT;
142979          pNot->pRight = p;
142980          p->pParent = pNot;
142981          if( pNotBranch ){
142982            pNot->pLeft = pNotBranch;
142983            pNotBranch->pParent = pNot;
142984          }
142985          pNotBranch = pNot;
142986          p = pPrev;
142987        }else{
142988          int eType = p->eType;
142989          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
142990
142991          /* The isRequirePhrase variable is set to true if a phrase or
142992          ** an expression contained in parenthesis is required. If a
142993          ** binary operator (AND, OR, NOT or NEAR) is encounted when
142994          ** isRequirePhrase is set, this is a syntax error.
142995          */
142996          if( !isPhrase && isRequirePhrase ){
142997            sqlite3Fts3ExprFree(p);
142998            rc = SQLITE_ERROR;
142999            goto exprparse_out;
143000          }
143001
143002          if( isPhrase && !isRequirePhrase ){
143003            /* Insert an implicit AND operator. */
143004            Fts3Expr *pAnd;
143005            assert( pRet && pPrev );
143006            pAnd = fts3MallocZero(sizeof(Fts3Expr));
143007            if( !pAnd ){
143008              sqlite3Fts3ExprFree(p);
143009              rc = SQLITE_NOMEM;
143010              goto exprparse_out;
143011            }
143012            pAnd->eType = FTSQUERY_AND;
143013            insertBinaryOperator(&pRet, pPrev, pAnd);
143014            pPrev = pAnd;
143015          }
143016
143017          /* This test catches attempts to make either operand of a NEAR
143018           ** operator something other than a phrase. For example, either of
143019           ** the following:
143020           **
143021           **    (bracketed expression) NEAR phrase
143022           **    phrase NEAR (bracketed expression)
143023           **
143024           ** Return an error in either case.
143025           */
143026          if( pPrev && (
143027            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
143028         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
143029          )){
143030            sqlite3Fts3ExprFree(p);
143031            rc = SQLITE_ERROR;
143032            goto exprparse_out;
143033          }
143034
143035          if( isPhrase ){
143036            if( pRet ){
143037              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
143038              pPrev->pRight = p;
143039              p->pParent = pPrev;
143040            }else{
143041              pRet = p;
143042            }
143043          }else{
143044            insertBinaryOperator(&pRet, pPrev, p);
143045          }
143046          isRequirePhrase = !isPhrase;
143047        }
143048        pPrev = p;
143049      }
143050      assert( nByte>0 );
143051    }
143052    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
143053    nIn -= nByte;
143054    zIn += nByte;
143055  }
143056
143057  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
143058    rc = SQLITE_ERROR;
143059  }
143060
143061  if( rc==SQLITE_DONE ){
143062    rc = SQLITE_OK;
143063    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
143064      if( !pRet ){
143065        rc = SQLITE_ERROR;
143066      }else{
143067        Fts3Expr *pIter = pNotBranch;
143068        while( pIter->pLeft ){
143069          pIter = pIter->pLeft;
143070        }
143071        pIter->pLeft = pRet;
143072        pRet->pParent = pIter;
143073        pRet = pNotBranch;
143074      }
143075    }
143076  }
143077  *pnConsumed = n - nIn;
143078
143079exprparse_out:
143080  if( rc!=SQLITE_OK ){
143081    sqlite3Fts3ExprFree(pRet);
143082    sqlite3Fts3ExprFree(pNotBranch);
143083    pRet = 0;
143084  }
143085  *ppExpr = pRet;
143086  return rc;
143087}
143088
143089/*
143090** Return SQLITE_ERROR if the maximum depth of the expression tree passed
143091** as the only argument is more than nMaxDepth.
143092*/
143093static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
143094  int rc = SQLITE_OK;
143095  if( p ){
143096    if( nMaxDepth<0 ){
143097      rc = SQLITE_TOOBIG;
143098    }else{
143099      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
143100      if( rc==SQLITE_OK ){
143101        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
143102      }
143103    }
143104  }
143105  return rc;
143106}
143107
143108/*
143109** This function attempts to transform the expression tree at (*pp) to
143110** an equivalent but more balanced form. The tree is modified in place.
143111** If successful, SQLITE_OK is returned and (*pp) set to point to the
143112** new root expression node.
143113**
143114** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
143115**
143116** Otherwise, if an error occurs, an SQLite error code is returned and
143117** expression (*pp) freed.
143118*/
143119static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
143120  int rc = SQLITE_OK;             /* Return code */
143121  Fts3Expr *pRoot = *pp;          /* Initial root node */
143122  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
143123  int eType = pRoot->eType;       /* Type of node in this tree */
143124
143125  if( nMaxDepth==0 ){
143126    rc = SQLITE_ERROR;
143127  }
143128
143129  if( rc==SQLITE_OK ){
143130    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
143131      Fts3Expr **apLeaf;
143132      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
143133      if( 0==apLeaf ){
143134        rc = SQLITE_NOMEM;
143135      }else{
143136        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
143137      }
143138
143139      if( rc==SQLITE_OK ){
143140        int i;
143141        Fts3Expr *p;
143142
143143        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
143144        for(p=pRoot; p->eType==eType; p=p->pLeft){
143145          assert( p->pParent==0 || p->pParent->pLeft==p );
143146          assert( p->pLeft && p->pRight );
143147        }
143148
143149        /* This loop runs once for each leaf in the tree of eType nodes. */
143150        while( 1 ){
143151          int iLvl;
143152          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
143153
143154          assert( pParent==0 || pParent->pLeft==p );
143155          p->pParent = 0;
143156          if( pParent ){
143157            pParent->pLeft = 0;
143158          }else{
143159            pRoot = 0;
143160          }
143161          rc = fts3ExprBalance(&p, nMaxDepth-1);
143162          if( rc!=SQLITE_OK ) break;
143163
143164          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
143165            if( apLeaf[iLvl]==0 ){
143166              apLeaf[iLvl] = p;
143167              p = 0;
143168            }else{
143169              assert( pFree );
143170              pFree->pLeft = apLeaf[iLvl];
143171              pFree->pRight = p;
143172              pFree->pLeft->pParent = pFree;
143173              pFree->pRight->pParent = pFree;
143174
143175              p = pFree;
143176              pFree = pFree->pParent;
143177              p->pParent = 0;
143178              apLeaf[iLvl] = 0;
143179            }
143180          }
143181          if( p ){
143182            sqlite3Fts3ExprFree(p);
143183            rc = SQLITE_TOOBIG;
143184            break;
143185          }
143186
143187          /* If that was the last leaf node, break out of the loop */
143188          if( pParent==0 ) break;
143189
143190          /* Set $p to point to the next leaf in the tree of eType nodes */
143191          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
143192
143193          /* Remove pParent from the original tree. */
143194          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
143195          pParent->pRight->pParent = pParent->pParent;
143196          if( pParent->pParent ){
143197            pParent->pParent->pLeft = pParent->pRight;
143198          }else{
143199            assert( pParent==pRoot );
143200            pRoot = pParent->pRight;
143201          }
143202
143203          /* Link pParent into the free node list. It will be used as an
143204          ** internal node of the new tree.  */
143205          pParent->pParent = pFree;
143206          pFree = pParent;
143207        }
143208
143209        if( rc==SQLITE_OK ){
143210          p = 0;
143211          for(i=0; i<nMaxDepth; i++){
143212            if( apLeaf[i] ){
143213              if( p==0 ){
143214                p = apLeaf[i];
143215                p->pParent = 0;
143216              }else{
143217                assert( pFree!=0 );
143218                pFree->pRight = p;
143219                pFree->pLeft = apLeaf[i];
143220                pFree->pLeft->pParent = pFree;
143221                pFree->pRight->pParent = pFree;
143222
143223                p = pFree;
143224                pFree = pFree->pParent;
143225                p->pParent = 0;
143226              }
143227            }
143228          }
143229          pRoot = p;
143230        }else{
143231          /* An error occurred. Delete the contents of the apLeaf[] array
143232          ** and pFree list. Everything else is cleaned up by the call to
143233          ** sqlite3Fts3ExprFree(pRoot) below.  */
143234          Fts3Expr *pDel;
143235          for(i=0; i<nMaxDepth; i++){
143236            sqlite3Fts3ExprFree(apLeaf[i]);
143237          }
143238          while( (pDel=pFree)!=0 ){
143239            pFree = pDel->pParent;
143240            sqlite3_free(pDel);
143241          }
143242        }
143243
143244        assert( pFree==0 );
143245        sqlite3_free( apLeaf );
143246      }
143247    }else if( eType==FTSQUERY_NOT ){
143248      Fts3Expr *pLeft = pRoot->pLeft;
143249      Fts3Expr *pRight = pRoot->pRight;
143250
143251      pRoot->pLeft = 0;
143252      pRoot->pRight = 0;
143253      pLeft->pParent = 0;
143254      pRight->pParent = 0;
143255
143256      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
143257      if( rc==SQLITE_OK ){
143258        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
143259      }
143260
143261      if( rc!=SQLITE_OK ){
143262        sqlite3Fts3ExprFree(pRight);
143263        sqlite3Fts3ExprFree(pLeft);
143264      }else{
143265        assert( pLeft && pRight );
143266        pRoot->pLeft = pLeft;
143267        pLeft->pParent = pRoot;
143268        pRoot->pRight = pRight;
143269        pRight->pParent = pRoot;
143270      }
143271    }
143272  }
143273
143274  if( rc!=SQLITE_OK ){
143275    sqlite3Fts3ExprFree(pRoot);
143276    pRoot = 0;
143277  }
143278  *pp = pRoot;
143279  return rc;
143280}
143281
143282/*
143283** This function is similar to sqlite3Fts3ExprParse(), with the following
143284** differences:
143285**
143286**   1. It does not do expression rebalancing.
143287**   2. It does not check that the expression does not exceed the
143288**      maximum allowable depth.
143289**   3. Even if it fails, *ppExpr may still be set to point to an
143290**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
143291**      in this case.
143292*/
143293static int fts3ExprParseUnbalanced(
143294  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
143295  int iLangid,                        /* Language id for tokenizer */
143296  char **azCol,                       /* Array of column names for fts3 table */
143297  int bFts4,                          /* True to allow FTS4-only syntax */
143298  int nCol,                           /* Number of entries in azCol[] */
143299  int iDefaultCol,                    /* Default column to query */
143300  const char *z, int n,               /* Text of MATCH query */
143301  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
143302){
143303  int nParsed;
143304  int rc;
143305  ParseContext sParse;
143306
143307  memset(&sParse, 0, sizeof(ParseContext));
143308  sParse.pTokenizer = pTokenizer;
143309  sParse.iLangid = iLangid;
143310  sParse.azCol = (const char **)azCol;
143311  sParse.nCol = nCol;
143312  sParse.iDefaultCol = iDefaultCol;
143313  sParse.bFts4 = bFts4;
143314  if( z==0 ){
143315    *ppExpr = 0;
143316    return SQLITE_OK;
143317  }
143318  if( n<0 ){
143319    n = (int)strlen(z);
143320  }
143321  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
143322  assert( rc==SQLITE_OK || *ppExpr==0 );
143323
143324  /* Check for mismatched parenthesis */
143325  if( rc==SQLITE_OK && sParse.nNest ){
143326    rc = SQLITE_ERROR;
143327  }
143328
143329  return rc;
143330}
143331
143332/*
143333** Parameters z and n contain a pointer to and length of a buffer containing
143334** an fts3 query expression, respectively. This function attempts to parse the
143335** query expression and create a tree of Fts3Expr structures representing the
143336** parsed expression. If successful, *ppExpr is set to point to the head
143337** of the parsed expression tree and SQLITE_OK is returned. If an error
143338** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
143339** error) is returned and *ppExpr is set to 0.
143340**
143341** If parameter n is a negative number, then z is assumed to point to a
143342** nul-terminated string and the length is determined using strlen().
143343**
143344** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
143345** use to normalize query tokens while parsing the expression. The azCol[]
143346** array, which is assumed to contain nCol entries, should contain the names
143347** of each column in the target fts3 table, in order from left to right.
143348** Column names must be nul-terminated strings.
143349**
143350** The iDefaultCol parameter should be passed the index of the table column
143351** that appears on the left-hand-side of the MATCH operator (the default
143352** column to match against for tokens for which a column name is not explicitly
143353** specified as part of the query string), or -1 if tokens may by default
143354** match any table column.
143355*/
143356SQLITE_PRIVATE int sqlite3Fts3ExprParse(
143357  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
143358  int iLangid,                        /* Language id for tokenizer */
143359  char **azCol,                       /* Array of column names for fts3 table */
143360  int bFts4,                          /* True to allow FTS4-only syntax */
143361  int nCol,                           /* Number of entries in azCol[] */
143362  int iDefaultCol,                    /* Default column to query */
143363  const char *z, int n,               /* Text of MATCH query */
143364  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
143365  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
143366){
143367  int rc = fts3ExprParseUnbalanced(
143368      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
143369  );
143370
143371  /* Rebalance the expression. And check that its depth does not exceed
143372  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
143373  if( rc==SQLITE_OK && *ppExpr ){
143374    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
143375    if( rc==SQLITE_OK ){
143376      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
143377    }
143378  }
143379
143380  if( rc!=SQLITE_OK ){
143381    sqlite3Fts3ExprFree(*ppExpr);
143382    *ppExpr = 0;
143383    if( rc==SQLITE_TOOBIG ){
143384      sqlite3Fts3ErrMsg(pzErr,
143385          "FTS expression tree is too large (maximum depth %d)",
143386          SQLITE_FTS3_MAX_EXPR_DEPTH
143387      );
143388      rc = SQLITE_ERROR;
143389    }else if( rc==SQLITE_ERROR ){
143390      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
143391    }
143392  }
143393
143394  return rc;
143395}
143396
143397/*
143398** Free a single node of an expression tree.
143399*/
143400static void fts3FreeExprNode(Fts3Expr *p){
143401  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
143402  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
143403  sqlite3_free(p->aMI);
143404  sqlite3_free(p);
143405}
143406
143407/*
143408** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
143409**
143410** This function would be simpler if it recursively called itself. But
143411** that would mean passing a sufficiently large expression to ExprParse()
143412** could cause a stack overflow.
143413*/
143414SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
143415  Fts3Expr *p;
143416  assert( pDel==0 || pDel->pParent==0 );
143417  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
143418    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
143419  }
143420  while( p ){
143421    Fts3Expr *pParent = p->pParent;
143422    fts3FreeExprNode(p);
143423    if( pParent && p==pParent->pLeft && pParent->pRight ){
143424      p = pParent->pRight;
143425      while( p && (p->pLeft || p->pRight) ){
143426        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
143427        p = (p->pLeft ? p->pLeft : p->pRight);
143428      }
143429    }else{
143430      p = pParent;
143431    }
143432  }
143433}
143434
143435/****************************************************************************
143436*****************************************************************************
143437** Everything after this point is just test code.
143438*/
143439
143440#ifdef SQLITE_TEST
143441
143442/* #include <stdio.h> */
143443
143444/*
143445** Function to query the hash-table of tokenizers (see README.tokenizers).
143446*/
143447static int queryTestTokenizer(
143448  sqlite3 *db,
143449  const char *zName,
143450  const sqlite3_tokenizer_module **pp
143451){
143452  int rc;
143453  sqlite3_stmt *pStmt;
143454  const char zSql[] = "SELECT fts3_tokenizer(?)";
143455
143456  *pp = 0;
143457  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
143458  if( rc!=SQLITE_OK ){
143459    return rc;
143460  }
143461
143462  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
143463  if( SQLITE_ROW==sqlite3_step(pStmt) ){
143464    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
143465      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
143466    }
143467  }
143468
143469  return sqlite3_finalize(pStmt);
143470}
143471
143472/*
143473** Return a pointer to a buffer containing a text representation of the
143474** expression passed as the first argument. The buffer is obtained from
143475** sqlite3_malloc(). It is the responsibility of the caller to use
143476** sqlite3_free() to release the memory. If an OOM condition is encountered,
143477** NULL is returned.
143478**
143479** If the second argument is not NULL, then its contents are prepended to
143480** the returned expression text and then freed using sqlite3_free().
143481*/
143482static char *exprToString(Fts3Expr *pExpr, char *zBuf){
143483  if( pExpr==0 ){
143484    return sqlite3_mprintf("");
143485  }
143486  switch( pExpr->eType ){
143487    case FTSQUERY_PHRASE: {
143488      Fts3Phrase *pPhrase = pExpr->pPhrase;
143489      int i;
143490      zBuf = sqlite3_mprintf(
143491          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
143492      for(i=0; zBuf && i<pPhrase->nToken; i++){
143493        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
143494            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
143495            (pPhrase->aToken[i].isPrefix?"+":"")
143496        );
143497      }
143498      return zBuf;
143499    }
143500
143501    case FTSQUERY_NEAR:
143502      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
143503      break;
143504    case FTSQUERY_NOT:
143505      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
143506      break;
143507    case FTSQUERY_AND:
143508      zBuf = sqlite3_mprintf("%zAND ", zBuf);
143509      break;
143510    case FTSQUERY_OR:
143511      zBuf = sqlite3_mprintf("%zOR ", zBuf);
143512      break;
143513  }
143514
143515  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
143516  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
143517  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
143518
143519  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
143520  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
143521
143522  return zBuf;
143523}
143524
143525/*
143526** This is the implementation of a scalar SQL function used to test the
143527** expression parser. It should be called as follows:
143528**
143529**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
143530**
143531** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
143532** to parse the query expression (see README.tokenizers). The second argument
143533** is the query expression to parse. Each subsequent argument is the name
143534** of a column of the fts3 table that the query expression may refer to.
143535** For example:
143536**
143537**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
143538*/
143539static void fts3ExprTest(
143540  sqlite3_context *context,
143541  int argc,
143542  sqlite3_value **argv
143543){
143544  sqlite3_tokenizer_module const *pModule = 0;
143545  sqlite3_tokenizer *pTokenizer = 0;
143546  int rc;
143547  char **azCol = 0;
143548  const char *zExpr;
143549  int nExpr;
143550  int nCol;
143551  int ii;
143552  Fts3Expr *pExpr;
143553  char *zBuf = 0;
143554  sqlite3 *db = sqlite3_context_db_handle(context);
143555
143556  if( argc<3 ){
143557    sqlite3_result_error(context,
143558        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
143559    );
143560    return;
143561  }
143562
143563  rc = queryTestTokenizer(db,
143564                          (const char *)sqlite3_value_text(argv[0]), &pModule);
143565  if( rc==SQLITE_NOMEM ){
143566    sqlite3_result_error_nomem(context);
143567    goto exprtest_out;
143568  }else if( !pModule ){
143569    sqlite3_result_error(context, "No such tokenizer module", -1);
143570    goto exprtest_out;
143571  }
143572
143573  rc = pModule->xCreate(0, 0, &pTokenizer);
143574  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
143575  if( rc==SQLITE_NOMEM ){
143576    sqlite3_result_error_nomem(context);
143577    goto exprtest_out;
143578  }
143579  pTokenizer->pModule = pModule;
143580
143581  zExpr = (const char *)sqlite3_value_text(argv[1]);
143582  nExpr = sqlite3_value_bytes(argv[1]);
143583  nCol = argc-2;
143584  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
143585  if( !azCol ){
143586    sqlite3_result_error_nomem(context);
143587    goto exprtest_out;
143588  }
143589  for(ii=0; ii<nCol; ii++){
143590    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
143591  }
143592
143593  if( sqlite3_user_data(context) ){
143594    char *zDummy = 0;
143595    rc = sqlite3Fts3ExprParse(
143596        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
143597    );
143598    assert( rc==SQLITE_OK || pExpr==0 );
143599    sqlite3_free(zDummy);
143600  }else{
143601    rc = fts3ExprParseUnbalanced(
143602        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
143603    );
143604  }
143605
143606  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
143607    sqlite3Fts3ExprFree(pExpr);
143608    sqlite3_result_error(context, "Error parsing expression", -1);
143609  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
143610    sqlite3_result_error_nomem(context);
143611  }else{
143612    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
143613    sqlite3_free(zBuf);
143614  }
143615
143616  sqlite3Fts3ExprFree(pExpr);
143617
143618exprtest_out:
143619  if( pModule && pTokenizer ){
143620    rc = pModule->xDestroy(pTokenizer);
143621  }
143622  sqlite3_free(azCol);
143623}
143624
143625/*
143626** Register the query expression parser test function fts3_exprtest()
143627** with database connection db.
143628*/
143629SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
143630  int rc = sqlite3_create_function(
143631      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
143632  );
143633  if( rc==SQLITE_OK ){
143634    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
143635        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
143636    );
143637  }
143638  return rc;
143639}
143640
143641#endif
143642#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
143643
143644/************** End of fts3_expr.c *******************************************/
143645/************** Begin file fts3_hash.c ***************************************/
143646/*
143647** 2001 September 22
143648**
143649** The author disclaims copyright to this source code.  In place of
143650** a legal notice, here is a blessing:
143651**
143652**    May you do good and not evil.
143653**    May you find forgiveness for yourself and forgive others.
143654**    May you share freely, never taking more than you give.
143655**
143656*************************************************************************
143657** This is the implementation of generic hash-tables used in SQLite.
143658** We've modified it slightly to serve as a standalone hash table
143659** implementation for the full-text indexing module.
143660*/
143661
143662/*
143663** The code in this file is only compiled if:
143664**
143665**     * The FTS3 module is being built as an extension
143666**       (in which case SQLITE_CORE is not defined), or
143667**
143668**     * The FTS3 module is being built into the core of
143669**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
143670*/
143671/* #include "fts3Int.h" */
143672#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
143673
143674/* #include <assert.h> */
143675/* #include <stdlib.h> */
143676/* #include <string.h> */
143677
143678/* #include "fts3_hash.h" */
143679
143680/*
143681** Malloc and Free functions
143682*/
143683static void *fts3HashMalloc(int n){
143684  void *p = sqlite3_malloc(n);
143685  if( p ){
143686    memset(p, 0, n);
143687  }
143688  return p;
143689}
143690static void fts3HashFree(void *p){
143691  sqlite3_free(p);
143692}
143693
143694/* Turn bulk memory into a hash table object by initializing the
143695** fields of the Hash structure.
143696**
143697** "pNew" is a pointer to the hash table that is to be initialized.
143698** keyClass is one of the constants
143699** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
143700** determines what kind of key the hash table will use.  "copyKey" is
143701** true if the hash table should make its own private copy of keys and
143702** false if it should just use the supplied pointer.
143703*/
143704SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
143705  assert( pNew!=0 );
143706  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
143707  pNew->keyClass = keyClass;
143708  pNew->copyKey = copyKey;
143709  pNew->first = 0;
143710  pNew->count = 0;
143711  pNew->htsize = 0;
143712  pNew->ht = 0;
143713}
143714
143715/* Remove all entries from a hash table.  Reclaim all memory.
143716** Call this routine to delete a hash table or to reset a hash table
143717** to the empty state.
143718*/
143719SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
143720  Fts3HashElem *elem;         /* For looping over all elements of the table */
143721
143722  assert( pH!=0 );
143723  elem = pH->first;
143724  pH->first = 0;
143725  fts3HashFree(pH->ht);
143726  pH->ht = 0;
143727  pH->htsize = 0;
143728  while( elem ){
143729    Fts3HashElem *next_elem = elem->next;
143730    if( pH->copyKey && elem->pKey ){
143731      fts3HashFree(elem->pKey);
143732    }
143733    fts3HashFree(elem);
143734    elem = next_elem;
143735  }
143736  pH->count = 0;
143737}
143738
143739/*
143740** Hash and comparison functions when the mode is FTS3_HASH_STRING
143741*/
143742static int fts3StrHash(const void *pKey, int nKey){
143743  const char *z = (const char *)pKey;
143744  unsigned h = 0;
143745  if( nKey<=0 ) nKey = (int) strlen(z);
143746  while( nKey > 0  ){
143747    h = (h<<3) ^ h ^ *z++;
143748    nKey--;
143749  }
143750  return (int)(h & 0x7fffffff);
143751}
143752static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
143753  if( n1!=n2 ) return 1;
143754  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
143755}
143756
143757/*
143758** Hash and comparison functions when the mode is FTS3_HASH_BINARY
143759*/
143760static int fts3BinHash(const void *pKey, int nKey){
143761  int h = 0;
143762  const char *z = (const char *)pKey;
143763  while( nKey-- > 0 ){
143764    h = (h<<3) ^ h ^ *(z++);
143765  }
143766  return h & 0x7fffffff;
143767}
143768static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
143769  if( n1!=n2 ) return 1;
143770  return memcmp(pKey1,pKey2,n1);
143771}
143772
143773/*
143774** Return a pointer to the appropriate hash function given the key class.
143775**
143776** The C syntax in this function definition may be unfamilar to some
143777** programmers, so we provide the following additional explanation:
143778**
143779** The name of the function is "ftsHashFunction".  The function takes a
143780** single parameter "keyClass".  The return value of ftsHashFunction()
143781** is a pointer to another function.  Specifically, the return value
143782** of ftsHashFunction() is a pointer to a function that takes two parameters
143783** with types "const void*" and "int" and returns an "int".
143784*/
143785static int (*ftsHashFunction(int keyClass))(const void*,int){
143786  if( keyClass==FTS3_HASH_STRING ){
143787    return &fts3StrHash;
143788  }else{
143789    assert( keyClass==FTS3_HASH_BINARY );
143790    return &fts3BinHash;
143791  }
143792}
143793
143794/*
143795** Return a pointer to the appropriate hash function given the key class.
143796**
143797** For help in interpreted the obscure C code in the function definition,
143798** see the header comment on the previous function.
143799*/
143800static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
143801  if( keyClass==FTS3_HASH_STRING ){
143802    return &fts3StrCompare;
143803  }else{
143804    assert( keyClass==FTS3_HASH_BINARY );
143805    return &fts3BinCompare;
143806  }
143807}
143808
143809/* Link an element into the hash table
143810*/
143811static void fts3HashInsertElement(
143812  Fts3Hash *pH,            /* The complete hash table */
143813  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
143814  Fts3HashElem *pNew       /* The element to be inserted */
143815){
143816  Fts3HashElem *pHead;     /* First element already in pEntry */
143817  pHead = pEntry->chain;
143818  if( pHead ){
143819    pNew->next = pHead;
143820    pNew->prev = pHead->prev;
143821    if( pHead->prev ){ pHead->prev->next = pNew; }
143822    else             { pH->first = pNew; }
143823    pHead->prev = pNew;
143824  }else{
143825    pNew->next = pH->first;
143826    if( pH->first ){ pH->first->prev = pNew; }
143827    pNew->prev = 0;
143828    pH->first = pNew;
143829  }
143830  pEntry->count++;
143831  pEntry->chain = pNew;
143832}
143833
143834
143835/* Resize the hash table so that it cantains "new_size" buckets.
143836** "new_size" must be a power of 2.  The hash table might fail
143837** to resize if sqliteMalloc() fails.
143838**
143839** Return non-zero if a memory allocation error occurs.
143840*/
143841static int fts3Rehash(Fts3Hash *pH, int new_size){
143842  struct _fts3ht *new_ht;          /* The new hash table */
143843  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
143844  int (*xHash)(const void*,int);   /* The hash function */
143845
143846  assert( (new_size & (new_size-1))==0 );
143847  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
143848  if( new_ht==0 ) return 1;
143849  fts3HashFree(pH->ht);
143850  pH->ht = new_ht;
143851  pH->htsize = new_size;
143852  xHash = ftsHashFunction(pH->keyClass);
143853  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
143854    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
143855    next_elem = elem->next;
143856    fts3HashInsertElement(pH, &new_ht[h], elem);
143857  }
143858  return 0;
143859}
143860
143861/* This function (for internal use only) locates an element in an
143862** hash table that matches the given key.  The hash for this key has
143863** already been computed and is passed as the 4th parameter.
143864*/
143865static Fts3HashElem *fts3FindElementByHash(
143866  const Fts3Hash *pH, /* The pH to be searched */
143867  const void *pKey,   /* The key we are searching for */
143868  int nKey,
143869  int h               /* The hash for this key. */
143870){
143871  Fts3HashElem *elem;            /* Used to loop thru the element list */
143872  int count;                     /* Number of elements left to test */
143873  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
143874
143875  if( pH->ht ){
143876    struct _fts3ht *pEntry = &pH->ht[h];
143877    elem = pEntry->chain;
143878    count = pEntry->count;
143879    xCompare = ftsCompareFunction(pH->keyClass);
143880    while( count-- && elem ){
143881      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
143882        return elem;
143883      }
143884      elem = elem->next;
143885    }
143886  }
143887  return 0;
143888}
143889
143890/* Remove a single entry from the hash table given a pointer to that
143891** element and a hash on the element's key.
143892*/
143893static void fts3RemoveElementByHash(
143894  Fts3Hash *pH,         /* The pH containing "elem" */
143895  Fts3HashElem* elem,   /* The element to be removed from the pH */
143896  int h                 /* Hash value for the element */
143897){
143898  struct _fts3ht *pEntry;
143899  if( elem->prev ){
143900    elem->prev->next = elem->next;
143901  }else{
143902    pH->first = elem->next;
143903  }
143904  if( elem->next ){
143905    elem->next->prev = elem->prev;
143906  }
143907  pEntry = &pH->ht[h];
143908  if( pEntry->chain==elem ){
143909    pEntry->chain = elem->next;
143910  }
143911  pEntry->count--;
143912  if( pEntry->count<=0 ){
143913    pEntry->chain = 0;
143914  }
143915  if( pH->copyKey && elem->pKey ){
143916    fts3HashFree(elem->pKey);
143917  }
143918  fts3HashFree( elem );
143919  pH->count--;
143920  if( pH->count<=0 ){
143921    assert( pH->first==0 );
143922    assert( pH->count==0 );
143923    fts3HashClear(pH);
143924  }
143925}
143926
143927SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
143928  const Fts3Hash *pH,
143929  const void *pKey,
143930  int nKey
143931){
143932  int h;                          /* A hash on key */
143933  int (*xHash)(const void*,int);  /* The hash function */
143934
143935  if( pH==0 || pH->ht==0 ) return 0;
143936  xHash = ftsHashFunction(pH->keyClass);
143937  assert( xHash!=0 );
143938  h = (*xHash)(pKey,nKey);
143939  assert( (pH->htsize & (pH->htsize-1))==0 );
143940  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
143941}
143942
143943/*
143944** Attempt to locate an element of the hash table pH with a key
143945** that matches pKey,nKey.  Return the data for this element if it is
143946** found, or NULL if there is no match.
143947*/
143948SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
143949  Fts3HashElem *pElem;            /* The element that matches key (if any) */
143950
143951  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
143952  return pElem ? pElem->data : 0;
143953}
143954
143955/* Insert an element into the hash table pH.  The key is pKey,nKey
143956** and the data is "data".
143957**
143958** If no element exists with a matching key, then a new
143959** element is created.  A copy of the key is made if the copyKey
143960** flag is set.  NULL is returned.
143961**
143962** If another element already exists with the same key, then the
143963** new data replaces the old data and the old data is returned.
143964** The key is not copied in this instance.  If a malloc fails, then
143965** the new data is returned and the hash table is unchanged.
143966**
143967** If the "data" parameter to this function is NULL, then the
143968** element corresponding to "key" is removed from the hash table.
143969*/
143970SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
143971  Fts3Hash *pH,        /* The hash table to insert into */
143972  const void *pKey,    /* The key */
143973  int nKey,            /* Number of bytes in the key */
143974  void *data           /* The data */
143975){
143976  int hraw;                 /* Raw hash value of the key */
143977  int h;                    /* the hash of the key modulo hash table size */
143978  Fts3HashElem *elem;       /* Used to loop thru the element list */
143979  Fts3HashElem *new_elem;   /* New element added to the pH */
143980  int (*xHash)(const void*,int);  /* The hash function */
143981
143982  assert( pH!=0 );
143983  xHash = ftsHashFunction(pH->keyClass);
143984  assert( xHash!=0 );
143985  hraw = (*xHash)(pKey, nKey);
143986  assert( (pH->htsize & (pH->htsize-1))==0 );
143987  h = hraw & (pH->htsize-1);
143988  elem = fts3FindElementByHash(pH,pKey,nKey,h);
143989  if( elem ){
143990    void *old_data = elem->data;
143991    if( data==0 ){
143992      fts3RemoveElementByHash(pH,elem,h);
143993    }else{
143994      elem->data = data;
143995    }
143996    return old_data;
143997  }
143998  if( data==0 ) return 0;
143999  if( (pH->htsize==0 && fts3Rehash(pH,8))
144000   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
144001  ){
144002    pH->count = 0;
144003    return data;
144004  }
144005  assert( pH->htsize>0 );
144006  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
144007  if( new_elem==0 ) return data;
144008  if( pH->copyKey && pKey!=0 ){
144009    new_elem->pKey = fts3HashMalloc( nKey );
144010    if( new_elem->pKey==0 ){
144011      fts3HashFree(new_elem);
144012      return data;
144013    }
144014    memcpy((void*)new_elem->pKey, pKey, nKey);
144015  }else{
144016    new_elem->pKey = (void*)pKey;
144017  }
144018  new_elem->nKey = nKey;
144019  pH->count++;
144020  assert( pH->htsize>0 );
144021  assert( (pH->htsize & (pH->htsize-1))==0 );
144022  h = hraw & (pH->htsize-1);
144023  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
144024  new_elem->data = data;
144025  return 0;
144026}
144027
144028#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
144029
144030/************** End of fts3_hash.c *******************************************/
144031/************** Begin file fts3_porter.c *************************************/
144032/*
144033** 2006 September 30
144034**
144035** The author disclaims copyright to this source code.  In place of
144036** a legal notice, here is a blessing:
144037**
144038**    May you do good and not evil.
144039**    May you find forgiveness for yourself and forgive others.
144040**    May you share freely, never taking more than you give.
144041**
144042*************************************************************************
144043** Implementation of the full-text-search tokenizer that implements
144044** a Porter stemmer.
144045*/
144046
144047/*
144048** The code in this file is only compiled if:
144049**
144050**     * The FTS3 module is being built as an extension
144051**       (in which case SQLITE_CORE is not defined), or
144052**
144053**     * The FTS3 module is being built into the core of
144054**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
144055*/
144056/* #include "fts3Int.h" */
144057#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
144058
144059/* #include <assert.h> */
144060/* #include <stdlib.h> */
144061/* #include <stdio.h> */
144062/* #include <string.h> */
144063
144064/* #include "fts3_tokenizer.h" */
144065
144066/*
144067** Class derived from sqlite3_tokenizer
144068*/
144069typedef struct porter_tokenizer {
144070  sqlite3_tokenizer base;      /* Base class */
144071} porter_tokenizer;
144072
144073/*
144074** Class derived from sqlite3_tokenizer_cursor
144075*/
144076typedef struct porter_tokenizer_cursor {
144077  sqlite3_tokenizer_cursor base;
144078  const char *zInput;          /* input we are tokenizing */
144079  int nInput;                  /* size of the input */
144080  int iOffset;                 /* current position in zInput */
144081  int iToken;                  /* index of next token to be returned */
144082  char *zToken;                /* storage for current token */
144083  int nAllocated;              /* space allocated to zToken buffer */
144084} porter_tokenizer_cursor;
144085
144086
144087/*
144088** Create a new tokenizer instance.
144089*/
144090static int porterCreate(
144091  int argc, const char * const *argv,
144092  sqlite3_tokenizer **ppTokenizer
144093){
144094  porter_tokenizer *t;
144095
144096  UNUSED_PARAMETER(argc);
144097  UNUSED_PARAMETER(argv);
144098
144099  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
144100  if( t==NULL ) return SQLITE_NOMEM;
144101  memset(t, 0, sizeof(*t));
144102  *ppTokenizer = &t->base;
144103  return SQLITE_OK;
144104}
144105
144106/*
144107** Destroy a tokenizer
144108*/
144109static int porterDestroy(sqlite3_tokenizer *pTokenizer){
144110  sqlite3_free(pTokenizer);
144111  return SQLITE_OK;
144112}
144113
144114/*
144115** Prepare to begin tokenizing a particular string.  The input
144116** string to be tokenized is zInput[0..nInput-1].  A cursor
144117** used to incrementally tokenize this string is returned in
144118** *ppCursor.
144119*/
144120static int porterOpen(
144121  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
144122  const char *zInput, int nInput,        /* String to be tokenized */
144123  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
144124){
144125  porter_tokenizer_cursor *c;
144126
144127  UNUSED_PARAMETER(pTokenizer);
144128
144129  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
144130  if( c==NULL ) return SQLITE_NOMEM;
144131
144132  c->zInput = zInput;
144133  if( zInput==0 ){
144134    c->nInput = 0;
144135  }else if( nInput<0 ){
144136    c->nInput = (int)strlen(zInput);
144137  }else{
144138    c->nInput = nInput;
144139  }
144140  c->iOffset = 0;                 /* start tokenizing at the beginning */
144141  c->iToken = 0;
144142  c->zToken = NULL;               /* no space allocated, yet. */
144143  c->nAllocated = 0;
144144
144145  *ppCursor = &c->base;
144146  return SQLITE_OK;
144147}
144148
144149/*
144150** Close a tokenization cursor previously opened by a call to
144151** porterOpen() above.
144152*/
144153static int porterClose(sqlite3_tokenizer_cursor *pCursor){
144154  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
144155  sqlite3_free(c->zToken);
144156  sqlite3_free(c);
144157  return SQLITE_OK;
144158}
144159/*
144160** Vowel or consonant
144161*/
144162static const char cType[] = {
144163   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
144164   1, 1, 1, 2, 1
144165};
144166
144167/*
144168** isConsonant() and isVowel() determine if their first character in
144169** the string they point to is a consonant or a vowel, according
144170** to Porter ruls.
144171**
144172** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
144173** 'Y' is a consonant unless it follows another consonant,
144174** in which case it is a vowel.
144175**
144176** In these routine, the letters are in reverse order.  So the 'y' rule
144177** is that 'y' is a consonant unless it is followed by another
144178** consonent.
144179*/
144180static int isVowel(const char*);
144181static int isConsonant(const char *z){
144182  int j;
144183  char x = *z;
144184  if( x==0 ) return 0;
144185  assert( x>='a' && x<='z' );
144186  j = cType[x-'a'];
144187  if( j<2 ) return j;
144188  return z[1]==0 || isVowel(z + 1);
144189}
144190static int isVowel(const char *z){
144191  int j;
144192  char x = *z;
144193  if( x==0 ) return 0;
144194  assert( x>='a' && x<='z' );
144195  j = cType[x-'a'];
144196  if( j<2 ) return 1-j;
144197  return isConsonant(z + 1);
144198}
144199
144200/*
144201** Let any sequence of one or more vowels be represented by V and let
144202** C be sequence of one or more consonants.  Then every word can be
144203** represented as:
144204**
144205**           [C] (VC){m} [V]
144206**
144207** In prose:  A word is an optional consonant followed by zero or
144208** vowel-consonant pairs followed by an optional vowel.  "m" is the
144209** number of vowel consonant pairs.  This routine computes the value
144210** of m for the first i bytes of a word.
144211**
144212** Return true if the m-value for z is 1 or more.  In other words,
144213** return true if z contains at least one vowel that is followed
144214** by a consonant.
144215**
144216** In this routine z[] is in reverse order.  So we are really looking
144217** for an instance of a consonant followed by a vowel.
144218*/
144219static int m_gt_0(const char *z){
144220  while( isVowel(z) ){ z++; }
144221  if( *z==0 ) return 0;
144222  while( isConsonant(z) ){ z++; }
144223  return *z!=0;
144224}
144225
144226/* Like mgt0 above except we are looking for a value of m which is
144227** exactly 1
144228*/
144229static int m_eq_1(const char *z){
144230  while( isVowel(z) ){ z++; }
144231  if( *z==0 ) return 0;
144232  while( isConsonant(z) ){ z++; }
144233  if( *z==0 ) return 0;
144234  while( isVowel(z) ){ z++; }
144235  if( *z==0 ) return 1;
144236  while( isConsonant(z) ){ z++; }
144237  return *z==0;
144238}
144239
144240/* Like mgt0 above except we are looking for a value of m>1 instead
144241** or m>0
144242*/
144243static int m_gt_1(const char *z){
144244  while( isVowel(z) ){ z++; }
144245  if( *z==0 ) return 0;
144246  while( isConsonant(z) ){ z++; }
144247  if( *z==0 ) return 0;
144248  while( isVowel(z) ){ z++; }
144249  if( *z==0 ) return 0;
144250  while( isConsonant(z) ){ z++; }
144251  return *z!=0;
144252}
144253
144254/*
144255** Return TRUE if there is a vowel anywhere within z[0..n-1]
144256*/
144257static int hasVowel(const char *z){
144258  while( isConsonant(z) ){ z++; }
144259  return *z!=0;
144260}
144261
144262/*
144263** Return TRUE if the word ends in a double consonant.
144264**
144265** The text is reversed here. So we are really looking at
144266** the first two characters of z[].
144267*/
144268static int doubleConsonant(const char *z){
144269  return isConsonant(z) && z[0]==z[1];
144270}
144271
144272/*
144273** Return TRUE if the word ends with three letters which
144274** are consonant-vowel-consonent and where the final consonant
144275** is not 'w', 'x', or 'y'.
144276**
144277** The word is reversed here.  So we are really checking the
144278** first three letters and the first one cannot be in [wxy].
144279*/
144280static int star_oh(const char *z){
144281  return
144282    isConsonant(z) &&
144283    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
144284    isVowel(z+1) &&
144285    isConsonant(z+2);
144286}
144287
144288/*
144289** If the word ends with zFrom and xCond() is true for the stem
144290** of the word that preceeds the zFrom ending, then change the
144291** ending to zTo.
144292**
144293** The input word *pz and zFrom are both in reverse order.  zTo
144294** is in normal order.
144295**
144296** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
144297** match.  Not that TRUE is returned even if xCond() fails and
144298** no substitution occurs.
144299*/
144300static int stem(
144301  char **pz,             /* The word being stemmed (Reversed) */
144302  const char *zFrom,     /* If the ending matches this... (Reversed) */
144303  const char *zTo,       /* ... change the ending to this (not reversed) */
144304  int (*xCond)(const char*)   /* Condition that must be true */
144305){
144306  char *z = *pz;
144307  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
144308  if( *zFrom!=0 ) return 0;
144309  if( xCond && !xCond(z) ) return 1;
144310  while( *zTo ){
144311    *(--z) = *(zTo++);
144312  }
144313  *pz = z;
144314  return 1;
144315}
144316
144317/*
144318** This is the fallback stemmer used when the porter stemmer is
144319** inappropriate.  The input word is copied into the output with
144320** US-ASCII case folding.  If the input word is too long (more
144321** than 20 bytes if it contains no digits or more than 6 bytes if
144322** it contains digits) then word is truncated to 20 or 6 bytes
144323** by taking 10 or 3 bytes from the beginning and end.
144324*/
144325static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
144326  int i, mx, j;
144327  int hasDigit = 0;
144328  for(i=0; i<nIn; i++){
144329    char c = zIn[i];
144330    if( c>='A' && c<='Z' ){
144331      zOut[i] = c - 'A' + 'a';
144332    }else{
144333      if( c>='0' && c<='9' ) hasDigit = 1;
144334      zOut[i] = c;
144335    }
144336  }
144337  mx = hasDigit ? 3 : 10;
144338  if( nIn>mx*2 ){
144339    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
144340      zOut[j] = zOut[i];
144341    }
144342    i = j;
144343  }
144344  zOut[i] = 0;
144345  *pnOut = i;
144346}
144347
144348
144349/*
144350** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
144351** zOut is at least big enough to hold nIn bytes.  Write the actual
144352** size of the output word (exclusive of the '\0' terminator) into *pnOut.
144353**
144354** Any upper-case characters in the US-ASCII character set ([A-Z])
144355** are converted to lower case.  Upper-case UTF characters are
144356** unchanged.
144357**
144358** Words that are longer than about 20 bytes are stemmed by retaining
144359** a few bytes from the beginning and the end of the word.  If the
144360** word contains digits, 3 bytes are taken from the beginning and
144361** 3 bytes from the end.  For long words without digits, 10 bytes
144362** are taken from each end.  US-ASCII case folding still applies.
144363**
144364** If the input word contains not digits but does characters not
144365** in [a-zA-Z] then no stemming is attempted and this routine just
144366** copies the input into the input into the output with US-ASCII
144367** case folding.
144368**
144369** Stemming never increases the length of the word.  So there is
144370** no chance of overflowing the zOut buffer.
144371*/
144372static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
144373  int i, j;
144374  char zReverse[28];
144375  char *z, *z2;
144376  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
144377    /* The word is too big or too small for the porter stemmer.
144378    ** Fallback to the copy stemmer */
144379    copy_stemmer(zIn, nIn, zOut, pnOut);
144380    return;
144381  }
144382  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
144383    char c = zIn[i];
144384    if( c>='A' && c<='Z' ){
144385      zReverse[j] = c + 'a' - 'A';
144386    }else if( c>='a' && c<='z' ){
144387      zReverse[j] = c;
144388    }else{
144389      /* The use of a character not in [a-zA-Z] means that we fallback
144390      ** to the copy stemmer */
144391      copy_stemmer(zIn, nIn, zOut, pnOut);
144392      return;
144393    }
144394  }
144395  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
144396  z = &zReverse[j+1];
144397
144398
144399  /* Step 1a */
144400  if( z[0]=='s' ){
144401    if(
144402     !stem(&z, "sess", "ss", 0) &&
144403     !stem(&z, "sei", "i", 0)  &&
144404     !stem(&z, "ss", "ss", 0)
144405    ){
144406      z++;
144407    }
144408  }
144409
144410  /* Step 1b */
144411  z2 = z;
144412  if( stem(&z, "dee", "ee", m_gt_0) ){
144413    /* Do nothing.  The work was all in the test */
144414  }else if(
144415     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
144416      && z!=z2
144417  ){
144418     if( stem(&z, "ta", "ate", 0) ||
144419         stem(&z, "lb", "ble", 0) ||
144420         stem(&z, "zi", "ize", 0) ){
144421       /* Do nothing.  The work was all in the test */
144422     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
144423       z++;
144424     }else if( m_eq_1(z) && star_oh(z) ){
144425       *(--z) = 'e';
144426     }
144427  }
144428
144429  /* Step 1c */
144430  if( z[0]=='y' && hasVowel(z+1) ){
144431    z[0] = 'i';
144432  }
144433
144434  /* Step 2 */
144435  switch( z[1] ){
144436   case 'a':
144437     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
144438       stem(&z, "lanoit", "tion", m_gt_0);
144439     }
144440     break;
144441   case 'c':
144442     if( !stem(&z, "icne", "ence", m_gt_0) ){
144443       stem(&z, "icna", "ance", m_gt_0);
144444     }
144445     break;
144446   case 'e':
144447     stem(&z, "rezi", "ize", m_gt_0);
144448     break;
144449   case 'g':
144450     stem(&z, "igol", "log", m_gt_0);
144451     break;
144452   case 'l':
144453     if( !stem(&z, "ilb", "ble", m_gt_0)
144454      && !stem(&z, "illa", "al", m_gt_0)
144455      && !stem(&z, "iltne", "ent", m_gt_0)
144456      && !stem(&z, "ile", "e", m_gt_0)
144457     ){
144458       stem(&z, "ilsuo", "ous", m_gt_0);
144459     }
144460     break;
144461   case 'o':
144462     if( !stem(&z, "noitazi", "ize", m_gt_0)
144463      && !stem(&z, "noita", "ate", m_gt_0)
144464     ){
144465       stem(&z, "rota", "ate", m_gt_0);
144466     }
144467     break;
144468   case 's':
144469     if( !stem(&z, "msila", "al", m_gt_0)
144470      && !stem(&z, "ssenevi", "ive", m_gt_0)
144471      && !stem(&z, "ssenluf", "ful", m_gt_0)
144472     ){
144473       stem(&z, "ssensuo", "ous", m_gt_0);
144474     }
144475     break;
144476   case 't':
144477     if( !stem(&z, "itila", "al", m_gt_0)
144478      && !stem(&z, "itivi", "ive", m_gt_0)
144479     ){
144480       stem(&z, "itilib", "ble", m_gt_0);
144481     }
144482     break;
144483  }
144484
144485  /* Step 3 */
144486  switch( z[0] ){
144487   case 'e':
144488     if( !stem(&z, "etaci", "ic", m_gt_0)
144489      && !stem(&z, "evita", "", m_gt_0)
144490     ){
144491       stem(&z, "ezila", "al", m_gt_0);
144492     }
144493     break;
144494   case 'i':
144495     stem(&z, "itici", "ic", m_gt_0);
144496     break;
144497   case 'l':
144498     if( !stem(&z, "laci", "ic", m_gt_0) ){
144499       stem(&z, "luf", "", m_gt_0);
144500     }
144501     break;
144502   case 's':
144503     stem(&z, "ssen", "", m_gt_0);
144504     break;
144505  }
144506
144507  /* Step 4 */
144508  switch( z[1] ){
144509   case 'a':
144510     if( z[0]=='l' && m_gt_1(z+2) ){
144511       z += 2;
144512     }
144513     break;
144514   case 'c':
144515     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
144516       z += 4;
144517     }
144518     break;
144519   case 'e':
144520     if( z[0]=='r' && m_gt_1(z+2) ){
144521       z += 2;
144522     }
144523     break;
144524   case 'i':
144525     if( z[0]=='c' && m_gt_1(z+2) ){
144526       z += 2;
144527     }
144528     break;
144529   case 'l':
144530     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
144531       z += 4;
144532     }
144533     break;
144534   case 'n':
144535     if( z[0]=='t' ){
144536       if( z[2]=='a' ){
144537         if( m_gt_1(z+3) ){
144538           z += 3;
144539         }
144540       }else if( z[2]=='e' ){
144541         if( !stem(&z, "tneme", "", m_gt_1)
144542          && !stem(&z, "tnem", "", m_gt_1)
144543         ){
144544           stem(&z, "tne", "", m_gt_1);
144545         }
144546       }
144547     }
144548     break;
144549   case 'o':
144550     if( z[0]=='u' ){
144551       if( m_gt_1(z+2) ){
144552         z += 2;
144553       }
144554     }else if( z[3]=='s' || z[3]=='t' ){
144555       stem(&z, "noi", "", m_gt_1);
144556     }
144557     break;
144558   case 's':
144559     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
144560       z += 3;
144561     }
144562     break;
144563   case 't':
144564     if( !stem(&z, "eta", "", m_gt_1) ){
144565       stem(&z, "iti", "", m_gt_1);
144566     }
144567     break;
144568   case 'u':
144569     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
144570       z += 3;
144571     }
144572     break;
144573   case 'v':
144574   case 'z':
144575     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
144576       z += 3;
144577     }
144578     break;
144579  }
144580
144581  /* Step 5a */
144582  if( z[0]=='e' ){
144583    if( m_gt_1(z+1) ){
144584      z++;
144585    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
144586      z++;
144587    }
144588  }
144589
144590  /* Step 5b */
144591  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
144592    z++;
144593  }
144594
144595  /* z[] is now the stemmed word in reverse order.  Flip it back
144596  ** around into forward order and return.
144597  */
144598  *pnOut = i = (int)strlen(z);
144599  zOut[i] = 0;
144600  while( *z ){
144601    zOut[--i] = *(z++);
144602  }
144603}
144604
144605/*
144606** Characters that can be part of a token.  We assume any character
144607** whose value is greater than 0x80 (any UTF character) can be
144608** part of a token.  In other words, delimiters all must have
144609** values of 0x7f or lower.
144610*/
144611static const char porterIdChar[] = {
144612/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
144613    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
144614    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
144615    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
144616    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
144617    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
144618};
144619#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
144620
144621/*
144622** Extract the next token from a tokenization cursor.  The cursor must
144623** have been opened by a prior call to porterOpen().
144624*/
144625static int porterNext(
144626  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
144627  const char **pzToken,               /* OUT: *pzToken is the token text */
144628  int *pnBytes,                       /* OUT: Number of bytes in token */
144629  int *piStartOffset,                 /* OUT: Starting offset of token */
144630  int *piEndOffset,                   /* OUT: Ending offset of token */
144631  int *piPosition                     /* OUT: Position integer of token */
144632){
144633  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
144634  const char *z = c->zInput;
144635
144636  while( c->iOffset<c->nInput ){
144637    int iStartOffset, ch;
144638
144639    /* Scan past delimiter characters */
144640    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
144641      c->iOffset++;
144642    }
144643
144644    /* Count non-delimiter characters. */
144645    iStartOffset = c->iOffset;
144646    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
144647      c->iOffset++;
144648    }
144649
144650    if( c->iOffset>iStartOffset ){
144651      int n = c->iOffset-iStartOffset;
144652      if( n>c->nAllocated ){
144653        char *pNew;
144654        c->nAllocated = n+20;
144655        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
144656        if( !pNew ) return SQLITE_NOMEM;
144657        c->zToken = pNew;
144658      }
144659      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
144660      *pzToken = c->zToken;
144661      *piStartOffset = iStartOffset;
144662      *piEndOffset = c->iOffset;
144663      *piPosition = c->iToken++;
144664      return SQLITE_OK;
144665    }
144666  }
144667  return SQLITE_DONE;
144668}
144669
144670/*
144671** The set of routines that implement the porter-stemmer tokenizer
144672*/
144673static const sqlite3_tokenizer_module porterTokenizerModule = {
144674  0,
144675  porterCreate,
144676  porterDestroy,
144677  porterOpen,
144678  porterClose,
144679  porterNext,
144680  0
144681};
144682
144683/*
144684** Allocate a new porter tokenizer.  Return a pointer to the new
144685** tokenizer in *ppModule
144686*/
144687SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
144688  sqlite3_tokenizer_module const**ppModule
144689){
144690  *ppModule = &porterTokenizerModule;
144691}
144692
144693#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
144694
144695/************** End of fts3_porter.c *****************************************/
144696/************** Begin file fts3_tokenizer.c **********************************/
144697/*
144698** 2007 June 22
144699**
144700** The author disclaims copyright to this source code.  In place of
144701** a legal notice, here is a blessing:
144702**
144703**    May you do good and not evil.
144704**    May you find forgiveness for yourself and forgive others.
144705**    May you share freely, never taking more than you give.
144706**
144707******************************************************************************
144708**
144709** This is part of an SQLite module implementing full-text search.
144710** This particular file implements the generic tokenizer interface.
144711*/
144712
144713/*
144714** The code in this file is only compiled if:
144715**
144716**     * The FTS3 module is being built as an extension
144717**       (in which case SQLITE_CORE is not defined), or
144718**
144719**     * The FTS3 module is being built into the core of
144720**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
144721*/
144722/* #include "fts3Int.h" */
144723#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
144724
144725/* #include <assert.h> */
144726/* #include <string.h> */
144727
144728/*
144729** Implementation of the SQL scalar function for accessing the underlying
144730** hash table. This function may be called as follows:
144731**
144732**   SELECT <function-name>(<key-name>);
144733**   SELECT <function-name>(<key-name>, <pointer>);
144734**
144735** where <function-name> is the name passed as the second argument
144736** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
144737**
144738** If the <pointer> argument is specified, it must be a blob value
144739** containing a pointer to be stored as the hash data corresponding
144740** to the string <key-name>. If <pointer> is not specified, then
144741** the string <key-name> must already exist in the has table. Otherwise,
144742** an error is returned.
144743**
144744** Whether or not the <pointer> argument is specified, the value returned
144745** is a blob containing the pointer stored as the hash data corresponding
144746** to string <key-name> (after the hash-table is updated, if applicable).
144747*/
144748static void scalarFunc(
144749  sqlite3_context *context,
144750  int argc,
144751  sqlite3_value **argv
144752){
144753  Fts3Hash *pHash;
144754  void *pPtr = 0;
144755  const unsigned char *zName;
144756  int nName;
144757
144758  assert( argc==1 || argc==2 );
144759
144760  pHash = (Fts3Hash *)sqlite3_user_data(context);
144761
144762  zName = sqlite3_value_text(argv[0]);
144763  nName = sqlite3_value_bytes(argv[0])+1;
144764
144765  if( argc==2 ){
144766    void *pOld;
144767    int n = sqlite3_value_bytes(argv[1]);
144768    if( zName==0 || n!=sizeof(pPtr) ){
144769      sqlite3_result_error(context, "argument type mismatch", -1);
144770      return;
144771    }
144772    pPtr = *(void **)sqlite3_value_blob(argv[1]);
144773    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
144774    if( pOld==pPtr ){
144775      sqlite3_result_error(context, "out of memory", -1);
144776      return;
144777    }
144778  }else{
144779    if( zName ){
144780      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
144781    }
144782    if( !pPtr ){
144783      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
144784      sqlite3_result_error(context, zErr, -1);
144785      sqlite3_free(zErr);
144786      return;
144787    }
144788  }
144789
144790  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
144791}
144792
144793SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
144794  static const char isFtsIdChar[] = {
144795      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
144796      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
144797      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
144798      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
144799      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
144800      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
144801      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
144802      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
144803  };
144804  return (c&0x80 || isFtsIdChar[(int)(c)]);
144805}
144806
144807SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
144808  const char *z1;
144809  const char *z2 = 0;
144810
144811  /* Find the start of the next token. */
144812  z1 = zStr;
144813  while( z2==0 ){
144814    char c = *z1;
144815    switch( c ){
144816      case '\0': return 0;        /* No more tokens here */
144817      case '\'':
144818      case '"':
144819      case '`': {
144820        z2 = z1;
144821        while( *++z2 && (*z2!=c || *++z2==c) );
144822        break;
144823      }
144824      case '[':
144825        z2 = &z1[1];
144826        while( *z2 && z2[0]!=']' ) z2++;
144827        if( *z2 ) z2++;
144828        break;
144829
144830      default:
144831        if( sqlite3Fts3IsIdChar(*z1) ){
144832          z2 = &z1[1];
144833          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
144834        }else{
144835          z1++;
144836        }
144837    }
144838  }
144839
144840  *pn = (int)(z2-z1);
144841  return z1;
144842}
144843
144844SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
144845  Fts3Hash *pHash,                /* Tokenizer hash table */
144846  const char *zArg,               /* Tokenizer name */
144847  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
144848  char **pzErr                    /* OUT: Set to malloced error message */
144849){
144850  int rc;
144851  char *z = (char *)zArg;
144852  int n = 0;
144853  char *zCopy;
144854  char *zEnd;                     /* Pointer to nul-term of zCopy */
144855  sqlite3_tokenizer_module *m;
144856
144857  zCopy = sqlite3_mprintf("%s", zArg);
144858  if( !zCopy ) return SQLITE_NOMEM;
144859  zEnd = &zCopy[strlen(zCopy)];
144860
144861  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
144862  if( z==0 ){
144863    assert( n==0 );
144864    z = zCopy;
144865  }
144866  z[n] = '\0';
144867  sqlite3Fts3Dequote(z);
144868
144869  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
144870  if( !m ){
144871    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
144872    rc = SQLITE_ERROR;
144873  }else{
144874    char const **aArg = 0;
144875    int iArg = 0;
144876    z = &z[n+1];
144877    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
144878      int nNew = sizeof(char *)*(iArg+1);
144879      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
144880      if( !aNew ){
144881        sqlite3_free(zCopy);
144882        sqlite3_free((void *)aArg);
144883        return SQLITE_NOMEM;
144884      }
144885      aArg = aNew;
144886      aArg[iArg++] = z;
144887      z[n] = '\0';
144888      sqlite3Fts3Dequote(z);
144889      z = &z[n+1];
144890    }
144891    rc = m->xCreate(iArg, aArg, ppTok);
144892    assert( rc!=SQLITE_OK || *ppTok );
144893    if( rc!=SQLITE_OK ){
144894      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
144895    }else{
144896      (*ppTok)->pModule = m;
144897    }
144898    sqlite3_free((void *)aArg);
144899  }
144900
144901  sqlite3_free(zCopy);
144902  return rc;
144903}
144904
144905
144906#ifdef SQLITE_TEST
144907
144908#include <tcl.h>
144909/* #include <string.h> */
144910
144911/*
144912** Implementation of a special SQL scalar function for testing tokenizers
144913** designed to be used in concert with the Tcl testing framework. This
144914** function must be called with two or more arguments:
144915**
144916**   SELECT <function-name>(<key-name>, ..., <input-string>);
144917**
144918** where <function-name> is the name passed as the second argument
144919** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
144920** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
144921**
144922** The return value is a string that may be interpreted as a Tcl
144923** list. For each token in the <input-string>, three elements are
144924** added to the returned list. The first is the token position, the
144925** second is the token text (folded, stemmed, etc.) and the third is the
144926** substring of <input-string> associated with the token. For example,
144927** using the built-in "simple" tokenizer:
144928**
144929**   SELECT fts_tokenizer_test('simple', 'I don't see how');
144930**
144931** will return the string:
144932**
144933**   "{0 i I 1 dont don't 2 see see 3 how how}"
144934**
144935*/
144936static void testFunc(
144937  sqlite3_context *context,
144938  int argc,
144939  sqlite3_value **argv
144940){
144941  Fts3Hash *pHash;
144942  sqlite3_tokenizer_module *p;
144943  sqlite3_tokenizer *pTokenizer = 0;
144944  sqlite3_tokenizer_cursor *pCsr = 0;
144945
144946  const char *zErr = 0;
144947
144948  const char *zName;
144949  int nName;
144950  const char *zInput;
144951  int nInput;
144952
144953  const char *azArg[64];
144954
144955  const char *zToken;
144956  int nToken = 0;
144957  int iStart = 0;
144958  int iEnd = 0;
144959  int iPos = 0;
144960  int i;
144961
144962  Tcl_Obj *pRet;
144963
144964  if( argc<2 ){
144965    sqlite3_result_error(context, "insufficient arguments", -1);
144966    return;
144967  }
144968
144969  nName = sqlite3_value_bytes(argv[0]);
144970  zName = (const char *)sqlite3_value_text(argv[0]);
144971  nInput = sqlite3_value_bytes(argv[argc-1]);
144972  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
144973
144974  pHash = (Fts3Hash *)sqlite3_user_data(context);
144975  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
144976
144977  if( !p ){
144978    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
144979    sqlite3_result_error(context, zErr2, -1);
144980    sqlite3_free(zErr2);
144981    return;
144982  }
144983
144984  pRet = Tcl_NewObj();
144985  Tcl_IncrRefCount(pRet);
144986
144987  for(i=1; i<argc-1; i++){
144988    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
144989  }
144990
144991  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
144992    zErr = "error in xCreate()";
144993    goto finish;
144994  }
144995  pTokenizer->pModule = p;
144996  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
144997    zErr = "error in xOpen()";
144998    goto finish;
144999  }
145000
145001  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
145002    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
145003    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
145004    zToken = &zInput[iStart];
145005    nToken = iEnd-iStart;
145006    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
145007  }
145008
145009  if( SQLITE_OK!=p->xClose(pCsr) ){
145010    zErr = "error in xClose()";
145011    goto finish;
145012  }
145013  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
145014    zErr = "error in xDestroy()";
145015    goto finish;
145016  }
145017
145018finish:
145019  if( zErr ){
145020    sqlite3_result_error(context, zErr, -1);
145021  }else{
145022    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
145023  }
145024  Tcl_DecrRefCount(pRet);
145025}
145026
145027static
145028int registerTokenizer(
145029  sqlite3 *db,
145030  char *zName,
145031  const sqlite3_tokenizer_module *p
145032){
145033  int rc;
145034  sqlite3_stmt *pStmt;
145035  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
145036
145037  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
145038  if( rc!=SQLITE_OK ){
145039    return rc;
145040  }
145041
145042  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
145043  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
145044  sqlite3_step(pStmt);
145045
145046  return sqlite3_finalize(pStmt);
145047}
145048
145049static
145050int queryTokenizer(
145051  sqlite3 *db,
145052  char *zName,
145053  const sqlite3_tokenizer_module **pp
145054){
145055  int rc;
145056  sqlite3_stmt *pStmt;
145057  const char zSql[] = "SELECT fts3_tokenizer(?)";
145058
145059  *pp = 0;
145060  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
145061  if( rc!=SQLITE_OK ){
145062    return rc;
145063  }
145064
145065  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
145066  if( SQLITE_ROW==sqlite3_step(pStmt) ){
145067    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
145068      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
145069    }
145070  }
145071
145072  return sqlite3_finalize(pStmt);
145073}
145074
145075SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145076
145077/*
145078** Implementation of the scalar function fts3_tokenizer_internal_test().
145079** This function is used for testing only, it is not included in the
145080** build unless SQLITE_TEST is defined.
145081**
145082** The purpose of this is to test that the fts3_tokenizer() function
145083** can be used as designed by the C-code in the queryTokenizer and
145084** registerTokenizer() functions above. These two functions are repeated
145085** in the README.tokenizer file as an example, so it is important to
145086** test them.
145087**
145088** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
145089** function with no arguments. An assert() will fail if a problem is
145090** detected. i.e.:
145091**
145092**     SELECT fts3_tokenizer_internal_test();
145093**
145094*/
145095static void intTestFunc(
145096  sqlite3_context *context,
145097  int argc,
145098  sqlite3_value **argv
145099){
145100  int rc;
145101  const sqlite3_tokenizer_module *p1;
145102  const sqlite3_tokenizer_module *p2;
145103  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
145104
145105  UNUSED_PARAMETER(argc);
145106  UNUSED_PARAMETER(argv);
145107
145108  /* Test the query function */
145109  sqlite3Fts3SimpleTokenizerModule(&p1);
145110  rc = queryTokenizer(db, "simple", &p2);
145111  assert( rc==SQLITE_OK );
145112  assert( p1==p2 );
145113  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
145114  assert( rc==SQLITE_ERROR );
145115  assert( p2==0 );
145116  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
145117
145118  /* Test the storage function */
145119  rc = registerTokenizer(db, "nosuchtokenizer", p1);
145120  assert( rc==SQLITE_OK );
145121  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
145122  assert( rc==SQLITE_OK );
145123  assert( p2==p1 );
145124
145125  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
145126}
145127
145128#endif
145129
145130/*
145131** Set up SQL objects in database db used to access the contents of
145132** the hash table pointed to by argument pHash. The hash table must
145133** been initialized to use string keys, and to take a private copy
145134** of the key when a value is inserted. i.e. by a call similar to:
145135**
145136**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
145137**
145138** This function adds a scalar function (see header comment above
145139** scalarFunc() in this file for details) and, if ENABLE_TABLE is
145140** defined at compilation time, a temporary virtual table (see header
145141** comment above struct HashTableVtab) to the database schema. Both
145142** provide read/write access to the contents of *pHash.
145143**
145144** The third argument to this function, zName, is used as the name
145145** of both the scalar and, if created, the virtual table.
145146*/
145147SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
145148  sqlite3 *db,
145149  Fts3Hash *pHash,
145150  const char *zName
145151){
145152  int rc = SQLITE_OK;
145153  void *p = (void *)pHash;
145154  const int any = SQLITE_ANY;
145155
145156#ifdef SQLITE_TEST
145157  char *zTest = 0;
145158  char *zTest2 = 0;
145159  void *pdb = (void *)db;
145160  zTest = sqlite3_mprintf("%s_test", zName);
145161  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
145162  if( !zTest || !zTest2 ){
145163    rc = SQLITE_NOMEM;
145164  }
145165#endif
145166
145167  if( SQLITE_OK==rc ){
145168    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
145169  }
145170  if( SQLITE_OK==rc ){
145171    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
145172  }
145173#ifdef SQLITE_TEST
145174  if( SQLITE_OK==rc ){
145175    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
145176  }
145177  if( SQLITE_OK==rc ){
145178    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
145179  }
145180#endif
145181
145182#ifdef SQLITE_TEST
145183  sqlite3_free(zTest);
145184  sqlite3_free(zTest2);
145185#endif
145186
145187  return rc;
145188}
145189
145190#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145191
145192/************** End of fts3_tokenizer.c **************************************/
145193/************** Begin file fts3_tokenizer1.c *********************************/
145194/*
145195** 2006 Oct 10
145196**
145197** The author disclaims copyright to this source code.  In place of
145198** a legal notice, here is a blessing:
145199**
145200**    May you do good and not evil.
145201**    May you find forgiveness for yourself and forgive others.
145202**    May you share freely, never taking more than you give.
145203**
145204******************************************************************************
145205**
145206** Implementation of the "simple" full-text-search tokenizer.
145207*/
145208
145209/*
145210** The code in this file is only compiled if:
145211**
145212**     * The FTS3 module is being built as an extension
145213**       (in which case SQLITE_CORE is not defined), or
145214**
145215**     * The FTS3 module is being built into the core of
145216**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
145217*/
145218/* #include "fts3Int.h" */
145219#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145220
145221/* #include <assert.h> */
145222/* #include <stdlib.h> */
145223/* #include <stdio.h> */
145224/* #include <string.h> */
145225
145226/* #include "fts3_tokenizer.h" */
145227
145228typedef struct simple_tokenizer {
145229  sqlite3_tokenizer base;
145230  char delim[128];             /* flag ASCII delimiters */
145231} simple_tokenizer;
145232
145233typedef struct simple_tokenizer_cursor {
145234  sqlite3_tokenizer_cursor base;
145235  const char *pInput;          /* input we are tokenizing */
145236  int nBytes;                  /* size of the input */
145237  int iOffset;                 /* current position in pInput */
145238  int iToken;                  /* index of next token to be returned */
145239  char *pToken;                /* storage for current token */
145240  int nTokenAllocated;         /* space allocated to zToken buffer */
145241} simple_tokenizer_cursor;
145242
145243
145244static int simpleDelim(simple_tokenizer *t, unsigned char c){
145245  return c<0x80 && t->delim[c];
145246}
145247static int fts3_isalnum(int x){
145248  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
145249}
145250
145251/*
145252** Create a new tokenizer instance.
145253*/
145254static int simpleCreate(
145255  int argc, const char * const *argv,
145256  sqlite3_tokenizer **ppTokenizer
145257){
145258  simple_tokenizer *t;
145259
145260  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
145261  if( t==NULL ) return SQLITE_NOMEM;
145262  memset(t, 0, sizeof(*t));
145263
145264  /* TODO(shess) Delimiters need to remain the same from run to run,
145265  ** else we need to reindex.  One solution would be a meta-table to
145266  ** track such information in the database, then we'd only want this
145267  ** information on the initial create.
145268  */
145269  if( argc>1 ){
145270    int i, n = (int)strlen(argv[1]);
145271    for(i=0; i<n; i++){
145272      unsigned char ch = argv[1][i];
145273      /* We explicitly don't support UTF-8 delimiters for now. */
145274      if( ch>=0x80 ){
145275        sqlite3_free(t);
145276        return SQLITE_ERROR;
145277      }
145278      t->delim[ch] = 1;
145279    }
145280  } else {
145281    /* Mark non-alphanumeric ASCII characters as delimiters */
145282    int i;
145283    for(i=1; i<0x80; i++){
145284      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
145285    }
145286  }
145287
145288  *ppTokenizer = &t->base;
145289  return SQLITE_OK;
145290}
145291
145292/*
145293** Destroy a tokenizer
145294*/
145295static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
145296  sqlite3_free(pTokenizer);
145297  return SQLITE_OK;
145298}
145299
145300/*
145301** Prepare to begin tokenizing a particular string.  The input
145302** string to be tokenized is pInput[0..nBytes-1].  A cursor
145303** used to incrementally tokenize this string is returned in
145304** *ppCursor.
145305*/
145306static int simpleOpen(
145307  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
145308  const char *pInput, int nBytes,        /* String to be tokenized */
145309  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
145310){
145311  simple_tokenizer_cursor *c;
145312
145313  UNUSED_PARAMETER(pTokenizer);
145314
145315  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
145316  if( c==NULL ) return SQLITE_NOMEM;
145317
145318  c->pInput = pInput;
145319  if( pInput==0 ){
145320    c->nBytes = 0;
145321  }else if( nBytes<0 ){
145322    c->nBytes = (int)strlen(pInput);
145323  }else{
145324    c->nBytes = nBytes;
145325  }
145326  c->iOffset = 0;                 /* start tokenizing at the beginning */
145327  c->iToken = 0;
145328  c->pToken = NULL;               /* no space allocated, yet. */
145329  c->nTokenAllocated = 0;
145330
145331  *ppCursor = &c->base;
145332  return SQLITE_OK;
145333}
145334
145335/*
145336** Close a tokenization cursor previously opened by a call to
145337** simpleOpen() above.
145338*/
145339static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
145340  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
145341  sqlite3_free(c->pToken);
145342  sqlite3_free(c);
145343  return SQLITE_OK;
145344}
145345
145346/*
145347** Extract the next token from a tokenization cursor.  The cursor must
145348** have been opened by a prior call to simpleOpen().
145349*/
145350static int simpleNext(
145351  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
145352  const char **ppToken,               /* OUT: *ppToken is the token text */
145353  int *pnBytes,                       /* OUT: Number of bytes in token */
145354  int *piStartOffset,                 /* OUT: Starting offset of token */
145355  int *piEndOffset,                   /* OUT: Ending offset of token */
145356  int *piPosition                     /* OUT: Position integer of token */
145357){
145358  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
145359  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
145360  unsigned char *p = (unsigned char *)c->pInput;
145361
145362  while( c->iOffset<c->nBytes ){
145363    int iStartOffset;
145364
145365    /* Scan past delimiter characters */
145366    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
145367      c->iOffset++;
145368    }
145369
145370    /* Count non-delimiter characters. */
145371    iStartOffset = c->iOffset;
145372    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
145373      c->iOffset++;
145374    }
145375
145376    if( c->iOffset>iStartOffset ){
145377      int i, n = c->iOffset-iStartOffset;
145378      if( n>c->nTokenAllocated ){
145379        char *pNew;
145380        c->nTokenAllocated = n+20;
145381        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
145382        if( !pNew ) return SQLITE_NOMEM;
145383        c->pToken = pNew;
145384      }
145385      for(i=0; i<n; i++){
145386        /* TODO(shess) This needs expansion to handle UTF-8
145387        ** case-insensitivity.
145388        */
145389        unsigned char ch = p[iStartOffset+i];
145390        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
145391      }
145392      *ppToken = c->pToken;
145393      *pnBytes = n;
145394      *piStartOffset = iStartOffset;
145395      *piEndOffset = c->iOffset;
145396      *piPosition = c->iToken++;
145397
145398      return SQLITE_OK;
145399    }
145400  }
145401  return SQLITE_DONE;
145402}
145403
145404/*
145405** The set of routines that implement the simple tokenizer
145406*/
145407static const sqlite3_tokenizer_module simpleTokenizerModule = {
145408  0,
145409  simpleCreate,
145410  simpleDestroy,
145411  simpleOpen,
145412  simpleClose,
145413  simpleNext,
145414  0,
145415};
145416
145417/*
145418** Allocate a new simple tokenizer.  Return a pointer to the new
145419** tokenizer in *ppModule
145420*/
145421SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
145422  sqlite3_tokenizer_module const**ppModule
145423){
145424  *ppModule = &simpleTokenizerModule;
145425}
145426
145427#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145428
145429/************** End of fts3_tokenizer1.c *************************************/
145430/************** Begin file fts3_tokenize_vtab.c ******************************/
145431/*
145432** 2013 Apr 22
145433**
145434** The author disclaims copyright to this source code.  In place of
145435** a legal notice, here is a blessing:
145436**
145437**    May you do good and not evil.
145438**    May you find forgiveness for yourself and forgive others.
145439**    May you share freely, never taking more than you give.
145440**
145441******************************************************************************
145442**
145443** This file contains code for the "fts3tokenize" virtual table module.
145444** An fts3tokenize virtual table is created as follows:
145445**
145446**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
145447**       <tokenizer-name>, <arg-1>, ...
145448**   );
145449**
145450** The table created has the following schema:
145451**
145452**   CREATE TABLE <tbl>(input, token, start, end, position)
145453**
145454** When queried, the query must include a WHERE clause of type:
145455**
145456**   input = <string>
145457**
145458** The virtual table module tokenizes this <string>, using the FTS3
145459** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
145460** statement and returns one row for each token in the result. With
145461** fields set as follows:
145462**
145463**   input:   Always set to a copy of <string>
145464**   token:   A token from the input.
145465**   start:   Byte offset of the token within the input <string>.
145466**   end:     Byte offset of the byte immediately following the end of the
145467**            token within the input string.
145468**   pos:     Token offset of token within input.
145469**
145470*/
145471/* #include "fts3Int.h" */
145472#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145473
145474/* #include <string.h> */
145475/* #include <assert.h> */
145476
145477typedef struct Fts3tokTable Fts3tokTable;
145478typedef struct Fts3tokCursor Fts3tokCursor;
145479
145480/*
145481** Virtual table structure.
145482*/
145483struct Fts3tokTable {
145484  sqlite3_vtab base;              /* Base class used by SQLite core */
145485  const sqlite3_tokenizer_module *pMod;
145486  sqlite3_tokenizer *pTok;
145487};
145488
145489/*
145490** Virtual table cursor structure.
145491*/
145492struct Fts3tokCursor {
145493  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
145494  char *zInput;                   /* Input string */
145495  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
145496  int iRowid;                     /* Current 'rowid' value */
145497  const char *zToken;             /* Current 'token' value */
145498  int nToken;                     /* Size of zToken in bytes */
145499  int iStart;                     /* Current 'start' value */
145500  int iEnd;                       /* Current 'end' value */
145501  int iPos;                       /* Current 'pos' value */
145502};
145503
145504/*
145505** Query FTS for the tokenizer implementation named zName.
145506*/
145507static int fts3tokQueryTokenizer(
145508  Fts3Hash *pHash,
145509  const char *zName,
145510  const sqlite3_tokenizer_module **pp,
145511  char **pzErr
145512){
145513  sqlite3_tokenizer_module *p;
145514  int nName = (int)strlen(zName);
145515
145516  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
145517  if( !p ){
145518    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
145519    return SQLITE_ERROR;
145520  }
145521
145522  *pp = p;
145523  return SQLITE_OK;
145524}
145525
145526/*
145527** The second argument, argv[], is an array of pointers to nul-terminated
145528** strings. This function makes a copy of the array and strings into a
145529** single block of memory. It then dequotes any of the strings that appear
145530** to be quoted.
145531**
145532** If successful, output parameter *pazDequote is set to point at the
145533** array of dequoted strings and SQLITE_OK is returned. The caller is
145534** responsible for eventually calling sqlite3_free() to free the array
145535** in this case. Or, if an error occurs, an SQLite error code is returned.
145536** The final value of *pazDequote is undefined in this case.
145537*/
145538static int fts3tokDequoteArray(
145539  int argc,                       /* Number of elements in argv[] */
145540  const char * const *argv,       /* Input array */
145541  char ***pazDequote              /* Output array */
145542){
145543  int rc = SQLITE_OK;             /* Return code */
145544  if( argc==0 ){
145545    *pazDequote = 0;
145546  }else{
145547    int i;
145548    int nByte = 0;
145549    char **azDequote;
145550
145551    for(i=0; i<argc; i++){
145552      nByte += (int)(strlen(argv[i]) + 1);
145553    }
145554
145555    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
145556    if( azDequote==0 ){
145557      rc = SQLITE_NOMEM;
145558    }else{
145559      char *pSpace = (char *)&azDequote[argc];
145560      for(i=0; i<argc; i++){
145561        int n = (int)strlen(argv[i]);
145562        azDequote[i] = pSpace;
145563        memcpy(pSpace, argv[i], n+1);
145564        sqlite3Fts3Dequote(pSpace);
145565        pSpace += (n+1);
145566      }
145567    }
145568  }
145569
145570  return rc;
145571}
145572
145573/*
145574** Schema of the tokenizer table.
145575*/
145576#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
145577
145578/*
145579** This function does all the work for both the xConnect and xCreate methods.
145580** These tables have no persistent representation of their own, so xConnect
145581** and xCreate are identical operations.
145582**
145583**   argv[0]: module name
145584**   argv[1]: database name
145585**   argv[2]: table name
145586**   argv[3]: first argument (tokenizer name)
145587*/
145588static int fts3tokConnectMethod(
145589  sqlite3 *db,                    /* Database connection */
145590  void *pHash,                    /* Hash table of tokenizers */
145591  int argc,                       /* Number of elements in argv array */
145592  const char * const *argv,       /* xCreate/xConnect argument array */
145593  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
145594  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
145595){
145596  Fts3tokTable *pTab = 0;
145597  const sqlite3_tokenizer_module *pMod = 0;
145598  sqlite3_tokenizer *pTok = 0;
145599  int rc;
145600  char **azDequote = 0;
145601  int nDequote;
145602
145603  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
145604  if( rc!=SQLITE_OK ) return rc;
145605
145606  nDequote = argc-3;
145607  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
145608
145609  if( rc==SQLITE_OK ){
145610    const char *zModule;
145611    if( nDequote<1 ){
145612      zModule = "simple";
145613    }else{
145614      zModule = azDequote[0];
145615    }
145616    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
145617  }
145618
145619  assert( (rc==SQLITE_OK)==(pMod!=0) );
145620  if( rc==SQLITE_OK ){
145621    const char * const *azArg = (const char * const *)&azDequote[1];
145622    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
145623  }
145624
145625  if( rc==SQLITE_OK ){
145626    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
145627    if( pTab==0 ){
145628      rc = SQLITE_NOMEM;
145629    }
145630  }
145631
145632  if( rc==SQLITE_OK ){
145633    memset(pTab, 0, sizeof(Fts3tokTable));
145634    pTab->pMod = pMod;
145635    pTab->pTok = pTok;
145636    *ppVtab = &pTab->base;
145637  }else{
145638    if( pTok ){
145639      pMod->xDestroy(pTok);
145640    }
145641  }
145642
145643  sqlite3_free(azDequote);
145644  return rc;
145645}
145646
145647/*
145648** This function does the work for both the xDisconnect and xDestroy methods.
145649** These tables have no persistent representation of their own, so xDisconnect
145650** and xDestroy are identical operations.
145651*/
145652static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
145653  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
145654
145655  pTab->pMod->xDestroy(pTab->pTok);
145656  sqlite3_free(pTab);
145657  return SQLITE_OK;
145658}
145659
145660/*
145661** xBestIndex - Analyze a WHERE and ORDER BY clause.
145662*/
145663static int fts3tokBestIndexMethod(
145664  sqlite3_vtab *pVTab,
145665  sqlite3_index_info *pInfo
145666){
145667  int i;
145668  UNUSED_PARAMETER(pVTab);
145669
145670  for(i=0; i<pInfo->nConstraint; i++){
145671    if( pInfo->aConstraint[i].usable
145672     && pInfo->aConstraint[i].iColumn==0
145673     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
145674    ){
145675      pInfo->idxNum = 1;
145676      pInfo->aConstraintUsage[i].argvIndex = 1;
145677      pInfo->aConstraintUsage[i].omit = 1;
145678      pInfo->estimatedCost = 1;
145679      return SQLITE_OK;
145680    }
145681  }
145682
145683  pInfo->idxNum = 0;
145684  assert( pInfo->estimatedCost>1000000.0 );
145685
145686  return SQLITE_OK;
145687}
145688
145689/*
145690** xOpen - Open a cursor.
145691*/
145692static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
145693  Fts3tokCursor *pCsr;
145694  UNUSED_PARAMETER(pVTab);
145695
145696  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
145697  if( pCsr==0 ){
145698    return SQLITE_NOMEM;
145699  }
145700  memset(pCsr, 0, sizeof(Fts3tokCursor));
145701
145702  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
145703  return SQLITE_OK;
145704}
145705
145706/*
145707** Reset the tokenizer cursor passed as the only argument. As if it had
145708** just been returned by fts3tokOpenMethod().
145709*/
145710static void fts3tokResetCursor(Fts3tokCursor *pCsr){
145711  if( pCsr->pCsr ){
145712    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
145713    pTab->pMod->xClose(pCsr->pCsr);
145714    pCsr->pCsr = 0;
145715  }
145716  sqlite3_free(pCsr->zInput);
145717  pCsr->zInput = 0;
145718  pCsr->zToken = 0;
145719  pCsr->nToken = 0;
145720  pCsr->iStart = 0;
145721  pCsr->iEnd = 0;
145722  pCsr->iPos = 0;
145723  pCsr->iRowid = 0;
145724}
145725
145726/*
145727** xClose - Close a cursor.
145728*/
145729static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
145730  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145731
145732  fts3tokResetCursor(pCsr);
145733  sqlite3_free(pCsr);
145734  return SQLITE_OK;
145735}
145736
145737/*
145738** xNext - Advance the cursor to the next row, if any.
145739*/
145740static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
145741  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145742  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
145743  int rc;                         /* Return code */
145744
145745  pCsr->iRowid++;
145746  rc = pTab->pMod->xNext(pCsr->pCsr,
145747      &pCsr->zToken, &pCsr->nToken,
145748      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
145749  );
145750
145751  if( rc!=SQLITE_OK ){
145752    fts3tokResetCursor(pCsr);
145753    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
145754  }
145755
145756  return rc;
145757}
145758
145759/*
145760** xFilter - Initialize a cursor to point at the start of its data.
145761*/
145762static int fts3tokFilterMethod(
145763  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
145764  int idxNum,                     /* Strategy index */
145765  const char *idxStr,             /* Unused */
145766  int nVal,                       /* Number of elements in apVal */
145767  sqlite3_value **apVal           /* Arguments for the indexing scheme */
145768){
145769  int rc = SQLITE_ERROR;
145770  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145771  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
145772  UNUSED_PARAMETER(idxStr);
145773  UNUSED_PARAMETER(nVal);
145774
145775  fts3tokResetCursor(pCsr);
145776  if( idxNum==1 ){
145777    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
145778    int nByte = sqlite3_value_bytes(apVal[0]);
145779    pCsr->zInput = sqlite3_malloc(nByte+1);
145780    if( pCsr->zInput==0 ){
145781      rc = SQLITE_NOMEM;
145782    }else{
145783      memcpy(pCsr->zInput, zByte, nByte);
145784      pCsr->zInput[nByte] = 0;
145785      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
145786      if( rc==SQLITE_OK ){
145787        pCsr->pCsr->pTokenizer = pTab->pTok;
145788      }
145789    }
145790  }
145791
145792  if( rc!=SQLITE_OK ) return rc;
145793  return fts3tokNextMethod(pCursor);
145794}
145795
145796/*
145797** xEof - Return true if the cursor is at EOF, or false otherwise.
145798*/
145799static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
145800  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145801  return (pCsr->zToken==0);
145802}
145803
145804/*
145805** xColumn - Return a column value.
145806*/
145807static int fts3tokColumnMethod(
145808  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145809  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
145810  int iCol                        /* Index of column to read value from */
145811){
145812  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145813
145814  /* CREATE TABLE x(input, token, start, end, position) */
145815  switch( iCol ){
145816    case 0:
145817      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
145818      break;
145819    case 1:
145820      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
145821      break;
145822    case 2:
145823      sqlite3_result_int(pCtx, pCsr->iStart);
145824      break;
145825    case 3:
145826      sqlite3_result_int(pCtx, pCsr->iEnd);
145827      break;
145828    default:
145829      assert( iCol==4 );
145830      sqlite3_result_int(pCtx, pCsr->iPos);
145831      break;
145832  }
145833  return SQLITE_OK;
145834}
145835
145836/*
145837** xRowid - Return the current rowid for the cursor.
145838*/
145839static int fts3tokRowidMethod(
145840  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145841  sqlite_int64 *pRowid            /* OUT: Rowid value */
145842){
145843  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145844  *pRowid = (sqlite3_int64)pCsr->iRowid;
145845  return SQLITE_OK;
145846}
145847
145848/*
145849** Register the fts3tok module with database connection db. Return SQLITE_OK
145850** if successful or an error code if sqlite3_create_module() fails.
145851*/
145852SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
145853  static const sqlite3_module fts3tok_module = {
145854     0,                           /* iVersion      */
145855     fts3tokConnectMethod,        /* xCreate       */
145856     fts3tokConnectMethod,        /* xConnect      */
145857     fts3tokBestIndexMethod,      /* xBestIndex    */
145858     fts3tokDisconnectMethod,     /* xDisconnect   */
145859     fts3tokDisconnectMethod,     /* xDestroy      */
145860     fts3tokOpenMethod,           /* xOpen         */
145861     fts3tokCloseMethod,          /* xClose        */
145862     fts3tokFilterMethod,         /* xFilter       */
145863     fts3tokNextMethod,           /* xNext         */
145864     fts3tokEofMethod,            /* xEof          */
145865     fts3tokColumnMethod,         /* xColumn       */
145866     fts3tokRowidMethod,          /* xRowid        */
145867     0,                           /* xUpdate       */
145868     0,                           /* xBegin        */
145869     0,                           /* xSync         */
145870     0,                           /* xCommit       */
145871     0,                           /* xRollback     */
145872     0,                           /* xFindFunction */
145873     0,                           /* xRename       */
145874     0,                           /* xSavepoint    */
145875     0,                           /* xRelease      */
145876     0                            /* xRollbackTo   */
145877  };
145878  int rc;                         /* Return code */
145879
145880  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
145881  return rc;
145882}
145883
145884#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145885
145886/************** End of fts3_tokenize_vtab.c **********************************/
145887/************** Begin file fts3_write.c **************************************/
145888/*
145889** 2009 Oct 23
145890**
145891** The author disclaims copyright to this source code.  In place of
145892** a legal notice, here is a blessing:
145893**
145894**    May you do good and not evil.
145895**    May you find forgiveness for yourself and forgive others.
145896**    May you share freely, never taking more than you give.
145897**
145898******************************************************************************
145899**
145900** This file is part of the SQLite FTS3 extension module. Specifically,
145901** this file contains code to insert, update and delete rows from FTS3
145902** tables. It also contains code to merge FTS3 b-tree segments. Some
145903** of the sub-routines used to merge segments are also used by the query
145904** code in fts3.c.
145905*/
145906
145907/* #include "fts3Int.h" */
145908#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145909
145910/* #include <string.h> */
145911/* #include <assert.h> */
145912/* #include <stdlib.h> */
145913
145914
145915#define FTS_MAX_APPENDABLE_HEIGHT 16
145916
145917/*
145918** When full-text index nodes are loaded from disk, the buffer that they
145919** are loaded into has the following number of bytes of padding at the end
145920** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
145921** of 920 bytes is allocated for it.
145922**
145923** This means that if we have a pointer into a buffer containing node data,
145924** it is always safe to read up to two varints from it without risking an
145925** overread, even if the node data is corrupted.
145926*/
145927#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
145928
145929/*
145930** Under certain circumstances, b-tree nodes (doclists) can be loaded into
145931** memory incrementally instead of all at once. This can be a big performance
145932** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
145933** method before retrieving all query results (as may happen, for example,
145934** if a query has a LIMIT clause).
145935**
145936** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
145937** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
145938** The code is written so that the hard lower-limit for each of these values
145939** is 1. Clearly such small values would be inefficient, but can be useful
145940** for testing purposes.
145941**
145942** If this module is built with SQLITE_TEST defined, these constants may
145943** be overridden at runtime for testing purposes. File fts3_test.c contains
145944** a Tcl interface to read and write the values.
145945*/
145946#ifdef SQLITE_TEST
145947int test_fts3_node_chunksize = (4*1024);
145948int test_fts3_node_chunk_threshold = (4*1024)*4;
145949# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
145950# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
145951#else
145952# define FTS3_NODE_CHUNKSIZE (4*1024)
145953# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
145954#endif
145955
145956/*
145957** The two values that may be meaningfully bound to the :1 parameter in
145958** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
145959*/
145960#define FTS_STAT_DOCTOTAL      0
145961#define FTS_STAT_INCRMERGEHINT 1
145962#define FTS_STAT_AUTOINCRMERGE 2
145963
145964/*
145965** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
145966** and incremental merge operation that takes place. This is used for
145967** debugging FTS only, it should not usually be turned on in production
145968** systems.
145969*/
145970#ifdef FTS3_LOG_MERGES
145971static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
145972  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
145973}
145974#else
145975#define fts3LogMerge(x, y)
145976#endif
145977
145978
145979typedef struct PendingList PendingList;
145980typedef struct SegmentNode SegmentNode;
145981typedef struct SegmentWriter SegmentWriter;
145982
145983/*
145984** An instance of the following data structure is used to build doclists
145985** incrementally. See function fts3PendingListAppend() for details.
145986*/
145987struct PendingList {
145988  int nData;
145989  char *aData;
145990  int nSpace;
145991  sqlite3_int64 iLastDocid;
145992  sqlite3_int64 iLastCol;
145993  sqlite3_int64 iLastPos;
145994};
145995
145996
145997/*
145998** Each cursor has a (possibly empty) linked list of the following objects.
145999*/
146000struct Fts3DeferredToken {
146001  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
146002  int iCol;                       /* Column token must occur in */
146003  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
146004  PendingList *pList;             /* Doclist is assembled here */
146005};
146006
146007/*
146008** An instance of this structure is used to iterate through the terms on
146009** a contiguous set of segment b-tree leaf nodes. Although the details of
146010** this structure are only manipulated by code in this file, opaque handles
146011** of type Fts3SegReader* are also used by code in fts3.c to iterate through
146012** terms when querying the full-text index. See functions:
146013**
146014**   sqlite3Fts3SegReaderNew()
146015**   sqlite3Fts3SegReaderFree()
146016**   sqlite3Fts3SegReaderIterate()
146017**
146018** Methods used to manipulate Fts3SegReader structures:
146019**
146020**   fts3SegReaderNext()
146021**   fts3SegReaderFirstDocid()
146022**   fts3SegReaderNextDocid()
146023*/
146024struct Fts3SegReader {
146025  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
146026  u8 bLookup;                     /* True for a lookup only */
146027  u8 rootOnly;                    /* True for a root-only reader */
146028
146029  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
146030  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
146031  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
146032  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
146033
146034  char *aNode;                    /* Pointer to node data (or NULL) */
146035  int nNode;                      /* Size of buffer at aNode (or 0) */
146036  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
146037  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
146038
146039  Fts3HashElem **ppNextElem;
146040
146041  /* Variables set by fts3SegReaderNext(). These may be read directly
146042  ** by the caller. They are valid from the time SegmentReaderNew() returns
146043  ** until SegmentReaderNext() returns something other than SQLITE_OK
146044  ** (i.e. SQLITE_DONE).
146045  */
146046  int nTerm;                      /* Number of bytes in current term */
146047  char *zTerm;                    /* Pointer to current term */
146048  int nTermAlloc;                 /* Allocated size of zTerm buffer */
146049  char *aDoclist;                 /* Pointer to doclist of current entry */
146050  int nDoclist;                   /* Size of doclist in current entry */
146051
146052  /* The following variables are used by fts3SegReaderNextDocid() to iterate
146053  ** through the current doclist (aDoclist/nDoclist).
146054  */
146055  char *pOffsetList;
146056  int nOffsetList;                /* For descending pending seg-readers only */
146057  sqlite3_int64 iDocid;
146058};
146059
146060#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
146061#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
146062
146063/*
146064** An instance of this structure is used to create a segment b-tree in the
146065** database. The internal details of this type are only accessed by the
146066** following functions:
146067**
146068**   fts3SegWriterAdd()
146069**   fts3SegWriterFlush()
146070**   fts3SegWriterFree()
146071*/
146072struct SegmentWriter {
146073  SegmentNode *pTree;             /* Pointer to interior tree structure */
146074  sqlite3_int64 iFirst;           /* First slot in %_segments written */
146075  sqlite3_int64 iFree;            /* Next free slot in %_segments */
146076  char *zTerm;                    /* Pointer to previous term buffer */
146077  int nTerm;                      /* Number of bytes in zTerm */
146078  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
146079  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
146080  int nSize;                      /* Size of allocation at aData */
146081  int nData;                      /* Bytes of data in aData */
146082  char *aData;                    /* Pointer to block from malloc() */
146083  i64 nLeafData;                  /* Number of bytes of leaf data written */
146084};
146085
146086/*
146087** Type SegmentNode is used by the following three functions to create
146088** the interior part of the segment b+-tree structures (everything except
146089** the leaf nodes). These functions and type are only ever used by code
146090** within the fts3SegWriterXXX() family of functions described above.
146091**
146092**   fts3NodeAddTerm()
146093**   fts3NodeWrite()
146094**   fts3NodeFree()
146095**
146096** When a b+tree is written to the database (either as a result of a merge
146097** or the pending-terms table being flushed), leaves are written into the
146098** database file as soon as they are completely populated. The interior of
146099** the tree is assembled in memory and written out only once all leaves have
146100** been populated and stored. This is Ok, as the b+-tree fanout is usually
146101** very large, meaning that the interior of the tree consumes relatively
146102** little memory.
146103*/
146104struct SegmentNode {
146105  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
146106  SegmentNode *pRight;            /* Pointer to right-sibling */
146107  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
146108  int nEntry;                     /* Number of terms written to node so far */
146109  char *zTerm;                    /* Pointer to previous term buffer */
146110  int nTerm;                      /* Number of bytes in zTerm */
146111  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
146112  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
146113  int nData;                      /* Bytes of valid data so far */
146114  char *aData;                    /* Node data */
146115};
146116
146117/*
146118** Valid values for the second argument to fts3SqlStmt().
146119*/
146120#define SQL_DELETE_CONTENT             0
146121#define SQL_IS_EMPTY                   1
146122#define SQL_DELETE_ALL_CONTENT         2
146123#define SQL_DELETE_ALL_SEGMENTS        3
146124#define SQL_DELETE_ALL_SEGDIR          4
146125#define SQL_DELETE_ALL_DOCSIZE         5
146126#define SQL_DELETE_ALL_STAT            6
146127#define SQL_SELECT_CONTENT_BY_ROWID    7
146128#define SQL_NEXT_SEGMENT_INDEX         8
146129#define SQL_INSERT_SEGMENTS            9
146130#define SQL_NEXT_SEGMENTS_ID          10
146131#define SQL_INSERT_SEGDIR             11
146132#define SQL_SELECT_LEVEL              12
146133#define SQL_SELECT_LEVEL_RANGE        13
146134#define SQL_SELECT_LEVEL_COUNT        14
146135#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
146136#define SQL_DELETE_SEGDIR_LEVEL       16
146137#define SQL_DELETE_SEGMENTS_RANGE     17
146138#define SQL_CONTENT_INSERT            18
146139#define SQL_DELETE_DOCSIZE            19
146140#define SQL_REPLACE_DOCSIZE           20
146141#define SQL_SELECT_DOCSIZE            21
146142#define SQL_SELECT_STAT               22
146143#define SQL_REPLACE_STAT              23
146144
146145#define SQL_SELECT_ALL_PREFIX_LEVEL   24
146146#define SQL_DELETE_ALL_TERMS_SEGDIR   25
146147#define SQL_DELETE_SEGDIR_RANGE       26
146148#define SQL_SELECT_ALL_LANGID         27
146149#define SQL_FIND_MERGE_LEVEL          28
146150#define SQL_MAX_LEAF_NODE_ESTIMATE    29
146151#define SQL_DELETE_SEGDIR_ENTRY       30
146152#define SQL_SHIFT_SEGDIR_ENTRY        31
146153#define SQL_SELECT_SEGDIR             32
146154#define SQL_CHOMP_SEGDIR              33
146155#define SQL_SEGMENT_IS_APPENDABLE     34
146156#define SQL_SELECT_INDEXES            35
146157#define SQL_SELECT_MXLEVEL            36
146158
146159#define SQL_SELECT_LEVEL_RANGE2       37
146160#define SQL_UPDATE_LEVEL_IDX          38
146161#define SQL_UPDATE_LEVEL              39
146162
146163/*
146164** This function is used to obtain an SQLite prepared statement handle
146165** for the statement identified by the second argument. If successful,
146166** *pp is set to the requested statement handle and SQLITE_OK returned.
146167** Otherwise, an SQLite error code is returned and *pp is set to 0.
146168**
146169** If argument apVal is not NULL, then it must point to an array with
146170** at least as many entries as the requested statement has bound
146171** parameters. The values are bound to the statements parameters before
146172** returning.
146173*/
146174static int fts3SqlStmt(
146175  Fts3Table *p,                   /* Virtual table handle */
146176  int eStmt,                      /* One of the SQL_XXX constants above */
146177  sqlite3_stmt **pp,              /* OUT: Statement handle */
146178  sqlite3_value **apVal           /* Values to bind to statement */
146179){
146180  const char *azSql[] = {
146181/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
146182/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
146183/* 2  */  "DELETE FROM %Q.'%q_content'",
146184/* 3  */  "DELETE FROM %Q.'%q_segments'",
146185/* 4  */  "DELETE FROM %Q.'%q_segdir'",
146186/* 5  */  "DELETE FROM %Q.'%q_docsize'",
146187/* 6  */  "DELETE FROM %Q.'%q_stat'",
146188/* 7  */  "SELECT %s WHERE rowid=?",
146189/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
146190/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
146191/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
146192/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
146193
146194          /* Return segments in order from oldest to newest.*/
146195/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146196            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
146197/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146198            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
146199            "ORDER BY level DESC, idx ASC",
146200
146201/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
146202/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
146203
146204/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
146205/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
146206/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
146207/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
146208/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
146209/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
146210/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
146211/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
146212/* 24 */  "",
146213/* 25 */  "",
146214
146215/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
146216/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
146217
146218/* This statement is used to determine which level to read the input from
146219** when performing an incremental merge. It returns the absolute level number
146220** of the oldest level in the db that contains at least ? segments. Or,
146221** if no level in the FTS index contains more than ? segments, the statement
146222** returns zero rows.  */
146223/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
146224         "  ORDER BY (level %% 1024) ASC LIMIT 1",
146225
146226/* Estimate the upper limit on the number of leaf nodes in a new segment
146227** created by merging the oldest :2 segments from absolute level :1. See
146228** function sqlite3Fts3Incrmerge() for details.  */
146229/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
146230         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
146231
146232/* SQL_DELETE_SEGDIR_ENTRY
146233**   Delete the %_segdir entry on absolute level :1 with index :2.  */
146234/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
146235
146236/* SQL_SHIFT_SEGDIR_ENTRY
146237**   Modify the idx value for the segment with idx=:3 on absolute level :2
146238**   to :1.  */
146239/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
146240
146241/* SQL_SELECT_SEGDIR
146242**   Read a single entry from the %_segdir table. The entry from absolute
146243**   level :1 with index value :2.  */
146244/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146245            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
146246
146247/* SQL_CHOMP_SEGDIR
146248**   Update the start_block (:1) and root (:2) fields of the %_segdir
146249**   entry located on absolute level :3 with index :4.  */
146250/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
146251            "WHERE level = ? AND idx = ?",
146252
146253/* SQL_SEGMENT_IS_APPENDABLE
146254**   Return a single row if the segment with end_block=? is appendable. Or
146255**   no rows otherwise.  */
146256/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
146257
146258/* SQL_SELECT_INDEXES
146259**   Return the list of valid segment indexes for absolute level ?  */
146260/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
146261
146262/* SQL_SELECT_MXLEVEL
146263**   Return the largest relative level in the FTS index or indexes.  */
146264/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
146265
146266          /* Return segments in order from oldest to newest.*/
146267/* 37 */  "SELECT level, idx, end_block "
146268            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
146269            "ORDER BY level DESC, idx ASC",
146270
146271          /* Update statements used while promoting segments */
146272/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
146273            "WHERE level=? AND idx=?",
146274/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
146275
146276  };
146277  int rc = SQLITE_OK;
146278  sqlite3_stmt *pStmt;
146279
146280  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
146281  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
146282
146283  pStmt = p->aStmt[eStmt];
146284  if( !pStmt ){
146285    char *zSql;
146286    if( eStmt==SQL_CONTENT_INSERT ){
146287      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
146288    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
146289      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
146290    }else{
146291      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
146292    }
146293    if( !zSql ){
146294      rc = SQLITE_NOMEM;
146295    }else{
146296      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
146297      sqlite3_free(zSql);
146298      assert( rc==SQLITE_OK || pStmt==0 );
146299      p->aStmt[eStmt] = pStmt;
146300    }
146301  }
146302  if( apVal ){
146303    int i;
146304    int nParam = sqlite3_bind_parameter_count(pStmt);
146305    for(i=0; rc==SQLITE_OK && i<nParam; i++){
146306      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
146307    }
146308  }
146309  *pp = pStmt;
146310  return rc;
146311}
146312
146313
146314static int fts3SelectDocsize(
146315  Fts3Table *pTab,                /* FTS3 table handle */
146316  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
146317  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146318){
146319  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
146320  int rc;                         /* Return code */
146321
146322  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
146323  if( rc==SQLITE_OK ){
146324    sqlite3_bind_int64(pStmt, 1, iDocid);
146325    rc = sqlite3_step(pStmt);
146326    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
146327      rc = sqlite3_reset(pStmt);
146328      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
146329      pStmt = 0;
146330    }else{
146331      rc = SQLITE_OK;
146332    }
146333  }
146334
146335  *ppStmt = pStmt;
146336  return rc;
146337}
146338
146339SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
146340  Fts3Table *pTab,                /* Fts3 table handle */
146341  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146342){
146343  sqlite3_stmt *pStmt = 0;
146344  int rc;
146345  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
146346  if( rc==SQLITE_OK ){
146347    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
146348    if( sqlite3_step(pStmt)!=SQLITE_ROW
146349     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
146350    ){
146351      rc = sqlite3_reset(pStmt);
146352      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
146353      pStmt = 0;
146354    }
146355  }
146356  *ppStmt = pStmt;
146357  return rc;
146358}
146359
146360SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
146361  Fts3Table *pTab,                /* Fts3 table handle */
146362  sqlite3_int64 iDocid,           /* Docid to read size data for */
146363  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146364){
146365  return fts3SelectDocsize(pTab, iDocid, ppStmt);
146366}
146367
146368/*
146369** Similar to fts3SqlStmt(). Except, after binding the parameters in
146370** array apVal[] to the SQL statement identified by eStmt, the statement
146371** is executed.
146372**
146373** Returns SQLITE_OK if the statement is successfully executed, or an
146374** SQLite error code otherwise.
146375*/
146376static void fts3SqlExec(
146377  int *pRC,                /* Result code */
146378  Fts3Table *p,            /* The FTS3 table */
146379  int eStmt,               /* Index of statement to evaluate */
146380  sqlite3_value **apVal    /* Parameters to bind */
146381){
146382  sqlite3_stmt *pStmt;
146383  int rc;
146384  if( *pRC ) return;
146385  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
146386  if( rc==SQLITE_OK ){
146387    sqlite3_step(pStmt);
146388    rc = sqlite3_reset(pStmt);
146389  }
146390  *pRC = rc;
146391}
146392
146393
146394/*
146395** This function ensures that the caller has obtained an exclusive
146396** shared-cache table-lock on the %_segdir table. This is required before
146397** writing data to the fts3 table. If this lock is not acquired first, then
146398** the caller may end up attempting to take this lock as part of committing
146399** a transaction, causing SQLite to return SQLITE_LOCKED or
146400** LOCKED_SHAREDCACHEto a COMMIT command.
146401**
146402** It is best to avoid this because if FTS3 returns any error when
146403** committing a transaction, the whole transaction will be rolled back.
146404** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
146405** It can still happen if the user locks the underlying tables directly
146406** instead of accessing them via FTS.
146407*/
146408static int fts3Writelock(Fts3Table *p){
146409  int rc = SQLITE_OK;
146410
146411  if( p->nPendingData==0 ){
146412    sqlite3_stmt *pStmt;
146413    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
146414    if( rc==SQLITE_OK ){
146415      sqlite3_bind_null(pStmt, 1);
146416      sqlite3_step(pStmt);
146417      rc = sqlite3_reset(pStmt);
146418    }
146419  }
146420
146421  return rc;
146422}
146423
146424/*
146425** FTS maintains a separate indexes for each language-id (a 32-bit integer).
146426** Within each language id, a separate index is maintained to store the
146427** document terms, and each configured prefix size (configured the FTS
146428** "prefix=" option). And each index consists of multiple levels ("relative
146429** levels").
146430**
146431** All three of these values (the language id, the specific index and the
146432** level within the index) are encoded in 64-bit integer values stored
146433** in the %_segdir table on disk. This function is used to convert three
146434** separate component values into the single 64-bit integer value that
146435** can be used to query the %_segdir table.
146436**
146437** Specifically, each language-id/index combination is allocated 1024
146438** 64-bit integer level values ("absolute levels"). The main terms index
146439** for language-id 0 is allocate values 0-1023. The first prefix index
146440** (if any) for language-id 0 is allocated values 1024-2047. And so on.
146441** Language 1 indexes are allocated immediately following language 0.
146442**
146443** So, for a system with nPrefix prefix indexes configured, the block of
146444** absolute levels that corresponds to language-id iLangid and index
146445** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
146446*/
146447static sqlite3_int64 getAbsoluteLevel(
146448  Fts3Table *p,                   /* FTS3 table handle */
146449  int iLangid,                    /* Language id */
146450  int iIndex,                     /* Index in p->aIndex[] */
146451  int iLevel                      /* Level of segments */
146452){
146453  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
146454  assert( iLangid>=0 );
146455  assert( p->nIndex>0 );
146456  assert( iIndex>=0 && iIndex<p->nIndex );
146457
146458  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
146459  return iBase + iLevel;
146460}
146461
146462/*
146463** Set *ppStmt to a statement handle that may be used to iterate through
146464** all rows in the %_segdir table, from oldest to newest. If successful,
146465** return SQLITE_OK. If an error occurs while preparing the statement,
146466** return an SQLite error code.
146467**
146468** There is only ever one instance of this SQL statement compiled for
146469** each FTS3 table.
146470**
146471** The statement returns the following columns from the %_segdir table:
146472**
146473**   0: idx
146474**   1: start_block
146475**   2: leaves_end_block
146476**   3: end_block
146477**   4: root
146478*/
146479SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
146480  Fts3Table *p,                   /* FTS3 table */
146481  int iLangid,                    /* Language being queried */
146482  int iIndex,                     /* Index for p->aIndex[] */
146483  int iLevel,                     /* Level to select (relative level) */
146484  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
146485){
146486  int rc;
146487  sqlite3_stmt *pStmt = 0;
146488
146489  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
146490  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
146491  assert( iIndex>=0 && iIndex<p->nIndex );
146492
146493  if( iLevel<0 ){
146494    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
146495    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
146496    if( rc==SQLITE_OK ){
146497      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
146498      sqlite3_bind_int64(pStmt, 2,
146499          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
146500      );
146501    }
146502  }else{
146503    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
146504    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
146505    if( rc==SQLITE_OK ){
146506      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
146507    }
146508  }
146509  *ppStmt = pStmt;
146510  return rc;
146511}
146512
146513
146514/*
146515** Append a single varint to a PendingList buffer. SQLITE_OK is returned
146516** if successful, or an SQLite error code otherwise.
146517**
146518** This function also serves to allocate the PendingList structure itself.
146519** For example, to create a new PendingList structure containing two
146520** varints:
146521**
146522**   PendingList *p = 0;
146523**   fts3PendingListAppendVarint(&p, 1);
146524**   fts3PendingListAppendVarint(&p, 2);
146525*/
146526static int fts3PendingListAppendVarint(
146527  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
146528  sqlite3_int64 i                 /* Value to append to data */
146529){
146530  PendingList *p = *pp;
146531
146532  /* Allocate or grow the PendingList as required. */
146533  if( !p ){
146534    p = sqlite3_malloc(sizeof(*p) + 100);
146535    if( !p ){
146536      return SQLITE_NOMEM;
146537    }
146538    p->nSpace = 100;
146539    p->aData = (char *)&p[1];
146540    p->nData = 0;
146541  }
146542  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
146543    int nNew = p->nSpace * 2;
146544    p = sqlite3_realloc(p, sizeof(*p) + nNew);
146545    if( !p ){
146546      sqlite3_free(*pp);
146547      *pp = 0;
146548      return SQLITE_NOMEM;
146549    }
146550    p->nSpace = nNew;
146551    p->aData = (char *)&p[1];
146552  }
146553
146554  /* Append the new serialized varint to the end of the list. */
146555  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
146556  p->aData[p->nData] = '\0';
146557  *pp = p;
146558  return SQLITE_OK;
146559}
146560
146561/*
146562** Add a docid/column/position entry to a PendingList structure. Non-zero
146563** is returned if the structure is sqlite3_realloced as part of adding
146564** the entry. Otherwise, zero.
146565**
146566** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
146567** Zero is always returned in this case. Otherwise, if no OOM error occurs,
146568** it is set to SQLITE_OK.
146569*/
146570static int fts3PendingListAppend(
146571  PendingList **pp,               /* IN/OUT: PendingList structure */
146572  sqlite3_int64 iDocid,           /* Docid for entry to add */
146573  sqlite3_int64 iCol,             /* Column for entry to add */
146574  sqlite3_int64 iPos,             /* Position of term for entry to add */
146575  int *pRc                        /* OUT: Return code */
146576){
146577  PendingList *p = *pp;
146578  int rc = SQLITE_OK;
146579
146580  assert( !p || p->iLastDocid<=iDocid );
146581
146582  if( !p || p->iLastDocid!=iDocid ){
146583    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
146584    if( p ){
146585      assert( p->nData<p->nSpace );
146586      assert( p->aData[p->nData]==0 );
146587      p->nData++;
146588    }
146589    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
146590      goto pendinglistappend_out;
146591    }
146592    p->iLastCol = -1;
146593    p->iLastPos = 0;
146594    p->iLastDocid = iDocid;
146595  }
146596  if( iCol>0 && p->iLastCol!=iCol ){
146597    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
146598     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
146599    ){
146600      goto pendinglistappend_out;
146601    }
146602    p->iLastCol = iCol;
146603    p->iLastPos = 0;
146604  }
146605  if( iCol>=0 ){
146606    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
146607    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
146608    if( rc==SQLITE_OK ){
146609      p->iLastPos = iPos;
146610    }
146611  }
146612
146613 pendinglistappend_out:
146614  *pRc = rc;
146615  if( p!=*pp ){
146616    *pp = p;
146617    return 1;
146618  }
146619  return 0;
146620}
146621
146622/*
146623** Free a PendingList object allocated by fts3PendingListAppend().
146624*/
146625static void fts3PendingListDelete(PendingList *pList){
146626  sqlite3_free(pList);
146627}
146628
146629/*
146630** Add an entry to one of the pending-terms hash tables.
146631*/
146632static int fts3PendingTermsAddOne(
146633  Fts3Table *p,
146634  int iCol,
146635  int iPos,
146636  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
146637  const char *zToken,
146638  int nToken
146639){
146640  PendingList *pList;
146641  int rc = SQLITE_OK;
146642
146643  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
146644  if( pList ){
146645    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
146646  }
146647  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
146648    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
146649      /* Malloc failed while inserting the new entry. This can only
146650      ** happen if there was no previous entry for this token.
146651      */
146652      assert( 0==fts3HashFind(pHash, zToken, nToken) );
146653      sqlite3_free(pList);
146654      rc = SQLITE_NOMEM;
146655    }
146656  }
146657  if( rc==SQLITE_OK ){
146658    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
146659  }
146660  return rc;
146661}
146662
146663/*
146664** Tokenize the nul-terminated string zText and add all tokens to the
146665** pending-terms hash-table. The docid used is that currently stored in
146666** p->iPrevDocid, and the column is specified by argument iCol.
146667**
146668** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
146669*/
146670static int fts3PendingTermsAdd(
146671  Fts3Table *p,                   /* Table into which text will be inserted */
146672  int iLangid,                    /* Language id to use */
146673  const char *zText,              /* Text of document to be inserted */
146674  int iCol,                       /* Column into which text is being inserted */
146675  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
146676){
146677  int rc;
146678  int iStart = 0;
146679  int iEnd = 0;
146680  int iPos = 0;
146681  int nWord = 0;
146682
146683  char const *zToken;
146684  int nToken = 0;
146685
146686  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
146687  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
146688  sqlite3_tokenizer_cursor *pCsr;
146689  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
146690      const char**,int*,int*,int*,int*);
146691
146692  assert( pTokenizer && pModule );
146693
146694  /* If the user has inserted a NULL value, this function may be called with
146695  ** zText==0. In this case, add zero token entries to the hash table and
146696  ** return early. */
146697  if( zText==0 ){
146698    *pnWord = 0;
146699    return SQLITE_OK;
146700  }
146701
146702  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
146703  if( rc!=SQLITE_OK ){
146704    return rc;
146705  }
146706
146707  xNext = pModule->xNext;
146708  while( SQLITE_OK==rc
146709      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
146710  ){
146711    int i;
146712    if( iPos>=nWord ) nWord = iPos+1;
146713
146714    /* Positions cannot be negative; we use -1 as a terminator internally.
146715    ** Tokens must have a non-zero length.
146716    */
146717    if( iPos<0 || !zToken || nToken<=0 ){
146718      rc = SQLITE_ERROR;
146719      break;
146720    }
146721
146722    /* Add the term to the terms index */
146723    rc = fts3PendingTermsAddOne(
146724        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
146725    );
146726
146727    /* Add the term to each of the prefix indexes that it is not too
146728    ** short for. */
146729    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
146730      struct Fts3Index *pIndex = &p->aIndex[i];
146731      if( nToken<pIndex->nPrefix ) continue;
146732      rc = fts3PendingTermsAddOne(
146733          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
146734      );
146735    }
146736  }
146737
146738  pModule->xClose(pCsr);
146739  *pnWord += nWord;
146740  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
146741}
146742
146743/*
146744** Calling this function indicates that subsequent calls to
146745** fts3PendingTermsAdd() are to add term/position-list pairs for the
146746** contents of the document with docid iDocid.
146747*/
146748static int fts3PendingTermsDocid(
146749  Fts3Table *p,                   /* Full-text table handle */
146750  int bDelete,                    /* True if this op is a delete */
146751  int iLangid,                    /* Language id of row being written */
146752  sqlite_int64 iDocid             /* Docid of row being written */
146753){
146754  assert( iLangid>=0 );
146755  assert( bDelete==1 || bDelete==0 );
146756
146757  /* TODO(shess) Explore whether partially flushing the buffer on
146758  ** forced-flush would provide better performance.  I suspect that if
146759  ** we ordered the doclists by size and flushed the largest until the
146760  ** buffer was half empty, that would let the less frequent terms
146761  ** generate longer doclists.
146762  */
146763  if( iDocid<p->iPrevDocid
146764   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
146765   || p->iPrevLangid!=iLangid
146766   || p->nPendingData>p->nMaxPendingData
146767  ){
146768    int rc = sqlite3Fts3PendingTermsFlush(p);
146769    if( rc!=SQLITE_OK ) return rc;
146770  }
146771  p->iPrevDocid = iDocid;
146772  p->iPrevLangid = iLangid;
146773  p->bPrevDelete = bDelete;
146774  return SQLITE_OK;
146775}
146776
146777/*
146778** Discard the contents of the pending-terms hash tables.
146779*/
146780SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
146781  int i;
146782  for(i=0; i<p->nIndex; i++){
146783    Fts3HashElem *pElem;
146784    Fts3Hash *pHash = &p->aIndex[i].hPending;
146785    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
146786      PendingList *pList = (PendingList *)fts3HashData(pElem);
146787      fts3PendingListDelete(pList);
146788    }
146789    fts3HashClear(pHash);
146790  }
146791  p->nPendingData = 0;
146792}
146793
146794/*
146795** This function is called by the xUpdate() method as part of an INSERT
146796** operation. It adds entries for each term in the new record to the
146797** pendingTerms hash table.
146798**
146799** Argument apVal is the same as the similarly named argument passed to
146800** fts3InsertData(). Parameter iDocid is the docid of the new row.
146801*/
146802static int fts3InsertTerms(
146803  Fts3Table *p,
146804  int iLangid,
146805  sqlite3_value **apVal,
146806  u32 *aSz
146807){
146808  int i;                          /* Iterator variable */
146809  for(i=2; i<p->nColumn+2; i++){
146810    int iCol = i-2;
146811    if( p->abNotindexed[iCol]==0 ){
146812      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
146813      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
146814      if( rc!=SQLITE_OK ){
146815        return rc;
146816      }
146817      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
146818    }
146819  }
146820  return SQLITE_OK;
146821}
146822
146823/*
146824** This function is called by the xUpdate() method for an INSERT operation.
146825** The apVal parameter is passed a copy of the apVal argument passed by
146826** SQLite to the xUpdate() method. i.e:
146827**
146828**   apVal[0]                Not used for INSERT.
146829**   apVal[1]                rowid
146830**   apVal[2]                Left-most user-defined column
146831**   ...
146832**   apVal[p->nColumn+1]     Right-most user-defined column
146833**   apVal[p->nColumn+2]     Hidden column with same name as table
146834**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
146835**   apVal[p->nColumn+4]     Hidden languageid column
146836*/
146837static int fts3InsertData(
146838  Fts3Table *p,                   /* Full-text table */
146839  sqlite3_value **apVal,          /* Array of values to insert */
146840  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
146841){
146842  int rc;                         /* Return code */
146843  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
146844
146845  if( p->zContentTbl ){
146846    sqlite3_value *pRowid = apVal[p->nColumn+3];
146847    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
146848      pRowid = apVal[1];
146849    }
146850    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
146851      return SQLITE_CONSTRAINT;
146852    }
146853    *piDocid = sqlite3_value_int64(pRowid);
146854    return SQLITE_OK;
146855  }
146856
146857  /* Locate the statement handle used to insert data into the %_content
146858  ** table. The SQL for this statement is:
146859  **
146860  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
146861  **
146862  ** The statement features N '?' variables, where N is the number of user
146863  ** defined columns in the FTS3 table, plus one for the docid field.
146864  */
146865  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
146866  if( rc==SQLITE_OK && p->zLanguageid ){
146867    rc = sqlite3_bind_int(
146868        pContentInsert, p->nColumn+2,
146869        sqlite3_value_int(apVal[p->nColumn+4])
146870    );
146871  }
146872  if( rc!=SQLITE_OK ) return rc;
146873
146874  /* There is a quirk here. The users INSERT statement may have specified
146875  ** a value for the "rowid" field, for the "docid" field, or for both.
146876  ** Which is a problem, since "rowid" and "docid" are aliases for the
146877  ** same value. For example:
146878  **
146879  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
146880  **
146881  ** In FTS3, this is an error. It is an error to specify non-NULL values
146882  ** for both docid and some other rowid alias.
146883  */
146884  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
146885    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
146886     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
146887    ){
146888      /* A rowid/docid conflict. */
146889      return SQLITE_ERROR;
146890    }
146891    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
146892    if( rc!=SQLITE_OK ) return rc;
146893  }
146894
146895  /* Execute the statement to insert the record. Set *piDocid to the
146896  ** new docid value.
146897  */
146898  sqlite3_step(pContentInsert);
146899  rc = sqlite3_reset(pContentInsert);
146900
146901  *piDocid = sqlite3_last_insert_rowid(p->db);
146902  return rc;
146903}
146904
146905
146906
146907/*
146908** Remove all data from the FTS3 table. Clear the hash table containing
146909** pending terms.
146910*/
146911static int fts3DeleteAll(Fts3Table *p, int bContent){
146912  int rc = SQLITE_OK;             /* Return code */
146913
146914  /* Discard the contents of the pending-terms hash table. */
146915  sqlite3Fts3PendingTermsClear(p);
146916
146917  /* Delete everything from the shadow tables. Except, leave %_content as
146918  ** is if bContent is false.  */
146919  assert( p->zContentTbl==0 || bContent==0 );
146920  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
146921  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
146922  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
146923  if( p->bHasDocsize ){
146924    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
146925  }
146926  if( p->bHasStat ){
146927    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
146928  }
146929  return rc;
146930}
146931
146932/*
146933**
146934*/
146935static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
146936  int iLangid = 0;
146937  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
146938  return iLangid;
146939}
146940
146941/*
146942** The first element in the apVal[] array is assumed to contain the docid
146943** (an integer) of a row about to be deleted. Remove all terms from the
146944** full-text index.
146945*/
146946static void fts3DeleteTerms(
146947  int *pRC,               /* Result code */
146948  Fts3Table *p,           /* The FTS table to delete from */
146949  sqlite3_value *pRowid,  /* The docid to be deleted */
146950  u32 *aSz,               /* Sizes of deleted document written here */
146951  int *pbFound            /* OUT: Set to true if row really does exist */
146952){
146953  int rc;
146954  sqlite3_stmt *pSelect;
146955
146956  assert( *pbFound==0 );
146957  if( *pRC ) return;
146958  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
146959  if( rc==SQLITE_OK ){
146960    if( SQLITE_ROW==sqlite3_step(pSelect) ){
146961      int i;
146962      int iLangid = langidFromSelect(p, pSelect);
146963      i64 iDocid = sqlite3_column_int64(pSelect, 0);
146964      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
146965      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
146966        int iCol = i-1;
146967        if( p->abNotindexed[iCol]==0 ){
146968          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
146969          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
146970          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
146971        }
146972      }
146973      if( rc!=SQLITE_OK ){
146974        sqlite3_reset(pSelect);
146975        *pRC = rc;
146976        return;
146977      }
146978      *pbFound = 1;
146979    }
146980    rc = sqlite3_reset(pSelect);
146981  }else{
146982    sqlite3_reset(pSelect);
146983  }
146984  *pRC = rc;
146985}
146986
146987/*
146988** Forward declaration to account for the circular dependency between
146989** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
146990*/
146991static int fts3SegmentMerge(Fts3Table *, int, int, int);
146992
146993/*
146994** This function allocates a new level iLevel index in the segdir table.
146995** Usually, indexes are allocated within a level sequentially starting
146996** with 0, so the allocated index is one greater than the value returned
146997** by:
146998**
146999**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
147000**
147001** However, if there are already FTS3_MERGE_COUNT indexes at the requested
147002** level, they are merged into a single level (iLevel+1) segment and the
147003** allocated index is 0.
147004**
147005** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
147006** returned. Otherwise, an SQLite error code is returned.
147007*/
147008static int fts3AllocateSegdirIdx(
147009  Fts3Table *p,
147010  int iLangid,                    /* Language id */
147011  int iIndex,                     /* Index for p->aIndex */
147012  int iLevel,
147013  int *piIdx
147014){
147015  int rc;                         /* Return Code */
147016  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
147017  int iNext = 0;                  /* Result of query pNextIdx */
147018
147019  assert( iLangid>=0 );
147020  assert( p->nIndex>=1 );
147021
147022  /* Set variable iNext to the next available segdir index at level iLevel. */
147023  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
147024  if( rc==SQLITE_OK ){
147025    sqlite3_bind_int64(
147026        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
147027    );
147028    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
147029      iNext = sqlite3_column_int(pNextIdx, 0);
147030    }
147031    rc = sqlite3_reset(pNextIdx);
147032  }
147033
147034  if( rc==SQLITE_OK ){
147035    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
147036    ** full, merge all segments in level iLevel into a single iLevel+1
147037    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
147038    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
147039    */
147040    if( iNext>=FTS3_MERGE_COUNT ){
147041      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
147042      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
147043      *piIdx = 0;
147044    }else{
147045      *piIdx = iNext;
147046    }
147047  }
147048
147049  return rc;
147050}
147051
147052/*
147053** The %_segments table is declared as follows:
147054**
147055**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
147056**
147057** This function reads data from a single row of the %_segments table. The
147058** specific row is identified by the iBlockid parameter. If paBlob is not
147059** NULL, then a buffer is allocated using sqlite3_malloc() and populated
147060** with the contents of the blob stored in the "block" column of the
147061** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
147062** to the size of the blob in bytes before returning.
147063**
147064** If an error occurs, or the table does not contain the specified row,
147065** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
147066** paBlob is non-NULL, then it is the responsibility of the caller to
147067** eventually free the returned buffer.
147068**
147069** This function may leave an open sqlite3_blob* handle in the
147070** Fts3Table.pSegments variable. This handle is reused by subsequent calls
147071** to this function. The handle may be closed by calling the
147072** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
147073** performance improvement, but the blob handle should always be closed
147074** before control is returned to the user (to prevent a lock being held
147075** on the database file for longer than necessary). Thus, any virtual table
147076** method (xFilter etc.) that may directly or indirectly call this function
147077** must call sqlite3Fts3SegmentsClose() before returning.
147078*/
147079SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
147080  Fts3Table *p,                   /* FTS3 table handle */
147081  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
147082  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
147083  int *pnBlob,                    /* OUT: Size of blob data */
147084  int *pnLoad                     /* OUT: Bytes actually loaded */
147085){
147086  int rc;                         /* Return code */
147087
147088  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
147089  assert( pnBlob );
147090
147091  if( p->pSegments ){
147092    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
147093  }else{
147094    if( 0==p->zSegmentsTbl ){
147095      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
147096      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
147097    }
147098    rc = sqlite3_blob_open(
147099       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
147100    );
147101  }
147102
147103  if( rc==SQLITE_OK ){
147104    int nByte = sqlite3_blob_bytes(p->pSegments);
147105    *pnBlob = nByte;
147106    if( paBlob ){
147107      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
147108      if( !aByte ){
147109        rc = SQLITE_NOMEM;
147110      }else{
147111        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
147112          nByte = FTS3_NODE_CHUNKSIZE;
147113          *pnLoad = nByte;
147114        }
147115        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
147116        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
147117        if( rc!=SQLITE_OK ){
147118          sqlite3_free(aByte);
147119          aByte = 0;
147120        }
147121      }
147122      *paBlob = aByte;
147123    }
147124  }
147125
147126  return rc;
147127}
147128
147129/*
147130** Close the blob handle at p->pSegments, if it is open. See comments above
147131** the sqlite3Fts3ReadBlock() function for details.
147132*/
147133SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
147134  sqlite3_blob_close(p->pSegments);
147135  p->pSegments = 0;
147136}
147137
147138static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
147139  int nRead;                      /* Number of bytes to read */
147140  int rc;                         /* Return code */
147141
147142  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
147143  rc = sqlite3_blob_read(
147144      pReader->pBlob,
147145      &pReader->aNode[pReader->nPopulate],
147146      nRead,
147147      pReader->nPopulate
147148  );
147149
147150  if( rc==SQLITE_OK ){
147151    pReader->nPopulate += nRead;
147152    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
147153    if( pReader->nPopulate==pReader->nNode ){
147154      sqlite3_blob_close(pReader->pBlob);
147155      pReader->pBlob = 0;
147156      pReader->nPopulate = 0;
147157    }
147158  }
147159  return rc;
147160}
147161
147162static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
147163  int rc = SQLITE_OK;
147164  assert( !pReader->pBlob
147165       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
147166  );
147167  while( pReader->pBlob && rc==SQLITE_OK
147168     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
147169  ){
147170    rc = fts3SegReaderIncrRead(pReader);
147171  }
147172  return rc;
147173}
147174
147175/*
147176** Set an Fts3SegReader cursor to point at EOF.
147177*/
147178static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
147179  if( !fts3SegReaderIsRootOnly(pSeg) ){
147180    sqlite3_free(pSeg->aNode);
147181    sqlite3_blob_close(pSeg->pBlob);
147182    pSeg->pBlob = 0;
147183  }
147184  pSeg->aNode = 0;
147185}
147186
147187/*
147188** Move the iterator passed as the first argument to the next term in the
147189** segment. If successful, SQLITE_OK is returned. If there is no next term,
147190** SQLITE_DONE. Otherwise, an SQLite error code.
147191*/
147192static int fts3SegReaderNext(
147193  Fts3Table *p,
147194  Fts3SegReader *pReader,
147195  int bIncr
147196){
147197  int rc;                         /* Return code of various sub-routines */
147198  char *pNext;                    /* Cursor variable */
147199  int nPrefix;                    /* Number of bytes in term prefix */
147200  int nSuffix;                    /* Number of bytes in term suffix */
147201
147202  if( !pReader->aDoclist ){
147203    pNext = pReader->aNode;
147204  }else{
147205    pNext = &pReader->aDoclist[pReader->nDoclist];
147206  }
147207
147208  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
147209
147210    if( fts3SegReaderIsPending(pReader) ){
147211      Fts3HashElem *pElem = *(pReader->ppNextElem);
147212      sqlite3_free(pReader->aNode);
147213      pReader->aNode = 0;
147214      if( pElem ){
147215        char *aCopy;
147216        PendingList *pList = (PendingList *)fts3HashData(pElem);
147217        int nCopy = pList->nData+1;
147218        pReader->zTerm = (char *)fts3HashKey(pElem);
147219        pReader->nTerm = fts3HashKeysize(pElem);
147220        aCopy = (char*)sqlite3_malloc(nCopy);
147221        if( !aCopy ) return SQLITE_NOMEM;
147222        memcpy(aCopy, pList->aData, nCopy);
147223        pReader->nNode = pReader->nDoclist = nCopy;
147224        pReader->aNode = pReader->aDoclist = aCopy;
147225        pReader->ppNextElem++;
147226        assert( pReader->aNode );
147227      }
147228      return SQLITE_OK;
147229    }
147230
147231    fts3SegReaderSetEof(pReader);
147232
147233    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
147234    ** blocks have already been traversed.  */
147235    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
147236    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
147237      return SQLITE_OK;
147238    }
147239
147240    rc = sqlite3Fts3ReadBlock(
147241        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
147242        (bIncr ? &pReader->nPopulate : 0)
147243    );
147244    if( rc!=SQLITE_OK ) return rc;
147245    assert( pReader->pBlob==0 );
147246    if( bIncr && pReader->nPopulate<pReader->nNode ){
147247      pReader->pBlob = p->pSegments;
147248      p->pSegments = 0;
147249    }
147250    pNext = pReader->aNode;
147251  }
147252
147253  assert( !fts3SegReaderIsPending(pReader) );
147254
147255  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
147256  if( rc!=SQLITE_OK ) return rc;
147257
147258  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
147259  ** safe (no risk of overread) even if the node data is corrupted. */
147260  pNext += fts3GetVarint32(pNext, &nPrefix);
147261  pNext += fts3GetVarint32(pNext, &nSuffix);
147262  if( nPrefix<0 || nSuffix<=0
147263   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
147264  ){
147265    return FTS_CORRUPT_VTAB;
147266  }
147267
147268  if( nPrefix+nSuffix>pReader->nTermAlloc ){
147269    int nNew = (nPrefix+nSuffix)*2;
147270    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
147271    if( !zNew ){
147272      return SQLITE_NOMEM;
147273    }
147274    pReader->zTerm = zNew;
147275    pReader->nTermAlloc = nNew;
147276  }
147277
147278  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
147279  if( rc!=SQLITE_OK ) return rc;
147280
147281  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
147282  pReader->nTerm = nPrefix+nSuffix;
147283  pNext += nSuffix;
147284  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
147285  pReader->aDoclist = pNext;
147286  pReader->pOffsetList = 0;
147287
147288  /* Check that the doclist does not appear to extend past the end of the
147289  ** b-tree node. And that the final byte of the doclist is 0x00. If either
147290  ** of these statements is untrue, then the data structure is corrupt.
147291  */
147292  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
147293   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
147294  ){
147295    return FTS_CORRUPT_VTAB;
147296  }
147297  return SQLITE_OK;
147298}
147299
147300/*
147301** Set the SegReader to point to the first docid in the doclist associated
147302** with the current term.
147303*/
147304static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
147305  int rc = SQLITE_OK;
147306  assert( pReader->aDoclist );
147307  assert( !pReader->pOffsetList );
147308  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
147309    u8 bEof = 0;
147310    pReader->iDocid = 0;
147311    pReader->nOffsetList = 0;
147312    sqlite3Fts3DoclistPrev(0,
147313        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
147314        &pReader->iDocid, &pReader->nOffsetList, &bEof
147315    );
147316  }else{
147317    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
147318    if( rc==SQLITE_OK ){
147319      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
147320      pReader->pOffsetList = &pReader->aDoclist[n];
147321    }
147322  }
147323  return rc;
147324}
147325
147326/*
147327** Advance the SegReader to point to the next docid in the doclist
147328** associated with the current term.
147329**
147330** If arguments ppOffsetList and pnOffsetList are not NULL, then
147331** *ppOffsetList is set to point to the first column-offset list
147332** in the doclist entry (i.e. immediately past the docid varint).
147333** *pnOffsetList is set to the length of the set of column-offset
147334** lists, not including the nul-terminator byte. For example:
147335*/
147336static int fts3SegReaderNextDocid(
147337  Fts3Table *pTab,
147338  Fts3SegReader *pReader,         /* Reader to advance to next docid */
147339  char **ppOffsetList,            /* OUT: Pointer to current position-list */
147340  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
147341){
147342  int rc = SQLITE_OK;
147343  char *p = pReader->pOffsetList;
147344  char c = 0;
147345
147346  assert( p );
147347
147348  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
147349    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
147350    ** Pending-terms doclists are always built up in ascending order, so
147351    ** we have to iterate through them backwards here. */
147352    u8 bEof = 0;
147353    if( ppOffsetList ){
147354      *ppOffsetList = pReader->pOffsetList;
147355      *pnOffsetList = pReader->nOffsetList - 1;
147356    }
147357    sqlite3Fts3DoclistPrev(0,
147358        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
147359        &pReader->nOffsetList, &bEof
147360    );
147361    if( bEof ){
147362      pReader->pOffsetList = 0;
147363    }else{
147364      pReader->pOffsetList = p;
147365    }
147366  }else{
147367    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
147368
147369    /* Pointer p currently points at the first byte of an offset list. The
147370    ** following block advances it to point one byte past the end of
147371    ** the same offset list. */
147372    while( 1 ){
147373
147374      /* The following line of code (and the "p++" below the while() loop) is
147375      ** normally all that is required to move pointer p to the desired
147376      ** position. The exception is if this node is being loaded from disk
147377      ** incrementally and pointer "p" now points to the first byte past
147378      ** the populated part of pReader->aNode[].
147379      */
147380      while( *p | c ) c = *p++ & 0x80;
147381      assert( *p==0 );
147382
147383      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
147384      rc = fts3SegReaderIncrRead(pReader);
147385      if( rc!=SQLITE_OK ) return rc;
147386    }
147387    p++;
147388
147389    /* If required, populate the output variables with a pointer to and the
147390    ** size of the previous offset-list.
147391    */
147392    if( ppOffsetList ){
147393      *ppOffsetList = pReader->pOffsetList;
147394      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
147395    }
147396
147397    /* List may have been edited in place by fts3EvalNearTrim() */
147398    while( p<pEnd && *p==0 ) p++;
147399
147400    /* If there are no more entries in the doclist, set pOffsetList to
147401    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
147402    ** Fts3SegReader.pOffsetList to point to the next offset list before
147403    ** returning.
147404    */
147405    if( p>=pEnd ){
147406      pReader->pOffsetList = 0;
147407    }else{
147408      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
147409      if( rc==SQLITE_OK ){
147410        sqlite3_int64 iDelta;
147411        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
147412        if( pTab->bDescIdx ){
147413          pReader->iDocid -= iDelta;
147414        }else{
147415          pReader->iDocid += iDelta;
147416        }
147417      }
147418    }
147419  }
147420
147421  return SQLITE_OK;
147422}
147423
147424
147425SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
147426  Fts3Cursor *pCsr,
147427  Fts3MultiSegReader *pMsr,
147428  int *pnOvfl
147429){
147430  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
147431  int nOvfl = 0;
147432  int ii;
147433  int rc = SQLITE_OK;
147434  int pgsz = p->nPgsz;
147435
147436  assert( p->bFts4 );
147437  assert( pgsz>0 );
147438
147439  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
147440    Fts3SegReader *pReader = pMsr->apSegment[ii];
147441    if( !fts3SegReaderIsPending(pReader)
147442     && !fts3SegReaderIsRootOnly(pReader)
147443    ){
147444      sqlite3_int64 jj;
147445      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
147446        int nBlob;
147447        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
147448        if( rc!=SQLITE_OK ) break;
147449        if( (nBlob+35)>pgsz ){
147450          nOvfl += (nBlob + 34)/pgsz;
147451        }
147452      }
147453    }
147454  }
147455  *pnOvfl = nOvfl;
147456  return rc;
147457}
147458
147459/*
147460** Free all allocations associated with the iterator passed as the
147461** second argument.
147462*/
147463SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
147464  if( pReader ){
147465    if( !fts3SegReaderIsPending(pReader) ){
147466      sqlite3_free(pReader->zTerm);
147467    }
147468    if( !fts3SegReaderIsRootOnly(pReader) ){
147469      sqlite3_free(pReader->aNode);
147470    }
147471    sqlite3_blob_close(pReader->pBlob);
147472  }
147473  sqlite3_free(pReader);
147474}
147475
147476/*
147477** Allocate a new SegReader object.
147478*/
147479SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
147480  int iAge,                       /* Segment "age". */
147481  int bLookup,                    /* True for a lookup only */
147482  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
147483  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
147484  sqlite3_int64 iEndBlock,        /* Final block of segment */
147485  const char *zRoot,              /* Buffer containing root node */
147486  int nRoot,                      /* Size of buffer containing root node */
147487  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
147488){
147489  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
147490  int nExtra = 0;                 /* Bytes to allocate segment root node */
147491
147492  assert( iStartLeaf<=iEndLeaf );
147493  if( iStartLeaf==0 ){
147494    nExtra = nRoot + FTS3_NODE_PADDING;
147495  }
147496
147497  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
147498  if( !pReader ){
147499    return SQLITE_NOMEM;
147500  }
147501  memset(pReader, 0, sizeof(Fts3SegReader));
147502  pReader->iIdx = iAge;
147503  pReader->bLookup = bLookup!=0;
147504  pReader->iStartBlock = iStartLeaf;
147505  pReader->iLeafEndBlock = iEndLeaf;
147506  pReader->iEndBlock = iEndBlock;
147507
147508  if( nExtra ){
147509    /* The entire segment is stored in the root node. */
147510    pReader->aNode = (char *)&pReader[1];
147511    pReader->rootOnly = 1;
147512    pReader->nNode = nRoot;
147513    memcpy(pReader->aNode, zRoot, nRoot);
147514    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
147515  }else{
147516    pReader->iCurrentBlock = iStartLeaf-1;
147517  }
147518  *ppReader = pReader;
147519  return SQLITE_OK;
147520}
147521
147522/*
147523** This is a comparison function used as a qsort() callback when sorting
147524** an array of pending terms by term. This occurs as part of flushing
147525** the contents of the pending-terms hash table to the database.
147526*/
147527static int SQLITE_CDECL fts3CompareElemByTerm(
147528  const void *lhs,
147529  const void *rhs
147530){
147531  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
147532  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
147533  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
147534  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
147535
147536  int n = (n1<n2 ? n1 : n2);
147537  int c = memcmp(z1, z2, n);
147538  if( c==0 ){
147539    c = n1 - n2;
147540  }
147541  return c;
147542}
147543
147544/*
147545** This function is used to allocate an Fts3SegReader that iterates through
147546** a subset of the terms stored in the Fts3Table.pendingTerms array.
147547**
147548** If the isPrefixIter parameter is zero, then the returned SegReader iterates
147549** through each term in the pending-terms table. Or, if isPrefixIter is
147550** non-zero, it iterates through each term and its prefixes. For example, if
147551** the pending terms hash table contains the terms "sqlite", "mysql" and
147552** "firebird", then the iterator visits the following 'terms' (in the order
147553** shown):
147554**
147555**   f fi fir fire fireb firebi firebir firebird
147556**   m my mys mysq mysql
147557**   s sq sql sqli sqlit sqlite
147558**
147559** Whereas if isPrefixIter is zero, the terms visited are:
147560**
147561**   firebird mysql sqlite
147562*/
147563SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
147564  Fts3Table *p,                   /* Virtual table handle */
147565  int iIndex,                     /* Index for p->aIndex */
147566  const char *zTerm,              /* Term to search for */
147567  int nTerm,                      /* Size of buffer zTerm */
147568  int bPrefix,                    /* True for a prefix iterator */
147569  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
147570){
147571  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
147572  Fts3HashElem *pE;               /* Iterator variable */
147573  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
147574  int nElem = 0;                  /* Size of array at aElem */
147575  int rc = SQLITE_OK;             /* Return Code */
147576  Fts3Hash *pHash;
147577
147578  pHash = &p->aIndex[iIndex].hPending;
147579  if( bPrefix ){
147580    int nAlloc = 0;               /* Size of allocated array at aElem */
147581
147582    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
147583      char *zKey = (char *)fts3HashKey(pE);
147584      int nKey = fts3HashKeysize(pE);
147585      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
147586        if( nElem==nAlloc ){
147587          Fts3HashElem **aElem2;
147588          nAlloc += 16;
147589          aElem2 = (Fts3HashElem **)sqlite3_realloc(
147590              aElem, nAlloc*sizeof(Fts3HashElem *)
147591          );
147592          if( !aElem2 ){
147593            rc = SQLITE_NOMEM;
147594            nElem = 0;
147595            break;
147596          }
147597          aElem = aElem2;
147598        }
147599
147600        aElem[nElem++] = pE;
147601      }
147602    }
147603
147604    /* If more than one term matches the prefix, sort the Fts3HashElem
147605    ** objects in term order using qsort(). This uses the same comparison
147606    ** callback as is used when flushing terms to disk.
147607    */
147608    if( nElem>1 ){
147609      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
147610    }
147611
147612  }else{
147613    /* The query is a simple term lookup that matches at most one term in
147614    ** the index. All that is required is a straight hash-lookup.
147615    **
147616    ** Because the stack address of pE may be accessed via the aElem pointer
147617    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
147618    ** within this entire function, not just this "else{...}" block.
147619    */
147620    pE = fts3HashFindElem(pHash, zTerm, nTerm);
147621    if( pE ){
147622      aElem = &pE;
147623      nElem = 1;
147624    }
147625  }
147626
147627  if( nElem>0 ){
147628    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
147629    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
147630    if( !pReader ){
147631      rc = SQLITE_NOMEM;
147632    }else{
147633      memset(pReader, 0, nByte);
147634      pReader->iIdx = 0x7FFFFFFF;
147635      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
147636      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
147637    }
147638  }
147639
147640  if( bPrefix ){
147641    sqlite3_free(aElem);
147642  }
147643  *ppReader = pReader;
147644  return rc;
147645}
147646
147647/*
147648** Compare the entries pointed to by two Fts3SegReader structures.
147649** Comparison is as follows:
147650**
147651**   1) EOF is greater than not EOF.
147652**
147653**   2) The current terms (if any) are compared using memcmp(). If one
147654**      term is a prefix of another, the longer term is considered the
147655**      larger.
147656**
147657**   3) By segment age. An older segment is considered larger.
147658*/
147659static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147660  int rc;
147661  if( pLhs->aNode && pRhs->aNode ){
147662    int rc2 = pLhs->nTerm - pRhs->nTerm;
147663    if( rc2<0 ){
147664      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
147665    }else{
147666      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
147667    }
147668    if( rc==0 ){
147669      rc = rc2;
147670    }
147671  }else{
147672    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
147673  }
147674  if( rc==0 ){
147675    rc = pRhs->iIdx - pLhs->iIdx;
147676  }
147677  assert( rc!=0 );
147678  return rc;
147679}
147680
147681/*
147682** A different comparison function for SegReader structures. In this
147683** version, it is assumed that each SegReader points to an entry in
147684** a doclist for identical terms. Comparison is made as follows:
147685**
147686**   1) EOF (end of doclist in this case) is greater than not EOF.
147687**
147688**   2) By current docid.
147689**
147690**   3) By segment age. An older segment is considered larger.
147691*/
147692static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147693  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
147694  if( rc==0 ){
147695    if( pLhs->iDocid==pRhs->iDocid ){
147696      rc = pRhs->iIdx - pLhs->iIdx;
147697    }else{
147698      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
147699    }
147700  }
147701  assert( pLhs->aNode && pRhs->aNode );
147702  return rc;
147703}
147704static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147705  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
147706  if( rc==0 ){
147707    if( pLhs->iDocid==pRhs->iDocid ){
147708      rc = pRhs->iIdx - pLhs->iIdx;
147709    }else{
147710      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
147711    }
147712  }
147713  assert( pLhs->aNode && pRhs->aNode );
147714  return rc;
147715}
147716
147717/*
147718** Compare the term that the Fts3SegReader object passed as the first argument
147719** points to with the term specified by arguments zTerm and nTerm.
147720**
147721** If the pSeg iterator is already at EOF, return 0. Otherwise, return
147722** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
147723** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
147724*/
147725static int fts3SegReaderTermCmp(
147726  Fts3SegReader *pSeg,            /* Segment reader object */
147727  const char *zTerm,              /* Term to compare to */
147728  int nTerm                       /* Size of term zTerm in bytes */
147729){
147730  int res = 0;
147731  if( pSeg->aNode ){
147732    if( pSeg->nTerm>nTerm ){
147733      res = memcmp(pSeg->zTerm, zTerm, nTerm);
147734    }else{
147735      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
147736    }
147737    if( res==0 ){
147738      res = pSeg->nTerm-nTerm;
147739    }
147740  }
147741  return res;
147742}
147743
147744/*
147745** Argument apSegment is an array of nSegment elements. It is known that
147746** the final (nSegment-nSuspect) members are already in sorted order
147747** (according to the comparison function provided). This function shuffles
147748** the array around until all entries are in sorted order.
147749*/
147750static void fts3SegReaderSort(
147751  Fts3SegReader **apSegment,                     /* Array to sort entries of */
147752  int nSegment,                                  /* Size of apSegment array */
147753  int nSuspect,                                  /* Unsorted entry count */
147754  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
147755){
147756  int i;                          /* Iterator variable */
147757
147758  assert( nSuspect<=nSegment );
147759
147760  if( nSuspect==nSegment ) nSuspect--;
147761  for(i=nSuspect-1; i>=0; i--){
147762    int j;
147763    for(j=i; j<(nSegment-1); j++){
147764      Fts3SegReader *pTmp;
147765      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
147766      pTmp = apSegment[j+1];
147767      apSegment[j+1] = apSegment[j];
147768      apSegment[j] = pTmp;
147769    }
147770  }
147771
147772#ifndef NDEBUG
147773  /* Check that the list really is sorted now. */
147774  for(i=0; i<(nSuspect-1); i++){
147775    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
147776  }
147777#endif
147778}
147779
147780/*
147781** Insert a record into the %_segments table.
147782*/
147783static int fts3WriteSegment(
147784  Fts3Table *p,                   /* Virtual table handle */
147785  sqlite3_int64 iBlock,           /* Block id for new block */
147786  char *z,                        /* Pointer to buffer containing block data */
147787  int n                           /* Size of buffer z in bytes */
147788){
147789  sqlite3_stmt *pStmt;
147790  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
147791  if( rc==SQLITE_OK ){
147792    sqlite3_bind_int64(pStmt, 1, iBlock);
147793    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
147794    sqlite3_step(pStmt);
147795    rc = sqlite3_reset(pStmt);
147796  }
147797  return rc;
147798}
147799
147800/*
147801** Find the largest relative level number in the table. If successful, set
147802** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
147803** set *pnMax to zero and return an SQLite error code.
147804*/
147805SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
147806  int rc;
147807  int mxLevel = 0;
147808  sqlite3_stmt *pStmt = 0;
147809
147810  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
147811  if( rc==SQLITE_OK ){
147812    if( SQLITE_ROW==sqlite3_step(pStmt) ){
147813      mxLevel = sqlite3_column_int(pStmt, 0);
147814    }
147815    rc = sqlite3_reset(pStmt);
147816  }
147817  *pnMax = mxLevel;
147818  return rc;
147819}
147820
147821/*
147822** Insert a record into the %_segdir table.
147823*/
147824static int fts3WriteSegdir(
147825  Fts3Table *p,                   /* Virtual table handle */
147826  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
147827  int iIdx,                       /* Value for "idx" field */
147828  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
147829  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
147830  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
147831  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
147832  char *zRoot,                    /* Blob value for "root" field */
147833  int nRoot                       /* Number of bytes in buffer zRoot */
147834){
147835  sqlite3_stmt *pStmt;
147836  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
147837  if( rc==SQLITE_OK ){
147838    sqlite3_bind_int64(pStmt, 1, iLevel);
147839    sqlite3_bind_int(pStmt, 2, iIdx);
147840    sqlite3_bind_int64(pStmt, 3, iStartBlock);
147841    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
147842    if( nLeafData==0 ){
147843      sqlite3_bind_int64(pStmt, 5, iEndBlock);
147844    }else{
147845      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
147846      if( !zEnd ) return SQLITE_NOMEM;
147847      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
147848    }
147849    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
147850    sqlite3_step(pStmt);
147851    rc = sqlite3_reset(pStmt);
147852  }
147853  return rc;
147854}
147855
147856/*
147857** Return the size of the common prefix (if any) shared by zPrev and
147858** zNext, in bytes. For example,
147859**
147860**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
147861**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
147862**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
147863*/
147864static int fts3PrefixCompress(
147865  const char *zPrev,              /* Buffer containing previous term */
147866  int nPrev,                      /* Size of buffer zPrev in bytes */
147867  const char *zNext,              /* Buffer containing next term */
147868  int nNext                       /* Size of buffer zNext in bytes */
147869){
147870  int n;
147871  UNUSED_PARAMETER(nNext);
147872  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
147873  return n;
147874}
147875
147876/*
147877** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
147878** (according to memcmp) than the previous term.
147879*/
147880static int fts3NodeAddTerm(
147881  Fts3Table *p,                   /* Virtual table handle */
147882  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
147883  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
147884  const char *zTerm,              /* Pointer to buffer containing term */
147885  int nTerm                       /* Size of term in bytes */
147886){
147887  SegmentNode *pTree = *ppTree;
147888  int rc;
147889  SegmentNode *pNew;
147890
147891  /* First try to append the term to the current node. Return early if
147892  ** this is possible.
147893  */
147894  if( pTree ){
147895    int nData = pTree->nData;     /* Current size of node in bytes */
147896    int nReq = nData;             /* Required space after adding zTerm */
147897    int nPrefix;                  /* Number of bytes of prefix compression */
147898    int nSuffix;                  /* Suffix length */
147899
147900    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
147901    nSuffix = nTerm-nPrefix;
147902
147903    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
147904    if( nReq<=p->nNodeSize || !pTree->zTerm ){
147905
147906      if( nReq>p->nNodeSize ){
147907        /* An unusual case: this is the first term to be added to the node
147908        ** and the static node buffer (p->nNodeSize bytes) is not large
147909        ** enough. Use a separately malloced buffer instead This wastes
147910        ** p->nNodeSize bytes, but since this scenario only comes about when
147911        ** the database contain two terms that share a prefix of almost 2KB,
147912        ** this is not expected to be a serious problem.
147913        */
147914        assert( pTree->aData==(char *)&pTree[1] );
147915        pTree->aData = (char *)sqlite3_malloc(nReq);
147916        if( !pTree->aData ){
147917          return SQLITE_NOMEM;
147918        }
147919      }
147920
147921      if( pTree->zTerm ){
147922        /* There is no prefix-length field for first term in a node */
147923        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
147924      }
147925
147926      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
147927      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
147928      pTree->nData = nData + nSuffix;
147929      pTree->nEntry++;
147930
147931      if( isCopyTerm ){
147932        if( pTree->nMalloc<nTerm ){
147933          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
147934          if( !zNew ){
147935            return SQLITE_NOMEM;
147936          }
147937          pTree->nMalloc = nTerm*2;
147938          pTree->zMalloc = zNew;
147939        }
147940        pTree->zTerm = pTree->zMalloc;
147941        memcpy(pTree->zTerm, zTerm, nTerm);
147942        pTree->nTerm = nTerm;
147943      }else{
147944        pTree->zTerm = (char *)zTerm;
147945        pTree->nTerm = nTerm;
147946      }
147947      return SQLITE_OK;
147948    }
147949  }
147950
147951  /* If control flows to here, it was not possible to append zTerm to the
147952  ** current node. Create a new node (a right-sibling of the current node).
147953  ** If this is the first node in the tree, the term is added to it.
147954  **
147955  ** Otherwise, the term is not added to the new node, it is left empty for
147956  ** now. Instead, the term is inserted into the parent of pTree. If pTree
147957  ** has no parent, one is created here.
147958  */
147959  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
147960  if( !pNew ){
147961    return SQLITE_NOMEM;
147962  }
147963  memset(pNew, 0, sizeof(SegmentNode));
147964  pNew->nData = 1 + FTS3_VARINT_MAX;
147965  pNew->aData = (char *)&pNew[1];
147966
147967  if( pTree ){
147968    SegmentNode *pParent = pTree->pParent;
147969    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
147970    if( pTree->pParent==0 ){
147971      pTree->pParent = pParent;
147972    }
147973    pTree->pRight = pNew;
147974    pNew->pLeftmost = pTree->pLeftmost;
147975    pNew->pParent = pParent;
147976    pNew->zMalloc = pTree->zMalloc;
147977    pNew->nMalloc = pTree->nMalloc;
147978    pTree->zMalloc = 0;
147979  }else{
147980    pNew->pLeftmost = pNew;
147981    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
147982  }
147983
147984  *ppTree = pNew;
147985  return rc;
147986}
147987
147988/*
147989** Helper function for fts3NodeWrite().
147990*/
147991static int fts3TreeFinishNode(
147992  SegmentNode *pTree,
147993  int iHeight,
147994  sqlite3_int64 iLeftChild
147995){
147996  int nStart;
147997  assert( iHeight>=1 && iHeight<128 );
147998  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
147999  pTree->aData[nStart] = (char)iHeight;
148000  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
148001  return nStart;
148002}
148003
148004/*
148005** Write the buffer for the segment node pTree and all of its peers to the
148006** database. Then call this function recursively to write the parent of
148007** pTree and its peers to the database.
148008**
148009** Except, if pTree is a root node, do not write it to the database. Instead,
148010** set output variables *paRoot and *pnRoot to contain the root node.
148011**
148012** If successful, SQLITE_OK is returned and output variable *piLast is
148013** set to the largest blockid written to the database (or zero if no
148014** blocks were written to the db). Otherwise, an SQLite error code is
148015** returned.
148016*/
148017static int fts3NodeWrite(
148018  Fts3Table *p,                   /* Virtual table handle */
148019  SegmentNode *pTree,             /* SegmentNode handle */
148020  int iHeight,                    /* Height of this node in tree */
148021  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
148022  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
148023  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
148024  char **paRoot,                  /* OUT: Data for root node */
148025  int *pnRoot                     /* OUT: Size of root node in bytes */
148026){
148027  int rc = SQLITE_OK;
148028
148029  if( !pTree->pParent ){
148030    /* Root node of the tree. */
148031    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
148032    *piLast = iFree-1;
148033    *pnRoot = pTree->nData - nStart;
148034    *paRoot = &pTree->aData[nStart];
148035  }else{
148036    SegmentNode *pIter;
148037    sqlite3_int64 iNextFree = iFree;
148038    sqlite3_int64 iNextLeaf = iLeaf;
148039    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
148040      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
148041      int nWrite = pIter->nData - nStart;
148042
148043      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
148044      iNextFree++;
148045      iNextLeaf += (pIter->nEntry+1);
148046    }
148047    if( rc==SQLITE_OK ){
148048      assert( iNextLeaf==iFree );
148049      rc = fts3NodeWrite(
148050          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
148051      );
148052    }
148053  }
148054
148055  return rc;
148056}
148057
148058/*
148059** Free all memory allocations associated with the tree pTree.
148060*/
148061static void fts3NodeFree(SegmentNode *pTree){
148062  if( pTree ){
148063    SegmentNode *p = pTree->pLeftmost;
148064    fts3NodeFree(p->pParent);
148065    while( p ){
148066      SegmentNode *pRight = p->pRight;
148067      if( p->aData!=(char *)&p[1] ){
148068        sqlite3_free(p->aData);
148069      }
148070      assert( pRight==0 || p->zMalloc==0 );
148071      sqlite3_free(p->zMalloc);
148072      sqlite3_free(p);
148073      p = pRight;
148074    }
148075  }
148076}
148077
148078/*
148079** Add a term to the segment being constructed by the SegmentWriter object
148080** *ppWriter. When adding the first term to a segment, *ppWriter should
148081** be passed NULL. This function will allocate a new SegmentWriter object
148082** and return it via the input/output variable *ppWriter in this case.
148083**
148084** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
148085*/
148086static int fts3SegWriterAdd(
148087  Fts3Table *p,                   /* Virtual table handle */
148088  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
148089  int isCopyTerm,                 /* True if buffer zTerm must be copied */
148090  const char *zTerm,              /* Pointer to buffer containing term */
148091  int nTerm,                      /* Size of term in bytes */
148092  const char *aDoclist,           /* Pointer to buffer containing doclist */
148093  int nDoclist                    /* Size of doclist in bytes */
148094){
148095  int nPrefix;                    /* Size of term prefix in bytes */
148096  int nSuffix;                    /* Size of term suffix in bytes */
148097  int nReq;                       /* Number of bytes required on leaf page */
148098  int nData;
148099  SegmentWriter *pWriter = *ppWriter;
148100
148101  if( !pWriter ){
148102    int rc;
148103    sqlite3_stmt *pStmt;
148104
148105    /* Allocate the SegmentWriter structure */
148106    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
148107    if( !pWriter ) return SQLITE_NOMEM;
148108    memset(pWriter, 0, sizeof(SegmentWriter));
148109    *ppWriter = pWriter;
148110
148111    /* Allocate a buffer in which to accumulate data */
148112    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
148113    if( !pWriter->aData ) return SQLITE_NOMEM;
148114    pWriter->nSize = p->nNodeSize;
148115
148116    /* Find the next free blockid in the %_segments table */
148117    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
148118    if( rc!=SQLITE_OK ) return rc;
148119    if( SQLITE_ROW==sqlite3_step(pStmt) ){
148120      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
148121      pWriter->iFirst = pWriter->iFree;
148122    }
148123    rc = sqlite3_reset(pStmt);
148124    if( rc!=SQLITE_OK ) return rc;
148125  }
148126  nData = pWriter->nData;
148127
148128  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
148129  nSuffix = nTerm-nPrefix;
148130
148131  /* Figure out how many bytes are required by this new entry */
148132  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
148133    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
148134    nSuffix +                               /* Term suffix */
148135    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
148136    nDoclist;                               /* Doclist data */
148137
148138  if( nData>0 && nData+nReq>p->nNodeSize ){
148139    int rc;
148140
148141    /* The current leaf node is full. Write it out to the database. */
148142    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
148143    if( rc!=SQLITE_OK ) return rc;
148144    p->nLeafAdd++;
148145
148146    /* Add the current term to the interior node tree. The term added to
148147    ** the interior tree must:
148148    **
148149    **   a) be greater than the largest term on the leaf node just written
148150    **      to the database (still available in pWriter->zTerm), and
148151    **
148152    **   b) be less than or equal to the term about to be added to the new
148153    **      leaf node (zTerm/nTerm).
148154    **
148155    ** In other words, it must be the prefix of zTerm 1 byte longer than
148156    ** the common prefix (if any) of zTerm and pWriter->zTerm.
148157    */
148158    assert( nPrefix<nTerm );
148159    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
148160    if( rc!=SQLITE_OK ) return rc;
148161
148162    nData = 0;
148163    pWriter->nTerm = 0;
148164
148165    nPrefix = 0;
148166    nSuffix = nTerm;
148167    nReq = 1 +                              /* varint containing prefix size */
148168      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
148169      nTerm +                               /* Term suffix */
148170      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
148171      nDoclist;                             /* Doclist data */
148172  }
148173
148174  /* Increase the total number of bytes written to account for the new entry. */
148175  pWriter->nLeafData += nReq;
148176
148177  /* If the buffer currently allocated is too small for this entry, realloc
148178  ** the buffer to make it large enough.
148179  */
148180  if( nReq>pWriter->nSize ){
148181    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
148182    if( !aNew ) return SQLITE_NOMEM;
148183    pWriter->aData = aNew;
148184    pWriter->nSize = nReq;
148185  }
148186  assert( nData+nReq<=pWriter->nSize );
148187
148188  /* Append the prefix-compressed term and doclist to the buffer. */
148189  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
148190  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
148191  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
148192  nData += nSuffix;
148193  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
148194  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
148195  pWriter->nData = nData + nDoclist;
148196
148197  /* Save the current term so that it can be used to prefix-compress the next.
148198  ** If the isCopyTerm parameter is true, then the buffer pointed to by
148199  ** zTerm is transient, so take a copy of the term data. Otherwise, just
148200  ** store a copy of the pointer.
148201  */
148202  if( isCopyTerm ){
148203    if( nTerm>pWriter->nMalloc ){
148204      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
148205      if( !zNew ){
148206        return SQLITE_NOMEM;
148207      }
148208      pWriter->nMalloc = nTerm*2;
148209      pWriter->zMalloc = zNew;
148210      pWriter->zTerm = zNew;
148211    }
148212    assert( pWriter->zTerm==pWriter->zMalloc );
148213    memcpy(pWriter->zTerm, zTerm, nTerm);
148214  }else{
148215    pWriter->zTerm = (char *)zTerm;
148216  }
148217  pWriter->nTerm = nTerm;
148218
148219  return SQLITE_OK;
148220}
148221
148222/*
148223** Flush all data associated with the SegmentWriter object pWriter to the
148224** database. This function must be called after all terms have been added
148225** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
148226** returned. Otherwise, an SQLite error code.
148227*/
148228static int fts3SegWriterFlush(
148229  Fts3Table *p,                   /* Virtual table handle */
148230  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
148231  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
148232  int iIdx                        /* Value for 'idx' column of %_segdir */
148233){
148234  int rc;                         /* Return code */
148235  if( pWriter->pTree ){
148236    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
148237    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
148238    char *zRoot = NULL;           /* Pointer to buffer containing root node */
148239    int nRoot = 0;                /* Size of buffer zRoot */
148240
148241    iLastLeaf = pWriter->iFree;
148242    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
148243    if( rc==SQLITE_OK ){
148244      rc = fts3NodeWrite(p, pWriter->pTree, 1,
148245          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
148246    }
148247    if( rc==SQLITE_OK ){
148248      rc = fts3WriteSegdir(p, iLevel, iIdx,
148249          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
148250    }
148251  }else{
148252    /* The entire tree fits on the root node. Write it to the segdir table. */
148253    rc = fts3WriteSegdir(p, iLevel, iIdx,
148254        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
148255  }
148256  p->nLeafAdd++;
148257  return rc;
148258}
148259
148260/*
148261** Release all memory held by the SegmentWriter object passed as the
148262** first argument.
148263*/
148264static void fts3SegWriterFree(SegmentWriter *pWriter){
148265  if( pWriter ){
148266    sqlite3_free(pWriter->aData);
148267    sqlite3_free(pWriter->zMalloc);
148268    fts3NodeFree(pWriter->pTree);
148269    sqlite3_free(pWriter);
148270  }
148271}
148272
148273/*
148274** The first value in the apVal[] array is assumed to contain an integer.
148275** This function tests if there exist any documents with docid values that
148276** are different from that integer. i.e. if deleting the document with docid
148277** pRowid would mean the FTS3 table were empty.
148278**
148279** If successful, *pisEmpty is set to true if the table is empty except for
148280** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
148281** error occurs, an SQLite error code is returned.
148282*/
148283static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
148284  sqlite3_stmt *pStmt;
148285  int rc;
148286  if( p->zContentTbl ){
148287    /* If using the content=xxx option, assume the table is never empty */
148288    *pisEmpty = 0;
148289    rc = SQLITE_OK;
148290  }else{
148291    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
148292    if( rc==SQLITE_OK ){
148293      if( SQLITE_ROW==sqlite3_step(pStmt) ){
148294        *pisEmpty = sqlite3_column_int(pStmt, 0);
148295      }
148296      rc = sqlite3_reset(pStmt);
148297    }
148298  }
148299  return rc;
148300}
148301
148302/*
148303** Set *pnMax to the largest segment level in the database for the index
148304** iIndex.
148305**
148306** Segment levels are stored in the 'level' column of the %_segdir table.
148307**
148308** Return SQLITE_OK if successful, or an SQLite error code if not.
148309*/
148310static int fts3SegmentMaxLevel(
148311  Fts3Table *p,
148312  int iLangid,
148313  int iIndex,
148314  sqlite3_int64 *pnMax
148315){
148316  sqlite3_stmt *pStmt;
148317  int rc;
148318  assert( iIndex>=0 && iIndex<p->nIndex );
148319
148320  /* Set pStmt to the compiled version of:
148321  **
148322  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
148323  **
148324  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
148325  */
148326  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
148327  if( rc!=SQLITE_OK ) return rc;
148328  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
148329  sqlite3_bind_int64(pStmt, 2,
148330      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
148331  );
148332  if( SQLITE_ROW==sqlite3_step(pStmt) ){
148333    *pnMax = sqlite3_column_int64(pStmt, 0);
148334  }
148335  return sqlite3_reset(pStmt);
148336}
148337
148338/*
148339** iAbsLevel is an absolute level that may be assumed to exist within
148340** the database. This function checks if it is the largest level number
148341** within its index. Assuming no error occurs, *pbMax is set to 1 if
148342** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
148343** is returned. If an error occurs, an error code is returned and the
148344** final value of *pbMax is undefined.
148345*/
148346static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
148347
148348  /* Set pStmt to the compiled version of:
148349  **
148350  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
148351  **
148352  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
148353  */
148354  sqlite3_stmt *pStmt;
148355  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
148356  if( rc!=SQLITE_OK ) return rc;
148357  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
148358  sqlite3_bind_int64(pStmt, 2,
148359      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
148360  );
148361
148362  *pbMax = 0;
148363  if( SQLITE_ROW==sqlite3_step(pStmt) ){
148364    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
148365  }
148366  return sqlite3_reset(pStmt);
148367}
148368
148369/*
148370** Delete all entries in the %_segments table associated with the segment
148371** opened with seg-reader pSeg. This function does not affect the contents
148372** of the %_segdir table.
148373*/
148374static int fts3DeleteSegment(
148375  Fts3Table *p,                   /* FTS table handle */
148376  Fts3SegReader *pSeg             /* Segment to delete */
148377){
148378  int rc = SQLITE_OK;             /* Return code */
148379  if( pSeg->iStartBlock ){
148380    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
148381    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
148382    if( rc==SQLITE_OK ){
148383      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
148384      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
148385      sqlite3_step(pDelete);
148386      rc = sqlite3_reset(pDelete);
148387    }
148388  }
148389  return rc;
148390}
148391
148392/*
148393** This function is used after merging multiple segments into a single large
148394** segment to delete the old, now redundant, segment b-trees. Specifically,
148395** it:
148396**
148397**   1) Deletes all %_segments entries for the segments associated with
148398**      each of the SegReader objects in the array passed as the third
148399**      argument, and
148400**
148401**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
148402**      entries regardless of level if (iLevel<0).
148403**
148404** SQLITE_OK is returned if successful, otherwise an SQLite error code.
148405*/
148406static int fts3DeleteSegdir(
148407  Fts3Table *p,                   /* Virtual table handle */
148408  int iLangid,                    /* Language id */
148409  int iIndex,                     /* Index for p->aIndex */
148410  int iLevel,                     /* Level of %_segdir entries to delete */
148411  Fts3SegReader **apSegment,      /* Array of SegReader objects */
148412  int nReader                     /* Size of array apSegment */
148413){
148414  int rc = SQLITE_OK;             /* Return Code */
148415  int i;                          /* Iterator variable */
148416  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
148417
148418  for(i=0; rc==SQLITE_OK && i<nReader; i++){
148419    rc = fts3DeleteSegment(p, apSegment[i]);
148420  }
148421  if( rc!=SQLITE_OK ){
148422    return rc;
148423  }
148424
148425  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
148426  if( iLevel==FTS3_SEGCURSOR_ALL ){
148427    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
148428    if( rc==SQLITE_OK ){
148429      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
148430      sqlite3_bind_int64(pDelete, 2,
148431          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
148432      );
148433    }
148434  }else{
148435    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
148436    if( rc==SQLITE_OK ){
148437      sqlite3_bind_int64(
148438          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
148439      );
148440    }
148441  }
148442
148443  if( rc==SQLITE_OK ){
148444    sqlite3_step(pDelete);
148445    rc = sqlite3_reset(pDelete);
148446  }
148447
148448  return rc;
148449}
148450
148451/*
148452** When this function is called, buffer *ppList (size *pnList bytes) contains
148453** a position list that may (or may not) feature multiple columns. This
148454** function adjusts the pointer *ppList and the length *pnList so that they
148455** identify the subset of the position list that corresponds to column iCol.
148456**
148457** If there are no entries in the input position list for column iCol, then
148458** *pnList is set to zero before returning.
148459**
148460** If parameter bZero is non-zero, then any part of the input list following
148461** the end of the output list is zeroed before returning.
148462*/
148463static void fts3ColumnFilter(
148464  int iCol,                       /* Column to filter on */
148465  int bZero,                      /* Zero out anything following *ppList */
148466  char **ppList,                  /* IN/OUT: Pointer to position list */
148467  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
148468){
148469  char *pList = *ppList;
148470  int nList = *pnList;
148471  char *pEnd = &pList[nList];
148472  int iCurrent = 0;
148473  char *p = pList;
148474
148475  assert( iCol>=0 );
148476  while( 1 ){
148477    char c = 0;
148478    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
148479
148480    if( iCol==iCurrent ){
148481      nList = (int)(p - pList);
148482      break;
148483    }
148484
148485    nList -= (int)(p - pList);
148486    pList = p;
148487    if( nList==0 ){
148488      break;
148489    }
148490    p = &pList[1];
148491    p += fts3GetVarint32(p, &iCurrent);
148492  }
148493
148494  if( bZero && &pList[nList]!=pEnd ){
148495    memset(&pList[nList], 0, pEnd - &pList[nList]);
148496  }
148497  *ppList = pList;
148498  *pnList = nList;
148499}
148500
148501/*
148502** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
148503** existing data). Grow the buffer if required.
148504**
148505** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
148506** trying to resize the buffer, return SQLITE_NOMEM.
148507*/
148508static int fts3MsrBufferData(
148509  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
148510  char *pList,
148511  int nList
148512){
148513  if( nList>pMsr->nBuffer ){
148514    char *pNew;
148515    pMsr->nBuffer = nList*2;
148516    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
148517    if( !pNew ) return SQLITE_NOMEM;
148518    pMsr->aBuffer = pNew;
148519  }
148520
148521  memcpy(pMsr->aBuffer, pList, nList);
148522  return SQLITE_OK;
148523}
148524
148525SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
148526  Fts3Table *p,                   /* Virtual table handle */
148527  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
148528  sqlite3_int64 *piDocid,         /* OUT: Docid value */
148529  char **paPoslist,               /* OUT: Pointer to position list */
148530  int *pnPoslist                  /* OUT: Size of position list in bytes */
148531){
148532  int nMerge = pMsr->nAdvance;
148533  Fts3SegReader **apSegment = pMsr->apSegment;
148534  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148535    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148536  );
148537
148538  if( nMerge==0 ){
148539    *paPoslist = 0;
148540    return SQLITE_OK;
148541  }
148542
148543  while( 1 ){
148544    Fts3SegReader *pSeg;
148545    pSeg = pMsr->apSegment[0];
148546
148547    if( pSeg->pOffsetList==0 ){
148548      *paPoslist = 0;
148549      break;
148550    }else{
148551      int rc;
148552      char *pList;
148553      int nList;
148554      int j;
148555      sqlite3_int64 iDocid = apSegment[0]->iDocid;
148556
148557      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
148558      j = 1;
148559      while( rc==SQLITE_OK
148560        && j<nMerge
148561        && apSegment[j]->pOffsetList
148562        && apSegment[j]->iDocid==iDocid
148563      ){
148564        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
148565        j++;
148566      }
148567      if( rc!=SQLITE_OK ) return rc;
148568      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
148569
148570      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
148571        rc = fts3MsrBufferData(pMsr, pList, nList+1);
148572        if( rc!=SQLITE_OK ) return rc;
148573        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
148574        pList = pMsr->aBuffer;
148575      }
148576
148577      if( pMsr->iColFilter>=0 ){
148578        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
148579      }
148580
148581      if( nList>0 ){
148582        *paPoslist = pList;
148583        *piDocid = iDocid;
148584        *pnPoslist = nList;
148585        break;
148586      }
148587    }
148588  }
148589
148590  return SQLITE_OK;
148591}
148592
148593static int fts3SegReaderStart(
148594  Fts3Table *p,                   /* Virtual table handle */
148595  Fts3MultiSegReader *pCsr,       /* Cursor object */
148596  const char *zTerm,              /* Term searched for (or NULL) */
148597  int nTerm                       /* Length of zTerm in bytes */
148598){
148599  int i;
148600  int nSeg = pCsr->nSegment;
148601
148602  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
148603  ** for, then advance each segment iterator until it points to a term of
148604  ** equal or greater value than the specified term. This prevents many
148605  ** unnecessary merge/sort operations for the case where single segment
148606  ** b-tree leaf nodes contain more than one term.
148607  */
148608  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
148609    int res = 0;
148610    Fts3SegReader *pSeg = pCsr->apSegment[i];
148611    do {
148612      int rc = fts3SegReaderNext(p, pSeg, 0);
148613      if( rc!=SQLITE_OK ) return rc;
148614    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
148615
148616    if( pSeg->bLookup && res!=0 ){
148617      fts3SegReaderSetEof(pSeg);
148618    }
148619  }
148620  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
148621
148622  return SQLITE_OK;
148623}
148624
148625SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
148626  Fts3Table *p,                   /* Virtual table handle */
148627  Fts3MultiSegReader *pCsr,       /* Cursor object */
148628  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
148629){
148630  pCsr->pFilter = pFilter;
148631  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
148632}
148633
148634SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
148635  Fts3Table *p,                   /* Virtual table handle */
148636  Fts3MultiSegReader *pCsr,       /* Cursor object */
148637  int iCol,                       /* Column to match on. */
148638  const char *zTerm,              /* Term to iterate through a doclist for */
148639  int nTerm                       /* Number of bytes in zTerm */
148640){
148641  int i;
148642  int rc;
148643  int nSegment = pCsr->nSegment;
148644  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148645    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148646  );
148647
148648  assert( pCsr->pFilter==0 );
148649  assert( zTerm && nTerm>0 );
148650
148651  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
148652  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
148653  if( rc!=SQLITE_OK ) return rc;
148654
148655  /* Determine how many of the segments actually point to zTerm/nTerm. */
148656  for(i=0; i<nSegment; i++){
148657    Fts3SegReader *pSeg = pCsr->apSegment[i];
148658    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
148659      break;
148660    }
148661  }
148662  pCsr->nAdvance = i;
148663
148664  /* Advance each of the segments to point to the first docid. */
148665  for(i=0; i<pCsr->nAdvance; i++){
148666    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
148667    if( rc!=SQLITE_OK ) return rc;
148668  }
148669  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
148670
148671  assert( iCol<0 || iCol<p->nColumn );
148672  pCsr->iColFilter = iCol;
148673
148674  return SQLITE_OK;
148675}
148676
148677/*
148678** This function is called on a MultiSegReader that has been started using
148679** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
148680** have been made. Calling this function puts the MultiSegReader in such
148681** a state that if the next two calls are:
148682**
148683**   sqlite3Fts3SegReaderStart()
148684**   sqlite3Fts3SegReaderStep()
148685**
148686** then the entire doclist for the term is available in
148687** MultiSegReader.aDoclist/nDoclist.
148688*/
148689SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
148690  int i;                          /* Used to iterate through segment-readers */
148691
148692  assert( pCsr->zTerm==0 );
148693  assert( pCsr->nTerm==0 );
148694  assert( pCsr->aDoclist==0 );
148695  assert( pCsr->nDoclist==0 );
148696
148697  pCsr->nAdvance = 0;
148698  pCsr->bRestart = 1;
148699  for(i=0; i<pCsr->nSegment; i++){
148700    pCsr->apSegment[i]->pOffsetList = 0;
148701    pCsr->apSegment[i]->nOffsetList = 0;
148702    pCsr->apSegment[i]->iDocid = 0;
148703  }
148704
148705  return SQLITE_OK;
148706}
148707
148708
148709SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
148710  Fts3Table *p,                   /* Virtual table handle */
148711  Fts3MultiSegReader *pCsr        /* Cursor object */
148712){
148713  int rc = SQLITE_OK;
148714
148715  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
148716  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
148717  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
148718  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
148719  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
148720  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
148721
148722  Fts3SegReader **apSegment = pCsr->apSegment;
148723  int nSegment = pCsr->nSegment;
148724  Fts3SegFilter *pFilter = pCsr->pFilter;
148725  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148726    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148727  );
148728
148729  if( pCsr->nSegment==0 ) return SQLITE_OK;
148730
148731  do {
148732    int nMerge;
148733    int i;
148734
148735    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
148736    ** forward. Then sort the list in order of current term again.
148737    */
148738    for(i=0; i<pCsr->nAdvance; i++){
148739      Fts3SegReader *pSeg = apSegment[i];
148740      if( pSeg->bLookup ){
148741        fts3SegReaderSetEof(pSeg);
148742      }else{
148743        rc = fts3SegReaderNext(p, pSeg, 0);
148744      }
148745      if( rc!=SQLITE_OK ) return rc;
148746    }
148747    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
148748    pCsr->nAdvance = 0;
148749
148750    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
148751    assert( rc==SQLITE_OK );
148752    if( apSegment[0]->aNode==0 ) break;
148753
148754    pCsr->nTerm = apSegment[0]->nTerm;
148755    pCsr->zTerm = apSegment[0]->zTerm;
148756
148757    /* If this is a prefix-search, and if the term that apSegment[0] points
148758    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
148759    ** required callbacks have been made. In this case exit early.
148760    **
148761    ** Similarly, if this is a search for an exact match, and the first term
148762    ** of segment apSegment[0] is not a match, exit early.
148763    */
148764    if( pFilter->zTerm && !isScan ){
148765      if( pCsr->nTerm<pFilter->nTerm
148766       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
148767       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
148768      ){
148769        break;
148770      }
148771    }
148772
148773    nMerge = 1;
148774    while( nMerge<nSegment
148775        && apSegment[nMerge]->aNode
148776        && apSegment[nMerge]->nTerm==pCsr->nTerm
148777        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
148778    ){
148779      nMerge++;
148780    }
148781
148782    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
148783    if( nMerge==1
148784     && !isIgnoreEmpty
148785     && !isFirst
148786     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
148787    ){
148788      pCsr->nDoclist = apSegment[0]->nDoclist;
148789      if( fts3SegReaderIsPending(apSegment[0]) ){
148790        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
148791        pCsr->aDoclist = pCsr->aBuffer;
148792      }else{
148793        pCsr->aDoclist = apSegment[0]->aDoclist;
148794      }
148795      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
148796    }else{
148797      int nDoclist = 0;           /* Size of doclist */
148798      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
148799
148800      /* The current term of the first nMerge entries in the array
148801      ** of Fts3SegReader objects is the same. The doclists must be merged
148802      ** and a single term returned with the merged doclist.
148803      */
148804      for(i=0; i<nMerge; i++){
148805        fts3SegReaderFirstDocid(p, apSegment[i]);
148806      }
148807      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
148808      while( apSegment[0]->pOffsetList ){
148809        int j;                    /* Number of segments that share a docid */
148810        char *pList = 0;
148811        int nList = 0;
148812        int nByte;
148813        sqlite3_int64 iDocid = apSegment[0]->iDocid;
148814        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
148815        j = 1;
148816        while( j<nMerge
148817            && apSegment[j]->pOffsetList
148818            && apSegment[j]->iDocid==iDocid
148819        ){
148820          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
148821          j++;
148822        }
148823
148824        if( isColFilter ){
148825          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
148826        }
148827
148828        if( !isIgnoreEmpty || nList>0 ){
148829
148830          /* Calculate the 'docid' delta value to write into the merged
148831          ** doclist. */
148832          sqlite3_int64 iDelta;
148833          if( p->bDescIdx && nDoclist>0 ){
148834            iDelta = iPrev - iDocid;
148835          }else{
148836            iDelta = iDocid - iPrev;
148837          }
148838          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
148839          assert( nDoclist>0 || iDelta==iDocid );
148840
148841          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
148842          if( nDoclist+nByte>pCsr->nBuffer ){
148843            char *aNew;
148844            pCsr->nBuffer = (nDoclist+nByte)*2;
148845            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
148846            if( !aNew ){
148847              return SQLITE_NOMEM;
148848            }
148849            pCsr->aBuffer = aNew;
148850          }
148851
148852          if( isFirst ){
148853            char *a = &pCsr->aBuffer[nDoclist];
148854            int nWrite;
148855
148856            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
148857            if( nWrite ){
148858              iPrev = iDocid;
148859              nDoclist += nWrite;
148860            }
148861          }else{
148862            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
148863            iPrev = iDocid;
148864            if( isRequirePos ){
148865              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
148866              nDoclist += nList;
148867              pCsr->aBuffer[nDoclist++] = '\0';
148868            }
148869          }
148870        }
148871
148872        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
148873      }
148874      if( nDoclist>0 ){
148875        pCsr->aDoclist = pCsr->aBuffer;
148876        pCsr->nDoclist = nDoclist;
148877        rc = SQLITE_ROW;
148878      }
148879    }
148880    pCsr->nAdvance = nMerge;
148881  }while( rc==SQLITE_OK );
148882
148883  return rc;
148884}
148885
148886
148887SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
148888  Fts3MultiSegReader *pCsr       /* Cursor object */
148889){
148890  if( pCsr ){
148891    int i;
148892    for(i=0; i<pCsr->nSegment; i++){
148893      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
148894    }
148895    sqlite3_free(pCsr->apSegment);
148896    sqlite3_free(pCsr->aBuffer);
148897
148898    pCsr->nSegment = 0;
148899    pCsr->apSegment = 0;
148900    pCsr->aBuffer = 0;
148901  }
148902}
148903
148904/*
148905** Decode the "end_block" field, selected by column iCol of the SELECT
148906** statement passed as the first argument.
148907**
148908** The "end_block" field may contain either an integer, or a text field
148909** containing the text representation of two non-negative integers separated
148910** by one or more space (0x20) characters. In the first case, set *piEndBlock
148911** to the integer value and *pnByte to zero before returning. In the second,
148912** set *piEndBlock to the first value and *pnByte to the second.
148913*/
148914static void fts3ReadEndBlockField(
148915  sqlite3_stmt *pStmt,
148916  int iCol,
148917  i64 *piEndBlock,
148918  i64 *pnByte
148919){
148920  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
148921  if( zText ){
148922    int i;
148923    int iMul = 1;
148924    i64 iVal = 0;
148925    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
148926      iVal = iVal*10 + (zText[i] - '0');
148927    }
148928    *piEndBlock = iVal;
148929    while( zText[i]==' ' ) i++;
148930    iVal = 0;
148931    if( zText[i]=='-' ){
148932      i++;
148933      iMul = -1;
148934    }
148935    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
148936      iVal = iVal*10 + (zText[i] - '0');
148937    }
148938    *pnByte = (iVal * (i64)iMul);
148939  }
148940}
148941
148942
148943/*
148944** A segment of size nByte bytes has just been written to absolute level
148945** iAbsLevel. Promote any segments that should be promoted as a result.
148946*/
148947static int fts3PromoteSegments(
148948  Fts3Table *p,                   /* FTS table handle */
148949  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
148950  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
148951){
148952  int rc = SQLITE_OK;
148953  sqlite3_stmt *pRange;
148954
148955  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
148956
148957  if( rc==SQLITE_OK ){
148958    int bOk = 0;
148959    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
148960    i64 nLimit = (nByte*3)/2;
148961
148962    /* Loop through all entries in the %_segdir table corresponding to
148963    ** segments in this index on levels greater than iAbsLevel. If there is
148964    ** at least one such segment, and it is possible to determine that all
148965    ** such segments are smaller than nLimit bytes in size, they will be
148966    ** promoted to level iAbsLevel.  */
148967    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
148968    sqlite3_bind_int64(pRange, 2, iLast);
148969    while( SQLITE_ROW==sqlite3_step(pRange) ){
148970      i64 nSize = 0, dummy;
148971      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
148972      if( nSize<=0 || nSize>nLimit ){
148973        /* If nSize==0, then the %_segdir.end_block field does not not
148974        ** contain a size value. This happens if it was written by an
148975        ** old version of FTS. In this case it is not possible to determine
148976        ** the size of the segment, and so segment promotion does not
148977        ** take place.  */
148978        bOk = 0;
148979        break;
148980      }
148981      bOk = 1;
148982    }
148983    rc = sqlite3_reset(pRange);
148984
148985    if( bOk ){
148986      int iIdx = 0;
148987      sqlite3_stmt *pUpdate1 = 0;
148988      sqlite3_stmt *pUpdate2 = 0;
148989
148990      if( rc==SQLITE_OK ){
148991        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
148992      }
148993      if( rc==SQLITE_OK ){
148994        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
148995      }
148996
148997      if( rc==SQLITE_OK ){
148998
148999        /* Loop through all %_segdir entries for segments in this index with
149000        ** levels equal to or greater than iAbsLevel. As each entry is visited,
149001        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
149002        ** oldest segment in the range, 1 for the next oldest, and so on.
149003        **
149004        ** In other words, move all segments being promoted to level -1,
149005        ** setting the "idx" fields as appropriate to keep them in the same
149006        ** order. The contents of level -1 (which is never used, except
149007        ** transiently here), will be moved back to level iAbsLevel below.  */
149008        sqlite3_bind_int64(pRange, 1, iAbsLevel);
149009        while( SQLITE_ROW==sqlite3_step(pRange) ){
149010          sqlite3_bind_int(pUpdate1, 1, iIdx++);
149011          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
149012          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
149013          sqlite3_step(pUpdate1);
149014          rc = sqlite3_reset(pUpdate1);
149015          if( rc!=SQLITE_OK ){
149016            sqlite3_reset(pRange);
149017            break;
149018          }
149019        }
149020      }
149021      if( rc==SQLITE_OK ){
149022        rc = sqlite3_reset(pRange);
149023      }
149024
149025      /* Move level -1 to level iAbsLevel */
149026      if( rc==SQLITE_OK ){
149027        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
149028        sqlite3_step(pUpdate2);
149029        rc = sqlite3_reset(pUpdate2);
149030      }
149031    }
149032  }
149033
149034
149035  return rc;
149036}
149037
149038/*
149039** Merge all level iLevel segments in the database into a single
149040** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
149041** single segment with a level equal to the numerically largest level
149042** currently present in the database.
149043**
149044** If this function is called with iLevel<0, but there is only one
149045** segment in the database, SQLITE_DONE is returned immediately.
149046** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
149047** an SQLite error code is returned.
149048*/
149049static int fts3SegmentMerge(
149050  Fts3Table *p,
149051  int iLangid,                    /* Language id to merge */
149052  int iIndex,                     /* Index in p->aIndex[] to merge */
149053  int iLevel                      /* Level to merge */
149054){
149055  int rc;                         /* Return code */
149056  int iIdx = 0;                   /* Index of new segment */
149057  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
149058  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
149059  Fts3SegFilter filter;           /* Segment term filter condition */
149060  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
149061  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
149062  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
149063
149064  assert( iLevel==FTS3_SEGCURSOR_ALL
149065       || iLevel==FTS3_SEGCURSOR_PENDING
149066       || iLevel>=0
149067  );
149068  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
149069  assert( iIndex>=0 && iIndex<p->nIndex );
149070
149071  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
149072  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
149073
149074  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
149075    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
149076    if( rc!=SQLITE_OK ) goto finished;
149077  }
149078
149079  if( iLevel==FTS3_SEGCURSOR_ALL ){
149080    /* This call is to merge all segments in the database to a single
149081    ** segment. The level of the new segment is equal to the numerically
149082    ** greatest segment level currently present in the database for this
149083    ** index. The idx of the new segment is always 0.  */
149084    if( csr.nSegment==1 ){
149085      rc = SQLITE_DONE;
149086      goto finished;
149087    }
149088    iNewLevel = iMaxLevel;
149089    bIgnoreEmpty = 1;
149090
149091  }else{
149092    /* This call is to merge all segments at level iLevel. find the next
149093    ** available segment index at level iLevel+1. The call to
149094    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
149095    ** a single iLevel+2 segment if necessary.  */
149096    assert( FTS3_SEGCURSOR_PENDING==-1 );
149097    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
149098    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
149099    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
149100  }
149101  if( rc!=SQLITE_OK ) goto finished;
149102
149103  assert( csr.nSegment>0 );
149104  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
149105  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
149106
149107  memset(&filter, 0, sizeof(Fts3SegFilter));
149108  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
149109  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
149110
149111  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
149112  while( SQLITE_OK==rc ){
149113    rc = sqlite3Fts3SegReaderStep(p, &csr);
149114    if( rc!=SQLITE_ROW ) break;
149115    rc = fts3SegWriterAdd(p, &pWriter, 1,
149116        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
149117  }
149118  if( rc!=SQLITE_OK ) goto finished;
149119  assert( pWriter || bIgnoreEmpty );
149120
149121  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
149122    rc = fts3DeleteSegdir(
149123        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
149124    );
149125    if( rc!=SQLITE_OK ) goto finished;
149126  }
149127  if( pWriter ){
149128    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
149129    if( rc==SQLITE_OK ){
149130      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
149131        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
149132      }
149133    }
149134  }
149135
149136 finished:
149137  fts3SegWriterFree(pWriter);
149138  sqlite3Fts3SegReaderFinish(&csr);
149139  return rc;
149140}
149141
149142
149143/*
149144** Flush the contents of pendingTerms to level 0 segments.
149145*/
149146SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
149147  int rc = SQLITE_OK;
149148  int i;
149149
149150  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
149151    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
149152    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
149153  }
149154  sqlite3Fts3PendingTermsClear(p);
149155
149156  /* Determine the auto-incr-merge setting if unknown.  If enabled,
149157  ** estimate the number of leaf blocks of content to be written
149158  */
149159  if( rc==SQLITE_OK && p->bHasStat
149160   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
149161  ){
149162    sqlite3_stmt *pStmt = 0;
149163    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
149164    if( rc==SQLITE_OK ){
149165      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
149166      rc = sqlite3_step(pStmt);
149167      if( rc==SQLITE_ROW ){
149168        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
149169        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
149170      }else if( rc==SQLITE_DONE ){
149171        p->nAutoincrmerge = 0;
149172      }
149173      rc = sqlite3_reset(pStmt);
149174    }
149175  }
149176  return rc;
149177}
149178
149179/*
149180** Encode N integers as varints into a blob.
149181*/
149182static void fts3EncodeIntArray(
149183  int N,             /* The number of integers to encode */
149184  u32 *a,            /* The integer values */
149185  char *zBuf,        /* Write the BLOB here */
149186  int *pNBuf         /* Write number of bytes if zBuf[] used here */
149187){
149188  int i, j;
149189  for(i=j=0; i<N; i++){
149190    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
149191  }
149192  *pNBuf = j;
149193}
149194
149195/*
149196** Decode a blob of varints into N integers
149197*/
149198static void fts3DecodeIntArray(
149199  int N,             /* The number of integers to decode */
149200  u32 *a,            /* Write the integer values */
149201  const char *zBuf,  /* The BLOB containing the varints */
149202  int nBuf           /* size of the BLOB */
149203){
149204  int i, j;
149205  UNUSED_PARAMETER(nBuf);
149206  for(i=j=0; i<N; i++){
149207    sqlite3_int64 x;
149208    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
149209    assert(j<=nBuf);
149210    a[i] = (u32)(x & 0xffffffff);
149211  }
149212}
149213
149214/*
149215** Insert the sizes (in tokens) for each column of the document
149216** with docid equal to p->iPrevDocid.  The sizes are encoded as
149217** a blob of varints.
149218*/
149219static void fts3InsertDocsize(
149220  int *pRC,                       /* Result code */
149221  Fts3Table *p,                   /* Table into which to insert */
149222  u32 *aSz                        /* Sizes of each column, in tokens */
149223){
149224  char *pBlob;             /* The BLOB encoding of the document size */
149225  int nBlob;               /* Number of bytes in the BLOB */
149226  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
149227  int rc;                  /* Result code from subfunctions */
149228
149229  if( *pRC ) return;
149230  pBlob = sqlite3_malloc( 10*p->nColumn );
149231  if( pBlob==0 ){
149232    *pRC = SQLITE_NOMEM;
149233    return;
149234  }
149235  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
149236  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
149237  if( rc ){
149238    sqlite3_free(pBlob);
149239    *pRC = rc;
149240    return;
149241  }
149242  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
149243  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
149244  sqlite3_step(pStmt);
149245  *pRC = sqlite3_reset(pStmt);
149246}
149247
149248/*
149249** Record 0 of the %_stat table contains a blob consisting of N varints,
149250** where N is the number of user defined columns in the fts3 table plus
149251** two. If nCol is the number of user defined columns, then values of the
149252** varints are set as follows:
149253**
149254**   Varint 0:       Total number of rows in the table.
149255**
149256**   Varint 1..nCol: For each column, the total number of tokens stored in
149257**                   the column for all rows of the table.
149258**
149259**   Varint 1+nCol:  The total size, in bytes, of all text values in all
149260**                   columns of all rows of the table.
149261**
149262*/
149263static void fts3UpdateDocTotals(
149264  int *pRC,                       /* The result code */
149265  Fts3Table *p,                   /* Table being updated */
149266  u32 *aSzIns,                    /* Size increases */
149267  u32 *aSzDel,                    /* Size decreases */
149268  int nChng                       /* Change in the number of documents */
149269){
149270  char *pBlob;             /* Storage for BLOB written into %_stat */
149271  int nBlob;               /* Size of BLOB written into %_stat */
149272  u32 *a;                  /* Array of integers that becomes the BLOB */
149273  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
149274  int i;                   /* Loop counter */
149275  int rc;                  /* Result code from subfunctions */
149276
149277  const int nStat = p->nColumn+2;
149278
149279  if( *pRC ) return;
149280  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
149281  if( a==0 ){
149282    *pRC = SQLITE_NOMEM;
149283    return;
149284  }
149285  pBlob = (char*)&a[nStat];
149286  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
149287  if( rc ){
149288    sqlite3_free(a);
149289    *pRC = rc;
149290    return;
149291  }
149292  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
149293  if( sqlite3_step(pStmt)==SQLITE_ROW ){
149294    fts3DecodeIntArray(nStat, a,
149295         sqlite3_column_blob(pStmt, 0),
149296         sqlite3_column_bytes(pStmt, 0));
149297  }else{
149298    memset(a, 0, sizeof(u32)*(nStat) );
149299  }
149300  rc = sqlite3_reset(pStmt);
149301  if( rc!=SQLITE_OK ){
149302    sqlite3_free(a);
149303    *pRC = rc;
149304    return;
149305  }
149306  if( nChng<0 && a[0]<(u32)(-nChng) ){
149307    a[0] = 0;
149308  }else{
149309    a[0] += nChng;
149310  }
149311  for(i=0; i<p->nColumn+1; i++){
149312    u32 x = a[i+1];
149313    if( x+aSzIns[i] < aSzDel[i] ){
149314      x = 0;
149315    }else{
149316      x = x + aSzIns[i] - aSzDel[i];
149317    }
149318    a[i+1] = x;
149319  }
149320  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
149321  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
149322  if( rc ){
149323    sqlite3_free(a);
149324    *pRC = rc;
149325    return;
149326  }
149327  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
149328  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
149329  sqlite3_step(pStmt);
149330  *pRC = sqlite3_reset(pStmt);
149331  sqlite3_free(a);
149332}
149333
149334/*
149335** Merge the entire database so that there is one segment for each
149336** iIndex/iLangid combination.
149337*/
149338static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
149339  int bSeenDone = 0;
149340  int rc;
149341  sqlite3_stmt *pAllLangid = 0;
149342
149343  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
149344  if( rc==SQLITE_OK ){
149345    int rc2;
149346    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
149347    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
149348    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
149349      int i;
149350      int iLangid = sqlite3_column_int(pAllLangid, 0);
149351      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
149352        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
149353        if( rc==SQLITE_DONE ){
149354          bSeenDone = 1;
149355          rc = SQLITE_OK;
149356        }
149357      }
149358    }
149359    rc2 = sqlite3_reset(pAllLangid);
149360    if( rc==SQLITE_OK ) rc = rc2;
149361  }
149362
149363  sqlite3Fts3SegmentsClose(p);
149364  sqlite3Fts3PendingTermsClear(p);
149365
149366  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
149367}
149368
149369/*
149370** This function is called when the user executes the following statement:
149371**
149372**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
149373**
149374** The entire FTS index is discarded and rebuilt. If the table is one
149375** created using the content=xxx option, then the new index is based on
149376** the current contents of the xxx table. Otherwise, it is rebuilt based
149377** on the contents of the %_content table.
149378*/
149379static int fts3DoRebuild(Fts3Table *p){
149380  int rc;                         /* Return Code */
149381
149382  rc = fts3DeleteAll(p, 0);
149383  if( rc==SQLITE_OK ){
149384    u32 *aSz = 0;
149385    u32 *aSzIns = 0;
149386    u32 *aSzDel = 0;
149387    sqlite3_stmt *pStmt = 0;
149388    int nEntry = 0;
149389
149390    /* Compose and prepare an SQL statement to loop through the content table */
149391    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
149392    if( !zSql ){
149393      rc = SQLITE_NOMEM;
149394    }else{
149395      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
149396      sqlite3_free(zSql);
149397    }
149398
149399    if( rc==SQLITE_OK ){
149400      int nByte = sizeof(u32) * (p->nColumn+1)*3;
149401      aSz = (u32 *)sqlite3_malloc(nByte);
149402      if( aSz==0 ){
149403        rc = SQLITE_NOMEM;
149404      }else{
149405        memset(aSz, 0, nByte);
149406        aSzIns = &aSz[p->nColumn+1];
149407        aSzDel = &aSzIns[p->nColumn+1];
149408      }
149409    }
149410
149411    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
149412      int iCol;
149413      int iLangid = langidFromSelect(p, pStmt);
149414      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
149415      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
149416      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
149417        if( p->abNotindexed[iCol]==0 ){
149418          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
149419          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
149420          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
149421        }
149422      }
149423      if( p->bHasDocsize ){
149424        fts3InsertDocsize(&rc, p, aSz);
149425      }
149426      if( rc!=SQLITE_OK ){
149427        sqlite3_finalize(pStmt);
149428        pStmt = 0;
149429      }else{
149430        nEntry++;
149431        for(iCol=0; iCol<=p->nColumn; iCol++){
149432          aSzIns[iCol] += aSz[iCol];
149433        }
149434      }
149435    }
149436    if( p->bFts4 ){
149437      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
149438    }
149439    sqlite3_free(aSz);
149440
149441    if( pStmt ){
149442      int rc2 = sqlite3_finalize(pStmt);
149443      if( rc==SQLITE_OK ){
149444        rc = rc2;
149445      }
149446    }
149447  }
149448
149449  return rc;
149450}
149451
149452
149453/*
149454** This function opens a cursor used to read the input data for an
149455** incremental merge operation. Specifically, it opens a cursor to scan
149456** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
149457** level iAbsLevel.
149458*/
149459static int fts3IncrmergeCsr(
149460  Fts3Table *p,                   /* FTS3 table handle */
149461  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
149462  int nSeg,                       /* Number of segments to merge */
149463  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
149464){
149465  int rc;                         /* Return Code */
149466  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
149467  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
149468
149469  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
149470  memset(pCsr, 0, sizeof(*pCsr));
149471  nByte = sizeof(Fts3SegReader *) * nSeg;
149472  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
149473
149474  if( pCsr->apSegment==0 ){
149475    rc = SQLITE_NOMEM;
149476  }else{
149477    memset(pCsr->apSegment, 0, nByte);
149478    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
149479  }
149480  if( rc==SQLITE_OK ){
149481    int i;
149482    int rc2;
149483    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
149484    assert( pCsr->nSegment==0 );
149485    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
149486      rc = sqlite3Fts3SegReaderNew(i, 0,
149487          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
149488          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
149489          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
149490          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
149491          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
149492          &pCsr->apSegment[i]
149493      );
149494      pCsr->nSegment++;
149495    }
149496    rc2 = sqlite3_reset(pStmt);
149497    if( rc==SQLITE_OK ) rc = rc2;
149498  }
149499
149500  return rc;
149501}
149502
149503typedef struct IncrmergeWriter IncrmergeWriter;
149504typedef struct NodeWriter NodeWriter;
149505typedef struct Blob Blob;
149506typedef struct NodeReader NodeReader;
149507
149508/*
149509** An instance of the following structure is used as a dynamic buffer
149510** to build up nodes or other blobs of data in.
149511**
149512** The function blobGrowBuffer() is used to extend the allocation.
149513*/
149514struct Blob {
149515  char *a;                        /* Pointer to allocation */
149516  int n;                          /* Number of valid bytes of data in a[] */
149517  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
149518};
149519
149520/*
149521** This structure is used to build up buffers containing segment b-tree
149522** nodes (blocks).
149523*/
149524struct NodeWriter {
149525  sqlite3_int64 iBlock;           /* Current block id */
149526  Blob key;                       /* Last key written to the current block */
149527  Blob block;                     /* Current block image */
149528};
149529
149530/*
149531** An object of this type contains the state required to create or append
149532** to an appendable b-tree segment.
149533*/
149534struct IncrmergeWriter {
149535  int nLeafEst;                   /* Space allocated for leaf blocks */
149536  int nWork;                      /* Number of leaf pages flushed */
149537  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
149538  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
149539  sqlite3_int64 iStart;           /* Block number of first allocated block */
149540  sqlite3_int64 iEnd;             /* Block number of last allocated block */
149541  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
149542  u8 bNoLeafData;                 /* If true, store 0 for segment size */
149543  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
149544};
149545
149546/*
149547** An object of the following type is used to read data from a single
149548** FTS segment node. See the following functions:
149549**
149550**     nodeReaderInit()
149551**     nodeReaderNext()
149552**     nodeReaderRelease()
149553*/
149554struct NodeReader {
149555  const char *aNode;
149556  int nNode;
149557  int iOff;                       /* Current offset within aNode[] */
149558
149559  /* Output variables. Containing the current node entry. */
149560  sqlite3_int64 iChild;           /* Pointer to child node */
149561  Blob term;                      /* Current term */
149562  const char *aDoclist;           /* Pointer to doclist */
149563  int nDoclist;                   /* Size of doclist in bytes */
149564};
149565
149566/*
149567** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
149568** Otherwise, if the allocation at pBlob->a is not already at least nMin
149569** bytes in size, extend (realloc) it to be so.
149570**
149571** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
149572** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
149573** to reflect the new size of the pBlob->a[] buffer.
149574*/
149575static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
149576  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
149577    int nAlloc = nMin;
149578    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
149579    if( a ){
149580      pBlob->nAlloc = nAlloc;
149581      pBlob->a = a;
149582    }else{
149583      *pRc = SQLITE_NOMEM;
149584    }
149585  }
149586}
149587
149588/*
149589** Attempt to advance the node-reader object passed as the first argument to
149590** the next entry on the node.
149591**
149592** Return an error code if an error occurs (SQLITE_NOMEM is possible).
149593** Otherwise return SQLITE_OK. If there is no next entry on the node
149594** (e.g. because the current entry is the last) set NodeReader->aNode to
149595** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
149596** variables for the new entry.
149597*/
149598static int nodeReaderNext(NodeReader *p){
149599  int bFirst = (p->term.n==0);    /* True for first term on the node */
149600  int nPrefix = 0;                /* Bytes to copy from previous term */
149601  int nSuffix = 0;                /* Bytes to append to the prefix */
149602  int rc = SQLITE_OK;             /* Return code */
149603
149604  assert( p->aNode );
149605  if( p->iChild && bFirst==0 ) p->iChild++;
149606  if( p->iOff>=p->nNode ){
149607    /* EOF */
149608    p->aNode = 0;
149609  }else{
149610    if( bFirst==0 ){
149611      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
149612    }
149613    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
149614
149615    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
149616    if( rc==SQLITE_OK ){
149617      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
149618      p->term.n = nPrefix+nSuffix;
149619      p->iOff += nSuffix;
149620      if( p->iChild==0 ){
149621        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
149622        p->aDoclist = &p->aNode[p->iOff];
149623        p->iOff += p->nDoclist;
149624      }
149625    }
149626  }
149627
149628  assert( p->iOff<=p->nNode );
149629
149630  return rc;
149631}
149632
149633/*
149634** Release all dynamic resources held by node-reader object *p.
149635*/
149636static void nodeReaderRelease(NodeReader *p){
149637  sqlite3_free(p->term.a);
149638}
149639
149640/*
149641** Initialize a node-reader object to read the node in buffer aNode/nNode.
149642**
149643** If successful, SQLITE_OK is returned and the NodeReader object set to
149644** point to the first entry on the node (if any). Otherwise, an SQLite
149645** error code is returned.
149646*/
149647static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
149648  memset(p, 0, sizeof(NodeReader));
149649  p->aNode = aNode;
149650  p->nNode = nNode;
149651
149652  /* Figure out if this is a leaf or an internal node. */
149653  if( p->aNode[0] ){
149654    /* An internal node. */
149655    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
149656  }else{
149657    p->iOff = 1;
149658  }
149659
149660  return nodeReaderNext(p);
149661}
149662
149663/*
149664** This function is called while writing an FTS segment each time a leaf o
149665** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
149666** to be greater than the largest key on the node just written, but smaller
149667** than or equal to the first key that will be written to the next leaf
149668** node.
149669**
149670** The block id of the leaf node just written to disk may be found in
149671** (pWriter->aNodeWriter[0].iBlock) when this function is called.
149672*/
149673static int fts3IncrmergePush(
149674  Fts3Table *p,                   /* Fts3 table handle */
149675  IncrmergeWriter *pWriter,       /* Writer object */
149676  const char *zTerm,              /* Term to write to internal node */
149677  int nTerm                       /* Bytes at zTerm */
149678){
149679  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
149680  int iLayer;
149681
149682  assert( nTerm>0 );
149683  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
149684    sqlite3_int64 iNextPtr = 0;
149685    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
149686    int rc = SQLITE_OK;
149687    int nPrefix;
149688    int nSuffix;
149689    int nSpace;
149690
149691    /* Figure out how much space the key will consume if it is written to
149692    ** the current node of layer iLayer. Due to the prefix compression,
149693    ** the space required changes depending on which node the key is to
149694    ** be added to.  */
149695    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
149696    nSuffix = nTerm - nPrefix;
149697    nSpace  = sqlite3Fts3VarintLen(nPrefix);
149698    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149699
149700    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
149701      /* If the current node of layer iLayer contains zero keys, or if adding
149702      ** the key to it will not cause it to grow to larger than nNodeSize
149703      ** bytes in size, write the key here.  */
149704
149705      Blob *pBlk = &pNode->block;
149706      if( pBlk->n==0 ){
149707        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
149708        if( rc==SQLITE_OK ){
149709          pBlk->a[0] = (char)iLayer;
149710          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
149711        }
149712      }
149713      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
149714      blobGrowBuffer(&pNode->key, nTerm, &rc);
149715
149716      if( rc==SQLITE_OK ){
149717        if( pNode->key.n ){
149718          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
149719        }
149720        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
149721        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
149722        pBlk->n += nSuffix;
149723
149724        memcpy(pNode->key.a, zTerm, nTerm);
149725        pNode->key.n = nTerm;
149726      }
149727    }else{
149728      /* Otherwise, flush the current node of layer iLayer to disk.
149729      ** Then allocate a new, empty sibling node. The key will be written
149730      ** into the parent of this node. */
149731      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
149732
149733      assert( pNode->block.nAlloc>=p->nNodeSize );
149734      pNode->block.a[0] = (char)iLayer;
149735      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
149736
149737      iNextPtr = pNode->iBlock;
149738      pNode->iBlock++;
149739      pNode->key.n = 0;
149740    }
149741
149742    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
149743    iPtr = iNextPtr;
149744  }
149745
149746  assert( 0 );
149747  return 0;
149748}
149749
149750/*
149751** Append a term and (optionally) doclist to the FTS segment node currently
149752** stored in blob *pNode. The node need not contain any terms, but the
149753** header must be written before this function is called.
149754**
149755** A node header is a single 0x00 byte for a leaf node, or a height varint
149756** followed by the left-hand-child varint for an internal node.
149757**
149758** The term to be appended is passed via arguments zTerm/nTerm. For a
149759** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
149760** node, both aDoclist and nDoclist must be passed 0.
149761**
149762** If the size of the value in blob pPrev is zero, then this is the first
149763** term written to the node. Otherwise, pPrev contains a copy of the
149764** previous term. Before this function returns, it is updated to contain a
149765** copy of zTerm/nTerm.
149766**
149767** It is assumed that the buffer associated with pNode is already large
149768** enough to accommodate the new entry. The buffer associated with pPrev
149769** is extended by this function if requrired.
149770**
149771** If an error (i.e. OOM condition) occurs, an SQLite error code is
149772** returned. Otherwise, SQLITE_OK.
149773*/
149774static int fts3AppendToNode(
149775  Blob *pNode,                    /* Current node image to append to */
149776  Blob *pPrev,                    /* Buffer containing previous term written */
149777  const char *zTerm,              /* New term to write */
149778  int nTerm,                      /* Size of zTerm in bytes */
149779  const char *aDoclist,           /* Doclist (or NULL) to write */
149780  int nDoclist                    /* Size of aDoclist in bytes */
149781){
149782  int rc = SQLITE_OK;             /* Return code */
149783  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
149784  int nPrefix;                    /* Size of term prefix in bytes */
149785  int nSuffix;                    /* Size of term suffix in bytes */
149786
149787  /* Node must have already been started. There must be a doclist for a
149788  ** leaf node, and there must not be a doclist for an internal node.  */
149789  assert( pNode->n>0 );
149790  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
149791
149792  blobGrowBuffer(pPrev, nTerm, &rc);
149793  if( rc!=SQLITE_OK ) return rc;
149794
149795  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
149796  nSuffix = nTerm - nPrefix;
149797  memcpy(pPrev->a, zTerm, nTerm);
149798  pPrev->n = nTerm;
149799
149800  if( bFirst==0 ){
149801    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
149802  }
149803  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
149804  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
149805  pNode->n += nSuffix;
149806
149807  if( aDoclist ){
149808    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
149809    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
149810    pNode->n += nDoclist;
149811  }
149812
149813  assert( pNode->n<=pNode->nAlloc );
149814
149815  return SQLITE_OK;
149816}
149817
149818/*
149819** Append the current term and doclist pointed to by cursor pCsr to the
149820** appendable b-tree segment opened for writing by pWriter.
149821**
149822** Return SQLITE_OK if successful, or an SQLite error code otherwise.
149823*/
149824static int fts3IncrmergeAppend(
149825  Fts3Table *p,                   /* Fts3 table handle */
149826  IncrmergeWriter *pWriter,       /* Writer object */
149827  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
149828){
149829  const char *zTerm = pCsr->zTerm;
149830  int nTerm = pCsr->nTerm;
149831  const char *aDoclist = pCsr->aDoclist;
149832  int nDoclist = pCsr->nDoclist;
149833  int rc = SQLITE_OK;           /* Return code */
149834  int nSpace;                   /* Total space in bytes required on leaf */
149835  int nPrefix;                  /* Size of prefix shared with previous term */
149836  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
149837  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
149838
149839  pLeaf = &pWriter->aNodeWriter[0];
149840  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
149841  nSuffix = nTerm - nPrefix;
149842
149843  nSpace  = sqlite3Fts3VarintLen(nPrefix);
149844  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149845  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
149846
149847  /* If the current block is not empty, and if adding this term/doclist
149848  ** to the current block would make it larger than Fts3Table.nNodeSize
149849  ** bytes, write this block out to the database. */
149850  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
149851    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
149852    pWriter->nWork++;
149853
149854    /* Add the current term to the parent node. The term added to the
149855    ** parent must:
149856    **
149857    **   a) be greater than the largest term on the leaf node just written
149858    **      to the database (still available in pLeaf->key), and
149859    **
149860    **   b) be less than or equal to the term about to be added to the new
149861    **      leaf node (zTerm/nTerm).
149862    **
149863    ** In other words, it must be the prefix of zTerm 1 byte longer than
149864    ** the common prefix (if any) of zTerm and pWriter->zTerm.
149865    */
149866    if( rc==SQLITE_OK ){
149867      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
149868    }
149869
149870    /* Advance to the next output block */
149871    pLeaf->iBlock++;
149872    pLeaf->key.n = 0;
149873    pLeaf->block.n = 0;
149874
149875    nSuffix = nTerm;
149876    nSpace  = 1;
149877    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149878    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
149879  }
149880
149881  pWriter->nLeafData += nSpace;
149882  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
149883  if( rc==SQLITE_OK ){
149884    if( pLeaf->block.n==0 ){
149885      pLeaf->block.n = 1;
149886      pLeaf->block.a[0] = '\0';
149887    }
149888    rc = fts3AppendToNode(
149889        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
149890    );
149891  }
149892
149893  return rc;
149894}
149895
149896/*
149897** This function is called to release all dynamic resources held by the
149898** merge-writer object pWriter, and if no error has occurred, to flush
149899** all outstanding node buffers held by pWriter to disk.
149900**
149901** If *pRc is not SQLITE_OK when this function is called, then no attempt
149902** is made to write any data to disk. Instead, this function serves only
149903** to release outstanding resources.
149904**
149905** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
149906** flushing buffers to disk, *pRc is set to an SQLite error code before
149907** returning.
149908*/
149909static void fts3IncrmergeRelease(
149910  Fts3Table *p,                   /* FTS3 table handle */
149911  IncrmergeWriter *pWriter,       /* Merge-writer object */
149912  int *pRc                        /* IN/OUT: Error code */
149913){
149914  int i;                          /* Used to iterate through non-root layers */
149915  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
149916  NodeWriter *pRoot;              /* NodeWriter for root node */
149917  int rc = *pRc;                  /* Error code */
149918
149919  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
149920  ** root node. If the segment fits entirely on a single leaf node, iRoot
149921  ** will be set to 0. If the root node is the parent of the leaves, iRoot
149922  ** will be 1. And so on.  */
149923  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
149924    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
149925    if( pNode->block.n>0 ) break;
149926    assert( *pRc || pNode->block.nAlloc==0 );
149927    assert( *pRc || pNode->key.nAlloc==0 );
149928    sqlite3_free(pNode->block.a);
149929    sqlite3_free(pNode->key.a);
149930  }
149931
149932  /* Empty output segment. This is a no-op. */
149933  if( iRoot<0 ) return;
149934
149935  /* The entire output segment fits on a single node. Normally, this means
149936  ** the node would be stored as a blob in the "root" column of the %_segdir
149937  ** table. However, this is not permitted in this case. The problem is that
149938  ** space has already been reserved in the %_segments table, and so the
149939  ** start_block and end_block fields of the %_segdir table must be populated.
149940  ** And, by design or by accident, released versions of FTS cannot handle
149941  ** segments that fit entirely on the root node with start_block!=0.
149942  **
149943  ** Instead, create a synthetic root node that contains nothing but a
149944  ** pointer to the single content node. So that the segment consists of a
149945  ** single leaf and a single interior (root) node.
149946  **
149947  ** Todo: Better might be to defer allocating space in the %_segments
149948  ** table until we are sure it is needed.
149949  */
149950  if( iRoot==0 ){
149951    Blob *pBlock = &pWriter->aNodeWriter[1].block;
149952    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
149953    if( rc==SQLITE_OK ){
149954      pBlock->a[0] = 0x01;
149955      pBlock->n = 1 + sqlite3Fts3PutVarint(
149956          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
149957      );
149958    }
149959    iRoot = 1;
149960  }
149961  pRoot = &pWriter->aNodeWriter[iRoot];
149962
149963  /* Flush all currently outstanding nodes to disk. */
149964  for(i=0; i<iRoot; i++){
149965    NodeWriter *pNode = &pWriter->aNodeWriter[i];
149966    if( pNode->block.n>0 && rc==SQLITE_OK ){
149967      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
149968    }
149969    sqlite3_free(pNode->block.a);
149970    sqlite3_free(pNode->key.a);
149971  }
149972
149973  /* Write the %_segdir record. */
149974  if( rc==SQLITE_OK ){
149975    rc = fts3WriteSegdir(p,
149976        pWriter->iAbsLevel+1,               /* level */
149977        pWriter->iIdx,                      /* idx */
149978        pWriter->iStart,                    /* start_block */
149979        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
149980        pWriter->iEnd,                      /* end_block */
149981        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
149982        pRoot->block.a, pRoot->block.n      /* root */
149983    );
149984  }
149985  sqlite3_free(pRoot->block.a);
149986  sqlite3_free(pRoot->key.a);
149987
149988  *pRc = rc;
149989}
149990
149991/*
149992** Compare the term in buffer zLhs (size in bytes nLhs) with that in
149993** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
149994** the other, it is considered to be smaller than the other.
149995**
149996** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
149997** if it is greater.
149998*/
149999static int fts3TermCmp(
150000  const char *zLhs, int nLhs,     /* LHS of comparison */
150001  const char *zRhs, int nRhs      /* RHS of comparison */
150002){
150003  int nCmp = MIN(nLhs, nRhs);
150004  int res;
150005
150006  res = memcmp(zLhs, zRhs, nCmp);
150007  if( res==0 ) res = nLhs - nRhs;
150008
150009  return res;
150010}
150011
150012
150013/*
150014** Query to see if the entry in the %_segments table with blockid iEnd is
150015** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
150016** returning. Otherwise, set *pbRes to 0.
150017**
150018** Or, if an error occurs while querying the database, return an SQLite
150019** error code. The final value of *pbRes is undefined in this case.
150020**
150021** This is used to test if a segment is an "appendable" segment. If it
150022** is, then a NULL entry has been inserted into the %_segments table
150023** with blockid %_segdir.end_block.
150024*/
150025static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
150026  int bRes = 0;                   /* Result to set *pbRes to */
150027  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
150028  int rc;                         /* Return code */
150029
150030  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
150031  if( rc==SQLITE_OK ){
150032    sqlite3_bind_int64(pCheck, 1, iEnd);
150033    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
150034    rc = sqlite3_reset(pCheck);
150035  }
150036
150037  *pbRes = bRes;
150038  return rc;
150039}
150040
150041/*
150042** This function is called when initializing an incremental-merge operation.
150043** It checks if the existing segment with index value iIdx at absolute level
150044** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
150045** merge-writer object *pWriter is initialized to write to it.
150046**
150047** An existing segment can be appended to by an incremental merge if:
150048**
150049**   * It was initially created as an appendable segment (with all required
150050**     space pre-allocated), and
150051**
150052**   * The first key read from the input (arguments zKey and nKey) is
150053**     greater than the largest key currently stored in the potential
150054**     output segment.
150055*/
150056static int fts3IncrmergeLoad(
150057  Fts3Table *p,                   /* Fts3 table handle */
150058  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
150059  int iIdx,                       /* Index of candidate output segment */
150060  const char *zKey,               /* First key to write */
150061  int nKey,                       /* Number of bytes in nKey */
150062  IncrmergeWriter *pWriter        /* Populate this object */
150063){
150064  int rc;                         /* Return code */
150065  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
150066
150067  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
150068  if( rc==SQLITE_OK ){
150069    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
150070    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
150071    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
150072    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
150073    int nRoot = 0;                /* Size of aRoot[] in bytes */
150074    int rc2;                      /* Return code from sqlite3_reset() */
150075    int bAppendable = 0;          /* Set to true if segment is appendable */
150076
150077    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
150078    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
150079    sqlite3_bind_int(pSelect, 2, iIdx);
150080    if( sqlite3_step(pSelect)==SQLITE_ROW ){
150081      iStart = sqlite3_column_int64(pSelect, 1);
150082      iLeafEnd = sqlite3_column_int64(pSelect, 2);
150083      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
150084      if( pWriter->nLeafData<0 ){
150085        pWriter->nLeafData = pWriter->nLeafData * -1;
150086      }
150087      pWriter->bNoLeafData = (pWriter->nLeafData==0);
150088      nRoot = sqlite3_column_bytes(pSelect, 4);
150089      aRoot = sqlite3_column_blob(pSelect, 4);
150090    }else{
150091      return sqlite3_reset(pSelect);
150092    }
150093
150094    /* Check for the zero-length marker in the %_segments table */
150095    rc = fts3IsAppendable(p, iEnd, &bAppendable);
150096
150097    /* Check that zKey/nKey is larger than the largest key the candidate */
150098    if( rc==SQLITE_OK && bAppendable ){
150099      char *aLeaf = 0;
150100      int nLeaf = 0;
150101
150102      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
150103      if( rc==SQLITE_OK ){
150104        NodeReader reader;
150105        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
150106            rc==SQLITE_OK && reader.aNode;
150107            rc = nodeReaderNext(&reader)
150108        ){
150109          assert( reader.aNode );
150110        }
150111        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
150112          bAppendable = 0;
150113        }
150114        nodeReaderRelease(&reader);
150115      }
150116      sqlite3_free(aLeaf);
150117    }
150118
150119    if( rc==SQLITE_OK && bAppendable ){
150120      /* It is possible to append to this segment. Set up the IncrmergeWriter
150121      ** object to do so.  */
150122      int i;
150123      int nHeight = (int)aRoot[0];
150124      NodeWriter *pNode;
150125
150126      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
150127      pWriter->iStart = iStart;
150128      pWriter->iEnd = iEnd;
150129      pWriter->iAbsLevel = iAbsLevel;
150130      pWriter->iIdx = iIdx;
150131
150132      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
150133        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
150134      }
150135
150136      pNode = &pWriter->aNodeWriter[nHeight];
150137      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
150138      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
150139      if( rc==SQLITE_OK ){
150140        memcpy(pNode->block.a, aRoot, nRoot);
150141        pNode->block.n = nRoot;
150142      }
150143
150144      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
150145        NodeReader reader;
150146        pNode = &pWriter->aNodeWriter[i];
150147
150148        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
150149        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
150150        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
150151        if( rc==SQLITE_OK ){
150152          memcpy(pNode->key.a, reader.term.a, reader.term.n);
150153          pNode->key.n = reader.term.n;
150154          if( i>0 ){
150155            char *aBlock = 0;
150156            int nBlock = 0;
150157            pNode = &pWriter->aNodeWriter[i-1];
150158            pNode->iBlock = reader.iChild;
150159            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
150160            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
150161            if( rc==SQLITE_OK ){
150162              memcpy(pNode->block.a, aBlock, nBlock);
150163              pNode->block.n = nBlock;
150164            }
150165            sqlite3_free(aBlock);
150166          }
150167        }
150168        nodeReaderRelease(&reader);
150169      }
150170    }
150171
150172    rc2 = sqlite3_reset(pSelect);
150173    if( rc==SQLITE_OK ) rc = rc2;
150174  }
150175
150176  return rc;
150177}
150178
150179/*
150180** Determine the largest segment index value that exists within absolute
150181** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
150182** one before returning SQLITE_OK. Or, if there are no segments at all
150183** within level iAbsLevel, set *piIdx to zero.
150184**
150185** If an error occurs, return an SQLite error code. The final value of
150186** *piIdx is undefined in this case.
150187*/
150188static int fts3IncrmergeOutputIdx(
150189  Fts3Table *p,                   /* FTS Table handle */
150190  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
150191  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
150192){
150193  int rc;
150194  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
150195
150196  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
150197  if( rc==SQLITE_OK ){
150198    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
150199    sqlite3_step(pOutputIdx);
150200    *piIdx = sqlite3_column_int(pOutputIdx, 0);
150201    rc = sqlite3_reset(pOutputIdx);
150202  }
150203
150204  return rc;
150205}
150206
150207/*
150208** Allocate an appendable output segment on absolute level iAbsLevel+1
150209** with idx value iIdx.
150210**
150211** In the %_segdir table, a segment is defined by the values in three
150212** columns:
150213**
150214**     start_block
150215**     leaves_end_block
150216**     end_block
150217**
150218** When an appendable segment is allocated, it is estimated that the
150219** maximum number of leaf blocks that may be required is the sum of the
150220** number of leaf blocks consumed by the input segments, plus the number
150221** of input segments, multiplied by two. This value is stored in stack
150222** variable nLeafEst.
150223**
150224** A total of 16*nLeafEst blocks are allocated when an appendable segment
150225** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
150226** array of leaf nodes starts at the first block allocated. The array
150227** of interior nodes that are parents of the leaf nodes start at block
150228** (start_block + (1 + end_block - start_block) / 16). And so on.
150229**
150230** In the actual code below, the value "16" is replaced with the
150231** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
150232*/
150233static int fts3IncrmergeWriter(
150234  Fts3Table *p,                   /* Fts3 table handle */
150235  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
150236  int iIdx,                       /* Index of new output segment */
150237  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
150238  IncrmergeWriter *pWriter        /* Populate this object */
150239){
150240  int rc;                         /* Return Code */
150241  int i;                          /* Iterator variable */
150242  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
150243  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
150244  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
150245
150246  /* Calculate nLeafEst. */
150247  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
150248  if( rc==SQLITE_OK ){
150249    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
150250    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
150251    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
150252      nLeafEst = sqlite3_column_int(pLeafEst, 0);
150253    }
150254    rc = sqlite3_reset(pLeafEst);
150255  }
150256  if( rc!=SQLITE_OK ) return rc;
150257
150258  /* Calculate the first block to use in the output segment */
150259  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
150260  if( rc==SQLITE_OK ){
150261    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
150262      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
150263      pWriter->iEnd = pWriter->iStart - 1;
150264      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
150265    }
150266    rc = sqlite3_reset(pFirstBlock);
150267  }
150268  if( rc!=SQLITE_OK ) return rc;
150269
150270  /* Insert the marker in the %_segments table to make sure nobody tries
150271  ** to steal the space just allocated. This is also used to identify
150272  ** appendable segments.  */
150273  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
150274  if( rc!=SQLITE_OK ) return rc;
150275
150276  pWriter->iAbsLevel = iAbsLevel;
150277  pWriter->nLeafEst = nLeafEst;
150278  pWriter->iIdx = iIdx;
150279
150280  /* Set up the array of NodeWriter objects */
150281  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
150282    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
150283  }
150284  return SQLITE_OK;
150285}
150286
150287/*
150288** Remove an entry from the %_segdir table. This involves running the
150289** following two statements:
150290**
150291**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
150292**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
150293**
150294** The DELETE statement removes the specific %_segdir level. The UPDATE
150295** statement ensures that the remaining segments have contiguously allocated
150296** idx values.
150297*/
150298static int fts3RemoveSegdirEntry(
150299  Fts3Table *p,                   /* FTS3 table handle */
150300  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
150301  int iIdx                        /* Index of %_segdir entry to delete */
150302){
150303  int rc;                         /* Return code */
150304  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
150305
150306  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
150307  if( rc==SQLITE_OK ){
150308    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
150309    sqlite3_bind_int(pDelete, 2, iIdx);
150310    sqlite3_step(pDelete);
150311    rc = sqlite3_reset(pDelete);
150312  }
150313
150314  return rc;
150315}
150316
150317/*
150318** One or more segments have just been removed from absolute level iAbsLevel.
150319** Update the 'idx' values of the remaining segments in the level so that
150320** the idx values are a contiguous sequence starting from 0.
150321*/
150322static int fts3RepackSegdirLevel(
150323  Fts3Table *p,                   /* FTS3 table handle */
150324  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
150325){
150326  int rc;                         /* Return code */
150327  int *aIdx = 0;                  /* Array of remaining idx values */
150328  int nIdx = 0;                   /* Valid entries in aIdx[] */
150329  int nAlloc = 0;                 /* Allocated size of aIdx[] */
150330  int i;                          /* Iterator variable */
150331  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
150332  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
150333
150334  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
150335  if( rc==SQLITE_OK ){
150336    int rc2;
150337    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
150338    while( SQLITE_ROW==sqlite3_step(pSelect) ){
150339      if( nIdx>=nAlloc ){
150340        int *aNew;
150341        nAlloc += 16;
150342        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
150343        if( !aNew ){
150344          rc = SQLITE_NOMEM;
150345          break;
150346        }
150347        aIdx = aNew;
150348      }
150349      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
150350    }
150351    rc2 = sqlite3_reset(pSelect);
150352    if( rc==SQLITE_OK ) rc = rc2;
150353  }
150354
150355  if( rc==SQLITE_OK ){
150356    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
150357  }
150358  if( rc==SQLITE_OK ){
150359    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
150360  }
150361
150362  assert( p->bIgnoreSavepoint==0 );
150363  p->bIgnoreSavepoint = 1;
150364  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
150365    if( aIdx[i]!=i ){
150366      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
150367      sqlite3_bind_int(pUpdate, 1, i);
150368      sqlite3_step(pUpdate);
150369      rc = sqlite3_reset(pUpdate);
150370    }
150371  }
150372  p->bIgnoreSavepoint = 0;
150373
150374  sqlite3_free(aIdx);
150375  return rc;
150376}
150377
150378static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
150379  pNode->a[0] = (char)iHeight;
150380  if( iChild ){
150381    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
150382    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
150383  }else{
150384    assert( pNode->nAlloc>=1 );
150385    pNode->n = 1;
150386  }
150387}
150388
150389/*
150390** The first two arguments are a pointer to and the size of a segment b-tree
150391** node. The node may be a leaf or an internal node.
150392**
150393** This function creates a new node image in blob object *pNew by copying
150394** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
150395** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
150396*/
150397static int fts3TruncateNode(
150398  const char *aNode,              /* Current node image */
150399  int nNode,                      /* Size of aNode in bytes */
150400  Blob *pNew,                     /* OUT: Write new node image here */
150401  const char *zTerm,              /* Omit all terms smaller than this */
150402  int nTerm,                      /* Size of zTerm in bytes */
150403  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
150404){
150405  NodeReader reader;              /* Reader object */
150406  Blob prev = {0, 0, 0};          /* Previous term written to new node */
150407  int rc = SQLITE_OK;             /* Return code */
150408  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
150409
150410  /* Allocate required output space */
150411  blobGrowBuffer(pNew, nNode, &rc);
150412  if( rc!=SQLITE_OK ) return rc;
150413  pNew->n = 0;
150414
150415  /* Populate new node buffer */
150416  for(rc = nodeReaderInit(&reader, aNode, nNode);
150417      rc==SQLITE_OK && reader.aNode;
150418      rc = nodeReaderNext(&reader)
150419  ){
150420    if( pNew->n==0 ){
150421      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
150422      if( res<0 || (bLeaf==0 && res==0) ) continue;
150423      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
150424      *piBlock = reader.iChild;
150425    }
150426    rc = fts3AppendToNode(
150427        pNew, &prev, reader.term.a, reader.term.n,
150428        reader.aDoclist, reader.nDoclist
150429    );
150430    if( rc!=SQLITE_OK ) break;
150431  }
150432  if( pNew->n==0 ){
150433    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
150434    *piBlock = reader.iChild;
150435  }
150436  assert( pNew->n<=pNew->nAlloc );
150437
150438  nodeReaderRelease(&reader);
150439  sqlite3_free(prev.a);
150440  return rc;
150441}
150442
150443/*
150444** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
150445** level iAbsLevel. This may involve deleting entries from the %_segments
150446** table, and modifying existing entries in both the %_segments and %_segdir
150447** tables.
150448**
150449** SQLITE_OK is returned if the segment is updated successfully. Or an
150450** SQLite error code otherwise.
150451*/
150452static int fts3TruncateSegment(
150453  Fts3Table *p,                   /* FTS3 table handle */
150454  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
150455  int iIdx,                       /* Index within level of segment to modify */
150456  const char *zTerm,              /* Remove terms smaller than this */
150457  int nTerm                      /* Number of bytes in buffer zTerm */
150458){
150459  int rc = SQLITE_OK;             /* Return code */
150460  Blob root = {0,0,0};            /* New root page image */
150461  Blob block = {0,0,0};           /* Buffer used for any other block */
150462  sqlite3_int64 iBlock = 0;       /* Block id */
150463  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
150464  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
150465  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
150466
150467  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
150468  if( rc==SQLITE_OK ){
150469    int rc2;                      /* sqlite3_reset() return code */
150470    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
150471    sqlite3_bind_int(pFetch, 2, iIdx);
150472    if( SQLITE_ROW==sqlite3_step(pFetch) ){
150473      const char *aRoot = sqlite3_column_blob(pFetch, 4);
150474      int nRoot = sqlite3_column_bytes(pFetch, 4);
150475      iOldStart = sqlite3_column_int64(pFetch, 1);
150476      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
150477    }
150478    rc2 = sqlite3_reset(pFetch);
150479    if( rc==SQLITE_OK ) rc = rc2;
150480  }
150481
150482  while( rc==SQLITE_OK && iBlock ){
150483    char *aBlock = 0;
150484    int nBlock = 0;
150485    iNewStart = iBlock;
150486
150487    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
150488    if( rc==SQLITE_OK ){
150489      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
150490    }
150491    if( rc==SQLITE_OK ){
150492      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
150493    }
150494    sqlite3_free(aBlock);
150495  }
150496
150497  /* Variable iNewStart now contains the first valid leaf node. */
150498  if( rc==SQLITE_OK && iNewStart ){
150499    sqlite3_stmt *pDel = 0;
150500    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
150501    if( rc==SQLITE_OK ){
150502      sqlite3_bind_int64(pDel, 1, iOldStart);
150503      sqlite3_bind_int64(pDel, 2, iNewStart-1);
150504      sqlite3_step(pDel);
150505      rc = sqlite3_reset(pDel);
150506    }
150507  }
150508
150509  if( rc==SQLITE_OK ){
150510    sqlite3_stmt *pChomp = 0;
150511    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
150512    if( rc==SQLITE_OK ){
150513      sqlite3_bind_int64(pChomp, 1, iNewStart);
150514      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
150515      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
150516      sqlite3_bind_int(pChomp, 4, iIdx);
150517      sqlite3_step(pChomp);
150518      rc = sqlite3_reset(pChomp);
150519    }
150520  }
150521
150522  sqlite3_free(root.a);
150523  sqlite3_free(block.a);
150524  return rc;
150525}
150526
150527/*
150528** This function is called after an incrmental-merge operation has run to
150529** merge (or partially merge) two or more segments from absolute level
150530** iAbsLevel.
150531**
150532** Each input segment is either removed from the db completely (if all of
150533** its data was copied to the output segment by the incrmerge operation)
150534** or modified in place so that it no longer contains those entries that
150535** have been duplicated in the output segment.
150536*/
150537static int fts3IncrmergeChomp(
150538  Fts3Table *p,                   /* FTS table handle */
150539  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
150540  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
150541  int *pnRem                      /* Number of segments not deleted */
150542){
150543  int i;
150544  int nRem = 0;
150545  int rc = SQLITE_OK;
150546
150547  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
150548    Fts3SegReader *pSeg = 0;
150549    int j;
150550
150551    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
150552    ** somewhere in the pCsr->apSegment[] array.  */
150553    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
150554      pSeg = pCsr->apSegment[j];
150555      if( pSeg->iIdx==i ) break;
150556    }
150557    assert( j<pCsr->nSegment && pSeg->iIdx==i );
150558
150559    if( pSeg->aNode==0 ){
150560      /* Seg-reader is at EOF. Remove the entire input segment. */
150561      rc = fts3DeleteSegment(p, pSeg);
150562      if( rc==SQLITE_OK ){
150563        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
150564      }
150565      *pnRem = 0;
150566    }else{
150567      /* The incremental merge did not copy all the data from this
150568      ** segment to the upper level. The segment is modified in place
150569      ** so that it contains no keys smaller than zTerm/nTerm. */
150570      const char *zTerm = pSeg->zTerm;
150571      int nTerm = pSeg->nTerm;
150572      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
150573      nRem++;
150574    }
150575  }
150576
150577  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
150578    rc = fts3RepackSegdirLevel(p, iAbsLevel);
150579  }
150580
150581  *pnRem = nRem;
150582  return rc;
150583}
150584
150585/*
150586** Store an incr-merge hint in the database.
150587*/
150588static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
150589  sqlite3_stmt *pReplace = 0;
150590  int rc;                         /* Return code */
150591
150592  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
150593  if( rc==SQLITE_OK ){
150594    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
150595    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
150596    sqlite3_step(pReplace);
150597    rc = sqlite3_reset(pReplace);
150598  }
150599
150600  return rc;
150601}
150602
150603/*
150604** Load an incr-merge hint from the database. The incr-merge hint, if one
150605** exists, is stored in the rowid==1 row of the %_stat table.
150606**
150607** If successful, populate blob *pHint with the value read from the %_stat
150608** table and return SQLITE_OK. Otherwise, if an error occurs, return an
150609** SQLite error code.
150610*/
150611static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
150612  sqlite3_stmt *pSelect = 0;
150613  int rc;
150614
150615  pHint->n = 0;
150616  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
150617  if( rc==SQLITE_OK ){
150618    int rc2;
150619    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
150620    if( SQLITE_ROW==sqlite3_step(pSelect) ){
150621      const char *aHint = sqlite3_column_blob(pSelect, 0);
150622      int nHint = sqlite3_column_bytes(pSelect, 0);
150623      if( aHint ){
150624        blobGrowBuffer(pHint, nHint, &rc);
150625        if( rc==SQLITE_OK ){
150626          memcpy(pHint->a, aHint, nHint);
150627          pHint->n = nHint;
150628        }
150629      }
150630    }
150631    rc2 = sqlite3_reset(pSelect);
150632    if( rc==SQLITE_OK ) rc = rc2;
150633  }
150634
150635  return rc;
150636}
150637
150638/*
150639** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
150640** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
150641** consists of two varints, the absolute level number of the input segments
150642** and the number of input segments.
150643**
150644** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
150645** set *pRc to an SQLite error code before returning.
150646*/
150647static void fts3IncrmergeHintPush(
150648  Blob *pHint,                    /* Hint blob to append to */
150649  i64 iAbsLevel,                  /* First varint to store in hint */
150650  int nInput,                     /* Second varint to store in hint */
150651  int *pRc                        /* IN/OUT: Error code */
150652){
150653  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
150654  if( *pRc==SQLITE_OK ){
150655    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
150656    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
150657  }
150658}
150659
150660/*
150661** Read the last entry (most recently pushed) from the hint blob *pHint
150662** and then remove the entry. Write the two values read to *piAbsLevel and
150663** *pnInput before returning.
150664**
150665** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
150666** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
150667*/
150668static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
150669  const int nHint = pHint->n;
150670  int i;
150671
150672  i = pHint->n-2;
150673  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
150674  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
150675
150676  pHint->n = i;
150677  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
150678  i += fts3GetVarint32(&pHint->a[i], pnInput);
150679  if( i!=nHint ) return FTS_CORRUPT_VTAB;
150680
150681  return SQLITE_OK;
150682}
150683
150684
150685/*
150686** Attempt an incremental merge that writes nMerge leaf blocks.
150687**
150688** Incremental merges happen nMin segments at a time. The segments
150689** to be merged are the nMin oldest segments (the ones with the smallest
150690** values for the _segdir.idx field) in the highest level that contains
150691** at least nMin segments. Multiple merges might occur in an attempt to
150692** write the quota of nMerge leaf blocks.
150693*/
150694SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
150695  int rc;                         /* Return code */
150696  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
150697  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
150698  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
150699  IncrmergeWriter *pWriter;       /* Writer object */
150700  int nSeg = 0;                   /* Number of input segments */
150701  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
150702  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
150703  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
150704
150705  /* Allocate space for the cursor, filter and writer objects */
150706  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
150707  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
150708  if( !pWriter ) return SQLITE_NOMEM;
150709  pFilter = (Fts3SegFilter *)&pWriter[1];
150710  pCsr = (Fts3MultiSegReader *)&pFilter[1];
150711
150712  rc = fts3IncrmergeHintLoad(p, &hint);
150713  while( rc==SQLITE_OK && nRem>0 ){
150714    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
150715    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
150716    int bUseHint = 0;             /* True if attempting to append */
150717    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
150718
150719    /* Search the %_segdir table for the absolute level with the smallest
150720    ** relative level number that contains at least nMin segments, if any.
150721    ** If one is found, set iAbsLevel to the absolute level number and
150722    ** nSeg to nMin. If no level with at least nMin segments can be found,
150723    ** set nSeg to -1.
150724    */
150725    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
150726    sqlite3_bind_int(pFindLevel, 1, nMin);
150727    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
150728      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
150729      nSeg = nMin;
150730    }else{
150731      nSeg = -1;
150732    }
150733    rc = sqlite3_reset(pFindLevel);
150734
150735    /* If the hint read from the %_stat table is not empty, check if the
150736    ** last entry in it specifies a relative level smaller than or equal
150737    ** to the level identified by the block above (if any). If so, this
150738    ** iteration of the loop will work on merging at the hinted level.
150739    */
150740    if( rc==SQLITE_OK && hint.n ){
150741      int nHint = hint.n;
150742      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
150743      int nHintSeg = 0;                     /* Hint number of segments */
150744
150745      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
150746      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
150747        iAbsLevel = iHintAbsLevel;
150748        nSeg = nHintSeg;
150749        bUseHint = 1;
150750        bDirtyHint = 1;
150751      }else{
150752        /* This undoes the effect of the HintPop() above - so that no entry
150753        ** is removed from the hint blob.  */
150754        hint.n = nHint;
150755      }
150756    }
150757
150758    /* If nSeg is less that zero, then there is no level with at least
150759    ** nMin segments and no hint in the %_stat table. No work to do.
150760    ** Exit early in this case.  */
150761    if( nSeg<0 ) break;
150762
150763    /* Open a cursor to iterate through the contents of the oldest nSeg
150764    ** indexes of absolute level iAbsLevel. If this cursor is opened using
150765    ** the 'hint' parameters, it is possible that there are less than nSeg
150766    ** segments available in level iAbsLevel. In this case, no work is
150767    ** done on iAbsLevel - fall through to the next iteration of the loop
150768    ** to start work on some other level.  */
150769    memset(pWriter, 0, nAlloc);
150770    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
150771
150772    if( rc==SQLITE_OK ){
150773      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
150774      assert( bUseHint==1 || bUseHint==0 );
150775      if( iIdx==0 || (bUseHint && iIdx==1) ){
150776        int bIgnore = 0;
150777        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
150778        if( bIgnore ){
150779          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
150780        }
150781      }
150782    }
150783
150784    if( rc==SQLITE_OK ){
150785      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
150786    }
150787    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
150788     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
150789     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
150790    ){
150791      if( bUseHint && iIdx>0 ){
150792        const char *zKey = pCsr->zTerm;
150793        int nKey = pCsr->nTerm;
150794        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
150795      }else{
150796        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
150797      }
150798
150799      if( rc==SQLITE_OK && pWriter->nLeafEst ){
150800        fts3LogMerge(nSeg, iAbsLevel);
150801        do {
150802          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
150803          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
150804          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
150805        }while( rc==SQLITE_ROW );
150806
150807        /* Update or delete the input segments */
150808        if( rc==SQLITE_OK ){
150809          nRem -= (1 + pWriter->nWork);
150810          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
150811          if( nSeg!=0 ){
150812            bDirtyHint = 1;
150813            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
150814          }
150815        }
150816      }
150817
150818      if( nSeg!=0 ){
150819        pWriter->nLeafData = pWriter->nLeafData * -1;
150820      }
150821      fts3IncrmergeRelease(p, pWriter, &rc);
150822      if( nSeg==0 && pWriter->bNoLeafData==0 ){
150823        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
150824      }
150825    }
150826
150827    sqlite3Fts3SegReaderFinish(pCsr);
150828  }
150829
150830  /* Write the hint values into the %_stat table for the next incr-merger */
150831  if( bDirtyHint && rc==SQLITE_OK ){
150832    rc = fts3IncrmergeHintStore(p, &hint);
150833  }
150834
150835  sqlite3_free(pWriter);
150836  sqlite3_free(hint.a);
150837  return rc;
150838}
150839
150840/*
150841** Convert the text beginning at *pz into an integer and return
150842** its value.  Advance *pz to point to the first character past
150843** the integer.
150844*/
150845static int fts3Getint(const char **pz){
150846  const char *z = *pz;
150847  int i = 0;
150848  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
150849  *pz = z;
150850  return i;
150851}
150852
150853/*
150854** Process statements of the form:
150855**
150856**    INSERT INTO table(table) VALUES('merge=A,B');
150857**
150858** A and B are integers that decode to be the number of leaf pages
150859** written for the merge, and the minimum number of segments on a level
150860** before it will be selected for a merge, respectively.
150861*/
150862static int fts3DoIncrmerge(
150863  Fts3Table *p,                   /* FTS3 table handle */
150864  const char *zParam              /* Nul-terminated string containing "A,B" */
150865){
150866  int rc;
150867  int nMin = (FTS3_MERGE_COUNT / 2);
150868  int nMerge = 0;
150869  const char *z = zParam;
150870
150871  /* Read the first integer value */
150872  nMerge = fts3Getint(&z);
150873
150874  /* If the first integer value is followed by a ',',  read the second
150875  ** integer value. */
150876  if( z[0]==',' && z[1]!='\0' ){
150877    z++;
150878    nMin = fts3Getint(&z);
150879  }
150880
150881  if( z[0]!='\0' || nMin<2 ){
150882    rc = SQLITE_ERROR;
150883  }else{
150884    rc = SQLITE_OK;
150885    if( !p->bHasStat ){
150886      assert( p->bFts4==0 );
150887      sqlite3Fts3CreateStatTable(&rc, p);
150888    }
150889    if( rc==SQLITE_OK ){
150890      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
150891    }
150892    sqlite3Fts3SegmentsClose(p);
150893  }
150894  return rc;
150895}
150896
150897/*
150898** Process statements of the form:
150899**
150900**    INSERT INTO table(table) VALUES('automerge=X');
150901**
150902** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
150903** turn it on.  The setting is persistent.
150904*/
150905static int fts3DoAutoincrmerge(
150906  Fts3Table *p,                   /* FTS3 table handle */
150907  const char *zParam              /* Nul-terminated string containing boolean */
150908){
150909  int rc = SQLITE_OK;
150910  sqlite3_stmt *pStmt = 0;
150911  p->nAutoincrmerge = fts3Getint(&zParam);
150912  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
150913    p->nAutoincrmerge = 8;
150914  }
150915  if( !p->bHasStat ){
150916    assert( p->bFts4==0 );
150917    sqlite3Fts3CreateStatTable(&rc, p);
150918    if( rc ) return rc;
150919  }
150920  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
150921  if( rc ) return rc;
150922  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
150923  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
150924  sqlite3_step(pStmt);
150925  rc = sqlite3_reset(pStmt);
150926  return rc;
150927}
150928
150929/*
150930** Return a 64-bit checksum for the FTS index entry specified by the
150931** arguments to this function.
150932*/
150933static u64 fts3ChecksumEntry(
150934  const char *zTerm,              /* Pointer to buffer containing term */
150935  int nTerm,                      /* Size of zTerm in bytes */
150936  int iLangid,                    /* Language id for current row */
150937  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
150938  i64 iDocid,                     /* Docid for current row. */
150939  int iCol,                       /* Column number */
150940  int iPos                        /* Position */
150941){
150942  int i;
150943  u64 ret = (u64)iDocid;
150944
150945  ret += (ret<<3) + iLangid;
150946  ret += (ret<<3) + iIndex;
150947  ret += (ret<<3) + iCol;
150948  ret += (ret<<3) + iPos;
150949  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
150950
150951  return ret;
150952}
150953
150954/*
150955** Return a checksum of all entries in the FTS index that correspond to
150956** language id iLangid. The checksum is calculated by XORing the checksums
150957** of each individual entry (see fts3ChecksumEntry()) together.
150958**
150959** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
150960** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
150961** return value is undefined in this case.
150962*/
150963static u64 fts3ChecksumIndex(
150964  Fts3Table *p,                   /* FTS3 table handle */
150965  int iLangid,                    /* Language id to return cksum for */
150966  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
150967  int *pRc                        /* OUT: Return code */
150968){
150969  Fts3SegFilter filter;
150970  Fts3MultiSegReader csr;
150971  int rc;
150972  u64 cksum = 0;
150973
150974  assert( *pRc==SQLITE_OK );
150975
150976  memset(&filter, 0, sizeof(filter));
150977  memset(&csr, 0, sizeof(csr));
150978  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
150979  filter.flags |= FTS3_SEGMENT_SCAN;
150980
150981  rc = sqlite3Fts3SegReaderCursor(
150982      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
150983  );
150984  if( rc==SQLITE_OK ){
150985    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
150986  }
150987
150988  if( rc==SQLITE_OK ){
150989    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
150990      char *pCsr = csr.aDoclist;
150991      char *pEnd = &pCsr[csr.nDoclist];
150992
150993      i64 iDocid = 0;
150994      i64 iCol = 0;
150995      i64 iPos = 0;
150996
150997      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
150998      while( pCsr<pEnd ){
150999        i64 iVal = 0;
151000        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
151001        if( pCsr<pEnd ){
151002          if( iVal==0 || iVal==1 ){
151003            iCol = 0;
151004            iPos = 0;
151005            if( iVal ){
151006              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
151007            }else{
151008              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
151009              iDocid += iVal;
151010            }
151011          }else{
151012            iPos += (iVal - 2);
151013            cksum = cksum ^ fts3ChecksumEntry(
151014                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
151015                (int)iCol, (int)iPos
151016            );
151017          }
151018        }
151019      }
151020    }
151021  }
151022  sqlite3Fts3SegReaderFinish(&csr);
151023
151024  *pRc = rc;
151025  return cksum;
151026}
151027
151028/*
151029** Check if the contents of the FTS index match the current contents of the
151030** content table. If no error occurs and the contents do match, set *pbOk
151031** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
151032** to false before returning.
151033**
151034** If an error occurs (e.g. an OOM or IO error), return an SQLite error
151035** code. The final value of *pbOk is undefined in this case.
151036*/
151037static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
151038  int rc = SQLITE_OK;             /* Return code */
151039  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
151040  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
151041  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
151042
151043  /* This block calculates the checksum according to the FTS index. */
151044  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
151045  if( rc==SQLITE_OK ){
151046    int rc2;
151047    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
151048    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
151049    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
151050      int iLangid = sqlite3_column_int(pAllLangid, 0);
151051      int i;
151052      for(i=0; i<p->nIndex; i++){
151053        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
151054      }
151055    }
151056    rc2 = sqlite3_reset(pAllLangid);
151057    if( rc==SQLITE_OK ) rc = rc2;
151058  }
151059
151060  /* This block calculates the checksum according to the %_content table */
151061  if( rc==SQLITE_OK ){
151062    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
151063    sqlite3_stmt *pStmt = 0;
151064    char *zSql;
151065
151066    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
151067    if( !zSql ){
151068      rc = SQLITE_NOMEM;
151069    }else{
151070      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
151071      sqlite3_free(zSql);
151072    }
151073
151074    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
151075      i64 iDocid = sqlite3_column_int64(pStmt, 0);
151076      int iLang = langidFromSelect(p, pStmt);
151077      int iCol;
151078
151079      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
151080        if( p->abNotindexed[iCol]==0 ){
151081          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
151082          int nText = sqlite3_column_bytes(pStmt, iCol+1);
151083          sqlite3_tokenizer_cursor *pT = 0;
151084
151085          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
151086          while( rc==SQLITE_OK ){
151087            char const *zToken;       /* Buffer containing token */
151088            int nToken = 0;           /* Number of bytes in token */
151089            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
151090            int iPos = 0;             /* Position of token in zText */
151091
151092            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
151093            if( rc==SQLITE_OK ){
151094              int i;
151095              cksum2 = cksum2 ^ fts3ChecksumEntry(
151096                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
151097              );
151098              for(i=1; i<p->nIndex; i++){
151099                if( p->aIndex[i].nPrefix<=nToken ){
151100                  cksum2 = cksum2 ^ fts3ChecksumEntry(
151101                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
151102                  );
151103                }
151104              }
151105            }
151106          }
151107          if( pT ) pModule->xClose(pT);
151108          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151109        }
151110      }
151111    }
151112
151113    sqlite3_finalize(pStmt);
151114  }
151115
151116  *pbOk = (cksum1==cksum2);
151117  return rc;
151118}
151119
151120/*
151121** Run the integrity-check. If no error occurs and the current contents of
151122** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
151123** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
151124**
151125** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
151126** error code.
151127**
151128** The integrity-check works as follows. For each token and indexed token
151129** prefix in the document set, a 64-bit checksum is calculated (by code
151130** in fts3ChecksumEntry()) based on the following:
151131**
151132**     + The index number (0 for the main index, 1 for the first prefix
151133**       index etc.),
151134**     + The token (or token prefix) text itself,
151135**     + The language-id of the row it appears in,
151136**     + The docid of the row it appears in,
151137**     + The column it appears in, and
151138**     + The tokens position within that column.
151139**
151140** The checksums for all entries in the index are XORed together to create
151141** a single checksum for the entire index.
151142**
151143** The integrity-check code calculates the same checksum in two ways:
151144**
151145**     1. By scanning the contents of the FTS index, and
151146**     2. By scanning and tokenizing the content table.
151147**
151148** If the two checksums are identical, the integrity-check is deemed to have
151149** passed.
151150*/
151151static int fts3DoIntegrityCheck(
151152  Fts3Table *p                    /* FTS3 table handle */
151153){
151154  int rc;
151155  int bOk = 0;
151156  rc = fts3IntegrityCheck(p, &bOk);
151157  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
151158  return rc;
151159}
151160
151161/*
151162** Handle a 'special' INSERT of the form:
151163**
151164**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
151165**
151166** Argument pVal contains the result of <expr>. Currently the only
151167** meaningful value to insert is the text 'optimize'.
151168*/
151169static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
151170  int rc;                         /* Return Code */
151171  const char *zVal = (const char *)sqlite3_value_text(pVal);
151172  int nVal = sqlite3_value_bytes(pVal);
151173
151174  if( !zVal ){
151175    return SQLITE_NOMEM;
151176  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
151177    rc = fts3DoOptimize(p, 0);
151178  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
151179    rc = fts3DoRebuild(p);
151180  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
151181    rc = fts3DoIntegrityCheck(p);
151182  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
151183    rc = fts3DoIncrmerge(p, &zVal[6]);
151184  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
151185    rc = fts3DoAutoincrmerge(p, &zVal[10]);
151186#ifdef SQLITE_TEST
151187  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
151188    p->nNodeSize = atoi(&zVal[9]);
151189    rc = SQLITE_OK;
151190  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
151191    p->nMaxPendingData = atoi(&zVal[11]);
151192    rc = SQLITE_OK;
151193  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
151194    p->bNoIncrDoclist = atoi(&zVal[21]);
151195    rc = SQLITE_OK;
151196#endif
151197  }else{
151198    rc = SQLITE_ERROR;
151199  }
151200
151201  return rc;
151202}
151203
151204#ifndef SQLITE_DISABLE_FTS4_DEFERRED
151205/*
151206** Delete all cached deferred doclists. Deferred doclists are cached
151207** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
151208*/
151209SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
151210  Fts3DeferredToken *pDef;
151211  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
151212    fts3PendingListDelete(pDef->pList);
151213    pDef->pList = 0;
151214  }
151215}
151216
151217/*
151218** Free all entries in the pCsr->pDeffered list. Entries are added to
151219** this list using sqlite3Fts3DeferToken().
151220*/
151221SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
151222  Fts3DeferredToken *pDef;
151223  Fts3DeferredToken *pNext;
151224  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
151225    pNext = pDef->pNext;
151226    fts3PendingListDelete(pDef->pList);
151227    sqlite3_free(pDef);
151228  }
151229  pCsr->pDeferred = 0;
151230}
151231
151232/*
151233** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
151234** based on the row that pCsr currently points to.
151235**
151236** A deferred-doclist is like any other doclist with position information
151237** included, except that it only contains entries for a single row of the
151238** table, not for all rows.
151239*/
151240SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
151241  int rc = SQLITE_OK;             /* Return code */
151242  if( pCsr->pDeferred ){
151243    int i;                        /* Used to iterate through table columns */
151244    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
151245    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
151246
151247    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
151248    sqlite3_tokenizer *pT = p->pTokenizer;
151249    sqlite3_tokenizer_module const *pModule = pT->pModule;
151250
151251    assert( pCsr->isRequireSeek==0 );
151252    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
151253
151254    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
151255      if( p->abNotindexed[i]==0 ){
151256        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
151257        sqlite3_tokenizer_cursor *pTC = 0;
151258
151259        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
151260        while( rc==SQLITE_OK ){
151261          char const *zToken;       /* Buffer containing token */
151262          int nToken = 0;           /* Number of bytes in token */
151263          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
151264          int iPos = 0;             /* Position of token in zText */
151265
151266          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
151267          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
151268            Fts3PhraseToken *pPT = pDef->pToken;
151269            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
151270                && (pPT->bFirst==0 || iPos==0)
151271                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
151272                && (0==memcmp(zToken, pPT->z, pPT->n))
151273              ){
151274              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
151275            }
151276          }
151277        }
151278        if( pTC ) pModule->xClose(pTC);
151279        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151280      }
151281    }
151282
151283    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
151284      if( pDef->pList ){
151285        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
151286      }
151287    }
151288  }
151289
151290  return rc;
151291}
151292
151293SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
151294  Fts3DeferredToken *p,
151295  char **ppData,
151296  int *pnData
151297){
151298  char *pRet;
151299  int nSkip;
151300  sqlite3_int64 dummy;
151301
151302  *ppData = 0;
151303  *pnData = 0;
151304
151305  if( p->pList==0 ){
151306    return SQLITE_OK;
151307  }
151308
151309  pRet = (char *)sqlite3_malloc(p->pList->nData);
151310  if( !pRet ) return SQLITE_NOMEM;
151311
151312  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
151313  *pnData = p->pList->nData - nSkip;
151314  *ppData = pRet;
151315
151316  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
151317  return SQLITE_OK;
151318}
151319
151320/*
151321** Add an entry for token pToken to the pCsr->pDeferred list.
151322*/
151323SQLITE_PRIVATE int sqlite3Fts3DeferToken(
151324  Fts3Cursor *pCsr,               /* Fts3 table cursor */
151325  Fts3PhraseToken *pToken,        /* Token to defer */
151326  int iCol                        /* Column that token must appear in (or -1) */
151327){
151328  Fts3DeferredToken *pDeferred;
151329  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
151330  if( !pDeferred ){
151331    return SQLITE_NOMEM;
151332  }
151333  memset(pDeferred, 0, sizeof(*pDeferred));
151334  pDeferred->pToken = pToken;
151335  pDeferred->pNext = pCsr->pDeferred;
151336  pDeferred->iCol = iCol;
151337  pCsr->pDeferred = pDeferred;
151338
151339  assert( pToken->pDeferred==0 );
151340  pToken->pDeferred = pDeferred;
151341
151342  return SQLITE_OK;
151343}
151344#endif
151345
151346/*
151347** SQLite value pRowid contains the rowid of a row that may or may not be
151348** present in the FTS3 table. If it is, delete it and adjust the contents
151349** of subsiduary data structures accordingly.
151350*/
151351static int fts3DeleteByRowid(
151352  Fts3Table *p,
151353  sqlite3_value *pRowid,
151354  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
151355  u32 *aSzDel
151356){
151357  int rc = SQLITE_OK;             /* Return code */
151358  int bFound = 0;                 /* True if *pRowid really is in the table */
151359
151360  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
151361  if( bFound && rc==SQLITE_OK ){
151362    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
151363    rc = fts3IsEmpty(p, pRowid, &isEmpty);
151364    if( rc==SQLITE_OK ){
151365      if( isEmpty ){
151366        /* Deleting this row means the whole table is empty. In this case
151367        ** delete the contents of all three tables and throw away any
151368        ** data in the pendingTerms hash table.  */
151369        rc = fts3DeleteAll(p, 1);
151370        *pnChng = 0;
151371        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
151372      }else{
151373        *pnChng = *pnChng - 1;
151374        if( p->zContentTbl==0 ){
151375          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
151376        }
151377        if( p->bHasDocsize ){
151378          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
151379        }
151380      }
151381    }
151382  }
151383
151384  return rc;
151385}
151386
151387/*
151388** This function does the work for the xUpdate method of FTS3 virtual
151389** tables. The schema of the virtual table being:
151390**
151391**     CREATE TABLE <table name>(
151392**       <user columns>,
151393**       <table name> HIDDEN,
151394**       docid HIDDEN,
151395**       <langid> HIDDEN
151396**     );
151397**
151398**
151399*/
151400SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
151401  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
151402  int nArg,                       /* Size of argument array */
151403  sqlite3_value **apVal,          /* Array of arguments */
151404  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
151405){
151406  Fts3Table *p = (Fts3Table *)pVtab;
151407  int rc = SQLITE_OK;             /* Return Code */
151408  int isRemove = 0;               /* True for an UPDATE or DELETE */
151409  u32 *aSzIns = 0;                /* Sizes of inserted documents */
151410  u32 *aSzDel = 0;                /* Sizes of deleted documents */
151411  int nChng = 0;                  /* Net change in number of documents */
151412  int bInsertDone = 0;
151413
151414  /* At this point it must be known if the %_stat table exists or not.
151415  ** So bHasStat may not be 2.  */
151416  assert( p->bHasStat==0 || p->bHasStat==1 );
151417
151418  assert( p->pSegments==0 );
151419  assert(
151420      nArg==1                     /* DELETE operations */
151421   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
151422  );
151423
151424  /* Check for a "special" INSERT operation. One of the form:
151425  **
151426  **   INSERT INTO xyz(xyz) VALUES('command');
151427  */
151428  if( nArg>1
151429   && sqlite3_value_type(apVal[0])==SQLITE_NULL
151430   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
151431  ){
151432    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
151433    goto update_out;
151434  }
151435
151436  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
151437    rc = SQLITE_CONSTRAINT;
151438    goto update_out;
151439  }
151440
151441  /* Allocate space to hold the change in document sizes */
151442  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
151443  if( aSzDel==0 ){
151444    rc = SQLITE_NOMEM;
151445    goto update_out;
151446  }
151447  aSzIns = &aSzDel[p->nColumn+1];
151448  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
151449
151450  rc = fts3Writelock(p);
151451  if( rc!=SQLITE_OK ) goto update_out;
151452
151453  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
151454  ** value, then this operation requires constraint handling.
151455  **
151456  ** If the on-conflict mode is REPLACE, this means that the existing row
151457  ** should be deleted from the database before inserting the new row. Or,
151458  ** if the on-conflict mode is other than REPLACE, then this method must
151459  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
151460  ** modify the database file.
151461  */
151462  if( nArg>1 && p->zContentTbl==0 ){
151463    /* Find the value object that holds the new rowid value. */
151464    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
151465    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
151466      pNewRowid = apVal[1];
151467    }
151468
151469    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
151470        sqlite3_value_type(apVal[0])==SQLITE_NULL
151471     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
151472    )){
151473      /* The new rowid is not NULL (in this case the rowid will be
151474      ** automatically assigned and there is no chance of a conflict), and
151475      ** the statement is either an INSERT or an UPDATE that modifies the
151476      ** rowid column. So if the conflict mode is REPLACE, then delete any
151477      ** existing row with rowid=pNewRowid.
151478      **
151479      ** Or, if the conflict mode is not REPLACE, insert the new record into
151480      ** the %_content table. If we hit the duplicate rowid constraint (or any
151481      ** other error) while doing so, return immediately.
151482      **
151483      ** This branch may also run if pNewRowid contains a value that cannot
151484      ** be losslessly converted to an integer. In this case, the eventual
151485      ** call to fts3InsertData() (either just below or further on in this
151486      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
151487      ** invoked, it will delete zero rows (since no row will have
151488      ** docid=$pNewRowid if $pNewRowid is not an integer value).
151489      */
151490      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
151491        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
151492      }else{
151493        rc = fts3InsertData(p, apVal, pRowid);
151494        bInsertDone = 1;
151495      }
151496    }
151497  }
151498  if( rc!=SQLITE_OK ){
151499    goto update_out;
151500  }
151501
151502  /* If this is a DELETE or UPDATE operation, remove the old record. */
151503  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
151504    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
151505    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
151506    isRemove = 1;
151507  }
151508
151509  /* If this is an INSERT or UPDATE operation, insert the new record. */
151510  if( nArg>1 && rc==SQLITE_OK ){
151511    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
151512    if( bInsertDone==0 ){
151513      rc = fts3InsertData(p, apVal, pRowid);
151514      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
151515        rc = FTS_CORRUPT_VTAB;
151516      }
151517    }
151518    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
151519      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
151520    }
151521    if( rc==SQLITE_OK ){
151522      assert( p->iPrevDocid==*pRowid );
151523      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
151524    }
151525    if( p->bHasDocsize ){
151526      fts3InsertDocsize(&rc, p, aSzIns);
151527    }
151528    nChng++;
151529  }
151530
151531  if( p->bFts4 ){
151532    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
151533  }
151534
151535 update_out:
151536  sqlite3_free(aSzDel);
151537  sqlite3Fts3SegmentsClose(p);
151538  return rc;
151539}
151540
151541/*
151542** Flush any data in the pending-terms hash table to disk. If successful,
151543** merge all segments in the database (including the new segment, if
151544** there was any data to flush) into a single segment.
151545*/
151546SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
151547  int rc;
151548  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
151549  if( rc==SQLITE_OK ){
151550    rc = fts3DoOptimize(p, 1);
151551    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
151552      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
151553      if( rc2!=SQLITE_OK ) rc = rc2;
151554    }else{
151555      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
151556      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
151557    }
151558  }
151559  sqlite3Fts3SegmentsClose(p);
151560  return rc;
151561}
151562
151563#endif
151564
151565/************** End of fts3_write.c ******************************************/
151566/************** Begin file fts3_snippet.c ************************************/
151567/*
151568** 2009 Oct 23
151569**
151570** The author disclaims copyright to this source code.  In place of
151571** a legal notice, here is a blessing:
151572**
151573**    May you do good and not evil.
151574**    May you find forgiveness for yourself and forgive others.
151575**    May you share freely, never taking more than you give.
151576**
151577******************************************************************************
151578*/
151579
151580/* #include "fts3Int.h" */
151581#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151582
151583/* #include <string.h> */
151584/* #include <assert.h> */
151585
151586/*
151587** Characters that may appear in the second argument to matchinfo().
151588*/
151589#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
151590#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
151591#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
151592#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
151593#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
151594#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
151595#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
151596#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
151597#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
151598
151599/*
151600** The default value for the second argument to matchinfo().
151601*/
151602#define FTS3_MATCHINFO_DEFAULT   "pcx"
151603
151604
151605/*
151606** Used as an fts3ExprIterate() context when loading phrase doclists to
151607** Fts3Expr.aDoclist[]/nDoclist.
151608*/
151609typedef struct LoadDoclistCtx LoadDoclistCtx;
151610struct LoadDoclistCtx {
151611  Fts3Cursor *pCsr;               /* FTS3 Cursor */
151612  int nPhrase;                    /* Number of phrases seen so far */
151613  int nToken;                     /* Number of tokens seen so far */
151614};
151615
151616/*
151617** The following types are used as part of the implementation of the
151618** fts3BestSnippet() routine.
151619*/
151620typedef struct SnippetIter SnippetIter;
151621typedef struct SnippetPhrase SnippetPhrase;
151622typedef struct SnippetFragment SnippetFragment;
151623
151624struct SnippetIter {
151625  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
151626  int iCol;                       /* Extract snippet from this column */
151627  int nSnippet;                   /* Requested snippet length (in tokens) */
151628  int nPhrase;                    /* Number of phrases in query */
151629  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
151630  int iCurrent;                   /* First token of current snippet */
151631};
151632
151633struct SnippetPhrase {
151634  int nToken;                     /* Number of tokens in phrase */
151635  char *pList;                    /* Pointer to start of phrase position list */
151636  int iHead;                      /* Next value in position list */
151637  char *pHead;                    /* Position list data following iHead */
151638  int iTail;                      /* Next value in trailing position list */
151639  char *pTail;                    /* Position list data following iTail */
151640};
151641
151642struct SnippetFragment {
151643  int iCol;                       /* Column snippet is extracted from */
151644  int iPos;                       /* Index of first token in snippet */
151645  u64 covered;                    /* Mask of query phrases covered */
151646  u64 hlmask;                     /* Mask of snippet terms to highlight */
151647};
151648
151649/*
151650** This type is used as an fts3ExprIterate() context object while
151651** accumulating the data returned by the matchinfo() function.
151652*/
151653typedef struct MatchInfo MatchInfo;
151654struct MatchInfo {
151655  Fts3Cursor *pCursor;            /* FTS3 Cursor */
151656  int nCol;                       /* Number of columns in table */
151657  int nPhrase;                    /* Number of matchable phrases in query */
151658  sqlite3_int64 nDoc;             /* Number of docs in database */
151659  char flag;
151660  u32 *aMatchinfo;                /* Pre-allocated buffer */
151661};
151662
151663/*
151664** An instance of this structure is used to manage a pair of buffers, each
151665** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
151666** for details.
151667*/
151668struct MatchinfoBuffer {
151669  u8 aRef[3];
151670  int nElem;
151671  int bGlobal;                    /* Set if global data is loaded */
151672  char *zMatchinfo;
151673  u32 aMatchinfo[1];
151674};
151675
151676
151677/*
151678** The snippet() and offsets() functions both return text values. An instance
151679** of the following structure is used to accumulate those values while the
151680** functions are running. See fts3StringAppend() for details.
151681*/
151682typedef struct StrBuffer StrBuffer;
151683struct StrBuffer {
151684  char *z;                        /* Pointer to buffer containing string */
151685  int n;                          /* Length of z in bytes (excl. nul-term) */
151686  int nAlloc;                     /* Allocated size of buffer z in bytes */
151687};
151688
151689
151690/*************************************************************************
151691** Start of MatchinfoBuffer code.
151692*/
151693
151694/*
151695** Allocate a two-slot MatchinfoBuffer object.
151696*/
151697static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
151698  MatchinfoBuffer *pRet;
151699  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
151700  int nStr = (int)strlen(zMatchinfo);
151701
151702  pRet = sqlite3_malloc(nByte + nStr+1);
151703  if( pRet ){
151704    memset(pRet, 0, nByte);
151705    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
151706    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
151707    pRet->nElem = nElem;
151708    pRet->zMatchinfo = ((char*)pRet) + nByte;
151709    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
151710    pRet->aRef[0] = 1;
151711  }
151712
151713  return pRet;
151714}
151715
151716static void fts3MIBufferFree(void *p){
151717  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
151718
151719  assert( (u32*)p==&pBuf->aMatchinfo[1]
151720       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
151721  );
151722  if( (u32*)p==&pBuf->aMatchinfo[1] ){
151723    pBuf->aRef[1] = 0;
151724  }else{
151725    pBuf->aRef[2] = 0;
151726  }
151727
151728  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
151729    sqlite3_free(pBuf);
151730  }
151731}
151732
151733static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
151734  void (*xRet)(void*) = 0;
151735  u32 *aOut = 0;
151736
151737  if( p->aRef[1]==0 ){
151738    p->aRef[1] = 1;
151739    aOut = &p->aMatchinfo[1];
151740    xRet = fts3MIBufferFree;
151741  }
151742  else if( p->aRef[2]==0 ){
151743    p->aRef[2] = 1;
151744    aOut = &p->aMatchinfo[p->nElem+2];
151745    xRet = fts3MIBufferFree;
151746  }else{
151747    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
151748    if( aOut ){
151749      xRet = sqlite3_free;
151750      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
151751    }
151752  }
151753
151754  *paOut = aOut;
151755  return xRet;
151756}
151757
151758static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
151759  p->bGlobal = 1;
151760  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
151761}
151762
151763/*
151764** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
151765*/
151766SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
151767  if( p ){
151768    assert( p->aRef[0]==1 );
151769    p->aRef[0] = 0;
151770    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
151771      sqlite3_free(p);
151772    }
151773  }
151774}
151775
151776/*
151777** End of MatchinfoBuffer code.
151778*************************************************************************/
151779
151780
151781/*
151782** This function is used to help iterate through a position-list. A position
151783** list is a list of unique integers, sorted from smallest to largest. Each
151784** element of the list is represented by an FTS3 varint that takes the value
151785** of the difference between the current element and the previous one plus
151786** two. For example, to store the position-list:
151787**
151788**     4 9 113
151789**
151790** the three varints:
151791**
151792**     6 7 106
151793**
151794** are encoded.
151795**
151796** When this function is called, *pp points to the start of an element of
151797** the list. *piPos contains the value of the previous entry in the list.
151798** After it returns, *piPos contains the value of the next element of the
151799** list and *pp is advanced to the following varint.
151800*/
151801static void fts3GetDeltaPosition(char **pp, int *piPos){
151802  int iVal;
151803  *pp += fts3GetVarint32(*pp, &iVal);
151804  *piPos += (iVal-2);
151805}
151806
151807/*
151808** Helper function for fts3ExprIterate() (see below).
151809*/
151810static int fts3ExprIterate2(
151811  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
151812  int *piPhrase,                  /* Pointer to phrase counter */
151813  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
151814  void *pCtx                      /* Second argument to pass to callback */
151815){
151816  int rc;                         /* Return code */
151817  int eType = pExpr->eType;     /* Type of expression node pExpr */
151818
151819  if( eType!=FTSQUERY_PHRASE ){
151820    assert( pExpr->pLeft && pExpr->pRight );
151821    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
151822    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
151823      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
151824    }
151825  }else{
151826    rc = x(pExpr, *piPhrase, pCtx);
151827    (*piPhrase)++;
151828  }
151829  return rc;
151830}
151831
151832/*
151833** Iterate through all phrase nodes in an FTS3 query, except those that
151834** are part of a sub-tree that is the right-hand-side of a NOT operator.
151835** For each phrase node found, the supplied callback function is invoked.
151836**
151837** If the callback function returns anything other than SQLITE_OK,
151838** the iteration is abandoned and the error code returned immediately.
151839** Otherwise, SQLITE_OK is returned after a callback has been made for
151840** all eligible phrase nodes.
151841*/
151842static int fts3ExprIterate(
151843  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
151844  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
151845  void *pCtx                      /* Second argument to pass to callback */
151846){
151847  int iPhrase = 0;                /* Variable used as the phrase counter */
151848  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
151849}
151850
151851
151852/*
151853** This is an fts3ExprIterate() callback used while loading the doclists
151854** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
151855** fts3ExprLoadDoclists().
151856*/
151857static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
151858  int rc = SQLITE_OK;
151859  Fts3Phrase *pPhrase = pExpr->pPhrase;
151860  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
151861
151862  UNUSED_PARAMETER(iPhrase);
151863
151864  p->nPhrase++;
151865  p->nToken += pPhrase->nToken;
151866
151867  return rc;
151868}
151869
151870/*
151871** Load the doclists for each phrase in the query associated with FTS3 cursor
151872** pCsr.
151873**
151874** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
151875** phrases in the expression (all phrases except those directly or
151876** indirectly descended from the right-hand-side of a NOT operator). If
151877** pnToken is not NULL, then it is set to the number of tokens in all
151878** matchable phrases of the expression.
151879*/
151880static int fts3ExprLoadDoclists(
151881  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
151882  int *pnPhrase,                  /* OUT: Number of phrases in query */
151883  int *pnToken                    /* OUT: Number of tokens in query */
151884){
151885  int rc;                         /* Return Code */
151886  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
151887  sCtx.pCsr = pCsr;
151888  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
151889  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
151890  if( pnToken ) *pnToken = sCtx.nToken;
151891  return rc;
151892}
151893
151894static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
151895  (*(int *)ctx)++;
151896  pExpr->iPhrase = iPhrase;
151897  return SQLITE_OK;
151898}
151899static int fts3ExprPhraseCount(Fts3Expr *pExpr){
151900  int nPhrase = 0;
151901  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
151902  return nPhrase;
151903}
151904
151905/*
151906** Advance the position list iterator specified by the first two
151907** arguments so that it points to the first element with a value greater
151908** than or equal to parameter iNext.
151909*/
151910static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
151911  char *pIter = *ppIter;
151912  if( pIter ){
151913    int iIter = *piIter;
151914
151915    while( iIter<iNext ){
151916      if( 0==(*pIter & 0xFE) ){
151917        iIter = -1;
151918        pIter = 0;
151919        break;
151920      }
151921      fts3GetDeltaPosition(&pIter, &iIter);
151922    }
151923
151924    *piIter = iIter;
151925    *ppIter = pIter;
151926  }
151927}
151928
151929/*
151930** Advance the snippet iterator to the next candidate snippet.
151931*/
151932static int fts3SnippetNextCandidate(SnippetIter *pIter){
151933  int i;                          /* Loop counter */
151934
151935  if( pIter->iCurrent<0 ){
151936    /* The SnippetIter object has just been initialized. The first snippet
151937    ** candidate always starts at offset 0 (even if this candidate has a
151938    ** score of 0.0).
151939    */
151940    pIter->iCurrent = 0;
151941
151942    /* Advance the 'head' iterator of each phrase to the first offset that
151943    ** is greater than or equal to (iNext+nSnippet).
151944    */
151945    for(i=0; i<pIter->nPhrase; i++){
151946      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151947      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
151948    }
151949  }else{
151950    int iStart;
151951    int iEnd = 0x7FFFFFFF;
151952
151953    for(i=0; i<pIter->nPhrase; i++){
151954      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151955      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
151956        iEnd = pPhrase->iHead;
151957      }
151958    }
151959    if( iEnd==0x7FFFFFFF ){
151960      return 1;
151961    }
151962
151963    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
151964    for(i=0; i<pIter->nPhrase; i++){
151965      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151966      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
151967      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
151968    }
151969  }
151970
151971  return 0;
151972}
151973
151974/*
151975** Retrieve information about the current candidate snippet of snippet
151976** iterator pIter.
151977*/
151978static void fts3SnippetDetails(
151979  SnippetIter *pIter,             /* Snippet iterator */
151980  u64 mCovered,                   /* Bitmask of phrases already covered */
151981  int *piToken,                   /* OUT: First token of proposed snippet */
151982  int *piScore,                   /* OUT: "Score" for this snippet */
151983  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
151984  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
151985){
151986  int iStart = pIter->iCurrent;   /* First token of snippet */
151987  int iScore = 0;                 /* Score of this snippet */
151988  int i;                          /* Loop counter */
151989  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
151990  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
151991
151992  for(i=0; i<pIter->nPhrase; i++){
151993    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151994    if( pPhrase->pTail ){
151995      char *pCsr = pPhrase->pTail;
151996      int iCsr = pPhrase->iTail;
151997
151998      while( iCsr<(iStart+pIter->nSnippet) ){
151999        int j;
152000        u64 mPhrase = (u64)1 << i;
152001        u64 mPos = (u64)1 << (iCsr - iStart);
152002        assert( iCsr>=iStart );
152003        if( (mCover|mCovered)&mPhrase ){
152004          iScore++;
152005        }else{
152006          iScore += 1000;
152007        }
152008        mCover |= mPhrase;
152009
152010        for(j=0; j<pPhrase->nToken; j++){
152011          mHighlight |= (mPos>>j);
152012        }
152013
152014        if( 0==(*pCsr & 0x0FE) ) break;
152015        fts3GetDeltaPosition(&pCsr, &iCsr);
152016      }
152017    }
152018  }
152019
152020  /* Set the output variables before returning. */
152021  *piToken = iStart;
152022  *piScore = iScore;
152023  *pmCover = mCover;
152024  *pmHighlight = mHighlight;
152025}
152026
152027/*
152028** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
152029** Each invocation populates an element of the SnippetIter.aPhrase[] array.
152030*/
152031static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
152032  SnippetIter *p = (SnippetIter *)ctx;
152033  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
152034  char *pCsr;
152035  int rc;
152036
152037  pPhrase->nToken = pExpr->pPhrase->nToken;
152038  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
152039  assert( rc==SQLITE_OK || pCsr==0 );
152040  if( pCsr ){
152041    int iFirst = 0;
152042    pPhrase->pList = pCsr;
152043    fts3GetDeltaPosition(&pCsr, &iFirst);
152044    assert( iFirst>=0 );
152045    pPhrase->pHead = pCsr;
152046    pPhrase->pTail = pCsr;
152047    pPhrase->iHead = iFirst;
152048    pPhrase->iTail = iFirst;
152049  }else{
152050    assert( rc!=SQLITE_OK || (
152051       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
152052    ));
152053  }
152054
152055  return rc;
152056}
152057
152058/*
152059** Select the fragment of text consisting of nFragment contiguous tokens
152060** from column iCol that represent the "best" snippet. The best snippet
152061** is the snippet with the highest score, where scores are calculated
152062** by adding:
152063**
152064**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
152065**
152066**   (b) +1000 points for the first occurrence of each matchable phrase in
152067**       the snippet for which the corresponding mCovered bit is not set.
152068**
152069** The selected snippet parameters are stored in structure *pFragment before
152070** returning. The score of the selected snippet is stored in *piScore
152071** before returning.
152072*/
152073static int fts3BestSnippet(
152074  int nSnippet,                   /* Desired snippet length */
152075  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
152076  int iCol,                       /* Index of column to create snippet from */
152077  u64 mCovered,                   /* Mask of phrases already covered */
152078  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
152079  SnippetFragment *pFragment,     /* OUT: Best snippet found */
152080  int *piScore                    /* OUT: Score of snippet pFragment */
152081){
152082  int rc;                         /* Return Code */
152083  int nList;                      /* Number of phrases in expression */
152084  SnippetIter sIter;              /* Iterates through snippet candidates */
152085  int nByte;                      /* Number of bytes of space to allocate */
152086  int iBestScore = -1;            /* Best snippet score found so far */
152087  int i;                          /* Loop counter */
152088
152089  memset(&sIter, 0, sizeof(sIter));
152090
152091  /* Iterate through the phrases in the expression to count them. The same
152092  ** callback makes sure the doclists are loaded for each phrase.
152093  */
152094  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
152095  if( rc!=SQLITE_OK ){
152096    return rc;
152097  }
152098
152099  /* Now that it is known how many phrases there are, allocate and zero
152100  ** the required space using malloc().
152101  */
152102  nByte = sizeof(SnippetPhrase) * nList;
152103  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
152104  if( !sIter.aPhrase ){
152105    return SQLITE_NOMEM;
152106  }
152107  memset(sIter.aPhrase, 0, nByte);
152108
152109  /* Initialize the contents of the SnippetIter object. Then iterate through
152110  ** the set of phrases in the expression to populate the aPhrase[] array.
152111  */
152112  sIter.pCsr = pCsr;
152113  sIter.iCol = iCol;
152114  sIter.nSnippet = nSnippet;
152115  sIter.nPhrase = nList;
152116  sIter.iCurrent = -1;
152117  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
152118  if( rc==SQLITE_OK ){
152119
152120    /* Set the *pmSeen output variable. */
152121    for(i=0; i<nList; i++){
152122      if( sIter.aPhrase[i].pHead ){
152123        *pmSeen |= (u64)1 << i;
152124      }
152125    }
152126
152127    /* Loop through all candidate snippets. Store the best snippet in
152128     ** *pFragment. Store its associated 'score' in iBestScore.
152129     */
152130    pFragment->iCol = iCol;
152131    while( !fts3SnippetNextCandidate(&sIter) ){
152132      int iPos;
152133      int iScore;
152134      u64 mCover;
152135      u64 mHighlite;
152136      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
152137      assert( iScore>=0 );
152138      if( iScore>iBestScore ){
152139        pFragment->iPos = iPos;
152140        pFragment->hlmask = mHighlite;
152141        pFragment->covered = mCover;
152142        iBestScore = iScore;
152143      }
152144    }
152145
152146    *piScore = iBestScore;
152147  }
152148  sqlite3_free(sIter.aPhrase);
152149  return rc;
152150}
152151
152152
152153/*
152154** Append a string to the string-buffer passed as the first argument.
152155**
152156** If nAppend is negative, then the length of the string zAppend is
152157** determined using strlen().
152158*/
152159static int fts3StringAppend(
152160  StrBuffer *pStr,                /* Buffer to append to */
152161  const char *zAppend,            /* Pointer to data to append to buffer */
152162  int nAppend                     /* Size of zAppend in bytes (or -1) */
152163){
152164  if( nAppend<0 ){
152165    nAppend = (int)strlen(zAppend);
152166  }
152167
152168  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
152169  ** to grow the buffer until so that it is big enough to accomadate the
152170  ** appended data.
152171  */
152172  if( pStr->n+nAppend+1>=pStr->nAlloc ){
152173    int nAlloc = pStr->nAlloc+nAppend+100;
152174    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
152175    if( !zNew ){
152176      return SQLITE_NOMEM;
152177    }
152178    pStr->z = zNew;
152179    pStr->nAlloc = nAlloc;
152180  }
152181  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
152182
152183  /* Append the data to the string buffer. */
152184  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
152185  pStr->n += nAppend;
152186  pStr->z[pStr->n] = '\0';
152187
152188  return SQLITE_OK;
152189}
152190
152191/*
152192** The fts3BestSnippet() function often selects snippets that end with a
152193** query term. That is, the final term of the snippet is always a term
152194** that requires highlighting. For example, if 'X' is a highlighted term
152195** and '.' is a non-highlighted term, BestSnippet() may select:
152196**
152197**     ........X.....X
152198**
152199** This function "shifts" the beginning of the snippet forward in the
152200** document so that there are approximately the same number of
152201** non-highlighted terms to the right of the final highlighted term as there
152202** are to the left of the first highlighted term. For example, to this:
152203**
152204**     ....X.....X....
152205**
152206** This is done as part of extracting the snippet text, not when selecting
152207** the snippet. Snippet selection is done based on doclists only, so there
152208** is no way for fts3BestSnippet() to know whether or not the document
152209** actually contains terms that follow the final highlighted term.
152210*/
152211static int fts3SnippetShift(
152212  Fts3Table *pTab,                /* FTS3 table snippet comes from */
152213  int iLangid,                    /* Language id to use in tokenizing */
152214  int nSnippet,                   /* Number of tokens desired for snippet */
152215  const char *zDoc,               /* Document text to extract snippet from */
152216  int nDoc,                       /* Size of buffer zDoc in bytes */
152217  int *piPos,                     /* IN/OUT: First token of snippet */
152218  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
152219){
152220  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
152221
152222  if( hlmask ){
152223    int nLeft;                    /* Tokens to the left of first highlight */
152224    int nRight;                   /* Tokens to the right of last highlight */
152225    int nDesired;                 /* Ideal number of tokens to shift forward */
152226
152227    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
152228    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
152229    nDesired = (nLeft-nRight)/2;
152230
152231    /* Ideally, the start of the snippet should be pushed forward in the
152232    ** document nDesired tokens. This block checks if there are actually
152233    ** nDesired tokens to the right of the snippet. If so, *piPos and
152234    ** *pHlMask are updated to shift the snippet nDesired tokens to the
152235    ** right. Otherwise, the snippet is shifted by the number of tokens
152236    ** available.
152237    */
152238    if( nDesired>0 ){
152239      int nShift;                 /* Number of tokens to shift snippet by */
152240      int iCurrent = 0;           /* Token counter */
152241      int rc;                     /* Return Code */
152242      sqlite3_tokenizer_module *pMod;
152243      sqlite3_tokenizer_cursor *pC;
152244      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
152245
152246      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
152247      ** or more tokens in zDoc/nDoc.
152248      */
152249      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
152250      if( rc!=SQLITE_OK ){
152251        return rc;
152252      }
152253      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
152254        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
152255        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
152256      }
152257      pMod->xClose(pC);
152258      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
152259
152260      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
152261      assert( nShift<=nDesired );
152262      if( nShift>0 ){
152263        *piPos += nShift;
152264        *pHlmask = hlmask >> nShift;
152265      }
152266    }
152267  }
152268  return SQLITE_OK;
152269}
152270
152271/*
152272** Extract the snippet text for fragment pFragment from cursor pCsr and
152273** append it to string buffer pOut.
152274*/
152275static int fts3SnippetText(
152276  Fts3Cursor *pCsr,               /* FTS3 Cursor */
152277  SnippetFragment *pFragment,     /* Snippet to extract */
152278  int iFragment,                  /* Fragment number */
152279  int isLast,                     /* True for final fragment in snippet */
152280  int nSnippet,                   /* Number of tokens in extracted snippet */
152281  const char *zOpen,              /* String inserted before highlighted term */
152282  const char *zClose,             /* String inserted after highlighted term */
152283  const char *zEllipsis,          /* String inserted between snippets */
152284  StrBuffer *pOut                 /* Write output here */
152285){
152286  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152287  int rc;                         /* Return code */
152288  const char *zDoc;               /* Document text to extract snippet from */
152289  int nDoc;                       /* Size of zDoc in bytes */
152290  int iCurrent = 0;               /* Current token number of document */
152291  int iEnd = 0;                   /* Byte offset of end of current token */
152292  int isShiftDone = 0;            /* True after snippet is shifted */
152293  int iPos = pFragment->iPos;     /* First token of snippet */
152294  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
152295  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
152296  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
152297  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
152298
152299  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
152300  if( zDoc==0 ){
152301    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
152302      return SQLITE_NOMEM;
152303    }
152304    return SQLITE_OK;
152305  }
152306  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
152307
152308  /* Open a token cursor on the document. */
152309  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
152310  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
152311  if( rc!=SQLITE_OK ){
152312    return rc;
152313  }
152314
152315  while( rc==SQLITE_OK ){
152316    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
152317    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
152318    int iBegin = 0;               /* Offset in zDoc of start of token */
152319    int iFin = 0;                 /* Offset in zDoc of end of token */
152320    int isHighlight = 0;          /* True for highlighted terms */
152321
152322    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
152323    ** in the FTS code the variable that the third argument to xNext points to
152324    ** is initialized to zero before the first (*but not necessarily
152325    ** subsequent*) call to xNext(). This is done for a particular application
152326    ** that needs to know whether or not the tokenizer is being used for
152327    ** snippet generation or for some other purpose.
152328    **
152329    ** Extreme care is required when writing code to depend on this
152330    ** initialization. It is not a documented part of the tokenizer interface.
152331    ** If a tokenizer is used directly by any code outside of FTS, this
152332    ** convention might not be respected.  */
152333    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
152334    if( rc!=SQLITE_OK ){
152335      if( rc==SQLITE_DONE ){
152336        /* Special case - the last token of the snippet is also the last token
152337        ** of the column. Append any punctuation that occurred between the end
152338        ** of the previous token and the end of the document to the output.
152339        ** Then break out of the loop. */
152340        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
152341      }
152342      break;
152343    }
152344    if( iCurrent<iPos ){ continue; }
152345
152346    if( !isShiftDone ){
152347      int n = nDoc - iBegin;
152348      rc = fts3SnippetShift(
152349          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
152350      );
152351      isShiftDone = 1;
152352
152353      /* Now that the shift has been done, check if the initial "..." are
152354      ** required. They are required if (a) this is not the first fragment,
152355      ** or (b) this fragment does not begin at position 0 of its column.
152356      */
152357      if( rc==SQLITE_OK ){
152358        if( iPos>0 || iFragment>0 ){
152359          rc = fts3StringAppend(pOut, zEllipsis, -1);
152360        }else if( iBegin ){
152361          rc = fts3StringAppend(pOut, zDoc, iBegin);
152362        }
152363      }
152364      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
152365    }
152366
152367    if( iCurrent>=(iPos+nSnippet) ){
152368      if( isLast ){
152369        rc = fts3StringAppend(pOut, zEllipsis, -1);
152370      }
152371      break;
152372    }
152373
152374    /* Set isHighlight to true if this term should be highlighted. */
152375    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
152376
152377    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
152378    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
152379    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
152380    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
152381
152382    iEnd = iFin;
152383  }
152384
152385  pMod->xClose(pC);
152386  return rc;
152387}
152388
152389
152390/*
152391** This function is used to count the entries in a column-list (a
152392** delta-encoded list of term offsets within a single column of a single
152393** row). When this function is called, *ppCollist should point to the
152394** beginning of the first varint in the column-list (the varint that
152395** contains the position of the first matching term in the column data).
152396** Before returning, *ppCollist is set to point to the first byte after
152397** the last varint in the column-list (either the 0x00 signifying the end
152398** of the position-list, or the 0x01 that precedes the column number of
152399** the next column in the position-list).
152400**
152401** The number of elements in the column-list is returned.
152402*/
152403static int fts3ColumnlistCount(char **ppCollist){
152404  char *pEnd = *ppCollist;
152405  char c = 0;
152406  int nEntry = 0;
152407
152408  /* A column-list is terminated by either a 0x01 or 0x00. */
152409  while( 0xFE & (*pEnd | c) ){
152410    c = *pEnd++ & 0x80;
152411    if( !c ) nEntry++;
152412  }
152413
152414  *ppCollist = pEnd;
152415  return nEntry;
152416}
152417
152418/*
152419** This function gathers 'y' or 'b' data for a single phrase.
152420*/
152421static void fts3ExprLHits(
152422  Fts3Expr *pExpr,                /* Phrase expression node */
152423  MatchInfo *p                    /* Matchinfo context */
152424){
152425  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
152426  int iStart;
152427  Fts3Phrase *pPhrase = pExpr->pPhrase;
152428  char *pIter = pPhrase->doclist.pList;
152429  int iCol = 0;
152430
152431  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
152432  if( p->flag==FTS3_MATCHINFO_LHITS ){
152433    iStart = pExpr->iPhrase * p->nCol;
152434  }else{
152435    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
152436  }
152437
152438  while( 1 ){
152439    int nHit = fts3ColumnlistCount(&pIter);
152440    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
152441      if( p->flag==FTS3_MATCHINFO_LHITS ){
152442        p->aMatchinfo[iStart + iCol] = (u32)nHit;
152443      }else if( nHit ){
152444        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
152445      }
152446    }
152447    assert( *pIter==0x00 || *pIter==0x01 );
152448    if( *pIter!=0x01 ) break;
152449    pIter++;
152450    pIter += fts3GetVarint32(pIter, &iCol);
152451  }
152452}
152453
152454/*
152455** Gather the results for matchinfo directives 'y' and 'b'.
152456*/
152457static void fts3ExprLHitGather(
152458  Fts3Expr *pExpr,
152459  MatchInfo *p
152460){
152461  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
152462  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
152463    if( pExpr->pLeft ){
152464      fts3ExprLHitGather(pExpr->pLeft, p);
152465      fts3ExprLHitGather(pExpr->pRight, p);
152466    }else{
152467      fts3ExprLHits(pExpr, p);
152468    }
152469  }
152470}
152471
152472/*
152473** fts3ExprIterate() callback used to collect the "global" matchinfo stats
152474** for a single query.
152475**
152476** fts3ExprIterate() callback to load the 'global' elements of a
152477** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
152478** of the matchinfo array that are constant for all rows returned by the
152479** current query.
152480**
152481** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
152482** function populates Matchinfo.aMatchinfo[] as follows:
152483**
152484**   for(iCol=0; iCol<nCol; iCol++){
152485**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
152486**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
152487**   }
152488**
152489** where X is the number of matches for phrase iPhrase is column iCol of all
152490** rows of the table. Y is the number of rows for which column iCol contains
152491** at least one instance of phrase iPhrase.
152492**
152493** If the phrase pExpr consists entirely of deferred tokens, then all X and
152494** Y values are set to nDoc, where nDoc is the number of documents in the
152495** file system. This is done because the full-text index doclist is required
152496** to calculate these values properly, and the full-text index doclist is
152497** not available for deferred tokens.
152498*/
152499static int fts3ExprGlobalHitsCb(
152500  Fts3Expr *pExpr,                /* Phrase expression node */
152501  int iPhrase,                    /* Phrase number (numbered from zero) */
152502  void *pCtx                      /* Pointer to MatchInfo structure */
152503){
152504  MatchInfo *p = (MatchInfo *)pCtx;
152505  return sqlite3Fts3EvalPhraseStats(
152506      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
152507  );
152508}
152509
152510/*
152511** fts3ExprIterate() callback used to collect the "local" part of the
152512** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
152513** array that are different for each row returned by the query.
152514*/
152515static int fts3ExprLocalHitsCb(
152516  Fts3Expr *pExpr,                /* Phrase expression node */
152517  int iPhrase,                    /* Phrase number */
152518  void *pCtx                      /* Pointer to MatchInfo structure */
152519){
152520  int rc = SQLITE_OK;
152521  MatchInfo *p = (MatchInfo *)pCtx;
152522  int iStart = iPhrase * p->nCol * 3;
152523  int i;
152524
152525  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
152526    char *pCsr;
152527    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
152528    if( pCsr ){
152529      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
152530    }else{
152531      p->aMatchinfo[iStart+i*3] = 0;
152532    }
152533  }
152534
152535  return rc;
152536}
152537
152538static int fts3MatchinfoCheck(
152539  Fts3Table *pTab,
152540  char cArg,
152541  char **pzErr
152542){
152543  if( (cArg==FTS3_MATCHINFO_NPHRASE)
152544   || (cArg==FTS3_MATCHINFO_NCOL)
152545   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
152546   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
152547   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
152548   || (cArg==FTS3_MATCHINFO_LCS)
152549   || (cArg==FTS3_MATCHINFO_HITS)
152550   || (cArg==FTS3_MATCHINFO_LHITS)
152551   || (cArg==FTS3_MATCHINFO_LHITS_BM)
152552  ){
152553    return SQLITE_OK;
152554  }
152555  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
152556  return SQLITE_ERROR;
152557}
152558
152559static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
152560  int nVal;                       /* Number of integers output by cArg */
152561
152562  switch( cArg ){
152563    case FTS3_MATCHINFO_NDOC:
152564    case FTS3_MATCHINFO_NPHRASE:
152565    case FTS3_MATCHINFO_NCOL:
152566      nVal = 1;
152567      break;
152568
152569    case FTS3_MATCHINFO_AVGLENGTH:
152570    case FTS3_MATCHINFO_LENGTH:
152571    case FTS3_MATCHINFO_LCS:
152572      nVal = pInfo->nCol;
152573      break;
152574
152575    case FTS3_MATCHINFO_LHITS:
152576      nVal = pInfo->nCol * pInfo->nPhrase;
152577      break;
152578
152579    case FTS3_MATCHINFO_LHITS_BM:
152580      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
152581      break;
152582
152583    default:
152584      assert( cArg==FTS3_MATCHINFO_HITS );
152585      nVal = pInfo->nCol * pInfo->nPhrase * 3;
152586      break;
152587  }
152588
152589  return nVal;
152590}
152591
152592static int fts3MatchinfoSelectDoctotal(
152593  Fts3Table *pTab,
152594  sqlite3_stmt **ppStmt,
152595  sqlite3_int64 *pnDoc,
152596  const char **paLen
152597){
152598  sqlite3_stmt *pStmt;
152599  const char *a;
152600  sqlite3_int64 nDoc;
152601
152602  if( !*ppStmt ){
152603    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
152604    if( rc!=SQLITE_OK ) return rc;
152605  }
152606  pStmt = *ppStmt;
152607  assert( sqlite3_data_count(pStmt)==1 );
152608
152609  a = sqlite3_column_blob(pStmt, 0);
152610  a += sqlite3Fts3GetVarint(a, &nDoc);
152611  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
152612  *pnDoc = (u32)nDoc;
152613
152614  if( paLen ) *paLen = a;
152615  return SQLITE_OK;
152616}
152617
152618/*
152619** An instance of the following structure is used to store state while
152620** iterating through a multi-column position-list corresponding to the
152621** hits for a single phrase on a single row in order to calculate the
152622** values for a matchinfo() FTS3_MATCHINFO_LCS request.
152623*/
152624typedef struct LcsIterator LcsIterator;
152625struct LcsIterator {
152626  Fts3Expr *pExpr;                /* Pointer to phrase expression */
152627  int iPosOffset;                 /* Tokens count up to end of this phrase */
152628  char *pRead;                    /* Cursor used to iterate through aDoclist */
152629  int iPos;                       /* Current position */
152630};
152631
152632/*
152633** If LcsIterator.iCol is set to the following value, the iterator has
152634** finished iterating through all offsets for all columns.
152635*/
152636#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
152637
152638static int fts3MatchinfoLcsCb(
152639  Fts3Expr *pExpr,                /* Phrase expression node */
152640  int iPhrase,                    /* Phrase number (numbered from zero) */
152641  void *pCtx                      /* Pointer to MatchInfo structure */
152642){
152643  LcsIterator *aIter = (LcsIterator *)pCtx;
152644  aIter[iPhrase].pExpr = pExpr;
152645  return SQLITE_OK;
152646}
152647
152648/*
152649** Advance the iterator passed as an argument to the next position. Return
152650** 1 if the iterator is at EOF or if it now points to the start of the
152651** position list for the next column.
152652*/
152653static int fts3LcsIteratorAdvance(LcsIterator *pIter){
152654  char *pRead = pIter->pRead;
152655  sqlite3_int64 iRead;
152656  int rc = 0;
152657
152658  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
152659  if( iRead==0 || iRead==1 ){
152660    pRead = 0;
152661    rc = 1;
152662  }else{
152663    pIter->iPos += (int)(iRead-2);
152664  }
152665
152666  pIter->pRead = pRead;
152667  return rc;
152668}
152669
152670/*
152671** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
152672**
152673** If the call is successful, the longest-common-substring lengths for each
152674** column are written into the first nCol elements of the pInfo->aMatchinfo[]
152675** array before returning. SQLITE_OK is returned in this case.
152676**
152677** Otherwise, if an error occurs, an SQLite error code is returned and the
152678** data written to the first nCol elements of pInfo->aMatchinfo[] is
152679** undefined.
152680*/
152681static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
152682  LcsIterator *aIter;
152683  int i;
152684  int iCol;
152685  int nToken = 0;
152686
152687  /* Allocate and populate the array of LcsIterator objects. The array
152688  ** contains one element for each matchable phrase in the query.
152689  **/
152690  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
152691  if( !aIter ) return SQLITE_NOMEM;
152692  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
152693  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
152694
152695  for(i=0; i<pInfo->nPhrase; i++){
152696    LcsIterator *pIter = &aIter[i];
152697    nToken -= pIter->pExpr->pPhrase->nToken;
152698    pIter->iPosOffset = nToken;
152699  }
152700
152701  for(iCol=0; iCol<pInfo->nCol; iCol++){
152702    int nLcs = 0;                 /* LCS value for this column */
152703    int nLive = 0;                /* Number of iterators in aIter not at EOF */
152704
152705    for(i=0; i<pInfo->nPhrase; i++){
152706      int rc;
152707      LcsIterator *pIt = &aIter[i];
152708      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
152709      if( rc!=SQLITE_OK ) return rc;
152710      if( pIt->pRead ){
152711        pIt->iPos = pIt->iPosOffset;
152712        fts3LcsIteratorAdvance(&aIter[i]);
152713        nLive++;
152714      }
152715    }
152716
152717    while( nLive>0 ){
152718      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
152719      int nThisLcs = 0;           /* LCS for the current iterator positions */
152720
152721      for(i=0; i<pInfo->nPhrase; i++){
152722        LcsIterator *pIter = &aIter[i];
152723        if( pIter->pRead==0 ){
152724          /* This iterator is already at EOF for this column. */
152725          nThisLcs = 0;
152726        }else{
152727          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
152728            pAdv = pIter;
152729          }
152730          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
152731            nThisLcs++;
152732          }else{
152733            nThisLcs = 1;
152734          }
152735          if( nThisLcs>nLcs ) nLcs = nThisLcs;
152736        }
152737      }
152738      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
152739    }
152740
152741    pInfo->aMatchinfo[iCol] = nLcs;
152742  }
152743
152744  sqlite3_free(aIter);
152745  return SQLITE_OK;
152746}
152747
152748/*
152749** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
152750** be returned by the matchinfo() function. Argument zArg contains the
152751** format string passed as the second argument to matchinfo (or the
152752** default value "pcx" if no second argument was specified). The format
152753** string has already been validated and the pInfo->aMatchinfo[] array
152754** is guaranteed to be large enough for the output.
152755**
152756** If bGlobal is true, then populate all fields of the matchinfo() output.
152757** If it is false, then assume that those fields that do not change between
152758** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
152759** have already been populated.
152760**
152761** Return SQLITE_OK if successful, or an SQLite error code if an error
152762** occurs. If a value other than SQLITE_OK is returned, the state the
152763** pInfo->aMatchinfo[] buffer is left in is undefined.
152764*/
152765static int fts3MatchinfoValues(
152766  Fts3Cursor *pCsr,               /* FTS3 cursor object */
152767  int bGlobal,                    /* True to grab the global stats */
152768  MatchInfo *pInfo,               /* Matchinfo context object */
152769  const char *zArg                /* Matchinfo format string */
152770){
152771  int rc = SQLITE_OK;
152772  int i;
152773  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152774  sqlite3_stmt *pSelect = 0;
152775
152776  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
152777    pInfo->flag = zArg[i];
152778    switch( zArg[i] ){
152779      case FTS3_MATCHINFO_NPHRASE:
152780        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
152781        break;
152782
152783      case FTS3_MATCHINFO_NCOL:
152784        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
152785        break;
152786
152787      case FTS3_MATCHINFO_NDOC:
152788        if( bGlobal ){
152789          sqlite3_int64 nDoc = 0;
152790          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
152791          pInfo->aMatchinfo[0] = (u32)nDoc;
152792        }
152793        break;
152794
152795      case FTS3_MATCHINFO_AVGLENGTH:
152796        if( bGlobal ){
152797          sqlite3_int64 nDoc;     /* Number of rows in table */
152798          const char *a;          /* Aggregate column length array */
152799
152800          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
152801          if( rc==SQLITE_OK ){
152802            int iCol;
152803            for(iCol=0; iCol<pInfo->nCol; iCol++){
152804              u32 iVal;
152805              sqlite3_int64 nToken;
152806              a += sqlite3Fts3GetVarint(a, &nToken);
152807              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
152808              pInfo->aMatchinfo[iCol] = iVal;
152809            }
152810          }
152811        }
152812        break;
152813
152814      case FTS3_MATCHINFO_LENGTH: {
152815        sqlite3_stmt *pSelectDocsize = 0;
152816        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
152817        if( rc==SQLITE_OK ){
152818          int iCol;
152819          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
152820          for(iCol=0; iCol<pInfo->nCol; iCol++){
152821            sqlite3_int64 nToken;
152822            a += sqlite3Fts3GetVarint(a, &nToken);
152823            pInfo->aMatchinfo[iCol] = (u32)nToken;
152824          }
152825        }
152826        sqlite3_reset(pSelectDocsize);
152827        break;
152828      }
152829
152830      case FTS3_MATCHINFO_LCS:
152831        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
152832        if( rc==SQLITE_OK ){
152833          rc = fts3MatchinfoLcs(pCsr, pInfo);
152834        }
152835        break;
152836
152837      case FTS3_MATCHINFO_LHITS_BM:
152838      case FTS3_MATCHINFO_LHITS: {
152839        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
152840        memset(pInfo->aMatchinfo, 0, nZero);
152841        fts3ExprLHitGather(pCsr->pExpr, pInfo);
152842        break;
152843      }
152844
152845      default: {
152846        Fts3Expr *pExpr;
152847        assert( zArg[i]==FTS3_MATCHINFO_HITS );
152848        pExpr = pCsr->pExpr;
152849        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
152850        if( rc!=SQLITE_OK ) break;
152851        if( bGlobal ){
152852          if( pCsr->pDeferred ){
152853            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
152854            if( rc!=SQLITE_OK ) break;
152855          }
152856          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
152857          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
152858          if( rc!=SQLITE_OK ) break;
152859        }
152860        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
152861        break;
152862      }
152863    }
152864
152865    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
152866  }
152867
152868  sqlite3_reset(pSelect);
152869  return rc;
152870}
152871
152872
152873/*
152874** Populate pCsr->aMatchinfo[] with data for the current row. The
152875** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
152876*/
152877static void fts3GetMatchinfo(
152878  sqlite3_context *pCtx,        /* Return results here */
152879  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
152880  const char *zArg                /* Second argument to matchinfo() function */
152881){
152882  MatchInfo sInfo;
152883  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152884  int rc = SQLITE_OK;
152885  int bGlobal = 0;                /* Collect 'global' stats as well as local */
152886
152887  u32 *aOut = 0;
152888  void (*xDestroyOut)(void*) = 0;
152889
152890  memset(&sInfo, 0, sizeof(MatchInfo));
152891  sInfo.pCursor = pCsr;
152892  sInfo.nCol = pTab->nColumn;
152893
152894  /* If there is cached matchinfo() data, but the format string for the
152895  ** cache does not match the format string for this request, discard
152896  ** the cached data. */
152897  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
152898    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
152899    pCsr->pMIBuffer = 0;
152900  }
152901
152902  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
152903  ** matchinfo function has been called for this query. In this case
152904  ** allocate the array used to accumulate the matchinfo data and
152905  ** initialize those elements that are constant for every row.
152906  */
152907  if( pCsr->pMIBuffer==0 ){
152908    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
152909    int i;                        /* Used to iterate through zArg */
152910
152911    /* Determine the number of phrases in the query */
152912    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
152913    sInfo.nPhrase = pCsr->nPhrase;
152914
152915    /* Determine the number of integers in the buffer returned by this call. */
152916    for(i=0; zArg[i]; i++){
152917      char *zErr = 0;
152918      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
152919        sqlite3_result_error(pCtx, zErr, -1);
152920        sqlite3_free(zErr);
152921        return;
152922      }
152923      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
152924    }
152925
152926    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
152927    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
152928    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
152929
152930    pCsr->isMatchinfoNeeded = 1;
152931    bGlobal = 1;
152932  }
152933
152934  if( rc==SQLITE_OK ){
152935    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
152936    if( xDestroyOut==0 ){
152937      rc = SQLITE_NOMEM;
152938    }
152939  }
152940
152941  if( rc==SQLITE_OK ){
152942    sInfo.aMatchinfo = aOut;
152943    sInfo.nPhrase = pCsr->nPhrase;
152944    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
152945    if( bGlobal ){
152946      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
152947    }
152948  }
152949
152950  if( rc!=SQLITE_OK ){
152951    sqlite3_result_error_code(pCtx, rc);
152952    if( xDestroyOut ) xDestroyOut(aOut);
152953  }else{
152954    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
152955    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
152956  }
152957}
152958
152959/*
152960** Implementation of snippet() function.
152961*/
152962SQLITE_PRIVATE void sqlite3Fts3Snippet(
152963  sqlite3_context *pCtx,          /* SQLite function call context */
152964  Fts3Cursor *pCsr,               /* Cursor object */
152965  const char *zStart,             /* Snippet start text - "<b>" */
152966  const char *zEnd,               /* Snippet end text - "</b>" */
152967  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
152968  int iCol,                       /* Extract snippet from this column */
152969  int nToken                      /* Approximate number of tokens in snippet */
152970){
152971  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152972  int rc = SQLITE_OK;
152973  int i;
152974  StrBuffer res = {0, 0, 0};
152975
152976  /* The returned text includes up to four fragments of text extracted from
152977  ** the data in the current row. The first iteration of the for(...) loop
152978  ** below attempts to locate a single fragment of text nToken tokens in
152979  ** size that contains at least one instance of all phrases in the query
152980  ** expression that appear in the current row. If such a fragment of text
152981  ** cannot be found, the second iteration of the loop attempts to locate
152982  ** a pair of fragments, and so on.
152983  */
152984  int nSnippet = 0;               /* Number of fragments in this snippet */
152985  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
152986  int nFToken = -1;               /* Number of tokens in each fragment */
152987
152988  if( !pCsr->pExpr ){
152989    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
152990    return;
152991  }
152992
152993  for(nSnippet=1; 1; nSnippet++){
152994
152995    int iSnip;                    /* Loop counter 0..nSnippet-1 */
152996    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
152997    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
152998
152999    if( nToken>=0 ){
153000      nFToken = (nToken+nSnippet-1) / nSnippet;
153001    }else{
153002      nFToken = -1 * nToken;
153003    }
153004
153005    for(iSnip=0; iSnip<nSnippet; iSnip++){
153006      int iBestScore = -1;        /* Best score of columns checked so far */
153007      int iRead;                  /* Used to iterate through columns */
153008      SnippetFragment *pFragment = &aSnippet[iSnip];
153009
153010      memset(pFragment, 0, sizeof(*pFragment));
153011
153012      /* Loop through all columns of the table being considered for snippets.
153013      ** If the iCol argument to this function was negative, this means all
153014      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
153015      */
153016      for(iRead=0; iRead<pTab->nColumn; iRead++){
153017        SnippetFragment sF = {0, 0, 0, 0};
153018        int iS = 0;
153019        if( iCol>=0 && iRead!=iCol ) continue;
153020
153021        /* Find the best snippet of nFToken tokens in column iRead. */
153022        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
153023        if( rc!=SQLITE_OK ){
153024          goto snippet_out;
153025        }
153026        if( iS>iBestScore ){
153027          *pFragment = sF;
153028          iBestScore = iS;
153029        }
153030      }
153031
153032      mCovered |= pFragment->covered;
153033    }
153034
153035    /* If all query phrases seen by fts3BestSnippet() are present in at least
153036    ** one of the nSnippet snippet fragments, break out of the loop.
153037    */
153038    assert( (mCovered&mSeen)==mCovered );
153039    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
153040  }
153041
153042  assert( nFToken>0 );
153043
153044  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
153045    rc = fts3SnippetText(pCsr, &aSnippet[i],
153046        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
153047    );
153048  }
153049
153050 snippet_out:
153051  sqlite3Fts3SegmentsClose(pTab);
153052  if( rc!=SQLITE_OK ){
153053    sqlite3_result_error_code(pCtx, rc);
153054    sqlite3_free(res.z);
153055  }else{
153056    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
153057  }
153058}
153059
153060
153061typedef struct TermOffset TermOffset;
153062typedef struct TermOffsetCtx TermOffsetCtx;
153063
153064struct TermOffset {
153065  char *pList;                    /* Position-list */
153066  int iPos;                       /* Position just read from pList */
153067  int iOff;                       /* Offset of this term from read positions */
153068};
153069
153070struct TermOffsetCtx {
153071  Fts3Cursor *pCsr;
153072  int iCol;                       /* Column of table to populate aTerm for */
153073  int iTerm;
153074  sqlite3_int64 iDocid;
153075  TermOffset *aTerm;
153076};
153077
153078/*
153079** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
153080*/
153081static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
153082  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
153083  int nTerm;                      /* Number of tokens in phrase */
153084  int iTerm;                      /* For looping through nTerm phrase terms */
153085  char *pList;                    /* Pointer to position list for phrase */
153086  int iPos = 0;                   /* First position in position-list */
153087  int rc;
153088
153089  UNUSED_PARAMETER(iPhrase);
153090  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
153091  nTerm = pExpr->pPhrase->nToken;
153092  if( pList ){
153093    fts3GetDeltaPosition(&pList, &iPos);
153094    assert( iPos>=0 );
153095  }
153096
153097  for(iTerm=0; iTerm<nTerm; iTerm++){
153098    TermOffset *pT = &p->aTerm[p->iTerm++];
153099    pT->iOff = nTerm-iTerm-1;
153100    pT->pList = pList;
153101    pT->iPos = iPos;
153102  }
153103
153104  return rc;
153105}
153106
153107/*
153108** Implementation of offsets() function.
153109*/
153110SQLITE_PRIVATE void sqlite3Fts3Offsets(
153111  sqlite3_context *pCtx,          /* SQLite function call context */
153112  Fts3Cursor *pCsr                /* Cursor object */
153113){
153114  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153115  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
153116  int rc;                         /* Return Code */
153117  int nToken;                     /* Number of tokens in query */
153118  int iCol;                       /* Column currently being processed */
153119  StrBuffer res = {0, 0, 0};      /* Result string */
153120  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
153121
153122  if( !pCsr->pExpr ){
153123    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
153124    return;
153125  }
153126
153127  memset(&sCtx, 0, sizeof(sCtx));
153128  assert( pCsr->isRequireSeek==0 );
153129
153130  /* Count the number of terms in the query */
153131  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
153132  if( rc!=SQLITE_OK ) goto offsets_out;
153133
153134  /* Allocate the array of TermOffset iterators. */
153135  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
153136  if( 0==sCtx.aTerm ){
153137    rc = SQLITE_NOMEM;
153138    goto offsets_out;
153139  }
153140  sCtx.iDocid = pCsr->iPrevId;
153141  sCtx.pCsr = pCsr;
153142
153143  /* Loop through the table columns, appending offset information to
153144  ** string-buffer res for each column.
153145  */
153146  for(iCol=0; iCol<pTab->nColumn; iCol++){
153147    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
153148    const char *ZDUMMY;           /* Dummy argument used with xNext() */
153149    int NDUMMY = 0;               /* Dummy argument used with xNext() */
153150    int iStart = 0;
153151    int iEnd = 0;
153152    int iCurrent = 0;
153153    const char *zDoc;
153154    int nDoc;
153155
153156    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
153157    ** no way that this operation can fail, so the return code from
153158    ** fts3ExprIterate() can be discarded.
153159    */
153160    sCtx.iCol = iCol;
153161    sCtx.iTerm = 0;
153162    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
153163
153164    /* Retreive the text stored in column iCol. If an SQL NULL is stored
153165    ** in column iCol, jump immediately to the next iteration of the loop.
153166    ** If an OOM occurs while retrieving the data (this can happen if SQLite
153167    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
153168    ** to the caller.
153169    */
153170    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
153171    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
153172    if( zDoc==0 ){
153173      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
153174        continue;
153175      }
153176      rc = SQLITE_NOMEM;
153177      goto offsets_out;
153178    }
153179
153180    /* Initialize a tokenizer iterator to iterate through column iCol. */
153181    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
153182        zDoc, nDoc, &pC
153183    );
153184    if( rc!=SQLITE_OK ) goto offsets_out;
153185
153186    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
153187    while( rc==SQLITE_OK ){
153188      int i;                      /* Used to loop through terms */
153189      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
153190      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
153191
153192      for(i=0; i<nToken; i++){
153193        TermOffset *pT = &sCtx.aTerm[i];
153194        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
153195          iMinPos = pT->iPos-pT->iOff;
153196          pTerm = pT;
153197        }
153198      }
153199
153200      if( !pTerm ){
153201        /* All offsets for this column have been gathered. */
153202        rc = SQLITE_DONE;
153203      }else{
153204        assert( iCurrent<=iMinPos );
153205        if( 0==(0xFE&*pTerm->pList) ){
153206          pTerm->pList = 0;
153207        }else{
153208          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
153209        }
153210        while( rc==SQLITE_OK && iCurrent<iMinPos ){
153211          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
153212        }
153213        if( rc==SQLITE_OK ){
153214          char aBuffer[64];
153215          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
153216              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
153217          );
153218          rc = fts3StringAppend(&res, aBuffer, -1);
153219        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
153220          rc = FTS_CORRUPT_VTAB;
153221        }
153222      }
153223    }
153224    if( rc==SQLITE_DONE ){
153225      rc = SQLITE_OK;
153226    }
153227
153228    pMod->xClose(pC);
153229    if( rc!=SQLITE_OK ) goto offsets_out;
153230  }
153231
153232 offsets_out:
153233  sqlite3_free(sCtx.aTerm);
153234  assert( rc!=SQLITE_DONE );
153235  sqlite3Fts3SegmentsClose(pTab);
153236  if( rc!=SQLITE_OK ){
153237    sqlite3_result_error_code(pCtx,  rc);
153238    sqlite3_free(res.z);
153239  }else{
153240    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
153241  }
153242  return;
153243}
153244
153245/*
153246** Implementation of matchinfo() function.
153247*/
153248SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
153249  sqlite3_context *pContext,      /* Function call context */
153250  Fts3Cursor *pCsr,               /* FTS3 table cursor */
153251  const char *zArg                /* Second arg to matchinfo() function */
153252){
153253  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153254  const char *zFormat;
153255
153256  if( zArg ){
153257    zFormat = zArg;
153258  }else{
153259    zFormat = FTS3_MATCHINFO_DEFAULT;
153260  }
153261
153262  if( !pCsr->pExpr ){
153263    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
153264    return;
153265  }else{
153266    /* Retrieve matchinfo() data. */
153267    fts3GetMatchinfo(pContext, pCsr, zFormat);
153268    sqlite3Fts3SegmentsClose(pTab);
153269  }
153270}
153271
153272#endif
153273
153274/************** End of fts3_snippet.c ****************************************/
153275/************** Begin file fts3_unicode.c ************************************/
153276/*
153277** 2012 May 24
153278**
153279** The author disclaims copyright to this source code.  In place of
153280** a legal notice, here is a blessing:
153281**
153282**    May you do good and not evil.
153283**    May you find forgiveness for yourself and forgive others.
153284**    May you share freely, never taking more than you give.
153285**
153286******************************************************************************
153287**
153288** Implementation of the "unicode" full-text-search tokenizer.
153289*/
153290
153291#ifndef SQLITE_DISABLE_FTS3_UNICODE
153292
153293/* #include "fts3Int.h" */
153294#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153295
153296/* #include <assert.h> */
153297/* #include <stdlib.h> */
153298/* #include <stdio.h> */
153299/* #include <string.h> */
153300
153301/* #include "fts3_tokenizer.h" */
153302
153303/*
153304** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
153305** from the sqlite3 source file utf.c. If this file is compiled as part
153306** of the amalgamation, they are not required.
153307*/
153308#ifndef SQLITE_AMALGAMATION
153309
153310static const unsigned char sqlite3Utf8Trans1[] = {
153311  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153312  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
153313  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
153314  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
153315  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153316  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
153317  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153318  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
153319};
153320
153321#define READ_UTF8(zIn, zTerm, c)                           \
153322  c = *(zIn++);                                            \
153323  if( c>=0xc0 ){                                           \
153324    c = sqlite3Utf8Trans1[c-0xc0];                         \
153325    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
153326      c = (c<<6) + (0x3f & *(zIn++));                      \
153327    }                                                      \
153328    if( c<0x80                                             \
153329        || (c&0xFFFFF800)==0xD800                          \
153330        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
153331  }
153332
153333#define WRITE_UTF8(zOut, c) {                          \
153334  if( c<0x00080 ){                                     \
153335    *zOut++ = (u8)(c&0xFF);                            \
153336  }                                                    \
153337  else if( c<0x00800 ){                                \
153338    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
153339    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153340  }                                                    \
153341  else if( c<0x10000 ){                                \
153342    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
153343    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
153344    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153345  }else{                                               \
153346    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
153347    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
153348    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
153349    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153350  }                                                    \
153351}
153352
153353#endif /* ifndef SQLITE_AMALGAMATION */
153354
153355typedef struct unicode_tokenizer unicode_tokenizer;
153356typedef struct unicode_cursor unicode_cursor;
153357
153358struct unicode_tokenizer {
153359  sqlite3_tokenizer base;
153360  int bRemoveDiacritic;
153361  int nException;
153362  int *aiException;
153363};
153364
153365struct unicode_cursor {
153366  sqlite3_tokenizer_cursor base;
153367  const unsigned char *aInput;    /* Input text being tokenized */
153368  int nInput;                     /* Size of aInput[] in bytes */
153369  int iOff;                       /* Current offset within aInput[] */
153370  int iToken;                     /* Index of next token to be returned */
153371  char *zToken;                   /* storage for current token */
153372  int nAlloc;                     /* space allocated at zToken */
153373};
153374
153375
153376/*
153377** Destroy a tokenizer allocated by unicodeCreate().
153378*/
153379static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
153380  if( pTokenizer ){
153381    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
153382    sqlite3_free(p->aiException);
153383    sqlite3_free(p);
153384  }
153385  return SQLITE_OK;
153386}
153387
153388/*
153389** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
153390** statement has specified that the tokenizer for this table shall consider
153391** all characters in string zIn/nIn to be separators (if bAlnum==0) or
153392** token characters (if bAlnum==1).
153393**
153394** For each codepoint in the zIn/nIn string, this function checks if the
153395** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
153396** If so, no action is taken. Otherwise, the codepoint is added to the
153397** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
153398** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
153399** codepoints in the aiException[] array.
153400**
153401** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
153402** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
153403** It is not possible to change the behavior of the tokenizer with respect
153404** to these codepoints.
153405*/
153406static int unicodeAddExceptions(
153407  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
153408  int bAlnum,                     /* Replace Isalnum() return value with this */
153409  const char *zIn,                /* Array of characters to make exceptions */
153410  int nIn                         /* Length of z in bytes */
153411){
153412  const unsigned char *z = (const unsigned char *)zIn;
153413  const unsigned char *zTerm = &z[nIn];
153414  int iCode;
153415  int nEntry = 0;
153416
153417  assert( bAlnum==0 || bAlnum==1 );
153418
153419  while( z<zTerm ){
153420    READ_UTF8(z, zTerm, iCode);
153421    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
153422    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
153423     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
153424    ){
153425      nEntry++;
153426    }
153427  }
153428
153429  if( nEntry ){
153430    int *aNew;                    /* New aiException[] array */
153431    int nNew;                     /* Number of valid entries in array aNew[] */
153432
153433    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
153434    if( aNew==0 ) return SQLITE_NOMEM;
153435    nNew = p->nException;
153436
153437    z = (const unsigned char *)zIn;
153438    while( z<zTerm ){
153439      READ_UTF8(z, zTerm, iCode);
153440      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
153441       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
153442      ){
153443        int i, j;
153444        for(i=0; i<nNew && aNew[i]<iCode; i++);
153445        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
153446        aNew[i] = iCode;
153447        nNew++;
153448      }
153449    }
153450    p->aiException = aNew;
153451    p->nException = nNew;
153452  }
153453
153454  return SQLITE_OK;
153455}
153456
153457/*
153458** Return true if the p->aiException[] array contains the value iCode.
153459*/
153460static int unicodeIsException(unicode_tokenizer *p, int iCode){
153461  if( p->nException>0 ){
153462    int *a = p->aiException;
153463    int iLo = 0;
153464    int iHi = p->nException-1;
153465
153466    while( iHi>=iLo ){
153467      int iTest = (iHi + iLo) / 2;
153468      if( iCode==a[iTest] ){
153469        return 1;
153470      }else if( iCode>a[iTest] ){
153471        iLo = iTest+1;
153472      }else{
153473        iHi = iTest-1;
153474      }
153475    }
153476  }
153477
153478  return 0;
153479}
153480
153481/*
153482** Return true if, for the purposes of tokenization, codepoint iCode is
153483** considered a token character (not a separator).
153484*/
153485static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
153486  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
153487  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
153488}
153489
153490/*
153491** Create a new tokenizer instance.
153492*/
153493static int unicodeCreate(
153494  int nArg,                       /* Size of array argv[] */
153495  const char * const *azArg,      /* Tokenizer creation arguments */
153496  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
153497){
153498  unicode_tokenizer *pNew;        /* New tokenizer object */
153499  int i;
153500  int rc = SQLITE_OK;
153501
153502  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
153503  if( pNew==NULL ) return SQLITE_NOMEM;
153504  memset(pNew, 0, sizeof(unicode_tokenizer));
153505  pNew->bRemoveDiacritic = 1;
153506
153507  for(i=0; rc==SQLITE_OK && i<nArg; i++){
153508    const char *z = azArg[i];
153509    int n = (int)strlen(z);
153510
153511    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
153512      pNew->bRemoveDiacritic = 1;
153513    }
153514    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
153515      pNew->bRemoveDiacritic = 0;
153516    }
153517    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
153518      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
153519    }
153520    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
153521      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
153522    }
153523    else{
153524      /* Unrecognized argument */
153525      rc  = SQLITE_ERROR;
153526    }
153527  }
153528
153529  if( rc!=SQLITE_OK ){
153530    unicodeDestroy((sqlite3_tokenizer *)pNew);
153531    pNew = 0;
153532  }
153533  *pp = (sqlite3_tokenizer *)pNew;
153534  return rc;
153535}
153536
153537/*
153538** Prepare to begin tokenizing a particular string.  The input
153539** string to be tokenized is pInput[0..nBytes-1].  A cursor
153540** used to incrementally tokenize this string is returned in
153541** *ppCursor.
153542*/
153543static int unicodeOpen(
153544  sqlite3_tokenizer *p,           /* The tokenizer */
153545  const char *aInput,             /* Input string */
153546  int nInput,                     /* Size of string aInput in bytes */
153547  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
153548){
153549  unicode_cursor *pCsr;
153550
153551  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
153552  if( pCsr==0 ){
153553    return SQLITE_NOMEM;
153554  }
153555  memset(pCsr, 0, sizeof(unicode_cursor));
153556
153557  pCsr->aInput = (const unsigned char *)aInput;
153558  if( aInput==0 ){
153559    pCsr->nInput = 0;
153560  }else if( nInput<0 ){
153561    pCsr->nInput = (int)strlen(aInput);
153562  }else{
153563    pCsr->nInput = nInput;
153564  }
153565
153566  *pp = &pCsr->base;
153567  UNUSED_PARAMETER(p);
153568  return SQLITE_OK;
153569}
153570
153571/*
153572** Close a tokenization cursor previously opened by a call to
153573** simpleOpen() above.
153574*/
153575static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
153576  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
153577  sqlite3_free(pCsr->zToken);
153578  sqlite3_free(pCsr);
153579  return SQLITE_OK;
153580}
153581
153582/*
153583** Extract the next token from a tokenization cursor.  The cursor must
153584** have been opened by a prior call to simpleOpen().
153585*/
153586static int unicodeNext(
153587  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
153588  const char **paToken,           /* OUT: Token text */
153589  int *pnToken,                   /* OUT: Number of bytes at *paToken */
153590  int *piStart,                   /* OUT: Starting offset of token */
153591  int *piEnd,                     /* OUT: Ending offset of token */
153592  int *piPos                      /* OUT: Position integer of token */
153593){
153594  unicode_cursor *pCsr = (unicode_cursor *)pC;
153595  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
153596  int iCode = 0;
153597  char *zOut;
153598  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
153599  const unsigned char *zStart = z;
153600  const unsigned char *zEnd;
153601  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
153602
153603  /* Scan past any delimiter characters before the start of the next token.
153604  ** Return SQLITE_DONE early if this takes us all the way to the end of
153605  ** the input.  */
153606  while( z<zTerm ){
153607    READ_UTF8(z, zTerm, iCode);
153608    if( unicodeIsAlnum(p, iCode) ) break;
153609    zStart = z;
153610  }
153611  if( zStart>=zTerm ) return SQLITE_DONE;
153612
153613  zOut = pCsr->zToken;
153614  do {
153615    int iOut;
153616
153617    /* Grow the output buffer if required. */
153618    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
153619      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
153620      if( !zNew ) return SQLITE_NOMEM;
153621      zOut = &zNew[zOut - pCsr->zToken];
153622      pCsr->zToken = zNew;
153623      pCsr->nAlloc += 64;
153624    }
153625
153626    /* Write the folded case of the last character read to the output */
153627    zEnd = z;
153628    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
153629    if( iOut ){
153630      WRITE_UTF8(zOut, iOut);
153631    }
153632
153633    /* If the cursor is not at EOF, read the next character */
153634    if( z>=zTerm ) break;
153635    READ_UTF8(z, zTerm, iCode);
153636  }while( unicodeIsAlnum(p, iCode)
153637       || sqlite3FtsUnicodeIsdiacritic(iCode)
153638  );
153639
153640  /* Set the output variables and return. */
153641  pCsr->iOff = (int)(z - pCsr->aInput);
153642  *paToken = pCsr->zToken;
153643  *pnToken = (int)(zOut - pCsr->zToken);
153644  *piStart = (int)(zStart - pCsr->aInput);
153645  *piEnd = (int)(zEnd - pCsr->aInput);
153646  *piPos = pCsr->iToken++;
153647  return SQLITE_OK;
153648}
153649
153650/*
153651** Set *ppModule to a pointer to the sqlite3_tokenizer_module
153652** structure for the unicode tokenizer.
153653*/
153654SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
153655  static const sqlite3_tokenizer_module module = {
153656    0,
153657    unicodeCreate,
153658    unicodeDestroy,
153659    unicodeOpen,
153660    unicodeClose,
153661    unicodeNext,
153662    0,
153663  };
153664  *ppModule = &module;
153665}
153666
153667#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153668#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
153669
153670/************** End of fts3_unicode.c ****************************************/
153671/************** Begin file fts3_unicode2.c ***********************************/
153672/*
153673** 2012 May 25
153674**
153675** The author disclaims copyright to this source code.  In place of
153676** a legal notice, here is a blessing:
153677**
153678**    May you do good and not evil.
153679**    May you find forgiveness for yourself and forgive others.
153680**    May you share freely, never taking more than you give.
153681**
153682******************************************************************************
153683*/
153684
153685/*
153686** DO NOT EDIT THIS MACHINE GENERATED FILE.
153687*/
153688
153689#ifndef SQLITE_DISABLE_FTS3_UNICODE
153690#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
153691
153692/* #include <assert.h> */
153693
153694/*
153695** Return true if the argument corresponds to a unicode codepoint
153696** classified as either a letter or a number. Otherwise false.
153697**
153698** The results are undefined if the value passed to this function
153699** is less than zero.
153700*/
153701SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
153702  /* Each unsigned integer in the following array corresponds to a contiguous
153703  ** range of unicode codepoints that are not either letters or numbers (i.e.
153704  ** codepoints for which this function should return 0).
153705  **
153706  ** The most significant 22 bits in each 32-bit value contain the first
153707  ** codepoint in the range. The least significant 10 bits are used to store
153708  ** the size of the range (always at least 1). In other words, the value
153709  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
153710  ** C. It is not possible to represent a range larger than 1023 codepoints
153711  ** using this format.
153712  */
153713  static const unsigned int aEntry[] = {
153714    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
153715    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
153716    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
153717    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
153718    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
153719    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
153720    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
153721    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
153722    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
153723    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
153724    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
153725    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
153726    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
153727    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
153728    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
153729    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
153730    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
153731    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
153732    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
153733    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
153734    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
153735    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
153736    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
153737    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
153738    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
153739    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
153740    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
153741    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
153742    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
153743    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
153744    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
153745    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
153746    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
153747    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
153748    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
153749    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
153750    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
153751    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
153752    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
153753    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
153754    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
153755    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
153756    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
153757    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
153758    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
153759    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
153760    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
153761    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
153762    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
153763    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
153764    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
153765    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
153766    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
153767    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
153768    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
153769    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
153770    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
153771    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
153772    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
153773    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
153774    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
153775    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
153776    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
153777    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
153778    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
153779    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
153780    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
153781    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
153782    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
153783    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
153784    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
153785    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
153786    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
153787    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
153788    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
153789    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
153790    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
153791    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
153792    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
153793    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
153794    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
153795    0x380400F0,
153796  };
153797  static const unsigned int aAscii[4] = {
153798    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
153799  };
153800
153801  if( c<128 ){
153802    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
153803  }else if( c<(1<<22) ){
153804    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
153805    int iRes = 0;
153806    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
153807    int iLo = 0;
153808    while( iHi>=iLo ){
153809      int iTest = (iHi + iLo) / 2;
153810      if( key >= aEntry[iTest] ){
153811        iRes = iTest;
153812        iLo = iTest+1;
153813      }else{
153814        iHi = iTest-1;
153815      }
153816    }
153817    assert( aEntry[0]<key );
153818    assert( key>=aEntry[iRes] );
153819    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
153820  }
153821  return 1;
153822}
153823
153824
153825/*
153826** If the argument is a codepoint corresponding to a lowercase letter
153827** in the ASCII range with a diacritic added, return the codepoint
153828** of the ASCII letter only. For example, if passed 235 - "LATIN
153829** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
153830** E"). The resuls of passing a codepoint that corresponds to an
153831** uppercase letter are undefined.
153832*/
153833static int remove_diacritic(int c){
153834  unsigned short aDia[] = {
153835        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
153836     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
153837     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
153838     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
153839     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
153840     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
153841     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
153842     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
153843    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
153844    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
153845    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
153846    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
153847    62924, 63050, 63082, 63274, 63390,
153848  };
153849  char aChar[] = {
153850    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
153851    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
153852    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
153853    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
153854    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
153855    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
153856    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
153857    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
153858    'e',  'i',  'o',  'u',  'y',
153859  };
153860
153861  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
153862  int iRes = 0;
153863  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
153864  int iLo = 0;
153865  while( iHi>=iLo ){
153866    int iTest = (iHi + iLo) / 2;
153867    if( key >= aDia[iTest] ){
153868      iRes = iTest;
153869      iLo = iTest+1;
153870    }else{
153871      iHi = iTest-1;
153872    }
153873  }
153874  assert( key>=aDia[iRes] );
153875  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
153876}
153877
153878
153879/*
153880** Return true if the argument interpreted as a unicode codepoint
153881** is a diacritical modifier character.
153882*/
153883SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
153884  unsigned int mask0 = 0x08029FDF;
153885  unsigned int mask1 = 0x000361F8;
153886  if( c<768 || c>817 ) return 0;
153887  return (c < 768+32) ?
153888      (mask0 & (1 << (c-768))) :
153889      (mask1 & (1 << (c-768-32)));
153890}
153891
153892
153893/*
153894** Interpret the argument as a unicode codepoint. If the codepoint
153895** is an upper case character that has a lower case equivalent,
153896** return the codepoint corresponding to the lower case version.
153897** Otherwise, return a copy of the argument.
153898**
153899** The results are undefined if the value passed to this function
153900** is less than zero.
153901*/
153902SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
153903  /* Each entry in the following array defines a rule for folding a range
153904  ** of codepoints to lower case. The rule applies to a range of nRange
153905  ** codepoints starting at codepoint iCode.
153906  **
153907  ** If the least significant bit in flags is clear, then the rule applies
153908  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
153909  ** need to be folded). Or, if it is set, then the rule only applies to
153910  ** every second codepoint in the range, starting with codepoint C.
153911  **
153912  ** The 7 most significant bits in flags are an index into the aiOff[]
153913  ** array. If a specific codepoint C does require folding, then its lower
153914  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
153915  **
153916  ** The contents of this array are generated by parsing the CaseFolding.txt
153917  ** file distributed as part of the "Unicode Character Database". See
153918  ** http://www.unicode.org for details.
153919  */
153920  static const struct TableEntry {
153921    unsigned short iCode;
153922    unsigned char flags;
153923    unsigned char nRange;
153924  } aEntry[] = {
153925    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
153926    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
153927    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
153928    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
153929    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
153930    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
153931    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
153932    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
153933    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
153934    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
153935    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
153936    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
153937    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
153938    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
153939    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
153940    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
153941    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
153942    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
153943    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
153944    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
153945    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
153946    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
153947    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
153948    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
153949    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
153950    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
153951    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
153952    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
153953    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
153954    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
153955    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
153956    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
153957    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
153958    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
153959    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
153960    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
153961    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
153962    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
153963    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
153964    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
153965    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
153966    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
153967    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
153968    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
153969    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
153970    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
153971    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
153972    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
153973    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
153974    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
153975    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
153976    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
153977    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
153978    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
153979    {65313, 14, 26},
153980  };
153981  static const unsigned short aiOff[] = {
153982   1,     2,     8,     15,    16,    26,    28,    32,
153983   37,    38,    40,    48,    63,    64,    69,    71,
153984   79,    80,    116,   202,   203,   205,   206,   207,
153985   209,   210,   211,   213,   214,   217,   218,   219,
153986   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
153987   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
153988   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
153989   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
153990   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
153991   65514, 65521, 65527, 65528, 65529,
153992  };
153993
153994  int ret = c;
153995
153996  assert( c>=0 );
153997  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
153998
153999  if( c<128 ){
154000    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
154001  }else if( c<65536 ){
154002    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
154003    int iLo = 0;
154004    int iRes = -1;
154005
154006    while( iHi>=iLo ){
154007      int iTest = (iHi + iLo) / 2;
154008      int cmp = (c - aEntry[iTest].iCode);
154009      if( cmp>=0 ){
154010        iRes = iTest;
154011        iLo = iTest+1;
154012      }else{
154013        iHi = iTest-1;
154014      }
154015    }
154016    assert( iRes<0 || c>=aEntry[iRes].iCode );
154017
154018    if( iRes>=0 ){
154019      const struct TableEntry *p = &aEntry[iRes];
154020      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
154021        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
154022        assert( ret>0 );
154023      }
154024    }
154025
154026    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
154027  }
154028
154029  else if( c>=66560 && c<66600 ){
154030    ret = c + 40;
154031  }
154032
154033  return ret;
154034}
154035#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
154036#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
154037
154038/************** End of fts3_unicode2.c ***************************************/
154039/************** Begin file rtree.c *******************************************/
154040/*
154041** 2001 September 15
154042**
154043** The author disclaims copyright to this source code.  In place of
154044** a legal notice, here is a blessing:
154045**
154046**    May you do good and not evil.
154047**    May you find forgiveness for yourself and forgive others.
154048**    May you share freely, never taking more than you give.
154049**
154050*************************************************************************
154051** This file contains code for implementations of the r-tree and r*-tree
154052** algorithms packaged as an SQLite virtual table module.
154053*/
154054
154055/*
154056** Database Format of R-Tree Tables
154057** --------------------------------
154058**
154059** The data structure for a single virtual r-tree table is stored in three
154060** native SQLite tables declared as follows. In each case, the '%' character
154061** in the table name is replaced with the user-supplied name of the r-tree
154062** table.
154063**
154064**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
154065**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
154066**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
154067**
154068** The data for each node of the r-tree structure is stored in the %_node
154069** table. For each node that is not the root node of the r-tree, there is
154070** an entry in the %_parent table associating the node with its parent.
154071** And for each row of data in the table, there is an entry in the %_rowid
154072** table that maps from the entries rowid to the id of the node that it
154073** is stored on.
154074**
154075** The root node of an r-tree always exists, even if the r-tree table is
154076** empty. The nodeno of the root node is always 1. All other nodes in the
154077** table must be the same size as the root node. The content of each node
154078** is formatted as follows:
154079**
154080**   1. If the node is the root node (node 1), then the first 2 bytes
154081**      of the node contain the tree depth as a big-endian integer.
154082**      For non-root nodes, the first 2 bytes are left unused.
154083**
154084**   2. The next 2 bytes contain the number of entries currently
154085**      stored in the node.
154086**
154087**   3. The remainder of the node contains the node entries. Each entry
154088**      consists of a single 8-byte integer followed by an even number
154089**      of 4-byte coordinates. For leaf nodes the integer is the rowid
154090**      of a record. For internal nodes it is the node number of a
154091**      child page.
154092*/
154093
154094#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
154095
154096#ifndef SQLITE_CORE
154097/*   #include "sqlite3ext.h" */
154098  SQLITE_EXTENSION_INIT1
154099#else
154100/*   #include "sqlite3.h" */
154101#endif
154102
154103/* #include <string.h> */
154104/* #include <assert.h> */
154105/* #include <stdio.h> */
154106
154107#ifndef SQLITE_AMALGAMATION
154108#include "sqlite3rtree.h"
154109typedef sqlite3_int64 i64;
154110typedef unsigned char u8;
154111typedef unsigned short u16;
154112typedef unsigned int u32;
154113#endif
154114
154115/*  The following macro is used to suppress compiler warnings.
154116*/
154117#ifndef UNUSED_PARAMETER
154118# define UNUSED_PARAMETER(x) (void)(x)
154119#endif
154120
154121typedef struct Rtree Rtree;
154122typedef struct RtreeCursor RtreeCursor;
154123typedef struct RtreeNode RtreeNode;
154124typedef struct RtreeCell RtreeCell;
154125typedef struct RtreeConstraint RtreeConstraint;
154126typedef struct RtreeMatchArg RtreeMatchArg;
154127typedef struct RtreeGeomCallback RtreeGeomCallback;
154128typedef union RtreeCoord RtreeCoord;
154129typedef struct RtreeSearchPoint RtreeSearchPoint;
154130
154131/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
154132#define RTREE_MAX_DIMENSIONS 5
154133
154134/* Size of hash table Rtree.aHash. This hash table is not expected to
154135** ever contain very many entries, so a fixed number of buckets is
154136** used.
154137*/
154138#define HASHSIZE 97
154139
154140/* The xBestIndex method of this virtual table requires an estimate of
154141** the number of rows in the virtual table to calculate the costs of
154142** various strategies. If possible, this estimate is loaded from the
154143** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
154144** Otherwise, if no sqlite_stat1 entry is available, use
154145** RTREE_DEFAULT_ROWEST.
154146*/
154147#define RTREE_DEFAULT_ROWEST 1048576
154148#define RTREE_MIN_ROWEST         100
154149
154150/*
154151** An rtree virtual-table object.
154152*/
154153struct Rtree {
154154  sqlite3_vtab base;          /* Base class.  Must be first */
154155  sqlite3 *db;                /* Host database connection */
154156  int iNodeSize;              /* Size in bytes of each node in the node table */
154157  u8 nDim;                    /* Number of dimensions */
154158  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
154159  u8 nBytesPerCell;           /* Bytes consumed per cell */
154160  int iDepth;                 /* Current depth of the r-tree structure */
154161  char *zDb;                  /* Name of database containing r-tree table */
154162  char *zName;                /* Name of r-tree table */
154163  int nBusy;                  /* Current number of users of this structure */
154164  i64 nRowEst;                /* Estimated number of rows in this table */
154165
154166  /* List of nodes removed during a CondenseTree operation. List is
154167  ** linked together via the pointer normally used for hash chains -
154168  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
154169  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
154170  */
154171  RtreeNode *pDeleted;
154172  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
154173
154174  /* Statements to read/write/delete a record from xxx_node */
154175  sqlite3_stmt *pReadNode;
154176  sqlite3_stmt *pWriteNode;
154177  sqlite3_stmt *pDeleteNode;
154178
154179  /* Statements to read/write/delete a record from xxx_rowid */
154180  sqlite3_stmt *pReadRowid;
154181  sqlite3_stmt *pWriteRowid;
154182  sqlite3_stmt *pDeleteRowid;
154183
154184  /* Statements to read/write/delete a record from xxx_parent */
154185  sqlite3_stmt *pReadParent;
154186  sqlite3_stmt *pWriteParent;
154187  sqlite3_stmt *pDeleteParent;
154188
154189  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
154190};
154191
154192/* Possible values for Rtree.eCoordType: */
154193#define RTREE_COORD_REAL32 0
154194#define RTREE_COORD_INT32  1
154195
154196/*
154197** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
154198** only deal with integer coordinates.  No floating point operations
154199** will be done.
154200*/
154201#ifdef SQLITE_RTREE_INT_ONLY
154202  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
154203  typedef int RtreeValue;                  /* Low accuracy coordinate */
154204# define RTREE_ZERO 0
154205#else
154206  typedef double RtreeDValue;              /* High accuracy coordinate */
154207  typedef float RtreeValue;                /* Low accuracy coordinate */
154208# define RTREE_ZERO 0.0
154209#endif
154210
154211/*
154212** When doing a search of an r-tree, instances of the following structure
154213** record intermediate results from the tree walk.
154214**
154215** The id is always a node-id.  For iLevel>=1 the id is the node-id of
154216** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
154217** the id is of the parent node and the cell that RtreeSearchPoint
154218** represents is the iCell-th entry in the parent node.
154219*/
154220struct RtreeSearchPoint {
154221  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
154222  sqlite3_int64 id;      /* Node ID */
154223  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
154224  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
154225  u8 iCell;              /* Cell index within the node */
154226};
154227
154228/*
154229** The minimum number of cells allowed for a node is a third of the
154230** maximum. In Gutman's notation:
154231**
154232**     m = M/3
154233**
154234** If an R*-tree "Reinsert" operation is required, the same number of
154235** cells are removed from the overfull node and reinserted into the tree.
154236*/
154237#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
154238#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
154239#define RTREE_MAXCELLS 51
154240
154241/*
154242** The smallest possible node-size is (512-64)==448 bytes. And the largest
154243** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
154244** Therefore all non-root nodes must contain at least 3 entries. Since
154245** 2^40 is greater than 2^64, an r-tree structure always has a depth of
154246** 40 or less.
154247*/
154248#define RTREE_MAX_DEPTH 40
154249
154250
154251/*
154252** Number of entries in the cursor RtreeNode cache.  The first entry is
154253** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
154254** entries cache the RtreeNode for the first elements of the priority queue.
154255*/
154256#define RTREE_CACHE_SZ  5
154257
154258/*
154259** An rtree cursor object.
154260*/
154261struct RtreeCursor {
154262  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
154263  u8 atEOF;                         /* True if at end of search */
154264  u8 bPoint;                        /* True if sPoint is valid */
154265  int iStrategy;                    /* Copy of idxNum search parameter */
154266  int nConstraint;                  /* Number of entries in aConstraint */
154267  RtreeConstraint *aConstraint;     /* Search constraints. */
154268  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
154269  int nPoint;                       /* Number of slots used in aPoint[] */
154270  int mxLevel;                      /* iLevel value for root of the tree */
154271  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
154272  RtreeSearchPoint sPoint;          /* Cached next search point */
154273  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
154274  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
154275};
154276
154277/* Return the Rtree of a RtreeCursor */
154278#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
154279
154280/*
154281** A coordinate can be either a floating point number or a integer.  All
154282** coordinates within a single R-Tree are always of the same time.
154283*/
154284union RtreeCoord {
154285  RtreeValue f;      /* Floating point value */
154286  int i;             /* Integer value */
154287  u32 u;             /* Unsigned for byte-order conversions */
154288};
154289
154290/*
154291** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
154292** formatted as a RtreeDValue (double or int64). This macro assumes that local
154293** variable pRtree points to the Rtree structure associated with the
154294** RtreeCoord.
154295*/
154296#ifdef SQLITE_RTREE_INT_ONLY
154297# define DCOORD(coord) ((RtreeDValue)coord.i)
154298#else
154299# define DCOORD(coord) (                           \
154300    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
154301      ((double)coord.f) :                           \
154302      ((double)coord.i)                             \
154303  )
154304#endif
154305
154306/*
154307** A search constraint.
154308*/
154309struct RtreeConstraint {
154310  int iCoord;                     /* Index of constrained coordinate */
154311  int op;                         /* Constraining operation */
154312  union {
154313    RtreeDValue rValue;             /* Constraint value. */
154314    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
154315    int (*xQueryFunc)(sqlite3_rtree_query_info*);
154316  } u;
154317  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
154318};
154319
154320/* Possible values for RtreeConstraint.op */
154321#define RTREE_EQ    0x41  /* A */
154322#define RTREE_LE    0x42  /* B */
154323#define RTREE_LT    0x43  /* C */
154324#define RTREE_GE    0x44  /* D */
154325#define RTREE_GT    0x45  /* E */
154326#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
154327#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
154328
154329
154330/*
154331** An rtree structure node.
154332*/
154333struct RtreeNode {
154334  RtreeNode *pParent;         /* Parent node */
154335  i64 iNode;                  /* The node number */
154336  int nRef;                   /* Number of references to this node */
154337  int isDirty;                /* True if the node needs to be written to disk */
154338  u8 *zData;                  /* Content of the node, as should be on disk */
154339  RtreeNode *pNext;           /* Next node in this hash collision chain */
154340};
154341
154342/* Return the number of cells in a node  */
154343#define NCELL(pNode) readInt16(&(pNode)->zData[2])
154344
154345/*
154346** A single cell from a node, deserialized
154347*/
154348struct RtreeCell {
154349  i64 iRowid;                                 /* Node or entry ID */
154350  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
154351};
154352
154353
154354/*
154355** This object becomes the sqlite3_user_data() for the SQL functions
154356** that are created by sqlite3_rtree_geometry_callback() and
154357** sqlite3_rtree_query_callback() and which appear on the right of MATCH
154358** operators in order to constrain a search.
154359**
154360** xGeom and xQueryFunc are the callback functions.  Exactly one of
154361** xGeom and xQueryFunc fields is non-NULL, depending on whether the
154362** SQL function was created using sqlite3_rtree_geometry_callback() or
154363** sqlite3_rtree_query_callback().
154364**
154365** This object is deleted automatically by the destructor mechanism in
154366** sqlite3_create_function_v2().
154367*/
154368struct RtreeGeomCallback {
154369  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
154370  int (*xQueryFunc)(sqlite3_rtree_query_info*);
154371  void (*xDestructor)(void*);
154372  void *pContext;
154373};
154374
154375
154376/*
154377** Value for the first field of every RtreeMatchArg object. The MATCH
154378** operator tests that the first field of a blob operand matches this
154379** value to avoid operating on invalid blobs (which could cause a segfault).
154380*/
154381#define RTREE_GEOMETRY_MAGIC 0x891245AB
154382
154383/*
154384** An instance of this structure (in the form of a BLOB) is returned by
154385** the SQL functions that sqlite3_rtree_geometry_callback() and
154386** sqlite3_rtree_query_callback() create, and is read as the right-hand
154387** operand to the MATCH operator of an R-Tree.
154388*/
154389struct RtreeMatchArg {
154390  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
154391  RtreeGeomCallback cb;       /* Info about the callback functions */
154392  int nParam;                 /* Number of parameters to the SQL function */
154393  sqlite3_value **apSqlParam; /* Original SQL parameter values */
154394  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
154395};
154396
154397#ifndef MAX
154398# define MAX(x,y) ((x) < (y) ? (y) : (x))
154399#endif
154400#ifndef MIN
154401# define MIN(x,y) ((x) > (y) ? (y) : (x))
154402#endif
154403
154404/*
154405** Functions to deserialize a 16 bit integer, 32 bit real number and
154406** 64 bit integer. The deserialized value is returned.
154407*/
154408static int readInt16(u8 *p){
154409  return (p[0]<<8) + p[1];
154410}
154411static void readCoord(u8 *p, RtreeCoord *pCoord){
154412  pCoord->u = (
154413    (((u32)p[0]) << 24) +
154414    (((u32)p[1]) << 16) +
154415    (((u32)p[2]) <<  8) +
154416    (((u32)p[3]) <<  0)
154417  );
154418}
154419static i64 readInt64(u8 *p){
154420  return (
154421    (((i64)p[0]) << 56) +
154422    (((i64)p[1]) << 48) +
154423    (((i64)p[2]) << 40) +
154424    (((i64)p[3]) << 32) +
154425    (((i64)p[4]) << 24) +
154426    (((i64)p[5]) << 16) +
154427    (((i64)p[6]) <<  8) +
154428    (((i64)p[7]) <<  0)
154429  );
154430}
154431
154432/*
154433** Functions to serialize a 16 bit integer, 32 bit real number and
154434** 64 bit integer. The value returned is the number of bytes written
154435** to the argument buffer (always 2, 4 and 8 respectively).
154436*/
154437static int writeInt16(u8 *p, int i){
154438  p[0] = (i>> 8)&0xFF;
154439  p[1] = (i>> 0)&0xFF;
154440  return 2;
154441}
154442static int writeCoord(u8 *p, RtreeCoord *pCoord){
154443  u32 i;
154444  assert( sizeof(RtreeCoord)==4 );
154445  assert( sizeof(u32)==4 );
154446  i = pCoord->u;
154447  p[0] = (i>>24)&0xFF;
154448  p[1] = (i>>16)&0xFF;
154449  p[2] = (i>> 8)&0xFF;
154450  p[3] = (i>> 0)&0xFF;
154451  return 4;
154452}
154453static int writeInt64(u8 *p, i64 i){
154454  p[0] = (i>>56)&0xFF;
154455  p[1] = (i>>48)&0xFF;
154456  p[2] = (i>>40)&0xFF;
154457  p[3] = (i>>32)&0xFF;
154458  p[4] = (i>>24)&0xFF;
154459  p[5] = (i>>16)&0xFF;
154460  p[6] = (i>> 8)&0xFF;
154461  p[7] = (i>> 0)&0xFF;
154462  return 8;
154463}
154464
154465/*
154466** Increment the reference count of node p.
154467*/
154468static void nodeReference(RtreeNode *p){
154469  if( p ){
154470    p->nRef++;
154471  }
154472}
154473
154474/*
154475** Clear the content of node p (set all bytes to 0x00).
154476*/
154477static void nodeZero(Rtree *pRtree, RtreeNode *p){
154478  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
154479  p->isDirty = 1;
154480}
154481
154482/*
154483** Given a node number iNode, return the corresponding key to use
154484** in the Rtree.aHash table.
154485*/
154486static int nodeHash(i64 iNode){
154487  return iNode % HASHSIZE;
154488}
154489
154490/*
154491** Search the node hash table for node iNode. If found, return a pointer
154492** to it. Otherwise, return 0.
154493*/
154494static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
154495  RtreeNode *p;
154496  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
154497  return p;
154498}
154499
154500/*
154501** Add node pNode to the node hash table.
154502*/
154503static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
154504  int iHash;
154505  assert( pNode->pNext==0 );
154506  iHash = nodeHash(pNode->iNode);
154507  pNode->pNext = pRtree->aHash[iHash];
154508  pRtree->aHash[iHash] = pNode;
154509}
154510
154511/*
154512** Remove node pNode from the node hash table.
154513*/
154514static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
154515  RtreeNode **pp;
154516  if( pNode->iNode!=0 ){
154517    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
154518    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
154519    *pp = pNode->pNext;
154520    pNode->pNext = 0;
154521  }
154522}
154523
154524/*
154525** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
154526** indicating that node has not yet been assigned a node number. It is
154527** assigned a node number when nodeWrite() is called to write the
154528** node contents out to the database.
154529*/
154530static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
154531  RtreeNode *pNode;
154532  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
154533  if( pNode ){
154534    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
154535    pNode->zData = (u8 *)&pNode[1];
154536    pNode->nRef = 1;
154537    pNode->pParent = pParent;
154538    pNode->isDirty = 1;
154539    nodeReference(pParent);
154540  }
154541  return pNode;
154542}
154543
154544/*
154545** Obtain a reference to an r-tree node.
154546*/
154547static int nodeAcquire(
154548  Rtree *pRtree,             /* R-tree structure */
154549  i64 iNode,                 /* Node number to load */
154550  RtreeNode *pParent,        /* Either the parent node or NULL */
154551  RtreeNode **ppNode         /* OUT: Acquired node */
154552){
154553  int rc;
154554  int rc2 = SQLITE_OK;
154555  RtreeNode *pNode;
154556
154557  /* Check if the requested node is already in the hash table. If so,
154558  ** increase its reference count and return it.
154559  */
154560  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
154561    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
154562    if( pParent && !pNode->pParent ){
154563      nodeReference(pParent);
154564      pNode->pParent = pParent;
154565    }
154566    pNode->nRef++;
154567    *ppNode = pNode;
154568    return SQLITE_OK;
154569  }
154570
154571  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
154572  rc = sqlite3_step(pRtree->pReadNode);
154573  if( rc==SQLITE_ROW ){
154574    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
154575    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
154576      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
154577      if( !pNode ){
154578        rc2 = SQLITE_NOMEM;
154579      }else{
154580        pNode->pParent = pParent;
154581        pNode->zData = (u8 *)&pNode[1];
154582        pNode->nRef = 1;
154583        pNode->iNode = iNode;
154584        pNode->isDirty = 0;
154585        pNode->pNext = 0;
154586        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
154587        nodeReference(pParent);
154588      }
154589    }
154590  }
154591  rc = sqlite3_reset(pRtree->pReadNode);
154592  if( rc==SQLITE_OK ) rc = rc2;
154593
154594  /* If the root node was just loaded, set pRtree->iDepth to the height
154595  ** of the r-tree structure. A height of zero means all data is stored on
154596  ** the root node. A height of one means the children of the root node
154597  ** are the leaves, and so on. If the depth as specified on the root node
154598  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
154599  */
154600  if( pNode && iNode==1 ){
154601    pRtree->iDepth = readInt16(pNode->zData);
154602    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
154603      rc = SQLITE_CORRUPT_VTAB;
154604    }
154605  }
154606
154607  /* If no error has occurred so far, check if the "number of entries"
154608  ** field on the node is too large. If so, set the return code to
154609  ** SQLITE_CORRUPT_VTAB.
154610  */
154611  if( pNode && rc==SQLITE_OK ){
154612    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
154613      rc = SQLITE_CORRUPT_VTAB;
154614    }
154615  }
154616
154617  if( rc==SQLITE_OK ){
154618    if( pNode!=0 ){
154619      nodeHashInsert(pRtree, pNode);
154620    }else{
154621      rc = SQLITE_CORRUPT_VTAB;
154622    }
154623    *ppNode = pNode;
154624  }else{
154625    sqlite3_free(pNode);
154626    *ppNode = 0;
154627  }
154628
154629  return rc;
154630}
154631
154632/*
154633** Overwrite cell iCell of node pNode with the contents of pCell.
154634*/
154635static void nodeOverwriteCell(
154636  Rtree *pRtree,             /* The overall R-Tree */
154637  RtreeNode *pNode,          /* The node into which the cell is to be written */
154638  RtreeCell *pCell,          /* The cell to write */
154639  int iCell                  /* Index into pNode into which pCell is written */
154640){
154641  int ii;
154642  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
154643  p += writeInt64(p, pCell->iRowid);
154644  for(ii=0; ii<(pRtree->nDim*2); ii++){
154645    p += writeCoord(p, &pCell->aCoord[ii]);
154646  }
154647  pNode->isDirty = 1;
154648}
154649
154650/*
154651** Remove the cell with index iCell from node pNode.
154652*/
154653static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
154654  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
154655  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
154656  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
154657  memmove(pDst, pSrc, nByte);
154658  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
154659  pNode->isDirty = 1;
154660}
154661
154662/*
154663** Insert the contents of cell pCell into node pNode. If the insert
154664** is successful, return SQLITE_OK.
154665**
154666** If there is not enough free space in pNode, return SQLITE_FULL.
154667*/
154668static int nodeInsertCell(
154669  Rtree *pRtree,                /* The overall R-Tree */
154670  RtreeNode *pNode,             /* Write new cell into this node */
154671  RtreeCell *pCell              /* The cell to be inserted */
154672){
154673  int nCell;                    /* Current number of cells in pNode */
154674  int nMaxCell;                 /* Maximum number of cells for pNode */
154675
154676  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
154677  nCell = NCELL(pNode);
154678
154679  assert( nCell<=nMaxCell );
154680  if( nCell<nMaxCell ){
154681    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
154682    writeInt16(&pNode->zData[2], nCell+1);
154683    pNode->isDirty = 1;
154684  }
154685
154686  return (nCell==nMaxCell);
154687}
154688
154689/*
154690** If the node is dirty, write it out to the database.
154691*/
154692static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
154693  int rc = SQLITE_OK;
154694  if( pNode->isDirty ){
154695    sqlite3_stmt *p = pRtree->pWriteNode;
154696    if( pNode->iNode ){
154697      sqlite3_bind_int64(p, 1, pNode->iNode);
154698    }else{
154699      sqlite3_bind_null(p, 1);
154700    }
154701    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
154702    sqlite3_step(p);
154703    pNode->isDirty = 0;
154704    rc = sqlite3_reset(p);
154705    if( pNode->iNode==0 && rc==SQLITE_OK ){
154706      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
154707      nodeHashInsert(pRtree, pNode);
154708    }
154709  }
154710  return rc;
154711}
154712
154713/*
154714** Release a reference to a node. If the node is dirty and the reference
154715** count drops to zero, the node data is written to the database.
154716*/
154717static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
154718  int rc = SQLITE_OK;
154719  if( pNode ){
154720    assert( pNode->nRef>0 );
154721    pNode->nRef--;
154722    if( pNode->nRef==0 ){
154723      if( pNode->iNode==1 ){
154724        pRtree->iDepth = -1;
154725      }
154726      if( pNode->pParent ){
154727        rc = nodeRelease(pRtree, pNode->pParent);
154728      }
154729      if( rc==SQLITE_OK ){
154730        rc = nodeWrite(pRtree, pNode);
154731      }
154732      nodeHashDelete(pRtree, pNode);
154733      sqlite3_free(pNode);
154734    }
154735  }
154736  return rc;
154737}
154738
154739/*
154740** Return the 64-bit integer value associated with cell iCell of
154741** node pNode. If pNode is a leaf node, this is a rowid. If it is
154742** an internal node, then the 64-bit integer is a child page number.
154743*/
154744static i64 nodeGetRowid(
154745  Rtree *pRtree,       /* The overall R-Tree */
154746  RtreeNode *pNode,    /* The node from which to extract the ID */
154747  int iCell            /* The cell index from which to extract the ID */
154748){
154749  assert( iCell<NCELL(pNode) );
154750  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
154751}
154752
154753/*
154754** Return coordinate iCoord from cell iCell in node pNode.
154755*/
154756static void nodeGetCoord(
154757  Rtree *pRtree,               /* The overall R-Tree */
154758  RtreeNode *pNode,            /* The node from which to extract a coordinate */
154759  int iCell,                   /* The index of the cell within the node */
154760  int iCoord,                  /* Which coordinate to extract */
154761  RtreeCoord *pCoord           /* OUT: Space to write result to */
154762){
154763  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
154764}
154765
154766/*
154767** Deserialize cell iCell of node pNode. Populate the structure pointed
154768** to by pCell with the results.
154769*/
154770static void nodeGetCell(
154771  Rtree *pRtree,               /* The overall R-Tree */
154772  RtreeNode *pNode,            /* The node containing the cell to be read */
154773  int iCell,                   /* Index of the cell within the node */
154774  RtreeCell *pCell             /* OUT: Write the cell contents here */
154775){
154776  u8 *pData;
154777  RtreeCoord *pCoord;
154778  int ii;
154779  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
154780  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
154781  pCoord = pCell->aCoord;
154782  for(ii=0; ii<pRtree->nDim*2; ii++){
154783    readCoord(&pData[ii*4], &pCoord[ii]);
154784  }
154785}
154786
154787
154788/* Forward declaration for the function that does the work of
154789** the virtual table module xCreate() and xConnect() methods.
154790*/
154791static int rtreeInit(
154792  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
154793);
154794
154795/*
154796** Rtree virtual table module xCreate method.
154797*/
154798static int rtreeCreate(
154799  sqlite3 *db,
154800  void *pAux,
154801  int argc, const char *const*argv,
154802  sqlite3_vtab **ppVtab,
154803  char **pzErr
154804){
154805  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
154806}
154807
154808/*
154809** Rtree virtual table module xConnect method.
154810*/
154811static int rtreeConnect(
154812  sqlite3 *db,
154813  void *pAux,
154814  int argc, const char *const*argv,
154815  sqlite3_vtab **ppVtab,
154816  char **pzErr
154817){
154818  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
154819}
154820
154821/*
154822** Increment the r-tree reference count.
154823*/
154824static void rtreeReference(Rtree *pRtree){
154825  pRtree->nBusy++;
154826}
154827
154828/*
154829** Decrement the r-tree reference count. When the reference count reaches
154830** zero the structure is deleted.
154831*/
154832static void rtreeRelease(Rtree *pRtree){
154833  pRtree->nBusy--;
154834  if( pRtree->nBusy==0 ){
154835    sqlite3_finalize(pRtree->pReadNode);
154836    sqlite3_finalize(pRtree->pWriteNode);
154837    sqlite3_finalize(pRtree->pDeleteNode);
154838    sqlite3_finalize(pRtree->pReadRowid);
154839    sqlite3_finalize(pRtree->pWriteRowid);
154840    sqlite3_finalize(pRtree->pDeleteRowid);
154841    sqlite3_finalize(pRtree->pReadParent);
154842    sqlite3_finalize(pRtree->pWriteParent);
154843    sqlite3_finalize(pRtree->pDeleteParent);
154844    sqlite3_free(pRtree);
154845  }
154846}
154847
154848/*
154849** Rtree virtual table module xDisconnect method.
154850*/
154851static int rtreeDisconnect(sqlite3_vtab *pVtab){
154852  rtreeRelease((Rtree *)pVtab);
154853  return SQLITE_OK;
154854}
154855
154856/*
154857** Rtree virtual table module xDestroy method.
154858*/
154859static int rtreeDestroy(sqlite3_vtab *pVtab){
154860  Rtree *pRtree = (Rtree *)pVtab;
154861  int rc;
154862  char *zCreate = sqlite3_mprintf(
154863    "DROP TABLE '%q'.'%q_node';"
154864    "DROP TABLE '%q'.'%q_rowid';"
154865    "DROP TABLE '%q'.'%q_parent';",
154866    pRtree->zDb, pRtree->zName,
154867    pRtree->zDb, pRtree->zName,
154868    pRtree->zDb, pRtree->zName
154869  );
154870  if( !zCreate ){
154871    rc = SQLITE_NOMEM;
154872  }else{
154873    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
154874    sqlite3_free(zCreate);
154875  }
154876  if( rc==SQLITE_OK ){
154877    rtreeRelease(pRtree);
154878  }
154879
154880  return rc;
154881}
154882
154883/*
154884** Rtree virtual table module xOpen method.
154885*/
154886static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
154887  int rc = SQLITE_NOMEM;
154888  RtreeCursor *pCsr;
154889
154890  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
154891  if( pCsr ){
154892    memset(pCsr, 0, sizeof(RtreeCursor));
154893    pCsr->base.pVtab = pVTab;
154894    rc = SQLITE_OK;
154895  }
154896  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
154897
154898  return rc;
154899}
154900
154901
154902/*
154903** Free the RtreeCursor.aConstraint[] array and its contents.
154904*/
154905static void freeCursorConstraints(RtreeCursor *pCsr){
154906  if( pCsr->aConstraint ){
154907    int i;                        /* Used to iterate through constraint array */
154908    for(i=0; i<pCsr->nConstraint; i++){
154909      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
154910      if( pInfo ){
154911        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
154912        sqlite3_free(pInfo);
154913      }
154914    }
154915    sqlite3_free(pCsr->aConstraint);
154916    pCsr->aConstraint = 0;
154917  }
154918}
154919
154920/*
154921** Rtree virtual table module xClose method.
154922*/
154923static int rtreeClose(sqlite3_vtab_cursor *cur){
154924  Rtree *pRtree = (Rtree *)(cur->pVtab);
154925  int ii;
154926  RtreeCursor *pCsr = (RtreeCursor *)cur;
154927  freeCursorConstraints(pCsr);
154928  sqlite3_free(pCsr->aPoint);
154929  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
154930  sqlite3_free(pCsr);
154931  return SQLITE_OK;
154932}
154933
154934/*
154935** Rtree virtual table module xEof method.
154936**
154937** Return non-zero if the cursor does not currently point to a valid
154938** record (i.e if the scan has finished), or zero otherwise.
154939*/
154940static int rtreeEof(sqlite3_vtab_cursor *cur){
154941  RtreeCursor *pCsr = (RtreeCursor *)cur;
154942  return pCsr->atEOF;
154943}
154944
154945/*
154946** Convert raw bits from the on-disk RTree record into a coordinate value.
154947** The on-disk format is big-endian and needs to be converted for little-
154948** endian platforms.  The on-disk record stores integer coordinates if
154949** eInt is true and it stores 32-bit floating point records if eInt is
154950** false.  a[] is the four bytes of the on-disk record to be decoded.
154951** Store the results in "r".
154952**
154953** There are three versions of this macro, one each for little-endian and
154954** big-endian processors and a third generic implementation.  The endian-
154955** specific implementations are much faster and are preferred if the
154956** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
154957** macro is part of sqliteInt.h and hence the endian-specific
154958** implementation will only be used if this module is compiled as part
154959** of the amalgamation.
154960*/
154961#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
154962#define RTREE_DECODE_COORD(eInt, a, r) {                        \
154963    RtreeCoord c;    /* Coordinate decoded */                   \
154964    memcpy(&c.u,a,4);                                           \
154965    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
154966          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
154967    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
154968}
154969#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
154970#define RTREE_DECODE_COORD(eInt, a, r) {                        \
154971    RtreeCoord c;    /* Coordinate decoded */                   \
154972    memcpy(&c.u,a,4);                                           \
154973    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
154974}
154975#else
154976#define RTREE_DECODE_COORD(eInt, a, r) {                        \
154977    RtreeCoord c;    /* Coordinate decoded */                   \
154978    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
154979           +((u32)a[2]<<8) + a[3];                              \
154980    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
154981}
154982#endif
154983
154984/*
154985** Check the RTree node or entry given by pCellData and p against the MATCH
154986** constraint pConstraint.
154987*/
154988static int rtreeCallbackConstraint(
154989  RtreeConstraint *pConstraint,  /* The constraint to test */
154990  int eInt,                      /* True if RTree holding integer coordinates */
154991  u8 *pCellData,                 /* Raw cell content */
154992  RtreeSearchPoint *pSearch,     /* Container of this cell */
154993  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
154994  int *peWithin                  /* OUT: visibility of the cell */
154995){
154996  int i;                                                /* Loop counter */
154997  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
154998  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
154999  int rc;                                             /* Callback return code */
155000  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
155001
155002  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
155003  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
155004
155005  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
155006    pInfo->iRowid = readInt64(pCellData);
155007  }
155008  pCellData += 8;
155009  for(i=0; i<nCoord; i++, pCellData += 4){
155010    RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
155011  }
155012  if( pConstraint->op==RTREE_MATCH ){
155013    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
155014                              nCoord, aCoord, &i);
155015    if( i==0 ) *peWithin = NOT_WITHIN;
155016    *prScore = RTREE_ZERO;
155017  }else{
155018    pInfo->aCoord = aCoord;
155019    pInfo->iLevel = pSearch->iLevel - 1;
155020    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
155021    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
155022    rc = pConstraint->u.xQueryFunc(pInfo);
155023    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
155024    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
155025      *prScore = pInfo->rScore;
155026    }
155027  }
155028  return rc;
155029}
155030
155031/*
155032** Check the internal RTree node given by pCellData against constraint p.
155033** If this constraint cannot be satisfied by any child within the node,
155034** set *peWithin to NOT_WITHIN.
155035*/
155036static void rtreeNonleafConstraint(
155037  RtreeConstraint *p,        /* The constraint to test */
155038  int eInt,                  /* True if RTree holds integer coordinates */
155039  u8 *pCellData,             /* Raw cell content as appears on disk */
155040  int *peWithin              /* Adjust downward, as appropriate */
155041){
155042  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
155043
155044  /* p->iCoord might point to either a lower or upper bound coordinate
155045  ** in a coordinate pair.  But make pCellData point to the lower bound.
155046  */
155047  pCellData += 8 + 4*(p->iCoord&0xfe);
155048
155049  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
155050      || p->op==RTREE_GT || p->op==RTREE_EQ );
155051  switch( p->op ){
155052    case RTREE_LE:
155053    case RTREE_LT:
155054    case RTREE_EQ:
155055      RTREE_DECODE_COORD(eInt, pCellData, val);
155056      /* val now holds the lower bound of the coordinate pair */
155057      if( p->u.rValue>=val ) return;
155058      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
155059      /* Fall through for the RTREE_EQ case */
155060
155061    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
155062      pCellData += 4;
155063      RTREE_DECODE_COORD(eInt, pCellData, val);
155064      /* val now holds the upper bound of the coordinate pair */
155065      if( p->u.rValue<=val ) return;
155066  }
155067  *peWithin = NOT_WITHIN;
155068}
155069
155070/*
155071** Check the leaf RTree cell given by pCellData against constraint p.
155072** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
155073** If the constraint is satisfied, leave *peWithin unchanged.
155074**
155075** The constraint is of the form:  xN op $val
155076**
155077** The op is given by p->op.  The xN is p->iCoord-th coordinate in
155078** pCellData.  $val is given by p->u.rValue.
155079*/
155080static void rtreeLeafConstraint(
155081  RtreeConstraint *p,        /* The constraint to test */
155082  int eInt,                  /* True if RTree holds integer coordinates */
155083  u8 *pCellData,             /* Raw cell content as appears on disk */
155084  int *peWithin              /* Adjust downward, as appropriate */
155085){
155086  RtreeDValue xN;      /* Coordinate value converted to a double */
155087
155088  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
155089      || p->op==RTREE_GT || p->op==RTREE_EQ );
155090  pCellData += 8 + p->iCoord*4;
155091  RTREE_DECODE_COORD(eInt, pCellData, xN);
155092  switch( p->op ){
155093    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
155094    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
155095    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
155096    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
155097    default:       if( xN == p->u.rValue ) return;  break;
155098  }
155099  *peWithin = NOT_WITHIN;
155100}
155101
155102/*
155103** One of the cells in node pNode is guaranteed to have a 64-bit
155104** integer value equal to iRowid. Return the index of this cell.
155105*/
155106static int nodeRowidIndex(
155107  Rtree *pRtree,
155108  RtreeNode *pNode,
155109  i64 iRowid,
155110  int *piIndex
155111){
155112  int ii;
155113  int nCell = NCELL(pNode);
155114  assert( nCell<200 );
155115  for(ii=0; ii<nCell; ii++){
155116    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
155117      *piIndex = ii;
155118      return SQLITE_OK;
155119    }
155120  }
155121  return SQLITE_CORRUPT_VTAB;
155122}
155123
155124/*
155125** Return the index of the cell containing a pointer to node pNode
155126** in its parent. If pNode is the root node, return -1.
155127*/
155128static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
155129  RtreeNode *pParent = pNode->pParent;
155130  if( pParent ){
155131    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
155132  }
155133  *piIndex = -1;
155134  return SQLITE_OK;
155135}
155136
155137/*
155138** Compare two search points.  Return negative, zero, or positive if the first
155139** is less than, equal to, or greater than the second.
155140**
155141** The rScore is the primary key.  Smaller rScore values come first.
155142** If the rScore is a tie, then use iLevel as the tie breaker with smaller
155143** iLevel values coming first.  In this way, if rScore is the same for all
155144** SearchPoints, then iLevel becomes the deciding factor and the result
155145** is a depth-first search, which is the desired default behavior.
155146*/
155147static int rtreeSearchPointCompare(
155148  const RtreeSearchPoint *pA,
155149  const RtreeSearchPoint *pB
155150){
155151  if( pA->rScore<pB->rScore ) return -1;
155152  if( pA->rScore>pB->rScore ) return +1;
155153  if( pA->iLevel<pB->iLevel ) return -1;
155154  if( pA->iLevel>pB->iLevel ) return +1;
155155  return 0;
155156}
155157
155158/*
155159** Interchange to search points in a cursor.
155160*/
155161static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
155162  RtreeSearchPoint t = p->aPoint[i];
155163  assert( i<j );
155164  p->aPoint[i] = p->aPoint[j];
155165  p->aPoint[j] = t;
155166  i++; j++;
155167  if( i<RTREE_CACHE_SZ ){
155168    if( j>=RTREE_CACHE_SZ ){
155169      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
155170      p->aNode[i] = 0;
155171    }else{
155172      RtreeNode *pTemp = p->aNode[i];
155173      p->aNode[i] = p->aNode[j];
155174      p->aNode[j] = pTemp;
155175    }
155176  }
155177}
155178
155179/*
155180** Return the search point with the lowest current score.
155181*/
155182static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
155183  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
155184}
155185
155186/*
155187** Get the RtreeNode for the search point with the lowest score.
155188*/
155189static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
155190  sqlite3_int64 id;
155191  int ii = 1 - pCur->bPoint;
155192  assert( ii==0 || ii==1 );
155193  assert( pCur->bPoint || pCur->nPoint );
155194  if( pCur->aNode[ii]==0 ){
155195    assert( pRC!=0 );
155196    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
155197    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
155198  }
155199  return pCur->aNode[ii];
155200}
155201
155202/*
155203** Push a new element onto the priority queue
155204*/
155205static RtreeSearchPoint *rtreeEnqueue(
155206  RtreeCursor *pCur,    /* The cursor */
155207  RtreeDValue rScore,   /* Score for the new search point */
155208  u8 iLevel             /* Level for the new search point */
155209){
155210  int i, j;
155211  RtreeSearchPoint *pNew;
155212  if( pCur->nPoint>=pCur->nPointAlloc ){
155213    int nNew = pCur->nPointAlloc*2 + 8;
155214    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
155215    if( pNew==0 ) return 0;
155216    pCur->aPoint = pNew;
155217    pCur->nPointAlloc = nNew;
155218  }
155219  i = pCur->nPoint++;
155220  pNew = pCur->aPoint + i;
155221  pNew->rScore = rScore;
155222  pNew->iLevel = iLevel;
155223  assert( iLevel<=RTREE_MAX_DEPTH );
155224  while( i>0 ){
155225    RtreeSearchPoint *pParent;
155226    j = (i-1)/2;
155227    pParent = pCur->aPoint + j;
155228    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
155229    rtreeSearchPointSwap(pCur, j, i);
155230    i = j;
155231    pNew = pParent;
155232  }
155233  return pNew;
155234}
155235
155236/*
155237** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
155238** NULL if malloc fails.
155239*/
155240static RtreeSearchPoint *rtreeSearchPointNew(
155241  RtreeCursor *pCur,    /* The cursor */
155242  RtreeDValue rScore,   /* Score for the new search point */
155243  u8 iLevel             /* Level for the new search point */
155244){
155245  RtreeSearchPoint *pNew, *pFirst;
155246  pFirst = rtreeSearchPointFirst(pCur);
155247  pCur->anQueue[iLevel]++;
155248  if( pFirst==0
155249   || pFirst->rScore>rScore
155250   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
155251  ){
155252    if( pCur->bPoint ){
155253      int ii;
155254      pNew = rtreeEnqueue(pCur, rScore, iLevel);
155255      if( pNew==0 ) return 0;
155256      ii = (int)(pNew - pCur->aPoint) + 1;
155257      if( ii<RTREE_CACHE_SZ ){
155258        assert( pCur->aNode[ii]==0 );
155259        pCur->aNode[ii] = pCur->aNode[0];
155260       }else{
155261        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
155262      }
155263      pCur->aNode[0] = 0;
155264      *pNew = pCur->sPoint;
155265    }
155266    pCur->sPoint.rScore = rScore;
155267    pCur->sPoint.iLevel = iLevel;
155268    pCur->bPoint = 1;
155269    return &pCur->sPoint;
155270  }else{
155271    return rtreeEnqueue(pCur, rScore, iLevel);
155272  }
155273}
155274
155275#if 0
155276/* Tracing routines for the RtreeSearchPoint queue */
155277static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
155278  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
155279  printf(" %d.%05lld.%02d %g %d",
155280    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
155281  );
155282  idx++;
155283  if( idx<RTREE_CACHE_SZ ){
155284    printf(" %p\n", pCur->aNode[idx]);
155285  }else{
155286    printf("\n");
155287  }
155288}
155289static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
155290  int ii;
155291  printf("=== %9s ", zPrefix);
155292  if( pCur->bPoint ){
155293    tracePoint(&pCur->sPoint, -1, pCur);
155294  }
155295  for(ii=0; ii<pCur->nPoint; ii++){
155296    if( ii>0 || pCur->bPoint ) printf("              ");
155297    tracePoint(&pCur->aPoint[ii], ii, pCur);
155298  }
155299}
155300# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
155301#else
155302# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
155303#endif
155304
155305/* Remove the search point with the lowest current score.
155306*/
155307static void rtreeSearchPointPop(RtreeCursor *p){
155308  int i, j, k, n;
155309  i = 1 - p->bPoint;
155310  assert( i==0 || i==1 );
155311  if( p->aNode[i] ){
155312    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
155313    p->aNode[i] = 0;
155314  }
155315  if( p->bPoint ){
155316    p->anQueue[p->sPoint.iLevel]--;
155317    p->bPoint = 0;
155318  }else if( p->nPoint ){
155319    p->anQueue[p->aPoint[0].iLevel]--;
155320    n = --p->nPoint;
155321    p->aPoint[0] = p->aPoint[n];
155322    if( n<RTREE_CACHE_SZ-1 ){
155323      p->aNode[1] = p->aNode[n+1];
155324      p->aNode[n+1] = 0;
155325    }
155326    i = 0;
155327    while( (j = i*2+1)<n ){
155328      k = j+1;
155329      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
155330        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
155331          rtreeSearchPointSwap(p, i, k);
155332          i = k;
155333        }else{
155334          break;
155335        }
155336      }else{
155337        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
155338          rtreeSearchPointSwap(p, i, j);
155339          i = j;
155340        }else{
155341          break;
155342        }
155343      }
155344    }
155345  }
155346}
155347
155348
155349/*
155350** Continue the search on cursor pCur until the front of the queue
155351** contains an entry suitable for returning as a result-set row,
155352** or until the RtreeSearchPoint queue is empty, indicating that the
155353** query has completed.
155354*/
155355static int rtreeStepToLeaf(RtreeCursor *pCur){
155356  RtreeSearchPoint *p;
155357  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
155358  RtreeNode *pNode;
155359  int eWithin;
155360  int rc = SQLITE_OK;
155361  int nCell;
155362  int nConstraint = pCur->nConstraint;
155363  int ii;
155364  int eInt;
155365  RtreeSearchPoint x;
155366
155367  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
155368  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
155369    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
155370    if( rc ) return rc;
155371    nCell = NCELL(pNode);
155372    assert( nCell<200 );
155373    while( p->iCell<nCell ){
155374      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
155375      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
155376      eWithin = FULLY_WITHIN;
155377      for(ii=0; ii<nConstraint; ii++){
155378        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
155379        if( pConstraint->op>=RTREE_MATCH ){
155380          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
155381                                       &rScore, &eWithin);
155382          if( rc ) return rc;
155383        }else if( p->iLevel==1 ){
155384          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
155385        }else{
155386          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
155387        }
155388        if( eWithin==NOT_WITHIN ) break;
155389      }
155390      p->iCell++;
155391      if( eWithin==NOT_WITHIN ) continue;
155392      x.iLevel = p->iLevel - 1;
155393      if( x.iLevel ){
155394        x.id = readInt64(pCellData);
155395        x.iCell = 0;
155396      }else{
155397        x.id = p->id;
155398        x.iCell = p->iCell - 1;
155399      }
155400      if( p->iCell>=nCell ){
155401        RTREE_QUEUE_TRACE(pCur, "POP-S:");
155402        rtreeSearchPointPop(pCur);
155403      }
155404      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
155405      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
155406      if( p==0 ) return SQLITE_NOMEM;
155407      p->eWithin = eWithin;
155408      p->id = x.id;
155409      p->iCell = x.iCell;
155410      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
155411      break;
155412    }
155413    if( p->iCell>=nCell ){
155414      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
155415      rtreeSearchPointPop(pCur);
155416    }
155417  }
155418  pCur->atEOF = p==0;
155419  return SQLITE_OK;
155420}
155421
155422/*
155423** Rtree virtual table module xNext method.
155424*/
155425static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
155426  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155427  int rc = SQLITE_OK;
155428
155429  /* Move to the next entry that matches the configured constraints. */
155430  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
155431  rtreeSearchPointPop(pCsr);
155432  rc = rtreeStepToLeaf(pCsr);
155433  return rc;
155434}
155435
155436/*
155437** Rtree virtual table module xRowid method.
155438*/
155439static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
155440  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155441  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
155442  int rc = SQLITE_OK;
155443  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
155444  if( rc==SQLITE_OK && p ){
155445    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
155446  }
155447  return rc;
155448}
155449
155450/*
155451** Rtree virtual table module xColumn method.
155452*/
155453static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
155454  Rtree *pRtree = (Rtree *)cur->pVtab;
155455  RtreeCursor *pCsr = (RtreeCursor *)cur;
155456  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
155457  RtreeCoord c;
155458  int rc = SQLITE_OK;
155459  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
155460
155461  if( rc ) return rc;
155462  if( p==0 ) return SQLITE_OK;
155463  if( i==0 ){
155464    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
155465  }else{
155466    if( rc ) return rc;
155467    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
155468#ifndef SQLITE_RTREE_INT_ONLY
155469    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
155470      sqlite3_result_double(ctx, c.f);
155471    }else
155472#endif
155473    {
155474      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
155475      sqlite3_result_int(ctx, c.i);
155476    }
155477  }
155478  return SQLITE_OK;
155479}
155480
155481/*
155482** Use nodeAcquire() to obtain the leaf node containing the record with
155483** rowid iRowid. If successful, set *ppLeaf to point to the node and
155484** return SQLITE_OK. If there is no such record in the table, set
155485** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
155486** to zero and return an SQLite error code.
155487*/
155488static int findLeafNode(
155489  Rtree *pRtree,              /* RTree to search */
155490  i64 iRowid,                 /* The rowid searching for */
155491  RtreeNode **ppLeaf,         /* Write the node here */
155492  sqlite3_int64 *piNode       /* Write the node-id here */
155493){
155494  int rc;
155495  *ppLeaf = 0;
155496  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
155497  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
155498    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
155499    if( piNode ) *piNode = iNode;
155500    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
155501    sqlite3_reset(pRtree->pReadRowid);
155502  }else{
155503    rc = sqlite3_reset(pRtree->pReadRowid);
155504  }
155505  return rc;
155506}
155507
155508/*
155509** This function is called to configure the RtreeConstraint object passed
155510** as the second argument for a MATCH constraint. The value passed as the
155511** first argument to this function is the right-hand operand to the MATCH
155512** operator.
155513*/
155514static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
155515  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
155516  sqlite3_rtree_query_info *pInfo;   /* Callback information */
155517  int nBlob;                         /* Size of the geometry function blob */
155518  int nExpected;                     /* Expected size of the BLOB */
155519
155520  /* Check that value is actually a blob. */
155521  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
155522
155523  /* Check that the blob is roughly the right size. */
155524  nBlob = sqlite3_value_bytes(pValue);
155525  if( nBlob<(int)sizeof(RtreeMatchArg) ){
155526    return SQLITE_ERROR;
155527  }
155528
155529  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
155530  if( !pInfo ) return SQLITE_NOMEM;
155531  memset(pInfo, 0, sizeof(*pInfo));
155532  pBlob = (RtreeMatchArg*)&pInfo[1];
155533
155534  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
155535  nExpected = (int)(sizeof(RtreeMatchArg) +
155536                    pBlob->nParam*sizeof(sqlite3_value*) +
155537                    (pBlob->nParam-1)*sizeof(RtreeDValue));
155538  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
155539    sqlite3_free(pInfo);
155540    return SQLITE_ERROR;
155541  }
155542  pInfo->pContext = pBlob->cb.pContext;
155543  pInfo->nParam = pBlob->nParam;
155544  pInfo->aParam = pBlob->aParam;
155545  pInfo->apSqlParam = pBlob->apSqlParam;
155546
155547  if( pBlob->cb.xGeom ){
155548    pCons->u.xGeom = pBlob->cb.xGeom;
155549  }else{
155550    pCons->op = RTREE_QUERY;
155551    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
155552  }
155553  pCons->pInfo = pInfo;
155554  return SQLITE_OK;
155555}
155556
155557/*
155558** Rtree virtual table module xFilter method.
155559*/
155560static int rtreeFilter(
155561  sqlite3_vtab_cursor *pVtabCursor,
155562  int idxNum, const char *idxStr,
155563  int argc, sqlite3_value **argv
155564){
155565  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
155566  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155567  RtreeNode *pRoot = 0;
155568  int ii;
155569  int rc = SQLITE_OK;
155570  int iCell = 0;
155571
155572  rtreeReference(pRtree);
155573
155574  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
155575  freeCursorConstraints(pCsr);
155576  sqlite3_free(pCsr->aPoint);
155577  memset(pCsr, 0, sizeof(RtreeCursor));
155578  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
155579
155580  pCsr->iStrategy = idxNum;
155581  if( idxNum==1 ){
155582    /* Special case - lookup by rowid. */
155583    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
155584    RtreeSearchPoint *p;     /* Search point for the the leaf */
155585    i64 iRowid = sqlite3_value_int64(argv[0]);
155586    i64 iNode = 0;
155587    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
155588    if( rc==SQLITE_OK && pLeaf!=0 ){
155589      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
155590      assert( p!=0 );  /* Always returns pCsr->sPoint */
155591      pCsr->aNode[0] = pLeaf;
155592      p->id = iNode;
155593      p->eWithin = PARTLY_WITHIN;
155594      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
155595      p->iCell = iCell;
155596      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
155597    }else{
155598      pCsr->atEOF = 1;
155599    }
155600  }else{
155601    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
155602    ** with the configured constraints.
155603    */
155604    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
155605    if( rc==SQLITE_OK && argc>0 ){
155606      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
155607      pCsr->nConstraint = argc;
155608      if( !pCsr->aConstraint ){
155609        rc = SQLITE_NOMEM;
155610      }else{
155611        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
155612        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
155613        assert( (idxStr==0 && argc==0)
155614                || (idxStr && (int)strlen(idxStr)==argc*2) );
155615        for(ii=0; ii<argc; ii++){
155616          RtreeConstraint *p = &pCsr->aConstraint[ii];
155617          p->op = idxStr[ii*2];
155618          p->iCoord = idxStr[ii*2+1]-'0';
155619          if( p->op>=RTREE_MATCH ){
155620            /* A MATCH operator. The right-hand-side must be a blob that
155621            ** can be cast into an RtreeMatchArg object. One created using
155622            ** an sqlite3_rtree_geometry_callback() SQL user function.
155623            */
155624            rc = deserializeGeometry(argv[ii], p);
155625            if( rc!=SQLITE_OK ){
155626              break;
155627            }
155628            p->pInfo->nCoord = pRtree->nDim*2;
155629            p->pInfo->anQueue = pCsr->anQueue;
155630            p->pInfo->mxLevel = pRtree->iDepth + 1;
155631          }else{
155632#ifdef SQLITE_RTREE_INT_ONLY
155633            p->u.rValue = sqlite3_value_int64(argv[ii]);
155634#else
155635            p->u.rValue = sqlite3_value_double(argv[ii]);
155636#endif
155637          }
155638        }
155639      }
155640    }
155641    if( rc==SQLITE_OK ){
155642      RtreeSearchPoint *pNew;
155643      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
155644      if( pNew==0 ) return SQLITE_NOMEM;
155645      pNew->id = 1;
155646      pNew->iCell = 0;
155647      pNew->eWithin = PARTLY_WITHIN;
155648      assert( pCsr->bPoint==1 );
155649      pCsr->aNode[0] = pRoot;
155650      pRoot = 0;
155651      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
155652      rc = rtreeStepToLeaf(pCsr);
155653    }
155654  }
155655
155656  nodeRelease(pRtree, pRoot);
155657  rtreeRelease(pRtree);
155658  return rc;
155659}
155660
155661/*
155662** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
155663** extension is currently being used by a version of SQLite too old to
155664** support estimatedRows. In that case this function is a no-op.
155665*/
155666static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
155667#if SQLITE_VERSION_NUMBER>=3008002
155668  if( sqlite3_libversion_number()>=3008002 ){
155669    pIdxInfo->estimatedRows = nRow;
155670  }
155671#endif
155672}
155673
155674/*
155675** Rtree virtual table module xBestIndex method. There are three
155676** table scan strategies to choose from (in order from most to
155677** least desirable):
155678**
155679**   idxNum     idxStr        Strategy
155680**   ------------------------------------------------
155681**     1        Unused        Direct lookup by rowid.
155682**     2        See below     R-tree query or full-table scan.
155683**   ------------------------------------------------
155684**
155685** If strategy 1 is used, then idxStr is not meaningful. If strategy
155686** 2 is used, idxStr is formatted to contain 2 bytes for each
155687** constraint used. The first two bytes of idxStr correspond to
155688** the constraint in sqlite3_index_info.aConstraintUsage[] with
155689** (argvIndex==1) etc.
155690**
155691** The first of each pair of bytes in idxStr identifies the constraint
155692** operator as follows:
155693**
155694**   Operator    Byte Value
155695**   ----------------------
155696**      =        0x41 ('A')
155697**     <=        0x42 ('B')
155698**      <        0x43 ('C')
155699**     >=        0x44 ('D')
155700**      >        0x45 ('E')
155701**   MATCH       0x46 ('F')
155702**   ----------------------
155703**
155704** The second of each pair of bytes identifies the coordinate column
155705** to which the constraint applies. The leftmost coordinate column
155706** is 'a', the second from the left 'b' etc.
155707*/
155708static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
155709  Rtree *pRtree = (Rtree*)tab;
155710  int rc = SQLITE_OK;
155711  int ii;
155712  int bMatch = 0;                 /* True if there exists a MATCH constraint */
155713  i64 nRow;                       /* Estimated rows returned by this scan */
155714
155715  int iIdx = 0;
155716  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
155717  memset(zIdxStr, 0, sizeof(zIdxStr));
155718
155719  /* Check if there exists a MATCH constraint - even an unusable one. If there
155720  ** is, do not consider the lookup-by-rowid plan as using such a plan would
155721  ** require the VDBE to evaluate the MATCH constraint, which is not currently
155722  ** possible. */
155723  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
155724    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
155725      bMatch = 1;
155726    }
155727  }
155728
155729  assert( pIdxInfo->idxStr==0 );
155730  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
155731    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
155732
155733    if( bMatch==0 && p->usable
155734     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
155735    ){
155736      /* We have an equality constraint on the rowid. Use strategy 1. */
155737      int jj;
155738      for(jj=0; jj<ii; jj++){
155739        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
155740        pIdxInfo->aConstraintUsage[jj].omit = 0;
155741      }
155742      pIdxInfo->idxNum = 1;
155743      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
155744      pIdxInfo->aConstraintUsage[jj].omit = 1;
155745
155746      /* This strategy involves a two rowid lookups on an B-Tree structures
155747      ** and then a linear search of an R-Tree node. This should be
155748      ** considered almost as quick as a direct rowid lookup (for which
155749      ** sqlite uses an internal cost of 0.0). It is expected to return
155750      ** a single row.
155751      */
155752      pIdxInfo->estimatedCost = 30.0;
155753      setEstimatedRows(pIdxInfo, 1);
155754      return SQLITE_OK;
155755    }
155756
155757    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
155758      u8 op;
155759      switch( p->op ){
155760        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
155761        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
155762        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
155763        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
155764        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
155765        default:
155766          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
155767          op = RTREE_MATCH;
155768          break;
155769      }
155770      zIdxStr[iIdx++] = op;
155771      zIdxStr[iIdx++] = p->iColumn - 1 + '0';
155772      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
155773      pIdxInfo->aConstraintUsage[ii].omit = 1;
155774    }
155775  }
155776
155777  pIdxInfo->idxNum = 2;
155778  pIdxInfo->needToFreeIdxStr = 1;
155779  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
155780    return SQLITE_NOMEM;
155781  }
155782
155783  nRow = pRtree->nRowEst / (iIdx + 1);
155784  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
155785  setEstimatedRows(pIdxInfo, nRow);
155786
155787  return rc;
155788}
155789
155790/*
155791** Return the N-dimensional volumn of the cell stored in *p.
155792*/
155793static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
155794  RtreeDValue area = (RtreeDValue)1;
155795  int ii;
155796  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155797    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
155798  }
155799  return area;
155800}
155801
155802/*
155803** Return the margin length of cell p. The margin length is the sum
155804** of the objects size in each dimension.
155805*/
155806static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
155807  RtreeDValue margin = (RtreeDValue)0;
155808  int ii;
155809  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155810    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
155811  }
155812  return margin;
155813}
155814
155815/*
155816** Store the union of cells p1 and p2 in p1.
155817*/
155818static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
155819  int ii;
155820  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
155821    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155822      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
155823      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
155824    }
155825  }else{
155826    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155827      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
155828      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
155829    }
155830  }
155831}
155832
155833/*
155834** Return true if the area covered by p2 is a subset of the area covered
155835** by p1. False otherwise.
155836*/
155837static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
155838  int ii;
155839  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
155840  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155841    RtreeCoord *a1 = &p1->aCoord[ii];
155842    RtreeCoord *a2 = &p2->aCoord[ii];
155843    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
155844     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
155845    ){
155846      return 0;
155847    }
155848  }
155849  return 1;
155850}
155851
155852/*
155853** Return the amount cell p would grow by if it were unioned with pCell.
155854*/
155855static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
155856  RtreeDValue area;
155857  RtreeCell cell;
155858  memcpy(&cell, p, sizeof(RtreeCell));
155859  area = cellArea(pRtree, &cell);
155860  cellUnion(pRtree, &cell, pCell);
155861  return (cellArea(pRtree, &cell)-area);
155862}
155863
155864static RtreeDValue cellOverlap(
155865  Rtree *pRtree,
155866  RtreeCell *p,
155867  RtreeCell *aCell,
155868  int nCell
155869){
155870  int ii;
155871  RtreeDValue overlap = RTREE_ZERO;
155872  for(ii=0; ii<nCell; ii++){
155873    int jj;
155874    RtreeDValue o = (RtreeDValue)1;
155875    for(jj=0; jj<(pRtree->nDim*2); jj+=2){
155876      RtreeDValue x1, x2;
155877      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
155878      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
155879      if( x2<x1 ){
155880        o = (RtreeDValue)0;
155881        break;
155882      }else{
155883        o = o * (x2-x1);
155884      }
155885    }
155886    overlap += o;
155887  }
155888  return overlap;
155889}
155890
155891
155892/*
155893** This function implements the ChooseLeaf algorithm from Gutman[84].
155894** ChooseSubTree in r*tree terminology.
155895*/
155896static int ChooseLeaf(
155897  Rtree *pRtree,               /* Rtree table */
155898  RtreeCell *pCell,            /* Cell to insert into rtree */
155899  int iHeight,                 /* Height of sub-tree rooted at pCell */
155900  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
155901){
155902  int rc;
155903  int ii;
155904  RtreeNode *pNode;
155905  rc = nodeAcquire(pRtree, 1, 0, &pNode);
155906
155907  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
155908    int iCell;
155909    sqlite3_int64 iBest = 0;
155910
155911    RtreeDValue fMinGrowth = RTREE_ZERO;
155912    RtreeDValue fMinArea = RTREE_ZERO;
155913
155914    int nCell = NCELL(pNode);
155915    RtreeCell cell;
155916    RtreeNode *pChild;
155917
155918    RtreeCell *aCell = 0;
155919
155920    /* Select the child node which will be enlarged the least if pCell
155921    ** is inserted into it. Resolve ties by choosing the entry with
155922    ** the smallest area.
155923    */
155924    for(iCell=0; iCell<nCell; iCell++){
155925      int bBest = 0;
155926      RtreeDValue growth;
155927      RtreeDValue area;
155928      nodeGetCell(pRtree, pNode, iCell, &cell);
155929      growth = cellGrowth(pRtree, &cell, pCell);
155930      area = cellArea(pRtree, &cell);
155931      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
155932        bBest = 1;
155933      }
155934      if( bBest ){
155935        fMinGrowth = growth;
155936        fMinArea = area;
155937        iBest = cell.iRowid;
155938      }
155939    }
155940
155941    sqlite3_free(aCell);
155942    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
155943    nodeRelease(pRtree, pNode);
155944    pNode = pChild;
155945  }
155946
155947  *ppLeaf = pNode;
155948  return rc;
155949}
155950
155951/*
155952** A cell with the same content as pCell has just been inserted into
155953** the node pNode. This function updates the bounding box cells in
155954** all ancestor elements.
155955*/
155956static int AdjustTree(
155957  Rtree *pRtree,                    /* Rtree table */
155958  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
155959  RtreeCell *pCell                  /* This cell was just inserted */
155960){
155961  RtreeNode *p = pNode;
155962  while( p->pParent ){
155963    RtreeNode *pParent = p->pParent;
155964    RtreeCell cell;
155965    int iCell;
155966
155967    if( nodeParentIndex(pRtree, p, &iCell) ){
155968      return SQLITE_CORRUPT_VTAB;
155969    }
155970
155971    nodeGetCell(pRtree, pParent, iCell, &cell);
155972    if( !cellContains(pRtree, &cell, pCell) ){
155973      cellUnion(pRtree, &cell, pCell);
155974      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
155975    }
155976
155977    p = pParent;
155978  }
155979  return SQLITE_OK;
155980}
155981
155982/*
155983** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
155984*/
155985static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
155986  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
155987  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
155988  sqlite3_step(pRtree->pWriteRowid);
155989  return sqlite3_reset(pRtree->pWriteRowid);
155990}
155991
155992/*
155993** Write mapping (iNode->iPar) to the <rtree>_parent table.
155994*/
155995static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
155996  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
155997  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
155998  sqlite3_step(pRtree->pWriteParent);
155999  return sqlite3_reset(pRtree->pWriteParent);
156000}
156001
156002static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
156003
156004
156005/*
156006** Arguments aIdx, aDistance and aSpare all point to arrays of size
156007** nIdx. The aIdx array contains the set of integers from 0 to
156008** (nIdx-1) in no particular order. This function sorts the values
156009** in aIdx according to the indexed values in aDistance. For
156010** example, assuming the inputs:
156011**
156012**   aIdx      = { 0,   1,   2,   3 }
156013**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
156014**
156015** this function sets the aIdx array to contain:
156016**
156017**   aIdx      = { 0,   1,   2,   3 }
156018**
156019** The aSpare array is used as temporary working space by the
156020** sorting algorithm.
156021*/
156022static void SortByDistance(
156023  int *aIdx,
156024  int nIdx,
156025  RtreeDValue *aDistance,
156026  int *aSpare
156027){
156028  if( nIdx>1 ){
156029    int iLeft = 0;
156030    int iRight = 0;
156031
156032    int nLeft = nIdx/2;
156033    int nRight = nIdx-nLeft;
156034    int *aLeft = aIdx;
156035    int *aRight = &aIdx[nLeft];
156036
156037    SortByDistance(aLeft, nLeft, aDistance, aSpare);
156038    SortByDistance(aRight, nRight, aDistance, aSpare);
156039
156040    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
156041    aLeft = aSpare;
156042
156043    while( iLeft<nLeft || iRight<nRight ){
156044      if( iLeft==nLeft ){
156045        aIdx[iLeft+iRight] = aRight[iRight];
156046        iRight++;
156047      }else if( iRight==nRight ){
156048        aIdx[iLeft+iRight] = aLeft[iLeft];
156049        iLeft++;
156050      }else{
156051        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
156052        RtreeDValue fRight = aDistance[aRight[iRight]];
156053        if( fLeft<fRight ){
156054          aIdx[iLeft+iRight] = aLeft[iLeft];
156055          iLeft++;
156056        }else{
156057          aIdx[iLeft+iRight] = aRight[iRight];
156058          iRight++;
156059        }
156060      }
156061    }
156062
156063#if 0
156064    /* Check that the sort worked */
156065    {
156066      int jj;
156067      for(jj=1; jj<nIdx; jj++){
156068        RtreeDValue left = aDistance[aIdx[jj-1]];
156069        RtreeDValue right = aDistance[aIdx[jj]];
156070        assert( left<=right );
156071      }
156072    }
156073#endif
156074  }
156075}
156076
156077/*
156078** Arguments aIdx, aCell and aSpare all point to arrays of size
156079** nIdx. The aIdx array contains the set of integers from 0 to
156080** (nIdx-1) in no particular order. This function sorts the values
156081** in aIdx according to dimension iDim of the cells in aCell. The
156082** minimum value of dimension iDim is considered first, the
156083** maximum used to break ties.
156084**
156085** The aSpare array is used as temporary working space by the
156086** sorting algorithm.
156087*/
156088static void SortByDimension(
156089  Rtree *pRtree,
156090  int *aIdx,
156091  int nIdx,
156092  int iDim,
156093  RtreeCell *aCell,
156094  int *aSpare
156095){
156096  if( nIdx>1 ){
156097
156098    int iLeft = 0;
156099    int iRight = 0;
156100
156101    int nLeft = nIdx/2;
156102    int nRight = nIdx-nLeft;
156103    int *aLeft = aIdx;
156104    int *aRight = &aIdx[nLeft];
156105
156106    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
156107    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
156108
156109    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
156110    aLeft = aSpare;
156111    while( iLeft<nLeft || iRight<nRight ){
156112      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
156113      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
156114      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
156115      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
156116      if( (iLeft!=nLeft) && ((iRight==nRight)
156117       || (xleft1<xright1)
156118       || (xleft1==xright1 && xleft2<xright2)
156119      )){
156120        aIdx[iLeft+iRight] = aLeft[iLeft];
156121        iLeft++;
156122      }else{
156123        aIdx[iLeft+iRight] = aRight[iRight];
156124        iRight++;
156125      }
156126    }
156127
156128#if 0
156129    /* Check that the sort worked */
156130    {
156131      int jj;
156132      for(jj=1; jj<nIdx; jj++){
156133        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
156134        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
156135        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
156136        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
156137        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
156138      }
156139    }
156140#endif
156141  }
156142}
156143
156144/*
156145** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
156146*/
156147static int splitNodeStartree(
156148  Rtree *pRtree,
156149  RtreeCell *aCell,
156150  int nCell,
156151  RtreeNode *pLeft,
156152  RtreeNode *pRight,
156153  RtreeCell *pBboxLeft,
156154  RtreeCell *pBboxRight
156155){
156156  int **aaSorted;
156157  int *aSpare;
156158  int ii;
156159
156160  int iBestDim = 0;
156161  int iBestSplit = 0;
156162  RtreeDValue fBestMargin = RTREE_ZERO;
156163
156164  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
156165
156166  aaSorted = (int **)sqlite3_malloc(nByte);
156167  if( !aaSorted ){
156168    return SQLITE_NOMEM;
156169  }
156170
156171  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
156172  memset(aaSorted, 0, nByte);
156173  for(ii=0; ii<pRtree->nDim; ii++){
156174    int jj;
156175    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
156176    for(jj=0; jj<nCell; jj++){
156177      aaSorted[ii][jj] = jj;
156178    }
156179    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
156180  }
156181
156182  for(ii=0; ii<pRtree->nDim; ii++){
156183    RtreeDValue margin = RTREE_ZERO;
156184    RtreeDValue fBestOverlap = RTREE_ZERO;
156185    RtreeDValue fBestArea = RTREE_ZERO;
156186    int iBestLeft = 0;
156187    int nLeft;
156188
156189    for(
156190      nLeft=RTREE_MINCELLS(pRtree);
156191      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
156192      nLeft++
156193    ){
156194      RtreeCell left;
156195      RtreeCell right;
156196      int kk;
156197      RtreeDValue overlap;
156198      RtreeDValue area;
156199
156200      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
156201      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
156202      for(kk=1; kk<(nCell-1); kk++){
156203        if( kk<nLeft ){
156204          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
156205        }else{
156206          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
156207        }
156208      }
156209      margin += cellMargin(pRtree, &left);
156210      margin += cellMargin(pRtree, &right);
156211      overlap = cellOverlap(pRtree, &left, &right, 1);
156212      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
156213      if( (nLeft==RTREE_MINCELLS(pRtree))
156214       || (overlap<fBestOverlap)
156215       || (overlap==fBestOverlap && area<fBestArea)
156216      ){
156217        iBestLeft = nLeft;
156218        fBestOverlap = overlap;
156219        fBestArea = area;
156220      }
156221    }
156222
156223    if( ii==0 || margin<fBestMargin ){
156224      iBestDim = ii;
156225      fBestMargin = margin;
156226      iBestSplit = iBestLeft;
156227    }
156228  }
156229
156230  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
156231  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
156232  for(ii=0; ii<nCell; ii++){
156233    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
156234    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
156235    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
156236    nodeInsertCell(pRtree, pTarget, pCell);
156237    cellUnion(pRtree, pBbox, pCell);
156238  }
156239
156240  sqlite3_free(aaSorted);
156241  return SQLITE_OK;
156242}
156243
156244
156245static int updateMapping(
156246  Rtree *pRtree,
156247  i64 iRowid,
156248  RtreeNode *pNode,
156249  int iHeight
156250){
156251  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
156252  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
156253  if( iHeight>0 ){
156254    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
156255    if( pChild ){
156256      nodeRelease(pRtree, pChild->pParent);
156257      nodeReference(pNode);
156258      pChild->pParent = pNode;
156259    }
156260  }
156261  return xSetMapping(pRtree, iRowid, pNode->iNode);
156262}
156263
156264static int SplitNode(
156265  Rtree *pRtree,
156266  RtreeNode *pNode,
156267  RtreeCell *pCell,
156268  int iHeight
156269){
156270  int i;
156271  int newCellIsRight = 0;
156272
156273  int rc = SQLITE_OK;
156274  int nCell = NCELL(pNode);
156275  RtreeCell *aCell;
156276  int *aiUsed;
156277
156278  RtreeNode *pLeft = 0;
156279  RtreeNode *pRight = 0;
156280
156281  RtreeCell leftbbox;
156282  RtreeCell rightbbox;
156283
156284  /* Allocate an array and populate it with a copy of pCell and
156285  ** all cells from node pLeft. Then zero the original node.
156286  */
156287  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
156288  if( !aCell ){
156289    rc = SQLITE_NOMEM;
156290    goto splitnode_out;
156291  }
156292  aiUsed = (int *)&aCell[nCell+1];
156293  memset(aiUsed, 0, sizeof(int)*(nCell+1));
156294  for(i=0; i<nCell; i++){
156295    nodeGetCell(pRtree, pNode, i, &aCell[i]);
156296  }
156297  nodeZero(pRtree, pNode);
156298  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
156299  nCell++;
156300
156301  if( pNode->iNode==1 ){
156302    pRight = nodeNew(pRtree, pNode);
156303    pLeft = nodeNew(pRtree, pNode);
156304    pRtree->iDepth++;
156305    pNode->isDirty = 1;
156306    writeInt16(pNode->zData, pRtree->iDepth);
156307  }else{
156308    pLeft = pNode;
156309    pRight = nodeNew(pRtree, pLeft->pParent);
156310    nodeReference(pLeft);
156311  }
156312
156313  if( !pLeft || !pRight ){
156314    rc = SQLITE_NOMEM;
156315    goto splitnode_out;
156316  }
156317
156318  memset(pLeft->zData, 0, pRtree->iNodeSize);
156319  memset(pRight->zData, 0, pRtree->iNodeSize);
156320
156321  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
156322                         &leftbbox, &rightbbox);
156323  if( rc!=SQLITE_OK ){
156324    goto splitnode_out;
156325  }
156326
156327  /* Ensure both child nodes have node numbers assigned to them by calling
156328  ** nodeWrite(). Node pRight always needs a node number, as it was created
156329  ** by nodeNew() above. But node pLeft sometimes already has a node number.
156330  ** In this case avoid the all to nodeWrite().
156331  */
156332  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
156333   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
156334  ){
156335    goto splitnode_out;
156336  }
156337
156338  rightbbox.iRowid = pRight->iNode;
156339  leftbbox.iRowid = pLeft->iNode;
156340
156341  if( pNode->iNode==1 ){
156342    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
156343    if( rc!=SQLITE_OK ){
156344      goto splitnode_out;
156345    }
156346  }else{
156347    RtreeNode *pParent = pLeft->pParent;
156348    int iCell;
156349    rc = nodeParentIndex(pRtree, pLeft, &iCell);
156350    if( rc==SQLITE_OK ){
156351      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
156352      rc = AdjustTree(pRtree, pParent, &leftbbox);
156353    }
156354    if( rc!=SQLITE_OK ){
156355      goto splitnode_out;
156356    }
156357  }
156358  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
156359    goto splitnode_out;
156360  }
156361
156362  for(i=0; i<NCELL(pRight); i++){
156363    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
156364    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
156365    if( iRowid==pCell->iRowid ){
156366      newCellIsRight = 1;
156367    }
156368    if( rc!=SQLITE_OK ){
156369      goto splitnode_out;
156370    }
156371  }
156372  if( pNode->iNode==1 ){
156373    for(i=0; i<NCELL(pLeft); i++){
156374      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
156375      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
156376      if( rc!=SQLITE_OK ){
156377        goto splitnode_out;
156378      }
156379    }
156380  }else if( newCellIsRight==0 ){
156381    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
156382  }
156383
156384  if( rc==SQLITE_OK ){
156385    rc = nodeRelease(pRtree, pRight);
156386    pRight = 0;
156387  }
156388  if( rc==SQLITE_OK ){
156389    rc = nodeRelease(pRtree, pLeft);
156390    pLeft = 0;
156391  }
156392
156393splitnode_out:
156394  nodeRelease(pRtree, pRight);
156395  nodeRelease(pRtree, pLeft);
156396  sqlite3_free(aCell);
156397  return rc;
156398}
156399
156400/*
156401** If node pLeaf is not the root of the r-tree and its pParent pointer is
156402** still NULL, load all ancestor nodes of pLeaf into memory and populate
156403** the pLeaf->pParent chain all the way up to the root node.
156404**
156405** This operation is required when a row is deleted (or updated - an update
156406** is implemented as a delete followed by an insert). SQLite provides the
156407** rowid of the row to delete, which can be used to find the leaf on which
156408** the entry resides (argument pLeaf). Once the leaf is located, this
156409** function is called to determine its ancestry.
156410*/
156411static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
156412  int rc = SQLITE_OK;
156413  RtreeNode *pChild = pLeaf;
156414  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
156415    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
156416    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
156417    rc = sqlite3_step(pRtree->pReadParent);
156418    if( rc==SQLITE_ROW ){
156419      RtreeNode *pTest;           /* Used to test for reference loops */
156420      i64 iNode;                  /* Node number of parent node */
156421
156422      /* Before setting pChild->pParent, test that we are not creating a
156423      ** loop of references (as we would if, say, pChild==pParent). We don't
156424      ** want to do this as it leads to a memory leak when trying to delete
156425      ** the referenced counted node structures.
156426      */
156427      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
156428      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
156429      if( !pTest ){
156430        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
156431      }
156432    }
156433    rc = sqlite3_reset(pRtree->pReadParent);
156434    if( rc==SQLITE_OK ) rc = rc2;
156435    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
156436    pChild = pChild->pParent;
156437  }
156438  return rc;
156439}
156440
156441static int deleteCell(Rtree *, RtreeNode *, int, int);
156442
156443static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
156444  int rc;
156445  int rc2;
156446  RtreeNode *pParent = 0;
156447  int iCell;
156448
156449  assert( pNode->nRef==1 );
156450
156451  /* Remove the entry in the parent cell. */
156452  rc = nodeParentIndex(pRtree, pNode, &iCell);
156453  if( rc==SQLITE_OK ){
156454    pParent = pNode->pParent;
156455    pNode->pParent = 0;
156456    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
156457  }
156458  rc2 = nodeRelease(pRtree, pParent);
156459  if( rc==SQLITE_OK ){
156460    rc = rc2;
156461  }
156462  if( rc!=SQLITE_OK ){
156463    return rc;
156464  }
156465
156466  /* Remove the xxx_node entry. */
156467  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
156468  sqlite3_step(pRtree->pDeleteNode);
156469  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
156470    return rc;
156471  }
156472
156473  /* Remove the xxx_parent entry. */
156474  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
156475  sqlite3_step(pRtree->pDeleteParent);
156476  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
156477    return rc;
156478  }
156479
156480  /* Remove the node from the in-memory hash table and link it into
156481  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
156482  */
156483  nodeHashDelete(pRtree, pNode);
156484  pNode->iNode = iHeight;
156485  pNode->pNext = pRtree->pDeleted;
156486  pNode->nRef++;
156487  pRtree->pDeleted = pNode;
156488
156489  return SQLITE_OK;
156490}
156491
156492static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
156493  RtreeNode *pParent = pNode->pParent;
156494  int rc = SQLITE_OK;
156495  if( pParent ){
156496    int ii;
156497    int nCell = NCELL(pNode);
156498    RtreeCell box;                            /* Bounding box for pNode */
156499    nodeGetCell(pRtree, pNode, 0, &box);
156500    for(ii=1; ii<nCell; ii++){
156501      RtreeCell cell;
156502      nodeGetCell(pRtree, pNode, ii, &cell);
156503      cellUnion(pRtree, &box, &cell);
156504    }
156505    box.iRowid = pNode->iNode;
156506    rc = nodeParentIndex(pRtree, pNode, &ii);
156507    if( rc==SQLITE_OK ){
156508      nodeOverwriteCell(pRtree, pParent, &box, ii);
156509      rc = fixBoundingBox(pRtree, pParent);
156510    }
156511  }
156512  return rc;
156513}
156514
156515/*
156516** Delete the cell at index iCell of node pNode. After removing the
156517** cell, adjust the r-tree data structure if required.
156518*/
156519static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
156520  RtreeNode *pParent;
156521  int rc;
156522
156523  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
156524    return rc;
156525  }
156526
156527  /* Remove the cell from the node. This call just moves bytes around
156528  ** the in-memory node image, so it cannot fail.
156529  */
156530  nodeDeleteCell(pRtree, pNode, iCell);
156531
156532  /* If the node is not the tree root and now has less than the minimum
156533  ** number of cells, remove it from the tree. Otherwise, update the
156534  ** cell in the parent node so that it tightly contains the updated
156535  ** node.
156536  */
156537  pParent = pNode->pParent;
156538  assert( pParent || pNode->iNode==1 );
156539  if( pParent ){
156540    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
156541      rc = removeNode(pRtree, pNode, iHeight);
156542    }else{
156543      rc = fixBoundingBox(pRtree, pNode);
156544    }
156545  }
156546
156547  return rc;
156548}
156549
156550static int Reinsert(
156551  Rtree *pRtree,
156552  RtreeNode *pNode,
156553  RtreeCell *pCell,
156554  int iHeight
156555){
156556  int *aOrder;
156557  int *aSpare;
156558  RtreeCell *aCell;
156559  RtreeDValue *aDistance;
156560  int nCell;
156561  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
156562  int iDim;
156563  int ii;
156564  int rc = SQLITE_OK;
156565  int n;
156566
156567  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
156568
156569  nCell = NCELL(pNode)+1;
156570  n = (nCell+1)&(~1);
156571
156572  /* Allocate the buffers used by this operation. The allocation is
156573  ** relinquished before this function returns.
156574  */
156575  aCell = (RtreeCell *)sqlite3_malloc(n * (
156576    sizeof(RtreeCell)     +         /* aCell array */
156577    sizeof(int)           +         /* aOrder array */
156578    sizeof(int)           +         /* aSpare array */
156579    sizeof(RtreeDValue)             /* aDistance array */
156580  ));
156581  if( !aCell ){
156582    return SQLITE_NOMEM;
156583  }
156584  aOrder    = (int *)&aCell[n];
156585  aSpare    = (int *)&aOrder[n];
156586  aDistance = (RtreeDValue *)&aSpare[n];
156587
156588  for(ii=0; ii<nCell; ii++){
156589    if( ii==(nCell-1) ){
156590      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
156591    }else{
156592      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
156593    }
156594    aOrder[ii] = ii;
156595    for(iDim=0; iDim<pRtree->nDim; iDim++){
156596      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
156597      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
156598    }
156599  }
156600  for(iDim=0; iDim<pRtree->nDim; iDim++){
156601    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
156602  }
156603
156604  for(ii=0; ii<nCell; ii++){
156605    aDistance[ii] = RTREE_ZERO;
156606    for(iDim=0; iDim<pRtree->nDim; iDim++){
156607      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
156608                               DCOORD(aCell[ii].aCoord[iDim*2]));
156609      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
156610    }
156611  }
156612
156613  SortByDistance(aOrder, nCell, aDistance, aSpare);
156614  nodeZero(pRtree, pNode);
156615
156616  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
156617    RtreeCell *p = &aCell[aOrder[ii]];
156618    nodeInsertCell(pRtree, pNode, p);
156619    if( p->iRowid==pCell->iRowid ){
156620      if( iHeight==0 ){
156621        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
156622      }else{
156623        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
156624      }
156625    }
156626  }
156627  if( rc==SQLITE_OK ){
156628    rc = fixBoundingBox(pRtree, pNode);
156629  }
156630  for(; rc==SQLITE_OK && ii<nCell; ii++){
156631    /* Find a node to store this cell in. pNode->iNode currently contains
156632    ** the height of the sub-tree headed by the cell.
156633    */
156634    RtreeNode *pInsert;
156635    RtreeCell *p = &aCell[aOrder[ii]];
156636    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
156637    if( rc==SQLITE_OK ){
156638      int rc2;
156639      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
156640      rc2 = nodeRelease(pRtree, pInsert);
156641      if( rc==SQLITE_OK ){
156642        rc = rc2;
156643      }
156644    }
156645  }
156646
156647  sqlite3_free(aCell);
156648  return rc;
156649}
156650
156651/*
156652** Insert cell pCell into node pNode. Node pNode is the head of a
156653** subtree iHeight high (leaf nodes have iHeight==0).
156654*/
156655static int rtreeInsertCell(
156656  Rtree *pRtree,
156657  RtreeNode *pNode,
156658  RtreeCell *pCell,
156659  int iHeight
156660){
156661  int rc = SQLITE_OK;
156662  if( iHeight>0 ){
156663    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
156664    if( pChild ){
156665      nodeRelease(pRtree, pChild->pParent);
156666      nodeReference(pNode);
156667      pChild->pParent = pNode;
156668    }
156669  }
156670  if( nodeInsertCell(pRtree, pNode, pCell) ){
156671    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
156672      rc = SplitNode(pRtree, pNode, pCell, iHeight);
156673    }else{
156674      pRtree->iReinsertHeight = iHeight;
156675      rc = Reinsert(pRtree, pNode, pCell, iHeight);
156676    }
156677  }else{
156678    rc = AdjustTree(pRtree, pNode, pCell);
156679    if( rc==SQLITE_OK ){
156680      if( iHeight==0 ){
156681        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
156682      }else{
156683        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
156684      }
156685    }
156686  }
156687  return rc;
156688}
156689
156690static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
156691  int ii;
156692  int rc = SQLITE_OK;
156693  int nCell = NCELL(pNode);
156694
156695  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
156696    RtreeNode *pInsert;
156697    RtreeCell cell;
156698    nodeGetCell(pRtree, pNode, ii, &cell);
156699
156700    /* Find a node to store this cell in. pNode->iNode currently contains
156701    ** the height of the sub-tree headed by the cell.
156702    */
156703    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
156704    if( rc==SQLITE_OK ){
156705      int rc2;
156706      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
156707      rc2 = nodeRelease(pRtree, pInsert);
156708      if( rc==SQLITE_OK ){
156709        rc = rc2;
156710      }
156711    }
156712  }
156713  return rc;
156714}
156715
156716/*
156717** Select a currently unused rowid for a new r-tree record.
156718*/
156719static int newRowid(Rtree *pRtree, i64 *piRowid){
156720  int rc;
156721  sqlite3_bind_null(pRtree->pWriteRowid, 1);
156722  sqlite3_bind_null(pRtree->pWriteRowid, 2);
156723  sqlite3_step(pRtree->pWriteRowid);
156724  rc = sqlite3_reset(pRtree->pWriteRowid);
156725  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
156726  return rc;
156727}
156728
156729/*
156730** Remove the entry with rowid=iDelete from the r-tree structure.
156731*/
156732static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
156733  int rc;                         /* Return code */
156734  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
156735  int iCell;                      /* Index of iDelete cell in pLeaf */
156736  RtreeNode *pRoot;               /* Root node of rtree structure */
156737
156738
156739  /* Obtain a reference to the root node to initialize Rtree.iDepth */
156740  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
156741
156742  /* Obtain a reference to the leaf node that contains the entry
156743  ** about to be deleted.
156744  */
156745  if( rc==SQLITE_OK ){
156746    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
156747  }
156748
156749  /* Delete the cell in question from the leaf node. */
156750  if( rc==SQLITE_OK ){
156751    int rc2;
156752    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
156753    if( rc==SQLITE_OK ){
156754      rc = deleteCell(pRtree, pLeaf, iCell, 0);
156755    }
156756    rc2 = nodeRelease(pRtree, pLeaf);
156757    if( rc==SQLITE_OK ){
156758      rc = rc2;
156759    }
156760  }
156761
156762  /* Delete the corresponding entry in the <rtree>_rowid table. */
156763  if( rc==SQLITE_OK ){
156764    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
156765    sqlite3_step(pRtree->pDeleteRowid);
156766    rc = sqlite3_reset(pRtree->pDeleteRowid);
156767  }
156768
156769  /* Check if the root node now has exactly one child. If so, remove
156770  ** it, schedule the contents of the child for reinsertion and
156771  ** reduce the tree height by one.
156772  **
156773  ** This is equivalent to copying the contents of the child into
156774  ** the root node (the operation that Gutman's paper says to perform
156775  ** in this scenario).
156776  */
156777  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
156778    int rc2;
156779    RtreeNode *pChild;
156780    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
156781    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
156782    if( rc==SQLITE_OK ){
156783      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
156784    }
156785    rc2 = nodeRelease(pRtree, pChild);
156786    if( rc==SQLITE_OK ) rc = rc2;
156787    if( rc==SQLITE_OK ){
156788      pRtree->iDepth--;
156789      writeInt16(pRoot->zData, pRtree->iDepth);
156790      pRoot->isDirty = 1;
156791    }
156792  }
156793
156794  /* Re-insert the contents of any underfull nodes removed from the tree. */
156795  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
156796    if( rc==SQLITE_OK ){
156797      rc = reinsertNodeContent(pRtree, pLeaf);
156798    }
156799    pRtree->pDeleted = pLeaf->pNext;
156800    sqlite3_free(pLeaf);
156801  }
156802
156803  /* Release the reference to the root node. */
156804  if( rc==SQLITE_OK ){
156805    rc = nodeRelease(pRtree, pRoot);
156806  }else{
156807    nodeRelease(pRtree, pRoot);
156808  }
156809
156810  return rc;
156811}
156812
156813/*
156814** Rounding constants for float->double conversion.
156815*/
156816#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
156817#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
156818
156819#if !defined(SQLITE_RTREE_INT_ONLY)
156820/*
156821** Convert an sqlite3_value into an RtreeValue (presumably a float)
156822** while taking care to round toward negative or positive, respectively.
156823*/
156824static RtreeValue rtreeValueDown(sqlite3_value *v){
156825  double d = sqlite3_value_double(v);
156826  float f = (float)d;
156827  if( f>d ){
156828    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
156829  }
156830  return f;
156831}
156832static RtreeValue rtreeValueUp(sqlite3_value *v){
156833  double d = sqlite3_value_double(v);
156834  float f = (float)d;
156835  if( f<d ){
156836    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
156837  }
156838  return f;
156839}
156840#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
156841
156842
156843/*
156844** The xUpdate method for rtree module virtual tables.
156845*/
156846static int rtreeUpdate(
156847  sqlite3_vtab *pVtab,
156848  int nData,
156849  sqlite3_value **azData,
156850  sqlite_int64 *pRowid
156851){
156852  Rtree *pRtree = (Rtree *)pVtab;
156853  int rc = SQLITE_OK;
156854  RtreeCell cell;                 /* New cell to insert if nData>1 */
156855  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
156856
156857  rtreeReference(pRtree);
156858  assert(nData>=1);
156859
156860  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
156861
156862  /* Constraint handling. A write operation on an r-tree table may return
156863  ** SQLITE_CONSTRAINT for two reasons:
156864  **
156865  **   1. A duplicate rowid value, or
156866  **   2. The supplied data violates the "x2>=x1" constraint.
156867  **
156868  ** In the first case, if the conflict-handling mode is REPLACE, then
156869  ** the conflicting row can be removed before proceeding. In the second
156870  ** case, SQLITE_CONSTRAINT must be returned regardless of the
156871  ** conflict-handling mode specified by the user.
156872  */
156873  if( nData>1 ){
156874    int ii;
156875
156876    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
156877    **
156878    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
156879    ** with "column" that are interpreted as table constraints.
156880    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
156881    ** This problem was discovered after years of use, so we silently ignore
156882    ** these kinds of misdeclared tables to avoid breaking any legacy.
156883    */
156884    assert( nData<=(pRtree->nDim*2 + 3) );
156885
156886#ifndef SQLITE_RTREE_INT_ONLY
156887    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
156888      for(ii=0; ii<nData-4; ii+=2){
156889        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
156890        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
156891        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
156892          rc = SQLITE_CONSTRAINT;
156893          goto constraint;
156894        }
156895      }
156896    }else
156897#endif
156898    {
156899      for(ii=0; ii<nData-4; ii+=2){
156900        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
156901        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
156902        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
156903          rc = SQLITE_CONSTRAINT;
156904          goto constraint;
156905        }
156906      }
156907    }
156908
156909    /* If a rowid value was supplied, check if it is already present in
156910    ** the table. If so, the constraint has failed. */
156911    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
156912      cell.iRowid = sqlite3_value_int64(azData[2]);
156913      if( sqlite3_value_type(azData[0])==SQLITE_NULL
156914       || sqlite3_value_int64(azData[0])!=cell.iRowid
156915      ){
156916        int steprc;
156917        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
156918        steprc = sqlite3_step(pRtree->pReadRowid);
156919        rc = sqlite3_reset(pRtree->pReadRowid);
156920        if( SQLITE_ROW==steprc ){
156921          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
156922            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
156923          }else{
156924            rc = SQLITE_CONSTRAINT;
156925            goto constraint;
156926          }
156927        }
156928      }
156929      bHaveRowid = 1;
156930    }
156931  }
156932
156933  /* If azData[0] is not an SQL NULL value, it is the rowid of a
156934  ** record to delete from the r-tree table. The following block does
156935  ** just that.
156936  */
156937  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
156938    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
156939  }
156940
156941  /* If the azData[] array contains more than one element, elements
156942  ** (azData[2]..azData[argc-1]) contain a new record to insert into
156943  ** the r-tree structure.
156944  */
156945  if( rc==SQLITE_OK && nData>1 ){
156946    /* Insert the new record into the r-tree */
156947    RtreeNode *pLeaf = 0;
156948
156949    /* Figure out the rowid of the new row. */
156950    if( bHaveRowid==0 ){
156951      rc = newRowid(pRtree, &cell.iRowid);
156952    }
156953    *pRowid = cell.iRowid;
156954
156955    if( rc==SQLITE_OK ){
156956      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
156957    }
156958    if( rc==SQLITE_OK ){
156959      int rc2;
156960      pRtree->iReinsertHeight = -1;
156961      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
156962      rc2 = nodeRelease(pRtree, pLeaf);
156963      if( rc==SQLITE_OK ){
156964        rc = rc2;
156965      }
156966    }
156967  }
156968
156969constraint:
156970  rtreeRelease(pRtree);
156971  return rc;
156972}
156973
156974/*
156975** The xRename method for rtree module virtual tables.
156976*/
156977static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
156978  Rtree *pRtree = (Rtree *)pVtab;
156979  int rc = SQLITE_NOMEM;
156980  char *zSql = sqlite3_mprintf(
156981    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
156982    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
156983    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
156984    , pRtree->zDb, pRtree->zName, zNewName
156985    , pRtree->zDb, pRtree->zName, zNewName
156986    , pRtree->zDb, pRtree->zName, zNewName
156987  );
156988  if( zSql ){
156989    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
156990    sqlite3_free(zSql);
156991  }
156992  return rc;
156993}
156994
156995/*
156996** This function populates the pRtree->nRowEst variable with an estimate
156997** of the number of rows in the virtual table. If possible, this is based
156998** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
156999*/
157000static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
157001  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
157002  char *zSql;
157003  sqlite3_stmt *p;
157004  int rc;
157005  i64 nRow = 0;
157006
157007  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
157008  if( zSql==0 ){
157009    rc = SQLITE_NOMEM;
157010  }else{
157011    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
157012    if( rc==SQLITE_OK ){
157013      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
157014      rc = sqlite3_finalize(p);
157015    }else if( rc!=SQLITE_NOMEM ){
157016      rc = SQLITE_OK;
157017    }
157018
157019    if( rc==SQLITE_OK ){
157020      if( nRow==0 ){
157021        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
157022      }else{
157023        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
157024      }
157025    }
157026    sqlite3_free(zSql);
157027  }
157028
157029  return rc;
157030}
157031
157032static sqlite3_module rtreeModule = {
157033  0,                          /* iVersion */
157034  rtreeCreate,                /* xCreate - create a table */
157035  rtreeConnect,               /* xConnect - connect to an existing table */
157036  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
157037  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
157038  rtreeDestroy,               /* xDestroy - Drop a table */
157039  rtreeOpen,                  /* xOpen - open a cursor */
157040  rtreeClose,                 /* xClose - close a cursor */
157041  rtreeFilter,                /* xFilter - configure scan constraints */
157042  rtreeNext,                  /* xNext - advance a cursor */
157043  rtreeEof,                   /* xEof */
157044  rtreeColumn,                /* xColumn - read data */
157045  rtreeRowid,                 /* xRowid - read data */
157046  rtreeUpdate,                /* xUpdate - write data */
157047  0,                          /* xBegin - begin transaction */
157048  0,                          /* xSync - sync transaction */
157049  0,                          /* xCommit - commit transaction */
157050  0,                          /* xRollback - rollback transaction */
157051  0,                          /* xFindFunction - function overloading */
157052  rtreeRename,                /* xRename - rename the table */
157053  0,                          /* xSavepoint */
157054  0,                          /* xRelease */
157055  0                           /* xRollbackTo */
157056};
157057
157058static int rtreeSqlInit(
157059  Rtree *pRtree,
157060  sqlite3 *db,
157061  const char *zDb,
157062  const char *zPrefix,
157063  int isCreate
157064){
157065  int rc = SQLITE_OK;
157066
157067  #define N_STATEMENT 9
157068  static const char *azSql[N_STATEMENT] = {
157069    /* Read and write the xxx_node table */
157070    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
157071    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
157072    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
157073
157074    /* Read and write the xxx_rowid table */
157075    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
157076    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
157077    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
157078
157079    /* Read and write the xxx_parent table */
157080    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
157081    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
157082    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
157083  };
157084  sqlite3_stmt **appStmt[N_STATEMENT];
157085  int i;
157086
157087  pRtree->db = db;
157088
157089  if( isCreate ){
157090    char *zCreate = sqlite3_mprintf(
157091"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
157092"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
157093"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
157094                                  " parentnode INTEGER);"
157095"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
157096      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
157097    );
157098    if( !zCreate ){
157099      return SQLITE_NOMEM;
157100    }
157101    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
157102    sqlite3_free(zCreate);
157103    if( rc!=SQLITE_OK ){
157104      return rc;
157105    }
157106  }
157107
157108  appStmt[0] = &pRtree->pReadNode;
157109  appStmt[1] = &pRtree->pWriteNode;
157110  appStmt[2] = &pRtree->pDeleteNode;
157111  appStmt[3] = &pRtree->pReadRowid;
157112  appStmt[4] = &pRtree->pWriteRowid;
157113  appStmt[5] = &pRtree->pDeleteRowid;
157114  appStmt[6] = &pRtree->pReadParent;
157115  appStmt[7] = &pRtree->pWriteParent;
157116  appStmt[8] = &pRtree->pDeleteParent;
157117
157118  rc = rtreeQueryStat1(db, pRtree);
157119  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
157120    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
157121    if( zSql ){
157122      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
157123    }else{
157124      rc = SQLITE_NOMEM;
157125    }
157126    sqlite3_free(zSql);
157127  }
157128
157129  return rc;
157130}
157131
157132/*
157133** The second argument to this function contains the text of an SQL statement
157134** that returns a single integer value. The statement is compiled and executed
157135** using database connection db. If successful, the integer value returned
157136** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
157137** code is returned and the value of *piVal after returning is not defined.
157138*/
157139static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
157140  int rc = SQLITE_NOMEM;
157141  if( zSql ){
157142    sqlite3_stmt *pStmt = 0;
157143    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
157144    if( rc==SQLITE_OK ){
157145      if( SQLITE_ROW==sqlite3_step(pStmt) ){
157146        *piVal = sqlite3_column_int(pStmt, 0);
157147      }
157148      rc = sqlite3_finalize(pStmt);
157149    }
157150  }
157151  return rc;
157152}
157153
157154/*
157155** This function is called from within the xConnect() or xCreate() method to
157156** determine the node-size used by the rtree table being created or connected
157157** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
157158** Otherwise, an SQLite error code is returned.
157159**
157160** If this function is being called as part of an xConnect(), then the rtree
157161** table already exists. In this case the node-size is determined by inspecting
157162** the root node of the tree.
157163**
157164** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
157165** This ensures that each node is stored on a single database page. If the
157166** database page-size is so large that more than RTREE_MAXCELLS entries
157167** would fit in a single node, use a smaller node-size.
157168*/
157169static int getNodeSize(
157170  sqlite3 *db,                    /* Database handle */
157171  Rtree *pRtree,                  /* Rtree handle */
157172  int isCreate,                   /* True for xCreate, false for xConnect */
157173  char **pzErr                    /* OUT: Error message, if any */
157174){
157175  int rc;
157176  char *zSql;
157177  if( isCreate ){
157178    int iPageSize = 0;
157179    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
157180    rc = getIntFromStmt(db, zSql, &iPageSize);
157181    if( rc==SQLITE_OK ){
157182      pRtree->iNodeSize = iPageSize-64;
157183      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
157184        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
157185      }
157186    }else{
157187      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157188    }
157189  }else{
157190    zSql = sqlite3_mprintf(
157191        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
157192        pRtree->zDb, pRtree->zName
157193    );
157194    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
157195    if( rc!=SQLITE_OK ){
157196      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157197    }
157198  }
157199
157200  sqlite3_free(zSql);
157201  return rc;
157202}
157203
157204/*
157205** This function is the implementation of both the xConnect and xCreate
157206** methods of the r-tree virtual table.
157207**
157208**   argv[0]   -> module name
157209**   argv[1]   -> database name
157210**   argv[2]   -> table name
157211**   argv[...] -> column names...
157212*/
157213static int rtreeInit(
157214  sqlite3 *db,                        /* Database connection */
157215  void *pAux,                         /* One of the RTREE_COORD_* constants */
157216  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
157217  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
157218  char **pzErr,                       /* OUT: Error message, if any */
157219  int isCreate                        /* True for xCreate, false for xConnect */
157220){
157221  int rc = SQLITE_OK;
157222  Rtree *pRtree;
157223  int nDb;              /* Length of string argv[1] */
157224  int nName;            /* Length of string argv[2] */
157225  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
157226
157227  const char *aErrMsg[] = {
157228    0,                                                    /* 0 */
157229    "Wrong number of columns for an rtree table",         /* 1 */
157230    "Too few columns for an rtree table",                 /* 2 */
157231    "Too many columns for an rtree table"                 /* 3 */
157232  };
157233
157234  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
157235  if( aErrMsg[iErr] ){
157236    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
157237    return SQLITE_ERROR;
157238  }
157239
157240  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
157241
157242  /* Allocate the sqlite3_vtab structure */
157243  nDb = (int)strlen(argv[1]);
157244  nName = (int)strlen(argv[2]);
157245  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
157246  if( !pRtree ){
157247    return SQLITE_NOMEM;
157248  }
157249  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
157250  pRtree->nBusy = 1;
157251  pRtree->base.pModule = &rtreeModule;
157252  pRtree->zDb = (char *)&pRtree[1];
157253  pRtree->zName = &pRtree->zDb[nDb+1];
157254  pRtree->nDim = (argc-4)/2;
157255  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
157256  pRtree->eCoordType = eCoordType;
157257  memcpy(pRtree->zDb, argv[1], nDb);
157258  memcpy(pRtree->zName, argv[2], nName);
157259
157260  /* Figure out the node size to use. */
157261  rc = getNodeSize(db, pRtree, isCreate, pzErr);
157262
157263  /* Create/Connect to the underlying relational database schema. If
157264  ** that is successful, call sqlite3_declare_vtab() to configure
157265  ** the r-tree table schema.
157266  */
157267  if( rc==SQLITE_OK ){
157268    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
157269      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157270    }else{
157271      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
157272      char *zTmp;
157273      int ii;
157274      for(ii=4; zSql && ii<argc; ii++){
157275        zTmp = zSql;
157276        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
157277        sqlite3_free(zTmp);
157278      }
157279      if( zSql ){
157280        zTmp = zSql;
157281        zSql = sqlite3_mprintf("%s);", zTmp);
157282        sqlite3_free(zTmp);
157283      }
157284      if( !zSql ){
157285        rc = SQLITE_NOMEM;
157286      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
157287        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157288      }
157289      sqlite3_free(zSql);
157290    }
157291  }
157292
157293  if( rc==SQLITE_OK ){
157294    *ppVtab = (sqlite3_vtab *)pRtree;
157295  }else{
157296    assert( *ppVtab==0 );
157297    assert( pRtree->nBusy==1 );
157298    rtreeRelease(pRtree);
157299  }
157300  return rc;
157301}
157302
157303
157304/*
157305** Implementation of a scalar function that decodes r-tree nodes to
157306** human readable strings. This can be used for debugging and analysis.
157307**
157308** The scalar function takes two arguments: (1) the number of dimensions
157309** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
157310** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
157311** deserialize all nodes, a statement like:
157312**
157313**   SELECT rtreenode(2, data) FROM rt_node;
157314**
157315** The human readable string takes the form of a Tcl list with one
157316** entry for each cell in the r-tree node. Each entry is itself a
157317** list, containing the 8-byte rowid/pageno followed by the
157318** <num-dimension>*2 coordinates.
157319*/
157320static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
157321  char *zText = 0;
157322  RtreeNode node;
157323  Rtree tree;
157324  int ii;
157325
157326  UNUSED_PARAMETER(nArg);
157327  memset(&node, 0, sizeof(RtreeNode));
157328  memset(&tree, 0, sizeof(Rtree));
157329  tree.nDim = sqlite3_value_int(apArg[0]);
157330  tree.nBytesPerCell = 8 + 8 * tree.nDim;
157331  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
157332
157333  for(ii=0; ii<NCELL(&node); ii++){
157334    char zCell[512];
157335    int nCell = 0;
157336    RtreeCell cell;
157337    int jj;
157338
157339    nodeGetCell(&tree, &node, ii, &cell);
157340    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
157341    nCell = (int)strlen(zCell);
157342    for(jj=0; jj<tree.nDim*2; jj++){
157343#ifndef SQLITE_RTREE_INT_ONLY
157344      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
157345                       (double)cell.aCoord[jj].f);
157346#else
157347      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
157348                       cell.aCoord[jj].i);
157349#endif
157350      nCell = (int)strlen(zCell);
157351    }
157352
157353    if( zText ){
157354      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
157355      sqlite3_free(zText);
157356      zText = zTextNew;
157357    }else{
157358      zText = sqlite3_mprintf("{%s}", zCell);
157359    }
157360  }
157361
157362  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
157363}
157364
157365/* This routine implements an SQL function that returns the "depth" parameter
157366** from the front of a blob that is an r-tree node.  For example:
157367**
157368**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
157369**
157370** The depth value is 0 for all nodes other than the root node, and the root
157371** node always has nodeno=1, so the example above is the primary use for this
157372** routine.  This routine is intended for testing and analysis only.
157373*/
157374static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
157375  UNUSED_PARAMETER(nArg);
157376  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
157377   || sqlite3_value_bytes(apArg[0])<2
157378  ){
157379    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
157380  }else{
157381    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
157382    sqlite3_result_int(ctx, readInt16(zBlob));
157383  }
157384}
157385
157386/*
157387** Register the r-tree module with database handle db. This creates the
157388** virtual table module "rtree" and the debugging/analysis scalar
157389** function "rtreenode".
157390*/
157391SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
157392  const int utf8 = SQLITE_UTF8;
157393  int rc;
157394
157395  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
157396  if( rc==SQLITE_OK ){
157397    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
157398  }
157399  if( rc==SQLITE_OK ){
157400#ifdef SQLITE_RTREE_INT_ONLY
157401    void *c = (void *)RTREE_COORD_INT32;
157402#else
157403    void *c = (void *)RTREE_COORD_REAL32;
157404#endif
157405    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
157406  }
157407  if( rc==SQLITE_OK ){
157408    void *c = (void *)RTREE_COORD_INT32;
157409    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
157410  }
157411
157412  return rc;
157413}
157414
157415/*
157416** This routine deletes the RtreeGeomCallback object that was attached
157417** one of the SQL functions create by sqlite3_rtree_geometry_callback()
157418** or sqlite3_rtree_query_callback().  In other words, this routine is the
157419** destructor for an RtreeGeomCallback objecct.  This routine is called when
157420** the corresponding SQL function is deleted.
157421*/
157422static void rtreeFreeCallback(void *p){
157423  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
157424  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
157425  sqlite3_free(p);
157426}
157427
157428/*
157429** This routine frees the BLOB that is returned by geomCallback().
157430*/
157431static void rtreeMatchArgFree(void *pArg){
157432  int i;
157433  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
157434  for(i=0; i<p->nParam; i++){
157435    sqlite3_value_free(p->apSqlParam[i]);
157436  }
157437  sqlite3_free(p);
157438}
157439
157440/*
157441** Each call to sqlite3_rtree_geometry_callback() or
157442** sqlite3_rtree_query_callback() creates an ordinary SQLite
157443** scalar function that is implemented by this routine.
157444**
157445** All this function does is construct an RtreeMatchArg object that
157446** contains the geometry-checking callback routines and a list of
157447** parameters to this function, then return that RtreeMatchArg object
157448** as a BLOB.
157449**
157450** The R-Tree MATCH operator will read the returned BLOB, deserialize
157451** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
157452** out which elements of the R-Tree should be returned by the query.
157453*/
157454static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
157455  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
157456  RtreeMatchArg *pBlob;
157457  int nBlob;
157458  int memErr = 0;
157459
157460  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
157461           + nArg*sizeof(sqlite3_value*);
157462  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
157463  if( !pBlob ){
157464    sqlite3_result_error_nomem(ctx);
157465  }else{
157466    int i;
157467    pBlob->magic = RTREE_GEOMETRY_MAGIC;
157468    pBlob->cb = pGeomCtx[0];
157469    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
157470    pBlob->nParam = nArg;
157471    for(i=0; i<nArg; i++){
157472      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
157473      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
157474#ifdef SQLITE_RTREE_INT_ONLY
157475      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
157476#else
157477      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
157478#endif
157479    }
157480    if( memErr ){
157481      sqlite3_result_error_nomem(ctx);
157482      rtreeMatchArgFree(pBlob);
157483    }else{
157484      sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
157485    }
157486  }
157487}
157488
157489/*
157490** Register a new geometry function for use with the r-tree MATCH operator.
157491*/
157492SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
157493  sqlite3 *db,                  /* Register SQL function on this connection */
157494  const char *zGeom,            /* Name of the new SQL function */
157495  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
157496  void *pContext                /* Extra data associated with the callback */
157497){
157498  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
157499
157500  /* Allocate and populate the context object. */
157501  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
157502  if( !pGeomCtx ) return SQLITE_NOMEM;
157503  pGeomCtx->xGeom = xGeom;
157504  pGeomCtx->xQueryFunc = 0;
157505  pGeomCtx->xDestructor = 0;
157506  pGeomCtx->pContext = pContext;
157507  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
157508      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
157509  );
157510}
157511
157512/*
157513** Register a new 2nd-generation geometry function for use with the
157514** r-tree MATCH operator.
157515*/
157516SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
157517  sqlite3 *db,                 /* Register SQL function on this connection */
157518  const char *zQueryFunc,      /* Name of new SQL function */
157519  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
157520  void *pContext,              /* Extra data passed into the callback */
157521  void (*xDestructor)(void*)   /* Destructor for the extra data */
157522){
157523  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
157524
157525  /* Allocate and populate the context object. */
157526  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
157527  if( !pGeomCtx ) return SQLITE_NOMEM;
157528  pGeomCtx->xGeom = 0;
157529  pGeomCtx->xQueryFunc = xQueryFunc;
157530  pGeomCtx->xDestructor = xDestructor;
157531  pGeomCtx->pContext = pContext;
157532  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
157533      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
157534  );
157535}
157536
157537#if !SQLITE_CORE
157538#ifdef _WIN32
157539__declspec(dllexport)
157540#endif
157541SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
157542  sqlite3 *db,
157543  char **pzErrMsg,
157544  const sqlite3_api_routines *pApi
157545){
157546  SQLITE_EXTENSION_INIT2(pApi)
157547  return sqlite3RtreeInit(db);
157548}
157549#endif
157550
157551#endif
157552
157553/************** End of rtree.c ***********************************************/
157554/************** Begin file icu.c *********************************************/
157555/*
157556** 2007 May 6
157557**
157558** The author disclaims copyright to this source code.  In place of
157559** a legal notice, here is a blessing:
157560**
157561**    May you do good and not evil.
157562**    May you find forgiveness for yourself and forgive others.
157563**    May you share freely, never taking more than you give.
157564**
157565*************************************************************************
157566** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
157567**
157568** This file implements an integration between the ICU library
157569** ("International Components for Unicode", an open-source library
157570** for handling unicode data) and SQLite. The integration uses
157571** ICU to provide the following to SQLite:
157572**
157573**   * An implementation of the SQL regexp() function (and hence REGEXP
157574**     operator) using the ICU uregex_XX() APIs.
157575**
157576**   * Implementations of the SQL scalar upper() and lower() functions
157577**     for case mapping.
157578**
157579**   * Integration of ICU and SQLite collation sequences.
157580**
157581**   * An implementation of the LIKE operator that uses ICU to
157582**     provide case-independent matching.
157583*/
157584
157585#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
157586
157587/* Include ICU headers */
157588#include <unicode/utypes.h>
157589#include <unicode/uregex.h>
157590#include <unicode/ustring.h>
157591#include <unicode/ucol.h>
157592
157593/* #include <assert.h> */
157594
157595#ifndef SQLITE_CORE
157596/*   #include "sqlite3ext.h" */
157597  SQLITE_EXTENSION_INIT1
157598#else
157599/*   #include "sqlite3.h" */
157600#endif
157601
157602/*
157603** Maximum length (in bytes) of the pattern in a LIKE or GLOB
157604** operator.
157605*/
157606#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
157607# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
157608#endif
157609
157610/*
157611** Version of sqlite3_free() that is always a function, never a macro.
157612*/
157613static void xFree(void *p){
157614  sqlite3_free(p);
157615}
157616
157617/*
157618** Compare two UTF-8 strings for equality where the first string is
157619** a "LIKE" expression. Return true (1) if they are the same and
157620** false (0) if they are different.
157621*/
157622static int icuLikeCompare(
157623  const uint8_t *zPattern,   /* LIKE pattern */
157624  const uint8_t *zString,    /* The UTF-8 string to compare against */
157625  const UChar32 uEsc         /* The escape character */
157626){
157627  static const int MATCH_ONE = (UChar32)'_';
157628  static const int MATCH_ALL = (UChar32)'%';
157629
157630  int iPattern = 0;       /* Current byte index in zPattern */
157631  int iString = 0;        /* Current byte index in zString */
157632
157633  int prevEscape = 0;     /* True if the previous character was uEsc */
157634
157635  while( zPattern[iPattern]!=0 ){
157636
157637    /* Read (and consume) the next character from the input pattern. */
157638    UChar32 uPattern;
157639    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
157640
157641    /* There are now 4 possibilities:
157642    **
157643    **     1. uPattern is an unescaped match-all character "%",
157644    **     2. uPattern is an unescaped match-one character "_",
157645    **     3. uPattern is an unescaped escape character, or
157646    **     4. uPattern is to be handled as an ordinary character
157647    */
157648    if( !prevEscape && uPattern==MATCH_ALL ){
157649      /* Case 1. */
157650      uint8_t c;
157651
157652      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
157653      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
157654      ** test string.
157655      */
157656      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
157657        if( c==MATCH_ONE ){
157658          if( zString[iString]==0 ) return 0;
157659          U8_FWD_1_UNSAFE(zString, iString);
157660        }
157661        iPattern++;
157662      }
157663
157664      if( zPattern[iPattern]==0 ) return 1;
157665
157666      while( zString[iString] ){
157667        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
157668          return 1;
157669        }
157670        U8_FWD_1_UNSAFE(zString, iString);
157671      }
157672      return 0;
157673
157674    }else if( !prevEscape && uPattern==MATCH_ONE ){
157675      /* Case 2. */
157676      if( zString[iString]==0 ) return 0;
157677      U8_FWD_1_UNSAFE(zString, iString);
157678
157679    }else if( !prevEscape && uPattern==uEsc){
157680      /* Case 3. */
157681      prevEscape = 1;
157682
157683    }else{
157684      /* Case 4. */
157685      UChar32 uString;
157686      U8_NEXT_UNSAFE(zString, iString, uString);
157687      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
157688      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
157689      if( uString!=uPattern ){
157690        return 0;
157691      }
157692      prevEscape = 0;
157693    }
157694  }
157695
157696  return zString[iString]==0;
157697}
157698
157699/*
157700** Implementation of the like() SQL function.  This function implements
157701** the build-in LIKE operator.  The first argument to the function is the
157702** pattern and the second argument is the string.  So, the SQL statements:
157703**
157704**       A LIKE B
157705**
157706** is implemented as like(B, A). If there is an escape character E,
157707**
157708**       A LIKE B ESCAPE E
157709**
157710** is mapped to like(B, A, E).
157711*/
157712static void icuLikeFunc(
157713  sqlite3_context *context,
157714  int argc,
157715  sqlite3_value **argv
157716){
157717  const unsigned char *zA = sqlite3_value_text(argv[0]);
157718  const unsigned char *zB = sqlite3_value_text(argv[1]);
157719  UChar32 uEsc = 0;
157720
157721  /* Limit the length of the LIKE or GLOB pattern to avoid problems
157722  ** of deep recursion and N*N behavior in patternCompare().
157723  */
157724  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
157725    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
157726    return;
157727  }
157728
157729
157730  if( argc==3 ){
157731    /* The escape character string must consist of a single UTF-8 character.
157732    ** Otherwise, return an error.
157733    */
157734    int nE= sqlite3_value_bytes(argv[2]);
157735    const unsigned char *zE = sqlite3_value_text(argv[2]);
157736    int i = 0;
157737    if( zE==0 ) return;
157738    U8_NEXT(zE, i, nE, uEsc);
157739    if( i!=nE){
157740      sqlite3_result_error(context,
157741          "ESCAPE expression must be a single character", -1);
157742      return;
157743    }
157744  }
157745
157746  if( zA && zB ){
157747    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
157748  }
157749}
157750
157751/*
157752** This function is called when an ICU function called from within
157753** the implementation of an SQL scalar function returns an error.
157754**
157755** The scalar function context passed as the first argument is
157756** loaded with an error message based on the following two args.
157757*/
157758static void icuFunctionError(
157759  sqlite3_context *pCtx,       /* SQLite scalar function context */
157760  const char *zName,           /* Name of ICU function that failed */
157761  UErrorCode e                 /* Error code returned by ICU function */
157762){
157763  char zBuf[128];
157764  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
157765  zBuf[127] = '\0';
157766  sqlite3_result_error(pCtx, zBuf, -1);
157767}
157768
157769/*
157770** Function to delete compiled regexp objects. Registered as
157771** a destructor function with sqlite3_set_auxdata().
157772*/
157773static void icuRegexpDelete(void *p){
157774  URegularExpression *pExpr = (URegularExpression *)p;
157775  uregex_close(pExpr);
157776}
157777
157778/*
157779** Implementation of SQLite REGEXP operator. This scalar function takes
157780** two arguments. The first is a regular expression pattern to compile
157781** the second is a string to match against that pattern. If either
157782** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
157783** is 1 if the string matches the pattern, or 0 otherwise.
157784**
157785** SQLite maps the regexp() function to the regexp() operator such
157786** that the following two are equivalent:
157787**
157788**     zString REGEXP zPattern
157789**     regexp(zPattern, zString)
157790**
157791** Uses the following ICU regexp APIs:
157792**
157793**     uregex_open()
157794**     uregex_matches()
157795**     uregex_close()
157796*/
157797static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
157798  UErrorCode status = U_ZERO_ERROR;
157799  URegularExpression *pExpr;
157800  UBool res;
157801  const UChar *zString = sqlite3_value_text16(apArg[1]);
157802
157803  (void)nArg;  /* Unused parameter */
157804
157805  /* If the left hand side of the regexp operator is NULL,
157806  ** then the result is also NULL.
157807  */
157808  if( !zString ){
157809    return;
157810  }
157811
157812  pExpr = sqlite3_get_auxdata(p, 0);
157813  if( !pExpr ){
157814    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
157815    if( !zPattern ){
157816      return;
157817    }
157818    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
157819
157820    if( U_SUCCESS(status) ){
157821      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
157822    }else{
157823      assert(!pExpr);
157824      icuFunctionError(p, "uregex_open", status);
157825      return;
157826    }
157827  }
157828
157829  /* Configure the text that the regular expression operates on. */
157830  uregex_setText(pExpr, zString, -1, &status);
157831  if( !U_SUCCESS(status) ){
157832    icuFunctionError(p, "uregex_setText", status);
157833    return;
157834  }
157835
157836  /* Attempt the match */
157837  res = uregex_matches(pExpr, 0, &status);
157838  if( !U_SUCCESS(status) ){
157839    icuFunctionError(p, "uregex_matches", status);
157840    return;
157841  }
157842
157843  /* Set the text that the regular expression operates on to a NULL
157844  ** pointer. This is not really necessary, but it is tidier than
157845  ** leaving the regular expression object configured with an invalid
157846  ** pointer after this function returns.
157847  */
157848  uregex_setText(pExpr, 0, 0, &status);
157849
157850  /* Return 1 or 0. */
157851  sqlite3_result_int(p, res ? 1 : 0);
157852}
157853
157854/*
157855** Implementations of scalar functions for case mapping - upper() and
157856** lower(). Function upper() converts its input to upper-case (ABC).
157857** Function lower() converts to lower-case (abc).
157858**
157859** ICU provides two types of case mapping, "general" case mapping and
157860** "language specific". Refer to ICU documentation for the differences
157861** between the two.
157862**
157863** To utilise "general" case mapping, the upper() or lower() scalar
157864** functions are invoked with one argument:
157865**
157866**     upper('ABC') -> 'abc'
157867**     lower('abc') -> 'ABC'
157868**
157869** To access ICU "language specific" case mapping, upper() or lower()
157870** should be invoked with two arguments. The second argument is the name
157871** of the locale to use. Passing an empty string ("") or SQL NULL value
157872** as the second argument is the same as invoking the 1 argument version
157873** of upper() or lower().
157874**
157875**     lower('I', 'en_us') -> 'i'
157876**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
157877**
157878** http://www.icu-project.org/userguide/posix.html#case_mappings
157879*/
157880static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
157881  const UChar *zInput;
157882  UChar *zOutput;
157883  int nInput;
157884  int nOutput;
157885
157886  UErrorCode status = U_ZERO_ERROR;
157887  const char *zLocale = 0;
157888
157889  assert(nArg==1 || nArg==2);
157890  if( nArg==2 ){
157891    zLocale = (const char *)sqlite3_value_text(apArg[1]);
157892  }
157893
157894  zInput = sqlite3_value_text16(apArg[0]);
157895  if( !zInput ){
157896    return;
157897  }
157898  nInput = sqlite3_value_bytes16(apArg[0]);
157899
157900  nOutput = nInput * 2 + 2;
157901  zOutput = sqlite3_malloc(nOutput);
157902  if( !zOutput ){
157903    return;
157904  }
157905
157906  if( sqlite3_user_data(p) ){
157907    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
157908  }else{
157909    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
157910  }
157911
157912  if( !U_SUCCESS(status) ){
157913    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
157914    return;
157915  }
157916
157917  sqlite3_result_text16(p, zOutput, -1, xFree);
157918}
157919
157920/*
157921** Collation sequence destructor function. The pCtx argument points to
157922** a UCollator structure previously allocated using ucol_open().
157923*/
157924static void icuCollationDel(void *pCtx){
157925  UCollator *p = (UCollator *)pCtx;
157926  ucol_close(p);
157927}
157928
157929/*
157930** Collation sequence comparison function. The pCtx argument points to
157931** a UCollator structure previously allocated using ucol_open().
157932*/
157933static int icuCollationColl(
157934  void *pCtx,
157935  int nLeft,
157936  const void *zLeft,
157937  int nRight,
157938  const void *zRight
157939){
157940  UCollationResult res;
157941  UCollator *p = (UCollator *)pCtx;
157942  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
157943  switch( res ){
157944    case UCOL_LESS:    return -1;
157945    case UCOL_GREATER: return +1;
157946    case UCOL_EQUAL:   return 0;
157947  }
157948  assert(!"Unexpected return value from ucol_strcoll()");
157949  return 0;
157950}
157951
157952/*
157953** Implementation of the scalar function icu_load_collation().
157954**
157955** This scalar function is used to add ICU collation based collation
157956** types to an SQLite database connection. It is intended to be called
157957** as follows:
157958**
157959**     SELECT icu_load_collation(<locale>, <collation-name>);
157960**
157961** Where <locale> is a string containing an ICU locale identifier (i.e.
157962** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
157963** collation sequence to create.
157964*/
157965static void icuLoadCollation(
157966  sqlite3_context *p,
157967  int nArg,
157968  sqlite3_value **apArg
157969){
157970  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
157971  UErrorCode status = U_ZERO_ERROR;
157972  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
157973  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
157974  UCollator *pUCollator;    /* ICU library collation object */
157975  int rc;                   /* Return code from sqlite3_create_collation_x() */
157976
157977  assert(nArg==2);
157978  (void)nArg; /* Unused parameter */
157979  zLocale = (const char *)sqlite3_value_text(apArg[0]);
157980  zName = (const char *)sqlite3_value_text(apArg[1]);
157981
157982  if( !zLocale || !zName ){
157983    return;
157984  }
157985
157986  pUCollator = ucol_open(zLocale, &status);
157987  if( !U_SUCCESS(status) ){
157988    icuFunctionError(p, "ucol_open", status);
157989    return;
157990  }
157991  assert(p);
157992
157993  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
157994      icuCollationColl, icuCollationDel
157995  );
157996  if( rc!=SQLITE_OK ){
157997    ucol_close(pUCollator);
157998    sqlite3_result_error(p, "Error registering collation function", -1);
157999  }
158000}
158001
158002/*
158003** Register the ICU extension functions with database db.
158004*/
158005SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
158006  struct IcuScalar {
158007    const char *zName;                        /* Function name */
158008    int nArg;                                 /* Number of arguments */
158009    int enc;                                  /* Optimal text encoding */
158010    void *pContext;                           /* sqlite3_user_data() context */
158011    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
158012  } scalars[] = {
158013    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
158014
158015    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
158016    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
158017    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
158018    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
158019
158020    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
158021    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
158022    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
158023    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
158024
158025    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
158026    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
158027
158028    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
158029  };
158030
158031  int rc = SQLITE_OK;
158032  int i;
158033
158034  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
158035    struct IcuScalar *p = &scalars[i];
158036    rc = sqlite3_create_function(
158037        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
158038    );
158039  }
158040
158041  return rc;
158042}
158043
158044#if !SQLITE_CORE
158045#ifdef _WIN32
158046__declspec(dllexport)
158047#endif
158048SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
158049  sqlite3 *db,
158050  char **pzErrMsg,
158051  const sqlite3_api_routines *pApi
158052){
158053  SQLITE_EXTENSION_INIT2(pApi)
158054  return sqlite3IcuInit(db);
158055}
158056#endif
158057
158058#endif
158059
158060/************** End of icu.c *************************************************/
158061/************** Begin file fts3_icu.c ****************************************/
158062/*
158063** 2007 June 22
158064**
158065** The author disclaims copyright to this source code.  In place of
158066** a legal notice, here is a blessing:
158067**
158068**    May you do good and not evil.
158069**    May you find forgiveness for yourself and forgive others.
158070**    May you share freely, never taking more than you give.
158071**
158072*************************************************************************
158073** This file implements a tokenizer for fts3 based on the ICU library.
158074*/
158075/* #include "fts3Int.h" */
158076#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
158077#ifdef SQLITE_ENABLE_ICU
158078
158079/* #include <assert.h> */
158080/* #include <string.h> */
158081/* #include "fts3_tokenizer.h" */
158082
158083#include <unicode/ubrk.h>
158084/* #include <unicode/ucol.h> */
158085/* #include <unicode/ustring.h> */
158086#include <unicode/utf16.h>
158087
158088typedef struct IcuTokenizer IcuTokenizer;
158089typedef struct IcuCursor IcuCursor;
158090
158091struct IcuTokenizer {
158092  sqlite3_tokenizer base;
158093  char *zLocale;
158094};
158095
158096struct IcuCursor {
158097  sqlite3_tokenizer_cursor base;
158098
158099  UBreakIterator *pIter;      /* ICU break-iterator object */
158100  int nChar;                  /* Number of UChar elements in pInput */
158101  UChar *aChar;               /* Copy of input using utf-16 encoding */
158102  int *aOffset;               /* Offsets of each character in utf-8 input */
158103
158104  int nBuffer;
158105  char *zBuffer;
158106
158107  int iToken;
158108};
158109
158110/*
158111** Create a new tokenizer instance.
158112*/
158113static int icuCreate(
158114  int argc,                            /* Number of entries in argv[] */
158115  const char * const *argv,            /* Tokenizer creation arguments */
158116  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
158117){
158118  IcuTokenizer *p;
158119  int n = 0;
158120
158121  if( argc>0 ){
158122    n = strlen(argv[0])+1;
158123  }
158124  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
158125  if( !p ){
158126    return SQLITE_NOMEM;
158127  }
158128  memset(p, 0, sizeof(IcuTokenizer));
158129
158130  if( n ){
158131    p->zLocale = (char *)&p[1];
158132    memcpy(p->zLocale, argv[0], n);
158133  }
158134
158135  *ppTokenizer = (sqlite3_tokenizer *)p;
158136
158137  return SQLITE_OK;
158138}
158139
158140/*
158141** Destroy a tokenizer
158142*/
158143static int icuDestroy(sqlite3_tokenizer *pTokenizer){
158144  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
158145  sqlite3_free(p);
158146  return SQLITE_OK;
158147}
158148
158149/*
158150** Prepare to begin tokenizing a particular string.  The input
158151** string to be tokenized is pInput[0..nBytes-1].  A cursor
158152** used to incrementally tokenize this string is returned in
158153** *ppCursor.
158154*/
158155static int icuOpen(
158156  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
158157  const char *zInput,                    /* Input string */
158158  int nInput,                            /* Length of zInput in bytes */
158159  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
158160){
158161  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
158162  IcuCursor *pCsr;
158163
158164  const int32_t opt = U_FOLD_CASE_DEFAULT;
158165  UErrorCode status = U_ZERO_ERROR;
158166  int nChar;
158167
158168  UChar32 c;
158169  int iInput = 0;
158170  int iOut = 0;
158171
158172  *ppCursor = 0;
158173
158174  if( zInput==0 ){
158175    nInput = 0;
158176    zInput = "";
158177  }else if( nInput<0 ){
158178    nInput = strlen(zInput);
158179  }
158180  nChar = nInput+1;
158181  pCsr = (IcuCursor *)sqlite3_malloc(
158182      sizeof(IcuCursor) +                /* IcuCursor */
158183      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
158184      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
158185  );
158186  if( !pCsr ){
158187    return SQLITE_NOMEM;
158188  }
158189  memset(pCsr, 0, sizeof(IcuCursor));
158190  pCsr->aChar = (UChar *)&pCsr[1];
158191  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
158192
158193  pCsr->aOffset[iOut] = iInput;
158194  U8_NEXT(zInput, iInput, nInput, c);
158195  while( c>0 ){
158196    int isError = 0;
158197    c = u_foldCase(c, opt);
158198    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
158199    if( isError ){
158200      sqlite3_free(pCsr);
158201      return SQLITE_ERROR;
158202    }
158203    pCsr->aOffset[iOut] = iInput;
158204
158205    if( iInput<nInput ){
158206      U8_NEXT(zInput, iInput, nInput, c);
158207    }else{
158208      c = 0;
158209    }
158210  }
158211
158212  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
158213  if( !U_SUCCESS(status) ){
158214    sqlite3_free(pCsr);
158215    return SQLITE_ERROR;
158216  }
158217  pCsr->nChar = iOut;
158218
158219  ubrk_first(pCsr->pIter);
158220  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
158221  return SQLITE_OK;
158222}
158223
158224/*
158225** Close a tokenization cursor previously opened by a call to icuOpen().
158226*/
158227static int icuClose(sqlite3_tokenizer_cursor *pCursor){
158228  IcuCursor *pCsr = (IcuCursor *)pCursor;
158229  ubrk_close(pCsr->pIter);
158230  sqlite3_free(pCsr->zBuffer);
158231  sqlite3_free(pCsr);
158232  return SQLITE_OK;
158233}
158234
158235/*
158236** Extract the next token from a tokenization cursor.
158237*/
158238static int icuNext(
158239  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
158240  const char **ppToken,               /* OUT: *ppToken is the token text */
158241  int *pnBytes,                       /* OUT: Number of bytes in token */
158242  int *piStartOffset,                 /* OUT: Starting offset of token */
158243  int *piEndOffset,                   /* OUT: Ending offset of token */
158244  int *piPosition                     /* OUT: Position integer of token */
158245){
158246  IcuCursor *pCsr = (IcuCursor *)pCursor;
158247
158248  int iStart = 0;
158249  int iEnd = 0;
158250  int nByte = 0;
158251
158252  while( iStart==iEnd ){
158253    UChar32 c;
158254
158255    iStart = ubrk_current(pCsr->pIter);
158256    iEnd = ubrk_next(pCsr->pIter);
158257    if( iEnd==UBRK_DONE ){
158258      return SQLITE_DONE;
158259    }
158260
158261    while( iStart<iEnd ){
158262      int iWhite = iStart;
158263      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
158264      if( u_isspace(c) ){
158265        iStart = iWhite;
158266      }else{
158267        break;
158268      }
158269    }
158270    assert(iStart<=iEnd);
158271  }
158272
158273  do {
158274    UErrorCode status = U_ZERO_ERROR;
158275    if( nByte ){
158276      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
158277      if( !zNew ){
158278        return SQLITE_NOMEM;
158279      }
158280      pCsr->zBuffer = zNew;
158281      pCsr->nBuffer = nByte;
158282    }
158283
158284    u_strToUTF8(
158285        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
158286        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
158287        &status                                  /* Output success/failure */
158288    );
158289  } while( nByte>pCsr->nBuffer );
158290
158291  *ppToken = pCsr->zBuffer;
158292  *pnBytes = nByte;
158293  *piStartOffset = pCsr->aOffset[iStart];
158294  *piEndOffset = pCsr->aOffset[iEnd];
158295  *piPosition = pCsr->iToken++;
158296
158297  return SQLITE_OK;
158298}
158299
158300/*
158301** The set of routines that implement the simple tokenizer
158302*/
158303static const sqlite3_tokenizer_module icuTokenizerModule = {
158304  0,                           /* iVersion    */
158305  icuCreate,                   /* xCreate     */
158306  icuDestroy,                  /* xCreate     */
158307  icuOpen,                     /* xOpen       */
158308  icuClose,                    /* xClose      */
158309  icuNext,                     /* xNext       */
158310  0,                           /* xLanguageid */
158311};
158312
158313/*
158314** Set *ppModule to point at the implementation of the ICU tokenizer.
158315*/
158316SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
158317  sqlite3_tokenizer_module const**ppModule
158318){
158319  *ppModule = &icuTokenizerModule;
158320}
158321
158322#endif /* defined(SQLITE_ENABLE_ICU) */
158323#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
158324
158325/************** End of fts3_icu.c ********************************************/
158326/************** Begin file sqlite3rbu.c **************************************/
158327/*
158328** 2014 August 30
158329**
158330** The author disclaims copyright to this source code.  In place of
158331** a legal notice, here is a blessing:
158332**
158333**    May you do good and not evil.
158334**    May you find forgiveness for yourself and forgive others.
158335**    May you share freely, never taking more than you give.
158336**
158337*************************************************************************
158338**
158339**
158340** OVERVIEW
158341**
158342**  The RBU extension requires that the RBU update be packaged as an
158343**  SQLite database. The tables it expects to find are described in
158344**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
158345**  that the user wishes to write to, a corresponding data_xyz table is
158346**  created in the RBU database and populated with one row for each row to
158347**  update, insert or delete from the target table.
158348**
158349**  The update proceeds in three stages:
158350**
158351**  1) The database is updated. The modified database pages are written
158352**     to a *-oal file. A *-oal file is just like a *-wal file, except
158353**     that it is named "<database>-oal" instead of "<database>-wal".
158354**     Because regular SQLite clients do not look for file named
158355**     "<database>-oal", they go on using the original database in
158356**     rollback mode while the *-oal file is being generated.
158357**
158358**     During this stage RBU does not update the database by writing
158359**     directly to the target tables. Instead it creates "imposter"
158360**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
158361**     to update each b-tree individually. All updates required by each
158362**     b-tree are completed before moving on to the next, and all
158363**     updates are done in sorted key order.
158364**
158365**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
158366**     location using a call to rename(2). Before doing this the RBU
158367**     module takes an EXCLUSIVE lock on the database file, ensuring
158368**     that there are no other active readers.
158369**
158370**     Once the EXCLUSIVE lock is released, any other database readers
158371**     detect the new *-wal file and read the database in wal mode. At
158372**     this point they see the new version of the database - including
158373**     the updates made as part of the RBU update.
158374**
158375**  3) The new *-wal file is checkpointed. This proceeds in the same way
158376**     as a regular database checkpoint, except that a single frame is
158377**     checkpointed each time sqlite3rbu_step() is called. If the RBU
158378**     handle is closed before the entire *-wal file is checkpointed,
158379**     the checkpoint progress is saved in the RBU database and the
158380**     checkpoint can be resumed by another RBU client at some point in
158381**     the future.
158382**
158383** POTENTIAL PROBLEMS
158384**
158385**  The rename() call might not be portable. And RBU is not currently
158386**  syncing the directory after renaming the file.
158387**
158388**  When state is saved, any commit to the *-oal file and the commit to
158389**  the RBU update database are not atomic. So if the power fails at the
158390**  wrong moment they might get out of sync. As the main database will be
158391**  committed before the RBU update database this will likely either just
158392**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
158393**  constraint violations).
158394**
158395**  If some client does modify the target database mid RBU update, or some
158396**  other error occurs, the RBU extension will keep throwing errors. It's
158397**  not really clear how to get out of this state. The system could just
158398**  by delete the RBU update database and *-oal file and have the device
158399**  download the update again and start over.
158400**
158401**  At present, for an UPDATE, both the new.* and old.* records are
158402**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
158403**  fields are collected.  This means we're probably writing a lot more
158404**  data to disk when saving the state of an ongoing update to the RBU
158405**  update database than is strictly necessary.
158406**
158407*/
158408
158409/* #include <assert.h> */
158410/* #include <string.h> */
158411/* #include <stdio.h> */
158412
158413/* #include "sqlite3.h" */
158414
158415#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
158416/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
158417/************** Begin file sqlite3rbu.h **************************************/
158418/*
158419** 2014 August 30
158420**
158421** The author disclaims copyright to this source code.  In place of
158422** a legal notice, here is a blessing:
158423**
158424**    May you do good and not evil.
158425**    May you find forgiveness for yourself and forgive others.
158426**    May you share freely, never taking more than you give.
158427**
158428*************************************************************************
158429**
158430** This file contains the public interface for the RBU extension.
158431*/
158432
158433/*
158434** SUMMARY
158435**
158436** Writing a transaction containing a large number of operations on
158437** b-tree indexes that are collectively larger than the available cache
158438** memory can be very inefficient.
158439**
158440** The problem is that in order to update a b-tree, the leaf page (at least)
158441** containing the entry being inserted or deleted must be modified. If the
158442** working set of leaves is larger than the available cache memory, then a
158443** single leaf that is modified more than once as part of the transaction
158444** may be loaded from or written to the persistent media multiple times.
158445** Additionally, because the index updates are likely to be applied in
158446** random order, access to pages within the database is also likely to be in
158447** random order, which is itself quite inefficient.
158448**
158449** One way to improve the situation is to sort the operations on each index
158450** by index key before applying them to the b-tree. This leads to an IO
158451** pattern that resembles a single linear scan through the index b-tree,
158452** and all but guarantees each modified leaf page is loaded and stored
158453** exactly once. SQLite uses this trick to improve the performance of
158454** CREATE INDEX commands. This extension allows it to be used to improve
158455** the performance of large transactions on existing databases.
158456**
158457** Additionally, this extension allows the work involved in writing the
158458** large transaction to be broken down into sub-transactions performed
158459** sequentially by separate processes. This is useful if the system cannot
158460** guarantee that a single update process will run for long enough to apply
158461** the entire update, for example because the update is being applied on a
158462** mobile device that is frequently rebooted. Even after the writer process
158463** has committed one or more sub-transactions, other database clients continue
158464** to read from the original database snapshot. In other words, partially
158465** applied transactions are not visible to other clients.
158466**
158467** "RBU" stands for "Resumable Bulk Update". As in a large database update
158468** transmitted via a wireless network to a mobile device. A transaction
158469** applied using this extension is hence refered to as an "RBU update".
158470**
158471**
158472** LIMITATIONS
158473**
158474** An "RBU update" transaction is subject to the following limitations:
158475**
158476**   * The transaction must consist of INSERT, UPDATE and DELETE operations
158477**     only.
158478**
158479**   * INSERT statements may not use any default values.
158480**
158481**   * UPDATE and DELETE statements must identify their target rows by
158482**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
158483**     KEY fields may not be updated or deleted. If the table being written
158484**     has no PRIMARY KEY, affected rows must be identified by rowid.
158485**
158486**   * UPDATE statements may not modify PRIMARY KEY columns.
158487**
158488**   * No triggers will be fired.
158489**
158490**   * No foreign key violations are detected or reported.
158491**
158492**   * CHECK constraints are not enforced.
158493**
158494**   * No constraint handling mode except for "OR ROLLBACK" is supported.
158495**
158496**
158497** PREPARATION
158498**
158499** An "RBU update" is stored as a separate SQLite database. A database
158500** containing an RBU update is an "RBU database". For each table in the
158501** target database to be updated, the RBU database should contain a table
158502** named "data_<target name>" containing the same set of columns as the
158503** target table, and one more - "rbu_control". The data_% table should
158504** have no PRIMARY KEY or UNIQUE constraints, but each column should have
158505** the same type as the corresponding column in the target database.
158506** The "rbu_control" column should have no type at all. For example, if
158507** the target database contains:
158508**
158509**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
158510**
158511** Then the RBU database should contain:
158512**
158513**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
158514**
158515** The order of the columns in the data_% table does not matter.
158516**
158517** Instead of a regular table, the RBU database may also contain virtual
158518** tables or view named using the data_<target> naming scheme.
158519**
158520** Instead of the plain data_<target> naming scheme, RBU database tables
158521** may also be named data<integer>_<target>, where <integer> is any sequence
158522** of zero or more numeric characters (0-9). This can be significant because
158523** tables within the RBU database are always processed in order sorted by
158524** name. By judicious selection of the the <integer> portion of the names
158525** of the RBU tables the user can therefore control the order in which they
158526** are processed. This can be useful, for example, to ensure that "external
158527** content" FTS4 tables are updated before their underlying content tables.
158528**
158529** If the target database table is a virtual table or a table that has no
158530** PRIMARY KEY declaration, the data_% table must also contain a column
158531** named "rbu_rowid". This column is mapped to the tables implicit primary
158532** key column - "rowid". Virtual tables for which the "rowid" column does
158533** not function like a primary key value cannot be updated using RBU. For
158534** example, if the target db contains either of the following:
158535**
158536**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
158537**   CREATE TABLE x1(a, b)
158538**
158539** then the RBU database should contain:
158540**
158541**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
158542**
158543** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
158544** target table must be present in the input table. For virtual tables,
158545** hidden columns are optional - they are updated by RBU if present in
158546** the input table, or not otherwise. For example, to write to an fts4
158547** table with a hidden languageid column such as:
158548**
158549**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
158550**
158551** Either of the following input table schemas may be used:
158552**
158553**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
158554**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
158555**
158556** For each row to INSERT into the target database as part of the RBU
158557** update, the corresponding data_% table should contain a single record
158558** with the "rbu_control" column set to contain integer value 0. The
158559** other columns should be set to the values that make up the new record
158560** to insert.
158561**
158562** If the target database table has an INTEGER PRIMARY KEY, it is not
158563** possible to insert a NULL value into the IPK column. Attempting to
158564** do so results in an SQLITE_MISMATCH error.
158565**
158566** For each row to DELETE from the target database as part of the RBU
158567** update, the corresponding data_% table should contain a single record
158568** with the "rbu_control" column set to contain integer value 1. The
158569** real primary key values of the row to delete should be stored in the
158570** corresponding columns of the data_% table. The values stored in the
158571** other columns are not used.
158572**
158573** For each row to UPDATE from the target database as part of the RBU
158574** update, the corresponding data_% table should contain a single record
158575** with the "rbu_control" column set to contain a value of type text.
158576** The real primary key values identifying the row to update should be
158577** stored in the corresponding columns of the data_% table row, as should
158578** the new values of all columns being update. The text value in the
158579** "rbu_control" column must contain the same number of characters as
158580** there are columns in the target database table, and must consist entirely
158581** of 'x' and '.' characters (or in some special cases 'd' - see below). For
158582** each column that is being updated, the corresponding character is set to
158583** 'x'. For those that remain as they are, the corresponding character of the
158584** rbu_control value should be set to '.'. For example, given the tables
158585** above, the update statement:
158586**
158587**   UPDATE t1 SET c = 'usa' WHERE a = 4;
158588**
158589** is represented by the data_t1 row created by:
158590**
158591**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
158592**
158593** Instead of an 'x' character, characters of the rbu_control value specified
158594** for UPDATEs may also be set to 'd'. In this case, instead of updating the
158595** target table with the value stored in the corresponding data_% column, the
158596** user-defined SQL function "rbu_delta()" is invoked and the result stored in
158597** the target table column. rbu_delta() is invoked with two arguments - the
158598** original value currently stored in the target table column and the
158599** value specified in the data_xxx table.
158600**
158601** For example, this row:
158602**
158603**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
158604**
158605** is similar to an UPDATE statement such as:
158606**
158607**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
158608**
158609** Finally, if an 'f' character appears in place of a 'd' or 's' in an
158610** ota_control string, the contents of the data_xxx table column is assumed
158611** to be a "fossil delta" - a patch to be applied to a blob value in the
158612** format used by the fossil source-code management system. In this case
158613** the existing value within the target database table must be of type BLOB.
158614** It is replaced by the result of applying the specified fossil delta to
158615** itself.
158616**
158617** If the target database table is a virtual table or a table with no PRIMARY
158618** KEY, the rbu_control value should not include a character corresponding
158619** to the rbu_rowid value. For example, this:
158620**
158621**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
158622**       VALUES(NULL, 'usa', 12, '.x');
158623**
158624** causes a result similar to:
158625**
158626**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
158627**
158628** The data_xxx tables themselves should have no PRIMARY KEY declarations.
158629** However, RBU is more efficient if reading the rows in from each data_xxx
158630** table in "rowid" order is roughly the same as reading them sorted by
158631** the PRIMARY KEY of the corresponding target database table. In other
158632** words, rows should be sorted using the destination table PRIMARY KEY
158633** fields before they are inserted into the data_xxx tables.
158634**
158635** USAGE
158636**
158637** The API declared below allows an application to apply an RBU update
158638** stored on disk to an existing target database. Essentially, the
158639** application:
158640**
158641**     1) Opens an RBU handle using the sqlite3rbu_open() function.
158642**
158643**     2) Registers any required virtual table modules with the database
158644**        handle returned by sqlite3rbu_db(). Also, if required, register
158645**        the rbu_delta() implementation.
158646**
158647**     3) Calls the sqlite3rbu_step() function one or more times on
158648**        the new handle. Each call to sqlite3rbu_step() performs a single
158649**        b-tree operation, so thousands of calls may be required to apply
158650**        a complete update.
158651**
158652**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
158653**        sqlite3rbu_step() has been called enough times to completely
158654**        apply the update to the target database, then the RBU database
158655**        is marked as fully applied. Otherwise, the state of the RBU
158656**        update application is saved in the RBU database for later
158657**        resumption.
158658**
158659** See comments below for more detail on APIs.
158660**
158661** If an update is only partially applied to the target database by the
158662** time sqlite3rbu_close() is called, various state information is saved
158663** within the RBU database. This allows subsequent processes to automatically
158664** resume the RBU update from where it left off.
158665**
158666** To remove all RBU extension state information, returning an RBU database
158667** to its original contents, it is sufficient to drop all tables that begin
158668** with the prefix "rbu_"
158669**
158670** DATABASE LOCKING
158671**
158672** An RBU update may not be applied to a database in WAL mode. Attempting
158673** to do so is an error (SQLITE_ERROR).
158674**
158675** While an RBU handle is open, a SHARED lock may be held on the target
158676** database file. This means it is possible for other clients to read the
158677** database, but not to write it.
158678**
158679** If an RBU update is started and then suspended before it is completed,
158680** then an external client writes to the database, then attempting to resume
158681** the suspended RBU update is also an error (SQLITE_BUSY).
158682*/
158683
158684#ifndef _SQLITE3RBU_H
158685#define _SQLITE3RBU_H
158686
158687/* #include "sqlite3.h"              ** Required for error code definitions ** */
158688
158689#if 0
158690extern "C" {
158691#endif
158692
158693typedef struct sqlite3rbu sqlite3rbu;
158694
158695/*
158696** Open an RBU handle.
158697**
158698** Argument zTarget is the path to the target database. Argument zRbu is
158699** the path to the RBU database. Each call to this function must be matched
158700** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
158701** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
158702** or zRbu begin with "file:", it will be interpreted as an SQLite
158703** database URI, not a regular file name.
158704**
158705** If the zState argument is passed a NULL value, the RBU extension stores
158706** the current state of the update (how many rows have been updated, which
158707** indexes are yet to be updated etc.) within the RBU database itself. This
158708** can be convenient, as it means that the RBU application does not need to
158709** organize removing a separate state file after the update is concluded.
158710** Or, if zState is non-NULL, it must be a path to a database file in which
158711** the RBU extension can store the state of the update.
158712**
158713** When resuming an RBU update, the zState argument must be passed the same
158714** value as when the RBU update was started.
158715**
158716** Once the RBU update is finished, the RBU extension does not
158717** automatically remove any zState database file, even if it created it.
158718**
158719** By default, RBU uses the default VFS to access the files on disk. To
158720** use a VFS other than the default, an SQLite "file:" URI containing a
158721** "vfs=..." option may be passed as the zTarget option.
158722**
158723** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
158724** SQLite's built-in VFSs, including the multiplexor VFS. However it does
158725** not work out of the box with zipvfs. Refer to the comment describing
158726** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
158727*/
158728SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
158729  const char *zTarget,
158730  const char *zRbu,
158731  const char *zState
158732);
158733
158734/*
158735** Internally, each RBU connection uses a separate SQLite database
158736** connection to access the target and rbu update databases. This
158737** API allows the application direct access to these database handles.
158738**
158739** The first argument passed to this function must be a valid, open, RBU
158740** handle. The second argument should be passed zero to access the target
158741** database handle, or non-zero to access the rbu update database handle.
158742** Accessing the underlying database handles may be useful in the
158743** following scenarios:
158744**
158745**   * If any target tables are virtual tables, it may be necessary to
158746**     call sqlite3_create_module() on the target database handle to
158747**     register the required virtual table implementations.
158748**
158749**   * If the data_xxx tables in the RBU source database are virtual
158750**     tables, the application may need to call sqlite3_create_module() on
158751**     the rbu update db handle to any required virtual table
158752**     implementations.
158753**
158754**   * If the application uses the "rbu_delta()" feature described above,
158755**     it must use sqlite3_create_function() or similar to register the
158756**     rbu_delta() implementation with the target database handle.
158757**
158758** If an error has occurred, either while opening or stepping the RBU object,
158759** this function may return NULL. The error code and message may be collected
158760** when sqlite3rbu_close() is called.
158761*/
158762SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
158763
158764/*
158765** Do some work towards applying the RBU update to the target db.
158766**
158767** Return SQLITE_DONE if the update has been completely applied, or
158768** SQLITE_OK if no error occurs but there remains work to do to apply
158769** the RBU update. If an error does occur, some other error code is
158770** returned.
158771**
158772** Once a call to sqlite3rbu_step() has returned a value other than
158773** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
158774** that immediately return the same value.
158775*/
158776SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
158777
158778/*
158779** Force RBU to save its state to disk.
158780**
158781** If a power failure or application crash occurs during an update, following
158782** system recovery RBU may resume the update from the point at which the state
158783** was last saved. In other words, from the most recent successful call to
158784** sqlite3rbu_close() or this function.
158785**
158786** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
158787*/
158788SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
158789
158790/*
158791** Close an RBU handle.
158792**
158793** If the RBU update has been completely applied, mark the RBU database
158794** as fully applied. Otherwise, assuming no error has occurred, save the
158795** current state of the RBU update appliation to the RBU database.
158796**
158797** If an error has already occurred as part of an sqlite3rbu_step()
158798** or sqlite3rbu_open() call, or if one occurs within this function, an
158799** SQLite error code is returned. Additionally, *pzErrmsg may be set to
158800** point to a buffer containing a utf-8 formatted English language error
158801** message. It is the responsibility of the caller to eventually free any
158802** such buffer using sqlite3_free().
158803**
158804** Otherwise, if no error occurs, this function returns SQLITE_OK if the
158805** update has been partially applied, or SQLITE_DONE if it has been
158806** completely applied.
158807*/
158808SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
158809
158810/*
158811** Return the total number of key-value operations (inserts, deletes or
158812** updates) that have been performed on the target database since the
158813** current RBU update was started.
158814*/
158815SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
158816
158817/*
158818** Create an RBU VFS named zName that accesses the underlying file-system
158819** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
158820** then the new RBU VFS uses the default system VFS to access the file-system.
158821** The new object is registered as a non-default VFS with SQLite before
158822** returning.
158823**
158824** Part of the RBU implementation uses a custom VFS object. Usually, this
158825** object is created and deleted automatically by RBU.
158826**
158827** The exception is for applications that also use zipvfs. In this case,
158828** the custom VFS must be explicitly created by the user before the RBU
158829** handle is opened. The RBU VFS should be installed so that the zipvfs
158830** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
158831** (for example multiplexor) to access the file-system. For example,
158832** to assemble an RBU enabled VFS stack that uses both zipvfs and
158833** multiplexor (error checking omitted):
158834**
158835**     // Create a VFS named "multiplex" (not the default).
158836**     sqlite3_multiplex_initialize(0, 0);
158837**
158838**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
158839**     // second argument were replaced with NULL, the "rbu" VFS would
158840**     // access the file-system via the system default VFS, bypassing the
158841**     // multiplexor.
158842**     sqlite3rbu_create_vfs("rbu", "multiplex");
158843**
158844**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
158845**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
158846**
158847**     // Make zipvfs the default VFS.
158848**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
158849**
158850** Because the default VFS created above includes a RBU functionality, it
158851** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
158852** that does not include the RBU layer results in an error.
158853**
158854** The overhead of adding the "rbu" VFS to the system is negligible for
158855** non-RBU users. There is no harm in an application accessing the
158856** file-system via "rbu" all the time, even if it only uses RBU functionality
158857** occasionally.
158858*/
158859SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
158860
158861/*
158862** Deregister and destroy an RBU vfs created by an earlier call to
158863** sqlite3rbu_create_vfs().
158864**
158865** VFS objects are not reference counted. If a VFS object is destroyed
158866** before all database handles that use it have been closed, the results
158867** are undefined.
158868*/
158869SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
158870
158871#if 0
158872}  /* end of the 'extern "C"' block */
158873#endif
158874
158875#endif /* _SQLITE3RBU_H */
158876
158877/************** End of sqlite3rbu.h ******************************************/
158878/************** Continuing where we left off in sqlite3rbu.c *****************/
158879
158880#if defined(_WIN32_WCE)
158881/* #include "windows.h" */
158882#endif
158883
158884/* Maximum number of prepared UPDATE statements held by this module */
158885#define SQLITE_RBU_UPDATE_CACHESIZE 16
158886
158887/*
158888** Swap two objects of type TYPE.
158889*/
158890#if !defined(SQLITE_AMALGAMATION)
158891# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
158892#endif
158893
158894/*
158895** The rbu_state table is used to save the state of a partially applied
158896** update so that it can be resumed later. The table consists of integer
158897** keys mapped to values as follows:
158898**
158899** RBU_STATE_STAGE:
158900**   May be set to integer values 1, 2, 4 or 5. As follows:
158901**       1: the *-rbu file is currently under construction.
158902**       2: the *-rbu file has been constructed, but not yet moved
158903**          to the *-wal path.
158904**       4: the checkpoint is underway.
158905**       5: the rbu update has been checkpointed.
158906**
158907** RBU_STATE_TBL:
158908**   Only valid if STAGE==1. The target database name of the table
158909**   currently being written.
158910**
158911** RBU_STATE_IDX:
158912**   Only valid if STAGE==1. The target database name of the index
158913**   currently being written, or NULL if the main table is currently being
158914**   updated.
158915**
158916** RBU_STATE_ROW:
158917**   Only valid if STAGE==1. Number of rows already processed for the current
158918**   table/index.
158919**
158920** RBU_STATE_PROGRESS:
158921**   Trbul number of sqlite3rbu_step() calls made so far as part of this
158922**   rbu update.
158923**
158924** RBU_STATE_CKPT:
158925**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
158926**   header created by recovering the *-wal file. This is used to detect
158927**   cases when another client appends frames to the *-wal file in the
158928**   middle of an incremental checkpoint (an incremental checkpoint cannot
158929**   be continued if this happens).
158930**
158931** RBU_STATE_COOKIE:
158932**   Valid if STAGE==1. The current change-counter cookie value in the
158933**   target db file.
158934**
158935** RBU_STATE_OALSZ:
158936**   Valid if STAGE==1. The size in bytes of the *-oal file.
158937*/
158938#define RBU_STATE_STAGE       1
158939#define RBU_STATE_TBL         2
158940#define RBU_STATE_IDX         3
158941#define RBU_STATE_ROW         4
158942#define RBU_STATE_PROGRESS    5
158943#define RBU_STATE_CKPT        6
158944#define RBU_STATE_COOKIE      7
158945#define RBU_STATE_OALSZ       8
158946
158947#define RBU_STAGE_OAL         1
158948#define RBU_STAGE_MOVE        2
158949#define RBU_STAGE_CAPTURE     3
158950#define RBU_STAGE_CKPT        4
158951#define RBU_STAGE_DONE        5
158952
158953
158954#define RBU_CREATE_STATE \
158955  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
158956
158957typedef struct RbuFrame RbuFrame;
158958typedef struct RbuObjIter RbuObjIter;
158959typedef struct RbuState RbuState;
158960typedef struct rbu_vfs rbu_vfs;
158961typedef struct rbu_file rbu_file;
158962typedef struct RbuUpdateStmt RbuUpdateStmt;
158963
158964#if !defined(SQLITE_AMALGAMATION)
158965typedef unsigned int u32;
158966typedef unsigned char u8;
158967typedef sqlite3_int64 i64;
158968#endif
158969
158970/*
158971** These values must match the values defined in wal.c for the equivalent
158972** locks. These are not magic numbers as they are part of the SQLite file
158973** format.
158974*/
158975#define WAL_LOCK_WRITE  0
158976#define WAL_LOCK_CKPT   1
158977#define WAL_LOCK_READ0  3
158978
158979/*
158980** A structure to store values read from the rbu_state table in memory.
158981*/
158982struct RbuState {
158983  int eStage;
158984  char *zTbl;
158985  char *zIdx;
158986  i64 iWalCksum;
158987  int nRow;
158988  i64 nProgress;
158989  u32 iCookie;
158990  i64 iOalSz;
158991};
158992
158993struct RbuUpdateStmt {
158994  char *zMask;                    /* Copy of update mask used with pUpdate */
158995  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
158996  RbuUpdateStmt *pNext;
158997};
158998
158999/*
159000** An iterator of this type is used to iterate through all objects in
159001** the target database that require updating. For each such table, the
159002** iterator visits, in order:
159003**
159004**     * the table itself,
159005**     * each index of the table (zero or more points to visit), and
159006**     * a special "cleanup table" state.
159007**
159008** abIndexed:
159009**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
159010**   it points to an array of flags nTblCol elements in size. The flag is
159011**   set for each column that is either a part of the PK or a part of an
159012**   index. Or clear otherwise.
159013**
159014*/
159015struct RbuObjIter {
159016  sqlite3_stmt *pTblIter;         /* Iterate through tables */
159017  sqlite3_stmt *pIdxIter;         /* Index iterator */
159018  int nTblCol;                    /* Size of azTblCol[] array */
159019  char **azTblCol;                /* Array of unquoted target column names */
159020  char **azTblType;               /* Array of target column types */
159021  int *aiSrcOrder;                /* src table col -> target table col */
159022  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
159023  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
159024  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
159025  int eType;                      /* Table type - an RBU_PK_XXX value */
159026
159027  /* Output variables. zTbl==0 implies EOF. */
159028  int bCleanup;                   /* True in "cleanup" state */
159029  const char *zTbl;               /* Name of target db table */
159030  const char *zDataTbl;           /* Name of rbu db table (or null) */
159031  const char *zIdx;               /* Name of target db index (or null) */
159032  int iTnum;                      /* Root page of current object */
159033  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
159034  int bUnique;                    /* Current index is unique */
159035
159036  /* Statements created by rbuObjIterPrepareAll() */
159037  int nCol;                       /* Number of columns in current object */
159038  sqlite3_stmt *pSelect;          /* Source data */
159039  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
159040  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
159041  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
159042
159043  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
159044  RbuUpdateStmt *pRbuUpdate;
159045};
159046
159047/*
159048** Values for RbuObjIter.eType
159049**
159050**     0: Table does not exist (error)
159051**     1: Table has an implicit rowid.
159052**     2: Table has an explicit IPK column.
159053**     3: Table has an external PK index.
159054**     4: Table is WITHOUT ROWID.
159055**     5: Table is a virtual table.
159056*/
159057#define RBU_PK_NOTABLE        0
159058#define RBU_PK_NONE           1
159059#define RBU_PK_IPK            2
159060#define RBU_PK_EXTERNAL       3
159061#define RBU_PK_WITHOUT_ROWID  4
159062#define RBU_PK_VTAB           5
159063
159064
159065/*
159066** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
159067** one of the following operations.
159068*/
159069#define RBU_INSERT     1          /* Insert on a main table b-tree */
159070#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
159071#define RBU_IDX_DELETE 3          /* Delete a row from an aux. index b-tree */
159072#define RBU_IDX_INSERT 4          /* Insert on an aux. index b-tree */
159073#define RBU_UPDATE     5          /* Update a row in a main table b-tree */
159074
159075
159076/*
159077** A single step of an incremental checkpoint - frame iWalFrame of the wal
159078** file should be copied to page iDbPage of the database file.
159079*/
159080struct RbuFrame {
159081  u32 iDbPage;
159082  u32 iWalFrame;
159083};
159084
159085/*
159086** RBU handle.
159087*/
159088struct sqlite3rbu {
159089  int eStage;                     /* Value of RBU_STATE_STAGE field */
159090  sqlite3 *dbMain;                /* target database handle */
159091  sqlite3 *dbRbu;                 /* rbu database handle */
159092  char *zTarget;                  /* Path to target db */
159093  char *zRbu;                     /* Path to rbu db */
159094  char *zState;                   /* Path to state db (or NULL if zRbu) */
159095  char zStateDb[5];               /* Db name for state ("stat" or "main") */
159096  int rc;                         /* Value returned by last rbu_step() call */
159097  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
159098  int nStep;                      /* Rows processed for current object */
159099  int nProgress;                  /* Rows processed for all objects */
159100  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
159101  const char *zVfsName;           /* Name of automatically created rbu vfs */
159102  rbu_file *pTargetFd;            /* File handle open on target db */
159103  i64 iOalSz;
159104
159105  /* The following state variables are used as part of the incremental
159106  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
159107  ** function rbuSetupCheckpoint() for details.  */
159108  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
159109  u32 mLock;
159110  int nFrame;                     /* Entries in aFrame[] array */
159111  int nFrameAlloc;                /* Allocated size of aFrame[] array */
159112  RbuFrame *aFrame;
159113  int pgsz;
159114  u8 *aBuf;
159115  i64 iWalCksum;
159116};
159117
159118/*
159119** An rbu VFS is implemented using an instance of this structure.
159120*/
159121struct rbu_vfs {
159122  sqlite3_vfs base;               /* rbu VFS shim methods */
159123  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
159124  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
159125  rbu_file *pMain;                /* Linked list of main db files */
159126};
159127
159128/*
159129** Each file opened by an rbu VFS is represented by an instance of
159130** the following structure.
159131*/
159132struct rbu_file {
159133  sqlite3_file base;              /* sqlite3_file methods */
159134  sqlite3_file *pReal;            /* Underlying file handle */
159135  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
159136  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
159137
159138  int openFlags;                  /* Flags this file was opened with */
159139  u32 iCookie;                    /* Cookie value for main db files */
159140  u8 iWriteVer;                   /* "write-version" value for main db files */
159141
159142  int nShm;                       /* Number of entries in apShm[] array */
159143  char **apShm;                   /* Array of mmap'd *-shm regions */
159144  char *zDel;                     /* Delete this when closing file */
159145
159146  const char *zWal;               /* Wal filename for this main db file */
159147  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
159148  rbu_file *pMainNext;            /* Next MAIN_DB file */
159149};
159150
159151
159152/*************************************************************************
159153** The following three functions, found below:
159154**
159155**   rbuDeltaGetInt()
159156**   rbuDeltaChecksum()
159157**   rbuDeltaApply()
159158**
159159** are lifted from the fossil source code (http://fossil-scm.org). They
159160** are used to implement the scalar SQL function rbu_fossil_delta().
159161*/
159162
159163/*
159164** Read bytes from *pz and convert them into a positive integer.  When
159165** finished, leave *pz pointing to the first character past the end of
159166** the integer.  The *pLen parameter holds the length of the string
159167** in *pz and is decremented once for each character in the integer.
159168*/
159169static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
159170  static const signed char zValue[] = {
159171    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159172    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159173    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159174     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
159175    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
159176    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
159177    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
159178    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
159179  };
159180  unsigned int v = 0;
159181  int c;
159182  unsigned char *z = (unsigned char*)*pz;
159183  unsigned char *zStart = z;
159184  while( (c = zValue[0x7f&*(z++)])>=0 ){
159185     v = (v<<6) + c;
159186  }
159187  z--;
159188  *pLen -= z - zStart;
159189  *pz = (char*)z;
159190  return v;
159191}
159192
159193/*
159194** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
159195*/
159196static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
159197  const unsigned char *z = (const unsigned char *)zIn;
159198  unsigned sum0 = 0;
159199  unsigned sum1 = 0;
159200  unsigned sum2 = 0;
159201  unsigned sum3 = 0;
159202  while(N >= 16){
159203    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
159204    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
159205    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
159206    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
159207    z += 16;
159208    N -= 16;
159209  }
159210  while(N >= 4){
159211    sum0 += z[0];
159212    sum1 += z[1];
159213    sum2 += z[2];
159214    sum3 += z[3];
159215    z += 4;
159216    N -= 4;
159217  }
159218  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
159219  switch(N){
159220    case 3:   sum3 += (z[2] << 8);
159221    case 2:   sum3 += (z[1] << 16);
159222    case 1:   sum3 += (z[0] << 24);
159223    default:  ;
159224  }
159225  return sum3;
159226}
159227
159228/*
159229** Apply a delta.
159230**
159231** The output buffer should be big enough to hold the whole output
159232** file and a NUL terminator at the end.  The delta_output_size()
159233** routine will determine this size for you.
159234**
159235** The delta string should be null-terminated.  But the delta string
159236** may contain embedded NUL characters (if the input and output are
159237** binary files) so we also have to pass in the length of the delta in
159238** the lenDelta parameter.
159239**
159240** This function returns the size of the output file in bytes (excluding
159241** the final NUL terminator character).  Except, if the delta string is
159242** malformed or intended for use with a source file other than zSrc,
159243** then this routine returns -1.
159244**
159245** Refer to the delta_create() documentation above for a description
159246** of the delta file format.
159247*/
159248static int rbuDeltaApply(
159249  const char *zSrc,      /* The source or pattern file */
159250  int lenSrc,            /* Length of the source file */
159251  const char *zDelta,    /* Delta to apply to the pattern */
159252  int lenDelta,          /* Length of the delta */
159253  char *zOut             /* Write the output into this preallocated buffer */
159254){
159255  unsigned int limit;
159256  unsigned int total = 0;
159257#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
159258  char *zOrigOut = zOut;
159259#endif
159260
159261  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
159262  if( *zDelta!='\n' ){
159263    /* ERROR: size integer not terminated by "\n" */
159264    return -1;
159265  }
159266  zDelta++; lenDelta--;
159267  while( *zDelta && lenDelta>0 ){
159268    unsigned int cnt, ofst;
159269    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
159270    switch( zDelta[0] ){
159271      case '@': {
159272        zDelta++; lenDelta--;
159273        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
159274        if( lenDelta>0 && zDelta[0]!=',' ){
159275          /* ERROR: copy command not terminated by ',' */
159276          return -1;
159277        }
159278        zDelta++; lenDelta--;
159279        total += cnt;
159280        if( total>limit ){
159281          /* ERROR: copy exceeds output file size */
159282          return -1;
159283        }
159284        if( (int)(ofst+cnt) > lenSrc ){
159285          /* ERROR: copy extends past end of input */
159286          return -1;
159287        }
159288        memcpy(zOut, &zSrc[ofst], cnt);
159289        zOut += cnt;
159290        break;
159291      }
159292      case ':': {
159293        zDelta++; lenDelta--;
159294        total += cnt;
159295        if( total>limit ){
159296          /* ERROR:  insert command gives an output larger than predicted */
159297          return -1;
159298        }
159299        if( (int)cnt>lenDelta ){
159300          /* ERROR: insert count exceeds size of delta */
159301          return -1;
159302        }
159303        memcpy(zOut, zDelta, cnt);
159304        zOut += cnt;
159305        zDelta += cnt;
159306        lenDelta -= cnt;
159307        break;
159308      }
159309      case ';': {
159310        zDelta++; lenDelta--;
159311        zOut[0] = 0;
159312#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
159313        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
159314          /* ERROR:  bad checksum */
159315          return -1;
159316        }
159317#endif
159318        if( total!=limit ){
159319          /* ERROR: generated size does not match predicted size */
159320          return -1;
159321        }
159322        return total;
159323      }
159324      default: {
159325        /* ERROR: unknown delta operator */
159326        return -1;
159327      }
159328    }
159329  }
159330  /* ERROR: unterminated delta */
159331  return -1;
159332}
159333
159334static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
159335  int size;
159336  size = rbuDeltaGetInt(&zDelta, &lenDelta);
159337  if( *zDelta!='\n' ){
159338    /* ERROR: size integer not terminated by "\n" */
159339    return -1;
159340  }
159341  return size;
159342}
159343
159344/*
159345** End of code taken from fossil.
159346*************************************************************************/
159347
159348/*
159349** Implementation of SQL scalar function rbu_fossil_delta().
159350**
159351** This function applies a fossil delta patch to a blob. Exactly two
159352** arguments must be passed to this function. The first is the blob to
159353** patch and the second the patch to apply. If no error occurs, this
159354** function returns the patched blob.
159355*/
159356static void rbuFossilDeltaFunc(
159357  sqlite3_context *context,
159358  int argc,
159359  sqlite3_value **argv
159360){
159361  const char *aDelta;
159362  int nDelta;
159363  const char *aOrig;
159364  int nOrig;
159365
159366  int nOut;
159367  int nOut2;
159368  char *aOut;
159369
159370  assert( argc==2 );
159371
159372  nOrig = sqlite3_value_bytes(argv[0]);
159373  aOrig = (const char*)sqlite3_value_blob(argv[0]);
159374  nDelta = sqlite3_value_bytes(argv[1]);
159375  aDelta = (const char*)sqlite3_value_blob(argv[1]);
159376
159377  /* Figure out the size of the output */
159378  nOut = rbuDeltaOutputSize(aDelta, nDelta);
159379  if( nOut<0 ){
159380    sqlite3_result_error(context, "corrupt fossil delta", -1);
159381    return;
159382  }
159383
159384  aOut = sqlite3_malloc(nOut+1);
159385  if( aOut==0 ){
159386    sqlite3_result_error_nomem(context);
159387  }else{
159388    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
159389    if( nOut2!=nOut ){
159390      sqlite3_result_error(context, "corrupt fossil delta", -1);
159391    }else{
159392      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
159393    }
159394  }
159395}
159396
159397
159398/*
159399** Prepare the SQL statement in buffer zSql against database handle db.
159400** If successful, set *ppStmt to point to the new statement and return
159401** SQLITE_OK.
159402**
159403** Otherwise, if an error does occur, set *ppStmt to NULL and return
159404** an SQLite error code. Additionally, set output variable *pzErrmsg to
159405** point to a buffer containing an error message. It is the responsibility
159406** of the caller to (eventually) free this buffer using sqlite3_free().
159407*/
159408static int prepareAndCollectError(
159409  sqlite3 *db,
159410  sqlite3_stmt **ppStmt,
159411  char **pzErrmsg,
159412  const char *zSql
159413){
159414  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
159415  if( rc!=SQLITE_OK ){
159416    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
159417    *ppStmt = 0;
159418  }
159419  return rc;
159420}
159421
159422/*
159423** Reset the SQL statement passed as the first argument. Return a copy
159424** of the value returned by sqlite3_reset().
159425**
159426** If an error has occurred, then set *pzErrmsg to point to a buffer
159427** containing an error message. It is the responsibility of the caller
159428** to eventually free this buffer using sqlite3_free().
159429*/
159430static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
159431  int rc = sqlite3_reset(pStmt);
159432  if( rc!=SQLITE_OK ){
159433    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
159434  }
159435  return rc;
159436}
159437
159438/*
159439** Unless it is NULL, argument zSql points to a buffer allocated using
159440** sqlite3_malloc containing an SQL statement. This function prepares the SQL
159441** statement against database db and frees the buffer. If statement
159442** compilation is successful, *ppStmt is set to point to the new statement
159443** handle and SQLITE_OK is returned.
159444**
159445** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
159446** returned. In this case, *pzErrmsg may also be set to point to an error
159447** message. It is the responsibility of the caller to free this error message
159448** buffer using sqlite3_free().
159449**
159450** If argument zSql is NULL, this function assumes that an OOM has occurred.
159451** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
159452*/
159453static int prepareFreeAndCollectError(
159454  sqlite3 *db,
159455  sqlite3_stmt **ppStmt,
159456  char **pzErrmsg,
159457  char *zSql
159458){
159459  int rc;
159460  assert( *pzErrmsg==0 );
159461  if( zSql==0 ){
159462    rc = SQLITE_NOMEM;
159463    *ppStmt = 0;
159464  }else{
159465    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
159466    sqlite3_free(zSql);
159467  }
159468  return rc;
159469}
159470
159471/*
159472** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
159473** by an earlier call to rbuObjIterCacheTableInfo().
159474*/
159475static void rbuObjIterFreeCols(RbuObjIter *pIter){
159476  int i;
159477  for(i=0; i<pIter->nTblCol; i++){
159478    sqlite3_free(pIter->azTblCol[i]);
159479    sqlite3_free(pIter->azTblType[i]);
159480  }
159481  sqlite3_free(pIter->azTblCol);
159482  pIter->azTblCol = 0;
159483  pIter->azTblType = 0;
159484  pIter->aiSrcOrder = 0;
159485  pIter->abTblPk = 0;
159486  pIter->abNotNull = 0;
159487  pIter->nTblCol = 0;
159488  pIter->eType = 0;               /* Invalid value */
159489}
159490
159491/*
159492** Finalize all statements and free all allocations that are specific to
159493** the current object (table/index pair).
159494*/
159495static void rbuObjIterClearStatements(RbuObjIter *pIter){
159496  RbuUpdateStmt *pUp;
159497
159498  sqlite3_finalize(pIter->pSelect);
159499  sqlite3_finalize(pIter->pInsert);
159500  sqlite3_finalize(pIter->pDelete);
159501  sqlite3_finalize(pIter->pTmpInsert);
159502  pUp = pIter->pRbuUpdate;
159503  while( pUp ){
159504    RbuUpdateStmt *pTmp = pUp->pNext;
159505    sqlite3_finalize(pUp->pUpdate);
159506    sqlite3_free(pUp);
159507    pUp = pTmp;
159508  }
159509
159510  pIter->pSelect = 0;
159511  pIter->pInsert = 0;
159512  pIter->pDelete = 0;
159513  pIter->pRbuUpdate = 0;
159514  pIter->pTmpInsert = 0;
159515  pIter->nCol = 0;
159516}
159517
159518/*
159519** Clean up any resources allocated as part of the iterator object passed
159520** as the only argument.
159521*/
159522static void rbuObjIterFinalize(RbuObjIter *pIter){
159523  rbuObjIterClearStatements(pIter);
159524  sqlite3_finalize(pIter->pTblIter);
159525  sqlite3_finalize(pIter->pIdxIter);
159526  rbuObjIterFreeCols(pIter);
159527  memset(pIter, 0, sizeof(RbuObjIter));
159528}
159529
159530/*
159531** Advance the iterator to the next position.
159532**
159533** If no error occurs, SQLITE_OK is returned and the iterator is left
159534** pointing to the next entry. Otherwise, an error code and message is
159535** left in the RBU handle passed as the first argument. A copy of the
159536** error code is returned.
159537*/
159538static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
159539  int rc = p->rc;
159540  if( rc==SQLITE_OK ){
159541
159542    /* Free any SQLite statements used while processing the previous object */
159543    rbuObjIterClearStatements(pIter);
159544    if( pIter->zIdx==0 ){
159545      rc = sqlite3_exec(p->dbMain,
159546          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
159547          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
159548          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
159549          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
159550          , 0, 0, &p->zErrmsg
159551      );
159552    }
159553
159554    if( rc==SQLITE_OK ){
159555      if( pIter->bCleanup ){
159556        rbuObjIterFreeCols(pIter);
159557        pIter->bCleanup = 0;
159558        rc = sqlite3_step(pIter->pTblIter);
159559        if( rc!=SQLITE_ROW ){
159560          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
159561          pIter->zTbl = 0;
159562        }else{
159563          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
159564          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
159565          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
159566        }
159567      }else{
159568        if( pIter->zIdx==0 ){
159569          sqlite3_stmt *pIdx = pIter->pIdxIter;
159570          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
159571        }
159572        if( rc==SQLITE_OK ){
159573          rc = sqlite3_step(pIter->pIdxIter);
159574          if( rc!=SQLITE_ROW ){
159575            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
159576            pIter->bCleanup = 1;
159577            pIter->zIdx = 0;
159578          }else{
159579            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
159580            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
159581            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
159582            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
159583          }
159584        }
159585      }
159586    }
159587  }
159588
159589  if( rc!=SQLITE_OK ){
159590    rbuObjIterFinalize(pIter);
159591    p->rc = rc;
159592  }
159593  return rc;
159594}
159595
159596
159597/*
159598** The implementation of the rbu_target_name() SQL function. This function
159599** accepts one argument - the name of a table in the RBU database. If the
159600** table name matches the pattern:
159601**
159602**     data[0-9]_<name>
159603**
159604** where <name> is any sequence of 1 or more characters, <name> is returned.
159605** Otherwise, if the only argument does not match the above pattern, an SQL
159606** NULL is returned.
159607**
159608**     "data_t1"     -> "t1"
159609**     "data0123_t2" -> "t2"
159610**     "dataAB_t3"   -> NULL
159611*/
159612static void rbuTargetNameFunc(
159613  sqlite3_context *context,
159614  int argc,
159615  sqlite3_value **argv
159616){
159617  const char *zIn;
159618  assert( argc==1 );
159619
159620  zIn = (const char*)sqlite3_value_text(argv[0]);
159621  if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
159622    int i;
159623    for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
159624    if( zIn[i]=='_' && zIn[i+1] ){
159625      sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
159626    }
159627  }
159628}
159629
159630/*
159631** Initialize the iterator structure passed as the second argument.
159632**
159633** If no error occurs, SQLITE_OK is returned and the iterator is left
159634** pointing to the first entry. Otherwise, an error code and message is
159635** left in the RBU handle passed as the first argument. A copy of the
159636** error code is returned.
159637*/
159638static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
159639  int rc;
159640  memset(pIter, 0, sizeof(RbuObjIter));
159641
159642  rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
159643      "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
159644      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
159645      "ORDER BY name"
159646  );
159647
159648  if( rc==SQLITE_OK ){
159649    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
159650        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
159651        "  FROM main.sqlite_master "
159652        "  WHERE type='index' AND tbl_name = ?"
159653    );
159654  }
159655
159656  pIter->bCleanup = 1;
159657  p->rc = rc;
159658  return rbuObjIterNext(p, pIter);
159659}
159660
159661/*
159662** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
159663** an error code is stored in the RBU handle passed as the first argument.
159664**
159665** If an error has already occurred (p->rc is already set to something other
159666** than SQLITE_OK), then this function returns NULL without modifying the
159667** stored error code. In this case it still calls sqlite3_free() on any
159668** printf() parameters associated with %z conversions.
159669*/
159670static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
159671  char *zSql = 0;
159672  va_list ap;
159673  va_start(ap, zFmt);
159674  zSql = sqlite3_vmprintf(zFmt, ap);
159675  if( p->rc==SQLITE_OK ){
159676    if( zSql==0 ) p->rc = SQLITE_NOMEM;
159677  }else{
159678    sqlite3_free(zSql);
159679    zSql = 0;
159680  }
159681  va_end(ap);
159682  return zSql;
159683}
159684
159685/*
159686** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
159687** arguments are the usual subsitution values. This function performs
159688** the printf() style substitutions and executes the result as an SQL
159689** statement on the RBU handles database.
159690**
159691** If an error occurs, an error code and error message is stored in the
159692** RBU handle. If an error has already occurred when this function is
159693** called, it is a no-op.
159694*/
159695static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
159696  va_list ap;
159697  char *zSql;
159698  va_start(ap, zFmt);
159699  zSql = sqlite3_vmprintf(zFmt, ap);
159700  if( p->rc==SQLITE_OK ){
159701    if( zSql==0 ){
159702      p->rc = SQLITE_NOMEM;
159703    }else{
159704      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
159705    }
159706  }
159707  sqlite3_free(zSql);
159708  va_end(ap);
159709  return p->rc;
159710}
159711
159712/*
159713** Attempt to allocate and return a pointer to a zeroed block of nByte
159714** bytes.
159715**
159716** If an error (i.e. an OOM condition) occurs, return NULL and leave an
159717** error code in the rbu handle passed as the first argument. Or, if an
159718** error has already occurred when this function is called, return NULL
159719** immediately without attempting the allocation or modifying the stored
159720** error code.
159721*/
159722static void *rbuMalloc(sqlite3rbu *p, int nByte){
159723  void *pRet = 0;
159724  if( p->rc==SQLITE_OK ){
159725    assert( nByte>0 );
159726    pRet = sqlite3_malloc(nByte);
159727    if( pRet==0 ){
159728      p->rc = SQLITE_NOMEM;
159729    }else{
159730      memset(pRet, 0, nByte);
159731    }
159732  }
159733  return pRet;
159734}
159735
159736
159737/*
159738** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
159739** there is room for at least nCol elements. If an OOM occurs, store an
159740** error code in the RBU handle passed as the first argument.
159741*/
159742static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
159743  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
159744  char **azNew;
159745
159746  azNew = (char**)rbuMalloc(p, nByte);
159747  if( azNew ){
159748    pIter->azTblCol = azNew;
159749    pIter->azTblType = &azNew[nCol];
159750    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
159751    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
159752    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
159753    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
159754  }
159755}
159756
159757/*
159758** The first argument must be a nul-terminated string. This function
159759** returns a copy of the string in memory obtained from sqlite3_malloc().
159760** It is the responsibility of the caller to eventually free this memory
159761** using sqlite3_free().
159762**
159763** If an OOM condition is encountered when attempting to allocate memory,
159764** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
159765** if the allocation succeeds, (*pRc) is left unchanged.
159766*/
159767static char *rbuStrndup(const char *zStr, int *pRc){
159768  char *zRet = 0;
159769
159770  assert( *pRc==SQLITE_OK );
159771  if( zStr ){
159772    int nCopy = strlen(zStr) + 1;
159773    zRet = (char*)sqlite3_malloc(nCopy);
159774    if( zRet ){
159775      memcpy(zRet, zStr, nCopy);
159776    }else{
159777      *pRc = SQLITE_NOMEM;
159778    }
159779  }
159780
159781  return zRet;
159782}
159783
159784/*
159785** Finalize the statement passed as the second argument.
159786**
159787** If the sqlite3_finalize() call indicates that an error occurs, and the
159788** rbu handle error code is not already set, set the error code and error
159789** message accordingly.
159790*/
159791static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
159792  sqlite3 *db = sqlite3_db_handle(pStmt);
159793  int rc = sqlite3_finalize(pStmt);
159794  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
159795    p->rc = rc;
159796    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
159797  }
159798}
159799
159800/* Determine the type of a table.
159801**
159802**   peType is of type (int*), a pointer to an output parameter of type
159803**   (int). This call sets the output parameter as follows, depending
159804**   on the type of the table specified by parameters dbName and zTbl.
159805**
159806**     RBU_PK_NOTABLE:       No such table.
159807**     RBU_PK_NONE:          Table has an implicit rowid.
159808**     RBU_PK_IPK:           Table has an explicit IPK column.
159809**     RBU_PK_EXTERNAL:      Table has an external PK index.
159810**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
159811**     RBU_PK_VTAB:          Table is a virtual table.
159812**
159813**   Argument *piPk is also of type (int*), and also points to an output
159814**   parameter. Unless the table has an external primary key index
159815**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
159816**   if the table does have an external primary key index, then *piPk
159817**   is set to the root page number of the primary key index before
159818**   returning.
159819**
159820** ALGORITHM:
159821**
159822**   if( no entry exists in sqlite_master ){
159823**     return RBU_PK_NOTABLE
159824**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
159825**     return RBU_PK_VTAB
159826**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
159827**     if( the index that is the pk exists in sqlite_master ){
159828**       *piPK = rootpage of that index.
159829**       return RBU_PK_EXTERNAL
159830**     }else{
159831**       return RBU_PK_WITHOUT_ROWID
159832**     }
159833**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
159834**     return RBU_PK_IPK
159835**   }else{
159836**     return RBU_PK_NONE
159837**   }
159838*/
159839static void rbuTableType(
159840  sqlite3rbu *p,
159841  const char *zTab,
159842  int *peType,
159843  int *piTnum,
159844  int *piPk
159845){
159846  /*
159847  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
159848  ** 1) PRAGMA index_list = ?
159849  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
159850  ** 3) PRAGMA table_info = ?
159851  */
159852  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
159853
159854  *peType = RBU_PK_NOTABLE;
159855  *piPk = 0;
159856
159857  assert( p->rc==SQLITE_OK );
159858  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
159859    sqlite3_mprintf(
159860          "SELECT (sql LIKE 'create virtual%%'), rootpage"
159861          "  FROM sqlite_master"
159862          " WHERE name=%Q", zTab
159863  ));
159864  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
159865    /* Either an error, or no such table. */
159866    goto rbuTableType_end;
159867  }
159868  if( sqlite3_column_int(aStmt[0], 0) ){
159869    *peType = RBU_PK_VTAB;                     /* virtual table */
159870    goto rbuTableType_end;
159871  }
159872  *piTnum = sqlite3_column_int(aStmt[0], 1);
159873
159874  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
159875    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
159876  );
159877  if( p->rc ) goto rbuTableType_end;
159878  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
159879    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
159880    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
159881    if( zOrig && zIdx && zOrig[0]=='p' ){
159882      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
159883          sqlite3_mprintf(
159884            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
159885      ));
159886      if( p->rc==SQLITE_OK ){
159887        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
159888          *piPk = sqlite3_column_int(aStmt[2], 0);
159889          *peType = RBU_PK_EXTERNAL;
159890        }else{
159891          *peType = RBU_PK_WITHOUT_ROWID;
159892        }
159893      }
159894      goto rbuTableType_end;
159895    }
159896  }
159897
159898  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
159899    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
159900  );
159901  if( p->rc==SQLITE_OK ){
159902    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
159903      if( sqlite3_column_int(aStmt[3],5)>0 ){
159904        *peType = RBU_PK_IPK;                /* explicit IPK column */
159905        goto rbuTableType_end;
159906      }
159907    }
159908    *peType = RBU_PK_NONE;
159909  }
159910
159911rbuTableType_end: {
159912    unsigned int i;
159913    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
159914      rbuFinalize(p, aStmt[i]);
159915    }
159916  }
159917}
159918
159919/*
159920** This is a helper function for rbuObjIterCacheTableInfo(). It populates
159921** the pIter->abIndexed[] array.
159922*/
159923static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
159924  sqlite3_stmt *pList = 0;
159925  int bIndex = 0;
159926
159927  if( p->rc==SQLITE_OK ){
159928    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
159929    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
159930        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
159931    );
159932  }
159933
159934  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
159935    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
159936    sqlite3_stmt *pXInfo = 0;
159937    if( zIdx==0 ) break;
159938    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
159939        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
159940    );
159941    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
159942      int iCid = sqlite3_column_int(pXInfo, 1);
159943      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
159944    }
159945    rbuFinalize(p, pXInfo);
159946    bIndex = 1;
159947  }
159948
159949  rbuFinalize(p, pList);
159950  if( bIndex==0 ) pIter->abIndexed = 0;
159951}
159952
159953
159954/*
159955** If they are not already populated, populate the pIter->azTblCol[],
159956** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
159957** the table (not index) that the iterator currently points to.
159958**
159959** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
159960** an error does occur, an error code and error message are also left in
159961** the RBU handle.
159962*/
159963static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
159964  if( pIter->azTblCol==0 ){
159965    sqlite3_stmt *pStmt = 0;
159966    int nCol = 0;
159967    int i;                        /* for() loop iterator variable */
159968    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
159969    int iOrder = 0;
159970    int iTnum = 0;
159971
159972    /* Figure out the type of table this step will deal with. */
159973    assert( pIter->eType==0 );
159974    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
159975    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
159976      p->rc = SQLITE_ERROR;
159977      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
159978    }
159979    if( p->rc ) return p->rc;
159980    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
159981
159982    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
159983         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
159984         || pIter->eType==RBU_PK_VTAB
159985    );
159986
159987    /* Populate the azTblCol[] and nTblCol variables based on the columns
159988    ** of the input table. Ignore any input table columns that begin with
159989    ** "rbu_".  */
159990    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
159991        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
159992    );
159993    if( p->rc==SQLITE_OK ){
159994      nCol = sqlite3_column_count(pStmt);
159995      rbuAllocateIterArrays(p, pIter, nCol);
159996    }
159997    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
159998      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
159999      if( sqlite3_strnicmp("rbu_", zName, 4) ){
160000        char *zCopy = rbuStrndup(zName, &p->rc);
160001        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
160002        pIter->azTblCol[pIter->nTblCol++] = zCopy;
160003      }
160004      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
160005        bRbuRowid = 1;
160006      }
160007    }
160008    sqlite3_finalize(pStmt);
160009    pStmt = 0;
160010
160011    if( p->rc==SQLITE_OK
160012     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
160013    ){
160014      p->rc = SQLITE_ERROR;
160015      p->zErrmsg = sqlite3_mprintf(
160016          "table %q %s rbu_rowid column", pIter->zDataTbl,
160017          (bRbuRowid ? "may not have" : "requires")
160018      );
160019    }
160020
160021    /* Check that all non-HIDDEN columns in the destination table are also
160022    ** present in the input table. Populate the abTblPk[], azTblType[] and
160023    ** aiTblOrder[] arrays at the same time.  */
160024    if( p->rc==SQLITE_OK ){
160025      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
160026          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
160027      );
160028    }
160029    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
160030      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
160031      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
160032      for(i=iOrder; i<pIter->nTblCol; i++){
160033        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
160034      }
160035      if( i==pIter->nTblCol ){
160036        p->rc = SQLITE_ERROR;
160037        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
160038            pIter->zDataTbl, zName
160039        );
160040      }else{
160041        int iPk = sqlite3_column_int(pStmt, 5);
160042        int bNotNull = sqlite3_column_int(pStmt, 3);
160043        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
160044
160045        if( i!=iOrder ){
160046          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
160047          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
160048        }
160049
160050        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
160051        pIter->abTblPk[iOrder] = (iPk!=0);
160052        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
160053        iOrder++;
160054      }
160055    }
160056
160057    rbuFinalize(p, pStmt);
160058    rbuObjIterCacheIndexedCols(p, pIter);
160059    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
160060  }
160061
160062  return p->rc;
160063}
160064
160065/*
160066** This function constructs and returns a pointer to a nul-terminated
160067** string containing some SQL clause or list based on one or more of the
160068** column names currently stored in the pIter->azTblCol[] array.
160069*/
160070static char *rbuObjIterGetCollist(
160071  sqlite3rbu *p,                  /* RBU object */
160072  RbuObjIter *pIter               /* Object iterator for column names */
160073){
160074  char *zList = 0;
160075  const char *zSep = "";
160076  int i;
160077  for(i=0; i<pIter->nTblCol; i++){
160078    const char *z = pIter->azTblCol[i];
160079    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
160080    zSep = ", ";
160081  }
160082  return zList;
160083}
160084
160085/*
160086** This function is used to create a SELECT list (the list of SQL
160087** expressions that follows a SELECT keyword) for a SELECT statement
160088** used to read from an data_xxx or rbu_tmp_xxx table while updating the
160089** index object currently indicated by the iterator object passed as the
160090** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
160091** to obtain the required information.
160092**
160093** If the index is of the following form:
160094**
160095**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
160096**
160097** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
160098** "ipk", the returned string is:
160099**
160100**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
160101**
160102** As well as the returned string, three other malloc'd strings are
160103** returned via output parameters. As follows:
160104**
160105**   pzImposterCols: ...
160106**   pzImposterPk: ...
160107**   pzWhere: ...
160108*/
160109static char *rbuObjIterGetIndexCols(
160110  sqlite3rbu *p,                  /* RBU object */
160111  RbuObjIter *pIter,              /* Object iterator for column names */
160112  char **pzImposterCols,          /* OUT: Columns for imposter table */
160113  char **pzImposterPk,            /* OUT: Imposter PK clause */
160114  char **pzWhere,                 /* OUT: WHERE clause */
160115  int *pnBind                     /* OUT: Trbul number of columns */
160116){
160117  int rc = p->rc;                 /* Error code */
160118  int rc2;                        /* sqlite3_finalize() return code */
160119  char *zRet = 0;                 /* String to return */
160120  char *zImpCols = 0;             /* String to return via *pzImposterCols */
160121  char *zImpPK = 0;               /* String to return via *pzImposterPK */
160122  char *zWhere = 0;               /* String to return via *pzWhere */
160123  int nBind = 0;                  /* Value to return via *pnBind */
160124  const char *zCom = "";          /* Set to ", " later on */
160125  const char *zAnd = "";          /* Set to " AND " later on */
160126  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
160127
160128  if( rc==SQLITE_OK ){
160129    assert( p->zErrmsg==0 );
160130    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160131        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
160132    );
160133  }
160134
160135  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160136    int iCid = sqlite3_column_int(pXInfo, 1);
160137    int bDesc = sqlite3_column_int(pXInfo, 3);
160138    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
160139    const char *zCol;
160140    const char *zType;
160141
160142    if( iCid<0 ){
160143      /* An integer primary key. If the table has an explicit IPK, use
160144      ** its name. Otherwise, use "rbu_rowid".  */
160145      if( pIter->eType==RBU_PK_IPK ){
160146        int i;
160147        for(i=0; pIter->abTblPk[i]==0; i++);
160148        assert( i<pIter->nTblCol );
160149        zCol = pIter->azTblCol[i];
160150      }else{
160151        zCol = "rbu_rowid";
160152      }
160153      zType = "INTEGER";
160154    }else{
160155      zCol = pIter->azTblCol[iCid];
160156      zType = pIter->azTblType[iCid];
160157    }
160158
160159    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
160160    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
160161      const char *zOrder = (bDesc ? " DESC" : "");
160162      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
160163          zImpPK, zCom, nBind, zCol, zOrder
160164      );
160165    }
160166    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
160167        zImpCols, zCom, nBind, zCol, zType, zCollate
160168    );
160169    zWhere = sqlite3_mprintf(
160170        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
160171    );
160172    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
160173    zCom = ", ";
160174    zAnd = " AND ";
160175    nBind++;
160176  }
160177
160178  rc2 = sqlite3_finalize(pXInfo);
160179  if( rc==SQLITE_OK ) rc = rc2;
160180
160181  if( rc!=SQLITE_OK ){
160182    sqlite3_free(zRet);
160183    sqlite3_free(zImpCols);
160184    sqlite3_free(zImpPK);
160185    sqlite3_free(zWhere);
160186    zRet = 0;
160187    zImpCols = 0;
160188    zImpPK = 0;
160189    zWhere = 0;
160190    p->rc = rc;
160191  }
160192
160193  *pzImposterCols = zImpCols;
160194  *pzImposterPk = zImpPK;
160195  *pzWhere = zWhere;
160196  *pnBind = nBind;
160197  return zRet;
160198}
160199
160200/*
160201** Assuming the current table columns are "a", "b" and "c", and the zObj
160202** paramter is passed "old", return a string of the form:
160203**
160204**     "old.a, old.b, old.b"
160205**
160206** With the column names escaped.
160207**
160208** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
160209** the text ", old._rowid_" to the returned value.
160210*/
160211static char *rbuObjIterGetOldlist(
160212  sqlite3rbu *p,
160213  RbuObjIter *pIter,
160214  const char *zObj
160215){
160216  char *zList = 0;
160217  if( p->rc==SQLITE_OK && pIter->abIndexed ){
160218    const char *zS = "";
160219    int i;
160220    for(i=0; i<pIter->nTblCol; i++){
160221      if( pIter->abIndexed[i] ){
160222        const char *zCol = pIter->azTblCol[i];
160223        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
160224      }else{
160225        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
160226      }
160227      zS = ", ";
160228      if( zList==0 ){
160229        p->rc = SQLITE_NOMEM;
160230        break;
160231      }
160232    }
160233
160234    /* For a table with implicit rowids, append "old._rowid_" to the list. */
160235    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160236      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
160237    }
160238  }
160239  return zList;
160240}
160241
160242/*
160243** Return an expression that can be used in a WHERE clause to match the
160244** primary key of the current table. For example, if the table is:
160245**
160246**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
160247**
160248** Return the string:
160249**
160250**   "b = ?1 AND c = ?2"
160251*/
160252static char *rbuObjIterGetWhere(
160253  sqlite3rbu *p,
160254  RbuObjIter *pIter
160255){
160256  char *zList = 0;
160257  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
160258    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
160259  }else if( pIter->eType==RBU_PK_EXTERNAL ){
160260    const char *zSep = "";
160261    int i;
160262    for(i=0; i<pIter->nTblCol; i++){
160263      if( pIter->abTblPk[i] ){
160264        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
160265        zSep = " AND ";
160266      }
160267    }
160268    zList = rbuMPrintf(p,
160269        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
160270    );
160271
160272  }else{
160273    const char *zSep = "";
160274    int i;
160275    for(i=0; i<pIter->nTblCol; i++){
160276      if( pIter->abTblPk[i] ){
160277        const char *zCol = pIter->azTblCol[i];
160278        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
160279        zSep = " AND ";
160280      }
160281    }
160282  }
160283  return zList;
160284}
160285
160286/*
160287** The SELECT statement iterating through the keys for the current object
160288** (p->objiter.pSelect) currently points to a valid row. However, there
160289** is something wrong with the rbu_control value in the rbu_control value
160290** stored in the (p->nCol+1)'th column. Set the error code and error message
160291** of the RBU handle to something reflecting this.
160292*/
160293static void rbuBadControlError(sqlite3rbu *p){
160294  p->rc = SQLITE_ERROR;
160295  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
160296}
160297
160298
160299/*
160300** Return a nul-terminated string containing the comma separated list of
160301** assignments that should be included following the "SET" keyword of
160302** an UPDATE statement used to update the table object that the iterator
160303** passed as the second argument currently points to if the rbu_control
160304** column of the data_xxx table entry is set to zMask.
160305**
160306** The memory for the returned string is obtained from sqlite3_malloc().
160307** It is the responsibility of the caller to eventually free it using
160308** sqlite3_free().
160309**
160310** If an OOM error is encountered when allocating space for the new
160311** string, an error code is left in the rbu handle passed as the first
160312** argument and NULL is returned. Or, if an error has already occurred
160313** when this function is called, NULL is returned immediately, without
160314** attempting the allocation or modifying the stored error code.
160315*/
160316static char *rbuObjIterGetSetlist(
160317  sqlite3rbu *p,
160318  RbuObjIter *pIter,
160319  const char *zMask
160320){
160321  char *zList = 0;
160322  if( p->rc==SQLITE_OK ){
160323    int i;
160324
160325    if( (int)strlen(zMask)!=pIter->nTblCol ){
160326      rbuBadControlError(p);
160327    }else{
160328      const char *zSep = "";
160329      for(i=0; i<pIter->nTblCol; i++){
160330        char c = zMask[pIter->aiSrcOrder[i]];
160331        if( c=='x' ){
160332          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
160333              zList, zSep, pIter->azTblCol[i], i+1
160334          );
160335          zSep = ", ";
160336        }
160337        else if( c=='d' ){
160338          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
160339              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
160340          );
160341          zSep = ", ";
160342        }
160343        else if( c=='f' ){
160344          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
160345              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
160346          );
160347          zSep = ", ";
160348        }
160349      }
160350    }
160351  }
160352  return zList;
160353}
160354
160355/*
160356** Return a nul-terminated string consisting of nByte comma separated
160357** "?" expressions. For example, if nByte is 3, return a pointer to
160358** a buffer containing the string "?,?,?".
160359**
160360** The memory for the returned string is obtained from sqlite3_malloc().
160361** It is the responsibility of the caller to eventually free it using
160362** sqlite3_free().
160363**
160364** If an OOM error is encountered when allocating space for the new
160365** string, an error code is left in the rbu handle passed as the first
160366** argument and NULL is returned. Or, if an error has already occurred
160367** when this function is called, NULL is returned immediately, without
160368** attempting the allocation or modifying the stored error code.
160369*/
160370static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
160371  char *zRet = 0;
160372  int nByte = nBind*2 + 1;
160373
160374  zRet = (char*)rbuMalloc(p, nByte);
160375  if( zRet ){
160376    int i;
160377    for(i=0; i<nBind; i++){
160378      zRet[i*2] = '?';
160379      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
160380    }
160381  }
160382  return zRet;
160383}
160384
160385/*
160386** The iterator currently points to a table (not index) of type
160387** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
160388** declaration for the corresponding imposter table. For example,
160389** if the iterator points to a table created as:
160390**
160391**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
160392**
160393** this function returns:
160394**
160395**   PRIMARY KEY("b", "a" DESC)
160396*/
160397static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
160398  char *z = 0;
160399  assert( pIter->zIdx==0 );
160400  if( p->rc==SQLITE_OK ){
160401    const char *zSep = "PRIMARY KEY(";
160402    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
160403    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
160404
160405    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
160406        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
160407    );
160408    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
160409      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
160410      if( zOrig && strcmp(zOrig, "pk")==0 ){
160411        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
160412        if( zIdx ){
160413          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160414              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
160415          );
160416        }
160417        break;
160418      }
160419    }
160420    rbuFinalize(p, pXList);
160421
160422    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160423      if( sqlite3_column_int(pXInfo, 5) ){
160424        /* int iCid = sqlite3_column_int(pXInfo, 0); */
160425        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
160426        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
160427        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
160428        zSep = ", ";
160429      }
160430    }
160431    z = rbuMPrintf(p, "%z)", z);
160432    rbuFinalize(p, pXInfo);
160433  }
160434  return z;
160435}
160436
160437/*
160438** This function creates the second imposter table used when writing to
160439** a table b-tree where the table has an external primary key. If the
160440** iterator passed as the second argument does not currently point to
160441** a table (not index) with an external primary key, this function is a
160442** no-op.
160443**
160444** Assuming the iterator does point to a table with an external PK, this
160445** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
160446** used to access that PK index. For example, if the target table is
160447** declared as follows:
160448**
160449**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
160450**
160451** then the imposter table schema is:
160452**
160453**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
160454**
160455*/
160456static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
160457  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
160458    int tnum = pIter->iPkTnum;    /* Root page of PK index */
160459    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
160460    const char *zIdx = 0;         /* Name of PK index */
160461    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
160462    const char *zComma = "";
160463    char *zCols = 0;              /* Used to build up list of table cols */
160464    char *zPk = 0;                /* Used to build up table PK declaration */
160465
160466    /* Figure out the name of the primary key index for the current table.
160467    ** This is needed for the argument to "PRAGMA index_xinfo". Set
160468    ** zIdx to point to a nul-terminated string containing this name. */
160469    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
160470        "SELECT name FROM sqlite_master WHERE rootpage = ?"
160471    );
160472    if( p->rc==SQLITE_OK ){
160473      sqlite3_bind_int(pQuery, 1, tnum);
160474      if( SQLITE_ROW==sqlite3_step(pQuery) ){
160475        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
160476      }
160477    }
160478    if( zIdx ){
160479      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160480          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
160481      );
160482    }
160483    rbuFinalize(p, pQuery);
160484
160485    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160486      int bKey = sqlite3_column_int(pXInfo, 5);
160487      if( bKey ){
160488        int iCid = sqlite3_column_int(pXInfo, 1);
160489        int bDesc = sqlite3_column_int(pXInfo, 3);
160490        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
160491        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
160492            iCid, pIter->azTblType[iCid], zCollate
160493        );
160494        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
160495        zComma = ", ";
160496      }
160497    }
160498    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
160499    rbuFinalize(p, pXInfo);
160500
160501    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
160502    rbuMPrintfExec(p, p->dbMain,
160503        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
160504        zCols, zPk
160505    );
160506    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160507  }
160508}
160509
160510/*
160511** If an error has already occurred when this function is called, it
160512** immediately returns zero (without doing any work). Or, if an error
160513** occurs during the execution of this function, it sets the error code
160514** in the sqlite3rbu object indicated by the first argument and returns
160515** zero.
160516**
160517** The iterator passed as the second argument is guaranteed to point to
160518** a table (not an index) when this function is called. This function
160519** attempts to create any imposter table required to write to the main
160520** table b-tree of the table before returning. Non-zero is returned if
160521** an imposter table are created, or zero otherwise.
160522**
160523** An imposter table is required in all cases except RBU_PK_VTAB. Only
160524** virtual tables are written to directly. The imposter table has the
160525** same schema as the actual target table (less any UNIQUE constraints).
160526** More precisely, the "same schema" means the same columns, types,
160527** collation sequences. For tables that do not have an external PRIMARY
160528** KEY, it also means the same PRIMARY KEY declaration.
160529*/
160530static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
160531  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
160532    int tnum = pIter->iTnum;
160533    const char *zComma = "";
160534    char *zSql = 0;
160535    int iCol;
160536    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
160537
160538    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
160539      const char *zPk = "";
160540      const char *zCol = pIter->azTblCol[iCol];
160541      const char *zColl = 0;
160542
160543      p->rc = sqlite3_table_column_metadata(
160544          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
160545      );
160546
160547      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
160548        /* If the target table column is an "INTEGER PRIMARY KEY", add
160549        ** "PRIMARY KEY" to the imposter table column declaration. */
160550        zPk = "PRIMARY KEY ";
160551      }
160552      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
160553          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
160554          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
160555      );
160556      zComma = ", ";
160557    }
160558
160559    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
160560      char *zPk = rbuWithoutRowidPK(p, pIter);
160561      if( zPk ){
160562        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
160563      }
160564    }
160565
160566    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
160567    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
160568        pIter->zTbl, zSql,
160569        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
160570    );
160571    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160572  }
160573}
160574
160575/*
160576** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
160577** Specifically a statement of the form:
160578**
160579**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
160580**
160581** The number of bound variables is equal to the number of columns in
160582** the target table, plus one (for the rbu_control column), plus one more
160583** (for the rbu_rowid column) if the target table is an implicit IPK or
160584** virtual table.
160585*/
160586static void rbuObjIterPrepareTmpInsert(
160587  sqlite3rbu *p,
160588  RbuObjIter *pIter,
160589  const char *zCollist,
160590  const char *zRbuRowid
160591){
160592  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
160593  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
160594  if( zBind ){
160595    assert( pIter->pTmpInsert==0 );
160596    p->rc = prepareFreeAndCollectError(
160597        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
160598          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
160599          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
160600    ));
160601  }
160602}
160603
160604static void rbuTmpInsertFunc(
160605  sqlite3_context *pCtx,
160606  int nVal,
160607  sqlite3_value **apVal
160608){
160609  sqlite3rbu *p = sqlite3_user_data(pCtx);
160610  int rc = SQLITE_OK;
160611  int i;
160612
160613  for(i=0; rc==SQLITE_OK && i<nVal; i++){
160614    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
160615  }
160616  if( rc==SQLITE_OK ){
160617    sqlite3_step(p->objiter.pTmpInsert);
160618    rc = sqlite3_reset(p->objiter.pTmpInsert);
160619  }
160620
160621  if( rc!=SQLITE_OK ){
160622    sqlite3_result_error_code(pCtx, rc);
160623  }
160624}
160625
160626/*
160627** Ensure that the SQLite statement handles required to update the
160628** target database object currently indicated by the iterator passed
160629** as the second argument are available.
160630*/
160631static int rbuObjIterPrepareAll(
160632  sqlite3rbu *p,
160633  RbuObjIter *pIter,
160634  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
160635){
160636  assert( pIter->bCleanup==0 );
160637  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
160638    const int tnum = pIter->iTnum;
160639    char *zCollist = 0;           /* List of indexed columns */
160640    char **pz = &p->zErrmsg;
160641    const char *zIdx = pIter->zIdx;
160642    char *zLimit = 0;
160643
160644    if( nOffset ){
160645      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
160646      if( !zLimit ) p->rc = SQLITE_NOMEM;
160647    }
160648
160649    if( zIdx ){
160650      const char *zTbl = pIter->zTbl;
160651      char *zImposterCols = 0;    /* Columns for imposter table */
160652      char *zImposterPK = 0;      /* Primary key declaration for imposter */
160653      char *zWhere = 0;           /* WHERE clause on PK columns */
160654      char *zBind = 0;
160655      int nBind = 0;
160656
160657      assert( pIter->eType!=RBU_PK_VTAB );
160658      zCollist = rbuObjIterGetIndexCols(
160659          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
160660      );
160661      zBind = rbuObjIterGetBindlist(p, nBind);
160662
160663      /* Create the imposter table used to write to this index. */
160664      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
160665      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
160666      rbuMPrintfExec(p, p->dbMain,
160667          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
160668          zTbl, zImposterCols, zImposterPK
160669      );
160670      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160671
160672      /* Create the statement to insert index entries */
160673      pIter->nCol = nBind;
160674      if( p->rc==SQLITE_OK ){
160675        p->rc = prepareFreeAndCollectError(
160676            p->dbMain, &pIter->pInsert, &p->zErrmsg,
160677          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
160678        );
160679      }
160680
160681      /* And to delete index entries */
160682      if( p->rc==SQLITE_OK ){
160683        p->rc = prepareFreeAndCollectError(
160684            p->dbMain, &pIter->pDelete, &p->zErrmsg,
160685          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
160686        );
160687      }
160688
160689      /* Create the SELECT statement to read keys in sorted order */
160690      if( p->rc==SQLITE_OK ){
160691        char *zSql;
160692        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160693          zSql = sqlite3_mprintf(
160694              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
160695              zCollist, p->zStateDb, pIter->zDataTbl,
160696              zCollist, zLimit
160697          );
160698        }else{
160699          zSql = sqlite3_mprintf(
160700              "SELECT %s, rbu_control FROM '%q' "
160701              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
160702              "UNION ALL "
160703              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
160704              "ORDER BY %s%s",
160705              zCollist, pIter->zDataTbl,
160706              zCollist, p->zStateDb, pIter->zDataTbl,
160707              zCollist, zLimit
160708          );
160709        }
160710        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
160711      }
160712
160713      sqlite3_free(zImposterCols);
160714      sqlite3_free(zImposterPK);
160715      sqlite3_free(zWhere);
160716      sqlite3_free(zBind);
160717    }else{
160718      int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
160719      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
160720      const char *zWrite;                   /* Imposter table name */
160721
160722      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
160723      char *zWhere = rbuObjIterGetWhere(p, pIter);
160724      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
160725      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
160726
160727      zCollist = rbuObjIterGetCollist(p, pIter);
160728      pIter->nCol = pIter->nTblCol;
160729
160730      /* Create the imposter table or tables (if required). */
160731      rbuCreateImposterTable(p, pIter);
160732      rbuCreateImposterTable2(p, pIter);
160733      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
160734
160735      /* Create the INSERT statement to write to the target PK b-tree */
160736      if( p->rc==SQLITE_OK ){
160737        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
160738            sqlite3_mprintf(
160739              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
160740              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
160741            )
160742        );
160743      }
160744
160745      /* Create the DELETE statement to write to the target PK b-tree */
160746      if( p->rc==SQLITE_OK ){
160747        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
160748            sqlite3_mprintf(
160749              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
160750            )
160751        );
160752      }
160753
160754      if( pIter->abIndexed ){
160755        const char *zRbuRowid = "";
160756        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160757          zRbuRowid = ", rbu_rowid";
160758        }
160759
160760        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
160761        rbuMPrintfExec(p, p->dbRbu,
160762            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
160763            "SELECT *%s FROM '%q' WHERE 0;"
160764            , p->zStateDb, pIter->zDataTbl
160765            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
160766            , pIter->zDataTbl
160767        );
160768
160769        rbuMPrintfExec(p, p->dbMain,
160770            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
160771            "BEGIN "
160772            "  SELECT rbu_tmp_insert(2, %s);"
160773            "END;"
160774
160775            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
160776            "BEGIN "
160777            "  SELECT rbu_tmp_insert(2, %s);"
160778            "END;"
160779
160780            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
160781            "BEGIN "
160782            "  SELECT rbu_tmp_insert(3, %s);"
160783            "END;",
160784            zWrite, zTbl, zOldlist,
160785            zWrite, zTbl, zOldlist,
160786            zWrite, zTbl, zNewlist
160787        );
160788
160789        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160790          rbuMPrintfExec(p, p->dbMain,
160791              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
160792              "BEGIN "
160793              "  SELECT rbu_tmp_insert(0, %s);"
160794              "END;",
160795              zWrite, zTbl, zNewlist
160796          );
160797        }
160798
160799        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
160800      }
160801
160802      /* Create the SELECT statement to read keys from data_xxx */
160803      if( p->rc==SQLITE_OK ){
160804        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
160805            sqlite3_mprintf(
160806              "SELECT %s, rbu_control%s FROM '%q'%s",
160807              zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
160808              pIter->zDataTbl, zLimit
160809            )
160810        );
160811      }
160812
160813      sqlite3_free(zWhere);
160814      sqlite3_free(zOldlist);
160815      sqlite3_free(zNewlist);
160816      sqlite3_free(zBindings);
160817    }
160818    sqlite3_free(zCollist);
160819    sqlite3_free(zLimit);
160820  }
160821
160822  return p->rc;
160823}
160824
160825/*
160826** Set output variable *ppStmt to point to an UPDATE statement that may
160827** be used to update the imposter table for the main table b-tree of the
160828** table object that pIter currently points to, assuming that the
160829** rbu_control column of the data_xyz table contains zMask.
160830**
160831** If the zMask string does not specify any columns to update, then this
160832** is not an error. Output variable *ppStmt is set to NULL in this case.
160833*/
160834static int rbuGetUpdateStmt(
160835  sqlite3rbu *p,                  /* RBU handle */
160836  RbuObjIter *pIter,              /* Object iterator */
160837  const char *zMask,              /* rbu_control value ('x.x.') */
160838  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
160839){
160840  RbuUpdateStmt **pp;
160841  RbuUpdateStmt *pUp = 0;
160842  int nUp = 0;
160843
160844  /* In case an error occurs */
160845  *ppStmt = 0;
160846
160847  /* Search for an existing statement. If one is found, shift it to the front
160848  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
160849  ** to the number of statements currently in the cache and pUp to the
160850  ** last object in the list.  */
160851  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
160852    pUp = *pp;
160853    if( strcmp(pUp->zMask, zMask)==0 ){
160854      *pp = pUp->pNext;
160855      pUp->pNext = pIter->pRbuUpdate;
160856      pIter->pRbuUpdate = pUp;
160857      *ppStmt = pUp->pUpdate;
160858      return SQLITE_OK;
160859    }
160860    nUp++;
160861  }
160862  assert( pUp==0 || pUp->pNext==0 );
160863
160864  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
160865    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
160866    *pp = 0;
160867    sqlite3_finalize(pUp->pUpdate);
160868    pUp->pUpdate = 0;
160869  }else{
160870    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
160871  }
160872
160873  if( pUp ){
160874    char *zWhere = rbuObjIterGetWhere(p, pIter);
160875    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
160876    char *zUpdate = 0;
160877
160878    pUp->zMask = (char*)&pUp[1];
160879    memcpy(pUp->zMask, zMask, pIter->nTblCol);
160880    pUp->pNext = pIter->pRbuUpdate;
160881    pIter->pRbuUpdate = pUp;
160882
160883    if( zSet ){
160884      const char *zPrefix = "";
160885
160886      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
160887      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
160888          zPrefix, pIter->zTbl, zSet, zWhere
160889      );
160890      p->rc = prepareFreeAndCollectError(
160891          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
160892      );
160893      *ppStmt = pUp->pUpdate;
160894    }
160895    sqlite3_free(zWhere);
160896    sqlite3_free(zSet);
160897  }
160898
160899  return p->rc;
160900}
160901
160902static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
160903  sqlite3 *db = 0;
160904  if( p->rc==SQLITE_OK ){
160905    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
160906    p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
160907    if( p->rc ){
160908      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
160909      sqlite3_close(db);
160910      db = 0;
160911    }
160912  }
160913  return db;
160914}
160915
160916/*
160917** Open the database handle and attach the RBU database as "rbu". If an
160918** error occurs, leave an error code and message in the RBU handle.
160919*/
160920static void rbuOpenDatabase(sqlite3rbu *p){
160921  assert( p->rc==SQLITE_OK );
160922  assert( p->dbMain==0 && p->dbRbu==0 );
160923
160924  p->eStage = 0;
160925  p->dbMain = rbuOpenDbhandle(p, p->zTarget);
160926  p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
160927
160928  /* If using separate RBU and state databases, attach the state database to
160929  ** the RBU db handle now.  */
160930  if( p->zState ){
160931    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
160932    memcpy(p->zStateDb, "stat", 4);
160933  }else{
160934    memcpy(p->zStateDb, "main", 4);
160935  }
160936
160937  if( p->rc==SQLITE_OK ){
160938    p->rc = sqlite3_create_function(p->dbMain,
160939        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
160940    );
160941  }
160942
160943  if( p->rc==SQLITE_OK ){
160944    p->rc = sqlite3_create_function(p->dbMain,
160945        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
160946    );
160947  }
160948
160949  if( p->rc==SQLITE_OK ){
160950    p->rc = sqlite3_create_function(p->dbRbu,
160951        "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
160952    );
160953  }
160954
160955  if( p->rc==SQLITE_OK ){
160956    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
160957  }
160958  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
160959
160960  /* Mark the database file just opened as an RBU target database. If
160961  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
160962  ** This is an error.  */
160963  if( p->rc==SQLITE_OK ){
160964    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
160965  }
160966
160967  if( p->rc==SQLITE_NOTFOUND ){
160968    p->rc = SQLITE_ERROR;
160969    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
160970  }
160971}
160972
160973/*
160974** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
160975** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
160976**
160977** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
160978** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
160979** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
160980** three characters, then shorten the suffix on z[] to be the last three
160981** characters of the original suffix.
160982**
160983** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
160984** do the suffix shortening regardless of URI parameter.
160985**
160986** Examples:
160987**
160988**     test.db-journal    =>   test.nal
160989**     test.db-wal        =>   test.wal
160990**     test.db-shm        =>   test.shm
160991**     test.db-mj7f3319fa =>   test.9fa
160992*/
160993static void rbuFileSuffix3(const char *zBase, char *z){
160994#ifdef SQLITE_ENABLE_8_3_NAMES
160995#if SQLITE_ENABLE_8_3_NAMES<2
160996  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
160997#endif
160998  {
160999    int i, sz;
161000    sz = sqlite3Strlen30(z);
161001    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
161002    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
161003  }
161004#endif
161005}
161006
161007/*
161008** Return the current wal-index header checksum for the target database
161009** as a 64-bit integer.
161010**
161011** The checksum is store in the first page of xShmMap memory as an 8-byte
161012** blob starting at byte offset 40.
161013*/
161014static i64 rbuShmChecksum(sqlite3rbu *p){
161015  i64 iRet = 0;
161016  if( p->rc==SQLITE_OK ){
161017    sqlite3_file *pDb = p->pTargetFd->pReal;
161018    u32 volatile *ptr;
161019    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
161020    if( p->rc==SQLITE_OK ){
161021      iRet = ((i64)ptr[10] << 32) + ptr[11];
161022    }
161023  }
161024  return iRet;
161025}
161026
161027/*
161028** This function is called as part of initializing or reinitializing an
161029** incremental checkpoint.
161030**
161031** It populates the sqlite3rbu.aFrame[] array with the set of
161032** (wal frame -> db page) copy operations required to checkpoint the
161033** current wal file, and obtains the set of shm locks required to safely
161034** perform the copy operations directly on the file-system.
161035**
161036** If argument pState is not NULL, then the incremental checkpoint is
161037** being resumed. In this case, if the checksum of the wal-index-header
161038** following recovery is not the same as the checksum saved in the RbuState
161039** object, then the rbu handle is set to DONE state. This occurs if some
161040** other client appends a transaction to the wal file in the middle of
161041** an incremental checkpoint.
161042*/
161043static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
161044
161045  /* If pState is NULL, then the wal file may not have been opened and
161046  ** recovered. Running a read-statement here to ensure that doing so
161047  ** does not interfere with the "capture" process below.  */
161048  if( pState==0 ){
161049    p->eStage = 0;
161050    if( p->rc==SQLITE_OK ){
161051      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
161052    }
161053  }
161054
161055  /* Assuming no error has occurred, run a "restart" checkpoint with the
161056  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
161057  ** special behaviour in the rbu VFS:
161058  **
161059  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
161060  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
161061  **     proceed with running a passive checkpoint instead of failing).
161062  **
161063  **   * Attempts to read from the *-wal file or write to the database file
161064  **     do not perform any IO. Instead, the frame/page combinations that
161065  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
161066  **     array.
161067  **
161068  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
161069  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
161070  **     no-ops. These locks will not be released until the connection
161071  **     is closed.
161072  **
161073  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
161074  **     error.
161075  **
161076  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
161077  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
161078  ** array populated with a set of (frame -> page) mappings. Because the
161079  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
161080  ** data from the wal file into the database file according to the
161081  ** contents of aFrame[].
161082  */
161083  if( p->rc==SQLITE_OK ){
161084    int rc2;
161085    p->eStage = RBU_STAGE_CAPTURE;
161086    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
161087    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
161088  }
161089
161090  if( p->rc==SQLITE_OK ){
161091    p->eStage = RBU_STAGE_CKPT;
161092    p->nStep = (pState ? pState->nRow : 0);
161093    p->aBuf = rbuMalloc(p, p->pgsz);
161094    p->iWalCksum = rbuShmChecksum(p);
161095  }
161096
161097  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
161098    p->rc = SQLITE_DONE;
161099    p->eStage = RBU_STAGE_DONE;
161100  }
161101}
161102
161103/*
161104** Called when iAmt bytes are read from offset iOff of the wal file while
161105** the rbu object is in capture mode. Record the frame number of the frame
161106** being read in the aFrame[] array.
161107*/
161108static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
161109  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
161110  u32 iFrame;
161111
161112  if( pRbu->mLock!=mReq ){
161113    pRbu->rc = SQLITE_BUSY;
161114    return SQLITE_INTERNAL;
161115  }
161116
161117  pRbu->pgsz = iAmt;
161118  if( pRbu->nFrame==pRbu->nFrameAlloc ){
161119    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
161120    RbuFrame *aNew;
161121    aNew = (RbuFrame*)sqlite3_realloc(pRbu->aFrame, nNew * sizeof(RbuFrame));
161122    if( aNew==0 ) return SQLITE_NOMEM;
161123    pRbu->aFrame = aNew;
161124    pRbu->nFrameAlloc = nNew;
161125  }
161126
161127  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
161128  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
161129  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
161130  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
161131  pRbu->nFrame++;
161132  return SQLITE_OK;
161133}
161134
161135/*
161136** Called when a page of data is written to offset iOff of the database
161137** file while the rbu handle is in capture mode. Record the page number
161138** of the page being written in the aFrame[] array.
161139*/
161140static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
161141  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
161142  return SQLITE_OK;
161143}
161144
161145/*
161146** This is called as part of an incremental checkpoint operation. Copy
161147** a single frame of data from the wal file into the database file, as
161148** indicated by the RbuFrame object.
161149*/
161150static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
161151  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
161152  sqlite3_file *pDb = p->pTargetFd->pReal;
161153  i64 iOff;
161154
161155  assert( p->rc==SQLITE_OK );
161156  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
161157  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
161158  if( p->rc ) return;
161159
161160  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
161161  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
161162}
161163
161164
161165/*
161166** Take an EXCLUSIVE lock on the database file.
161167*/
161168static void rbuLockDatabase(sqlite3rbu *p){
161169  sqlite3_file *pReal = p->pTargetFd->pReal;
161170  assert( p->rc==SQLITE_OK );
161171  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
161172  if( p->rc==SQLITE_OK ){
161173    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
161174  }
161175}
161176
161177#if defined(_WIN32_WCE)
161178static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
161179  int nChar;
161180  LPWSTR zWideFilename;
161181
161182  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
161183  if( nChar==0 ){
161184    return 0;
161185  }
161186  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
161187  if( zWideFilename==0 ){
161188    return 0;
161189  }
161190  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
161191  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
161192                                nChar);
161193  if( nChar==0 ){
161194    sqlite3_free(zWideFilename);
161195    zWideFilename = 0;
161196  }
161197  return zWideFilename;
161198}
161199#endif
161200
161201/*
161202** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
161203** on the database file. This proc moves the *-oal file to the *-wal path,
161204** then reopens the database file (this time in vanilla, non-oal, WAL mode).
161205** If an error occurs, leave an error code and error message in the rbu
161206** handle.
161207*/
161208static void rbuMoveOalFile(sqlite3rbu *p){
161209  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
161210
161211  char *zWal = sqlite3_mprintf("%s-wal", zBase);
161212  char *zOal = sqlite3_mprintf("%s-oal", zBase);
161213
161214  assert( p->eStage==RBU_STAGE_MOVE );
161215  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
161216  if( zWal==0 || zOal==0 ){
161217    p->rc = SQLITE_NOMEM;
161218  }else{
161219    /* Move the *-oal file to *-wal. At this point connection p->db is
161220    ** holding a SHARED lock on the target database file (because it is
161221    ** in WAL mode). So no other connection may be writing the db.
161222    **
161223    ** In order to ensure that there are no database readers, an EXCLUSIVE
161224    ** lock is obtained here before the *-oal is moved to *-wal.
161225    */
161226    rbuLockDatabase(p);
161227    if( p->rc==SQLITE_OK ){
161228      rbuFileSuffix3(zBase, zWal);
161229      rbuFileSuffix3(zBase, zOal);
161230
161231      /* Re-open the databases. */
161232      rbuObjIterFinalize(&p->objiter);
161233      sqlite3_close(p->dbMain);
161234      sqlite3_close(p->dbRbu);
161235      p->dbMain = 0;
161236      p->dbRbu = 0;
161237
161238#if defined(_WIN32_WCE)
161239      {
161240        LPWSTR zWideOal;
161241        LPWSTR zWideWal;
161242
161243        zWideOal = rbuWinUtf8ToUnicode(zOal);
161244        if( zWideOal ){
161245          zWideWal = rbuWinUtf8ToUnicode(zWal);
161246          if( zWideWal ){
161247            if( MoveFileW(zWideOal, zWideWal) ){
161248              p->rc = SQLITE_OK;
161249            }else{
161250              p->rc = SQLITE_IOERR;
161251            }
161252            sqlite3_free(zWideWal);
161253          }else{
161254            p->rc = SQLITE_IOERR_NOMEM;
161255          }
161256          sqlite3_free(zWideOal);
161257        }else{
161258          p->rc = SQLITE_IOERR_NOMEM;
161259        }
161260      }
161261#else
161262      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
161263#endif
161264
161265      if( p->rc==SQLITE_OK ){
161266        rbuOpenDatabase(p);
161267        rbuSetupCheckpoint(p, 0);
161268      }
161269    }
161270  }
161271
161272  sqlite3_free(zWal);
161273  sqlite3_free(zOal);
161274}
161275
161276/*
161277** The SELECT statement iterating through the keys for the current object
161278** (p->objiter.pSelect) currently points to a valid row. This function
161279** determines the type of operation requested by this row and returns
161280** one of the following values to indicate the result:
161281**
161282**     * RBU_INSERT
161283**     * RBU_DELETE
161284**     * RBU_IDX_DELETE
161285**     * RBU_UPDATE
161286**
161287** If RBU_UPDATE is returned, then output variable *pzMask is set to
161288** point to the text value indicating the columns to update.
161289**
161290** If the rbu_control field contains an invalid value, an error code and
161291** message are left in the RBU handle and zero returned.
161292*/
161293static int rbuStepType(sqlite3rbu *p, const char **pzMask){
161294  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
161295  int res = 0;                    /* Return value */
161296
161297  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
161298    case SQLITE_INTEGER: {
161299      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
161300      if( iVal==0 ){
161301        res = RBU_INSERT;
161302      }else if( iVal==1 ){
161303        res = RBU_DELETE;
161304      }else if( iVal==2 ){
161305        res = RBU_IDX_DELETE;
161306      }else if( iVal==3 ){
161307        res = RBU_IDX_INSERT;
161308      }
161309      break;
161310    }
161311
161312    case SQLITE_TEXT: {
161313      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
161314      if( z==0 ){
161315        p->rc = SQLITE_NOMEM;
161316      }else{
161317        *pzMask = (const char*)z;
161318      }
161319      res = RBU_UPDATE;
161320
161321      break;
161322    }
161323
161324    default:
161325      break;
161326  }
161327
161328  if( res==0 ){
161329    rbuBadControlError(p);
161330  }
161331  return res;
161332}
161333
161334#ifdef SQLITE_DEBUG
161335/*
161336** Assert that column iCol of statement pStmt is named zName.
161337*/
161338static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
161339  const char *zCol = sqlite3_column_name(pStmt, iCol);
161340  assert( 0==sqlite3_stricmp(zName, zCol) );
161341}
161342#else
161343# define assertColumnName(x,y,z)
161344#endif
161345
161346/*
161347** This function does the work for an sqlite3rbu_step() call.
161348**
161349** The object-iterator (p->objiter) currently points to a valid object,
161350** and the input cursor (p->objiter.pSelect) currently points to a valid
161351** input row. Perform whatever processing is required and return.
161352**
161353** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
161354** and message is left in the RBU handle and a copy of the error code
161355** returned.
161356*/
161357static int rbuStep(sqlite3rbu *p){
161358  RbuObjIter *pIter = &p->objiter;
161359  const char *zMask = 0;
161360  int i;
161361  int eType = rbuStepType(p, &zMask);
161362
161363  if( eType ){
161364    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
161365
161366    if( pIter->zIdx==0 && eType==RBU_IDX_DELETE ){
161367      rbuBadControlError(p);
161368    }
161369    else if(
161370        eType==RBU_INSERT
161371     || eType==RBU_DELETE
161372     || eType==RBU_IDX_DELETE
161373     || eType==RBU_IDX_INSERT
161374    ){
161375      sqlite3_value *pVal;
161376      sqlite3_stmt *pWriter;
161377
161378      assert( eType!=RBU_UPDATE );
161379      assert( eType!=RBU_DELETE || pIter->zIdx==0 );
161380
161381      if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
161382        pWriter = pIter->pDelete;
161383      }else{
161384        pWriter = pIter->pInsert;
161385      }
161386
161387      for(i=0; i<pIter->nCol; i++){
161388        /* If this is an INSERT into a table b-tree and the table has an
161389        ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
161390        ** to write a NULL into the IPK column. That is not permitted.  */
161391        if( eType==RBU_INSERT
161392         && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
161393         && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
161394        ){
161395          p->rc = SQLITE_MISMATCH;
161396          p->zErrmsg = sqlite3_mprintf("datatype mismatch");
161397          goto step_out;
161398        }
161399
161400        if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
161401          continue;
161402        }
161403
161404        pVal = sqlite3_column_value(pIter->pSelect, i);
161405        p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
161406        if( p->rc ) goto step_out;
161407      }
161408      if( pIter->zIdx==0
161409       && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
161410      ){
161411        /* For a virtual table, or a table with no primary key, the
161412        ** SELECT statement is:
161413        **
161414        **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
161415        **
161416        ** Hence column_value(pIter->nCol+1).
161417        */
161418        assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
161419        pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
161420        p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
161421      }
161422      if( p->rc==SQLITE_OK ){
161423        sqlite3_step(pWriter);
161424        p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
161425      }
161426    }else{
161427      sqlite3_value *pVal;
161428      sqlite3_stmt *pUpdate = 0;
161429      assert( eType==RBU_UPDATE );
161430      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
161431      if( pUpdate ){
161432        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
161433          char c = zMask[pIter->aiSrcOrder[i]];
161434          pVal = sqlite3_column_value(pIter->pSelect, i);
161435          if( pIter->abTblPk[i] || c!='.' ){
161436            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
161437          }
161438        }
161439        if( p->rc==SQLITE_OK
161440         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
161441        ){
161442          /* Bind the rbu_rowid value to column _rowid_ */
161443          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
161444          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
161445          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
161446        }
161447        if( p->rc==SQLITE_OK ){
161448          sqlite3_step(pUpdate);
161449          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
161450        }
161451      }
161452    }
161453  }
161454
161455 step_out:
161456  return p->rc;
161457}
161458
161459/*
161460** Increment the schema cookie of the main database opened by p->dbMain.
161461*/
161462static void rbuIncrSchemaCookie(sqlite3rbu *p){
161463  if( p->rc==SQLITE_OK ){
161464    int iCookie = 1000000;
161465    sqlite3_stmt *pStmt;
161466
161467    p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
161468        "PRAGMA schema_version"
161469    );
161470    if( p->rc==SQLITE_OK ){
161471      /* Coverage: it may be that this sqlite3_step() cannot fail. There
161472      ** is already a transaction open, so the prepared statement cannot
161473      ** throw an SQLITE_SCHEMA exception. The only database page the
161474      ** statement reads is page 1, which is guaranteed to be in the cache.
161475      ** And no memory allocations are required.  */
161476      if( SQLITE_ROW==sqlite3_step(pStmt) ){
161477        iCookie = sqlite3_column_int(pStmt, 0);
161478      }
161479      rbuFinalize(p, pStmt);
161480    }
161481    if( p->rc==SQLITE_OK ){
161482      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
161483    }
161484  }
161485}
161486
161487/*
161488** Update the contents of the rbu_state table within the rbu database. The
161489** value stored in the RBU_STATE_STAGE column is eStage. All other values
161490** are determined by inspecting the rbu handle passed as the first argument.
161491*/
161492static void rbuSaveState(sqlite3rbu *p, int eStage){
161493  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
161494    sqlite3_stmt *pInsert = 0;
161495    int rc;
161496
161497    assert( p->zErrmsg==0 );
161498    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
161499        sqlite3_mprintf(
161500          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
161501          "(%d, %d), "
161502          "(%d, %Q), "
161503          "(%d, %Q), "
161504          "(%d, %d), "
161505          "(%d, %d), "
161506          "(%d, %lld), "
161507          "(%d, %lld), "
161508          "(%d, %lld) ",
161509          p->zStateDb,
161510          RBU_STATE_STAGE, eStage,
161511          RBU_STATE_TBL, p->objiter.zTbl,
161512          RBU_STATE_IDX, p->objiter.zIdx,
161513          RBU_STATE_ROW, p->nStep,
161514          RBU_STATE_PROGRESS, p->nProgress,
161515          RBU_STATE_CKPT, p->iWalCksum,
161516          RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
161517          RBU_STATE_OALSZ, p->iOalSz
161518      )
161519    );
161520    assert( pInsert==0 || rc==SQLITE_OK );
161521
161522    if( rc==SQLITE_OK ){
161523      sqlite3_step(pInsert);
161524      rc = sqlite3_finalize(pInsert);
161525    }
161526    if( rc!=SQLITE_OK ) p->rc = rc;
161527  }
161528}
161529
161530
161531/*
161532** Step the RBU object.
161533*/
161534SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
161535  if( p ){
161536    switch( p->eStage ){
161537      case RBU_STAGE_OAL: {
161538        RbuObjIter *pIter = &p->objiter;
161539        while( p->rc==SQLITE_OK && pIter->zTbl ){
161540
161541          if( pIter->bCleanup ){
161542            /* Clean up the rbu_tmp_xxx table for the previous table. It
161543            ** cannot be dropped as there are currently active SQL statements.
161544            ** But the contents can be deleted.  */
161545            if( pIter->abIndexed ){
161546              rbuMPrintfExec(p, p->dbRbu,
161547                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
161548              );
161549            }
161550          }else{
161551            rbuObjIterPrepareAll(p, pIter, 0);
161552
161553            /* Advance to the next row to process. */
161554            if( p->rc==SQLITE_OK ){
161555              int rc = sqlite3_step(pIter->pSelect);
161556              if( rc==SQLITE_ROW ){
161557                p->nProgress++;
161558                p->nStep++;
161559                return rbuStep(p);
161560              }
161561              p->rc = sqlite3_reset(pIter->pSelect);
161562              p->nStep = 0;
161563            }
161564          }
161565
161566          rbuObjIterNext(p, pIter);
161567        }
161568
161569        if( p->rc==SQLITE_OK ){
161570          assert( pIter->zTbl==0 );
161571          rbuSaveState(p, RBU_STAGE_MOVE);
161572          rbuIncrSchemaCookie(p);
161573          if( p->rc==SQLITE_OK ){
161574            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
161575          }
161576          if( p->rc==SQLITE_OK ){
161577            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
161578          }
161579          p->eStage = RBU_STAGE_MOVE;
161580        }
161581        break;
161582      }
161583
161584      case RBU_STAGE_MOVE: {
161585        if( p->rc==SQLITE_OK ){
161586          rbuMoveOalFile(p);
161587          p->nProgress++;
161588        }
161589        break;
161590      }
161591
161592      case RBU_STAGE_CKPT: {
161593        if( p->rc==SQLITE_OK ){
161594          if( p->nStep>=p->nFrame ){
161595            sqlite3_file *pDb = p->pTargetFd->pReal;
161596
161597            /* Sync the db file */
161598            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
161599
161600            /* Update nBackfill */
161601            if( p->rc==SQLITE_OK ){
161602              void volatile *ptr;
161603              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
161604              if( p->rc==SQLITE_OK ){
161605                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
161606              }
161607            }
161608
161609            if( p->rc==SQLITE_OK ){
161610              p->eStage = RBU_STAGE_DONE;
161611              p->rc = SQLITE_DONE;
161612            }
161613          }else{
161614            RbuFrame *pFrame = &p->aFrame[p->nStep];
161615            rbuCheckpointFrame(p, pFrame);
161616            p->nStep++;
161617          }
161618          p->nProgress++;
161619        }
161620        break;
161621      }
161622
161623      default:
161624        break;
161625    }
161626    return p->rc;
161627  }else{
161628    return SQLITE_NOMEM;
161629  }
161630}
161631
161632/*
161633** Free an RbuState object allocated by rbuLoadState().
161634*/
161635static void rbuFreeState(RbuState *p){
161636  if( p ){
161637    sqlite3_free(p->zTbl);
161638    sqlite3_free(p->zIdx);
161639    sqlite3_free(p);
161640  }
161641}
161642
161643/*
161644** Allocate an RbuState object and load the contents of the rbu_state
161645** table into it. Return a pointer to the new object. It is the
161646** responsibility of the caller to eventually free the object using
161647** sqlite3_free().
161648**
161649** If an error occurs, leave an error code and message in the rbu handle
161650** and return NULL.
161651*/
161652static RbuState *rbuLoadState(sqlite3rbu *p){
161653  RbuState *pRet = 0;
161654  sqlite3_stmt *pStmt = 0;
161655  int rc;
161656  int rc2;
161657
161658  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
161659  if( pRet==0 ) return 0;
161660
161661  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
161662      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
161663  );
161664  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
161665    switch( sqlite3_column_int(pStmt, 0) ){
161666      case RBU_STATE_STAGE:
161667        pRet->eStage = sqlite3_column_int(pStmt, 1);
161668        if( pRet->eStage!=RBU_STAGE_OAL
161669         && pRet->eStage!=RBU_STAGE_MOVE
161670         && pRet->eStage!=RBU_STAGE_CKPT
161671        ){
161672          p->rc = SQLITE_CORRUPT;
161673        }
161674        break;
161675
161676      case RBU_STATE_TBL:
161677        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
161678        break;
161679
161680      case RBU_STATE_IDX:
161681        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
161682        break;
161683
161684      case RBU_STATE_ROW:
161685        pRet->nRow = sqlite3_column_int(pStmt, 1);
161686        break;
161687
161688      case RBU_STATE_PROGRESS:
161689        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
161690        break;
161691
161692      case RBU_STATE_CKPT:
161693        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
161694        break;
161695
161696      case RBU_STATE_COOKIE:
161697        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
161698        break;
161699
161700      case RBU_STATE_OALSZ:
161701        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
161702        break;
161703
161704      default:
161705        rc = SQLITE_CORRUPT;
161706        break;
161707    }
161708  }
161709  rc2 = sqlite3_finalize(pStmt);
161710  if( rc==SQLITE_OK ) rc = rc2;
161711
161712  p->rc = rc;
161713  return pRet;
161714}
161715
161716/*
161717** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
161718** otherwise. Either or both argument may be NULL. Two NULL values are
161719** considered equal, and NULL is considered distinct from all other values.
161720*/
161721static int rbuStrCompare(const char *z1, const char *z2){
161722  if( z1==0 && z2==0 ) return 0;
161723  if( z1==0 || z2==0 ) return 1;
161724  return (sqlite3_stricmp(z1, z2)!=0);
161725}
161726
161727/*
161728** This function is called as part of sqlite3rbu_open() when initializing
161729** an rbu handle in OAL stage. If the rbu update has not started (i.e.
161730** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
161731** things so that the next call to sqlite3rbu_step() continues on from
161732** where the previous rbu handle left off.
161733**
161734** If an error occurs, an error code and error message are left in the
161735** rbu handle passed as the first argument.
161736*/
161737static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
161738  assert( p->rc==SQLITE_OK );
161739  if( pState->zTbl ){
161740    RbuObjIter *pIter = &p->objiter;
161741    int rc = SQLITE_OK;
161742
161743    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
161744       || rbuStrCompare(pIter->zIdx, pState->zIdx)
161745       || rbuStrCompare(pIter->zTbl, pState->zTbl)
161746    )){
161747      rc = rbuObjIterNext(p, pIter);
161748    }
161749
161750    if( rc==SQLITE_OK && !pIter->zTbl ){
161751      rc = SQLITE_ERROR;
161752      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
161753    }
161754
161755    if( rc==SQLITE_OK ){
161756      p->nStep = pState->nRow;
161757      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
161758    }
161759
161760    p->rc = rc;
161761  }
161762}
161763
161764/*
161765** If there is a "*-oal" file in the file-system corresponding to the
161766** target database in the file-system, delete it. If an error occurs,
161767** leave an error code and error message in the rbu handle.
161768*/
161769static void rbuDeleteOalFile(sqlite3rbu *p){
161770  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
161771  if( zOal ){
161772    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
161773    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
161774    pVfs->xDelete(pVfs, zOal, 0);
161775    sqlite3_free(zOal);
161776  }
161777}
161778
161779/*
161780** Allocate a private rbu VFS for the rbu handle passed as the only
161781** argument. This VFS will be used unless the call to sqlite3rbu_open()
161782** specified a URI with a vfs=? option in place of a target database
161783** file name.
161784*/
161785static void rbuCreateVfs(sqlite3rbu *p){
161786  int rnd;
161787  char zRnd[64];
161788
161789  assert( p->rc==SQLITE_OK );
161790  sqlite3_randomness(sizeof(int), (void*)&rnd);
161791  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
161792  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
161793  if( p->rc==SQLITE_OK ){
161794    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
161795    assert( pVfs );
161796    p->zVfsName = pVfs->zName;
161797  }
161798}
161799
161800/*
161801** Destroy the private VFS created for the rbu handle passed as the only
161802** argument by an earlier call to rbuCreateVfs().
161803*/
161804static void rbuDeleteVfs(sqlite3rbu *p){
161805  if( p->zVfsName ){
161806    sqlite3rbu_destroy_vfs(p->zVfsName);
161807    p->zVfsName = 0;
161808  }
161809}
161810
161811/*
161812** Open and return a new RBU handle.
161813*/
161814SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
161815  const char *zTarget,
161816  const char *zRbu,
161817  const char *zState
161818){
161819  sqlite3rbu *p;
161820  int nTarget = strlen(zTarget);
161821  int nRbu = strlen(zRbu);
161822  int nState = zState ? strlen(zState) : 0;
161823
161824  p = (sqlite3rbu*)sqlite3_malloc(sizeof(sqlite3rbu)+nTarget+1+nRbu+1+nState+1);
161825  if( p ){
161826    RbuState *pState = 0;
161827
161828    /* Create the custom VFS. */
161829    memset(p, 0, sizeof(sqlite3rbu));
161830    rbuCreateVfs(p);
161831
161832    /* Open the target database */
161833    if( p->rc==SQLITE_OK ){
161834      p->zTarget = (char*)&p[1];
161835      memcpy(p->zTarget, zTarget, nTarget+1);
161836      p->zRbu = &p->zTarget[nTarget+1];
161837      memcpy(p->zRbu, zRbu, nRbu+1);
161838      if( zState ){
161839        p->zState = &p->zRbu[nRbu+1];
161840        memcpy(p->zState, zState, nState+1);
161841      }
161842      rbuOpenDatabase(p);
161843    }
161844
161845    /* If it has not already been created, create the rbu_state table */
161846    rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
161847
161848    if( p->rc==SQLITE_OK ){
161849      pState = rbuLoadState(p);
161850      assert( pState || p->rc!=SQLITE_OK );
161851      if( p->rc==SQLITE_OK ){
161852
161853        if( pState->eStage==0 ){
161854          rbuDeleteOalFile(p);
161855          p->eStage = RBU_STAGE_OAL;
161856        }else{
161857          p->eStage = pState->eStage;
161858        }
161859        p->nProgress = pState->nProgress;
161860        p->iOalSz = pState->iOalSz;
161861      }
161862    }
161863    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
161864
161865    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
161866      if( p->eStage==RBU_STAGE_OAL ){
161867        p->rc = SQLITE_ERROR;
161868        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
161869      }else if( p->eStage==RBU_STAGE_MOVE ){
161870        p->eStage = RBU_STAGE_CKPT;
161871        p->nStep = 0;
161872      }
161873    }
161874
161875    if( p->rc==SQLITE_OK
161876     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
161877     && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
161878    ){
161879      /* At this point (pTargetFd->iCookie) contains the value of the
161880      ** change-counter cookie (the thing that gets incremented when a
161881      ** transaction is committed in rollback mode) currently stored on
161882      ** page 1 of the database file. */
161883      p->rc = SQLITE_BUSY;
161884      p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
161885    }
161886
161887    if( p->rc==SQLITE_OK ){
161888      if( p->eStage==RBU_STAGE_OAL ){
161889        sqlite3 *db = p->dbMain;
161890
161891        /* Open transactions both databases. The *-oal file is opened or
161892        ** created at this point. */
161893        p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
161894        if( p->rc==SQLITE_OK ){
161895          p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
161896        }
161897
161898        /* Check if the main database is a zipvfs db. If it is, set the upper
161899        ** level pager to use "journal_mode=off". This prevents it from
161900        ** generating a large journal using a temp file.  */
161901        if( p->rc==SQLITE_OK ){
161902          int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
161903          if( frc==SQLITE_OK ){
161904            p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
161905          }
161906        }
161907
161908        /* Point the object iterator at the first object */
161909        if( p->rc==SQLITE_OK ){
161910          p->rc = rbuObjIterFirst(p, &p->objiter);
161911        }
161912
161913        /* If the RBU database contains no data_xxx tables, declare the RBU
161914        ** update finished.  */
161915        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
161916          p->rc = SQLITE_DONE;
161917        }
161918
161919        if( p->rc==SQLITE_OK ){
161920          rbuSetupOal(p, pState);
161921        }
161922
161923      }else if( p->eStage==RBU_STAGE_MOVE ){
161924        /* no-op */
161925      }else if( p->eStage==RBU_STAGE_CKPT ){
161926        rbuSetupCheckpoint(p, pState);
161927      }else if( p->eStage==RBU_STAGE_DONE ){
161928        p->rc = SQLITE_DONE;
161929      }else{
161930        p->rc = SQLITE_CORRUPT;
161931      }
161932    }
161933
161934    rbuFreeState(pState);
161935  }
161936
161937  return p;
161938}
161939
161940
161941/*
161942** Return the database handle used by pRbu.
161943*/
161944SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
161945  sqlite3 *db = 0;
161946  if( pRbu ){
161947    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
161948  }
161949  return db;
161950}
161951
161952
161953/*
161954** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
161955** then edit any error message string so as to remove all occurrences of
161956** the pattern "rbu_imp_[0-9]*".
161957*/
161958static void rbuEditErrmsg(sqlite3rbu *p){
161959  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
161960    int i;
161961    int nErrmsg = strlen(p->zErrmsg);
161962    for(i=0; i<(nErrmsg-8); i++){
161963      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
161964        int nDel = 8;
161965        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
161966        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
161967        nErrmsg -= nDel;
161968      }
161969    }
161970  }
161971}
161972
161973/*
161974** Close the RBU handle.
161975*/
161976SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
161977  int rc;
161978  if( p ){
161979
161980    /* Commit the transaction to the *-oal file. */
161981    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
161982      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
161983    }
161984
161985    rbuSaveState(p, p->eStage);
161986
161987    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
161988      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
161989    }
161990
161991    /* Close any open statement handles. */
161992    rbuObjIterFinalize(&p->objiter);
161993
161994    /* Close the open database handle and VFS object. */
161995    sqlite3_close(p->dbMain);
161996    sqlite3_close(p->dbRbu);
161997    rbuDeleteVfs(p);
161998    sqlite3_free(p->aBuf);
161999    sqlite3_free(p->aFrame);
162000
162001    rbuEditErrmsg(p);
162002    rc = p->rc;
162003    *pzErrmsg = p->zErrmsg;
162004    sqlite3_free(p);
162005  }else{
162006    rc = SQLITE_NOMEM;
162007    *pzErrmsg = 0;
162008  }
162009  return rc;
162010}
162011
162012/*
162013** Return the total number of key-value operations (inserts, deletes or
162014** updates) that have been performed on the target database since the
162015** current RBU update was started.
162016*/
162017SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
162018  return pRbu->nProgress;
162019}
162020
162021SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
162022  int rc = p->rc;
162023
162024  if( rc==SQLITE_DONE ) return SQLITE_OK;
162025
162026  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
162027  if( p->eStage==RBU_STAGE_OAL ){
162028    assert( rc!=SQLITE_DONE );
162029    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
162030  }
162031
162032  p->rc = rc;
162033  rbuSaveState(p, p->eStage);
162034  rc = p->rc;
162035
162036  if( p->eStage==RBU_STAGE_OAL ){
162037    assert( rc!=SQLITE_DONE );
162038    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
162039    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
162040    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
162041  }
162042
162043  p->rc = rc;
162044  return rc;
162045}
162046
162047/**************************************************************************
162048** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
162049** of a standard VFS in the following ways:
162050**
162051** 1. Whenever the first page of a main database file is read or
162052**    written, the value of the change-counter cookie is stored in
162053**    rbu_file.iCookie. Similarly, the value of the "write-version"
162054**    database header field is stored in rbu_file.iWriteVer. This ensures
162055**    that the values are always trustworthy within an open transaction.
162056**
162057** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
162058**    member variable of the associated database file descriptor is set
162059**    to point to the new file. A mutex protected linked list of all main
162060**    db fds opened using a particular RBU VFS is maintained at
162061**    rbu_vfs.pMain to facilitate this.
162062**
162063** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
162064**    object can be marked as the target database of an RBU update. This
162065**    turns on the following extra special behaviour:
162066**
162067** 3a. If xAccess() is called to check if there exists a *-wal file
162068**     associated with an RBU target database currently in RBU_STAGE_OAL
162069**     stage (preparing the *-oal file), the following special handling
162070**     applies:
162071**
162072**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
162073**        target database may not be in wal mode already.
162074**
162075**      * if the *-wal file does not exist, set the output parameter to
162076**        non-zero (to tell SQLite that it does exist) anyway.
162077**
162078**     Then, when xOpen() is called to open the *-wal file associated with
162079**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
162080**     file, the rbu vfs opens the corresponding *-oal file instead.
162081**
162082** 3b. The *-shm pages returned by xShmMap() for a target db file in
162083**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
162084**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
162085**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
162086**     because assert() statements in some VFS implementations fail if
162087**     xShmLock() is called before xShmMap().
162088**
162089** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
162090**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
162091**     fails with an SQLITE_BUSY error. This is to stop RBU connections
162092**     from automatically checkpointing a *-wal (or *-oal) file from within
162093**     sqlite3_close().
162094**
162095** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
162096**     all xWrite() calls on the target database file perform no IO.
162097**     Instead the frame and page numbers that would be read and written
162098**     are recorded. Additionally, successful attempts to obtain exclusive
162099**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
162100**     database file are recorded. xShmLock() calls to unlock the same
162101**     locks are no-ops (so that once obtained, these locks are never
162102**     relinquished). Finally, calls to xSync() on the target database
162103**     file fail with SQLITE_INTERNAL errors.
162104*/
162105
162106static void rbuUnlockShm(rbu_file *p){
162107  if( p->pRbu ){
162108    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
162109    int i;
162110    for(i=0; i<SQLITE_SHM_NLOCK;i++){
162111      if( (1<<i) & p->pRbu->mLock ){
162112        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
162113      }
162114    }
162115    p->pRbu->mLock = 0;
162116  }
162117}
162118
162119/*
162120** Close an rbu file.
162121*/
162122static int rbuVfsClose(sqlite3_file *pFile){
162123  rbu_file *p = (rbu_file*)pFile;
162124  int rc;
162125  int i;
162126
162127  /* Free the contents of the apShm[] array. And the array itself. */
162128  for(i=0; i<p->nShm; i++){
162129    sqlite3_free(p->apShm[i]);
162130  }
162131  sqlite3_free(p->apShm);
162132  p->apShm = 0;
162133  sqlite3_free(p->zDel);
162134
162135  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
162136    rbu_file **pp;
162137    sqlite3_mutex_enter(p->pRbuVfs->mutex);
162138    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
162139    *pp = p->pMainNext;
162140    sqlite3_mutex_leave(p->pRbuVfs->mutex);
162141    rbuUnlockShm(p);
162142    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
162143  }
162144
162145  /* Close the underlying file handle */
162146  rc = p->pReal->pMethods->xClose(p->pReal);
162147  return rc;
162148}
162149
162150
162151/*
162152** Read and return an unsigned 32-bit big-endian integer from the buffer
162153** passed as the only argument.
162154*/
162155static u32 rbuGetU32(u8 *aBuf){
162156  return ((u32)aBuf[0] << 24)
162157       + ((u32)aBuf[1] << 16)
162158       + ((u32)aBuf[2] <<  8)
162159       + ((u32)aBuf[3]);
162160}
162161
162162/*
162163** Read data from an rbuVfs-file.
162164*/
162165static int rbuVfsRead(
162166  sqlite3_file *pFile,
162167  void *zBuf,
162168  int iAmt,
162169  sqlite_int64 iOfst
162170){
162171  rbu_file *p = (rbu_file*)pFile;
162172  sqlite3rbu *pRbu = p->pRbu;
162173  int rc;
162174
162175  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
162176    assert( p->openFlags & SQLITE_OPEN_WAL );
162177    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
162178  }else{
162179    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
162180     && (p->openFlags & SQLITE_OPEN_WAL)
162181     && iOfst>=pRbu->iOalSz
162182    ){
162183      rc = SQLITE_OK;
162184      memset(zBuf, 0, iAmt);
162185    }else{
162186      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
162187    }
162188    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
162189      /* These look like magic numbers. But they are stable, as they are part
162190       ** of the definition of the SQLite file format, which may not change. */
162191      u8 *pBuf = (u8*)zBuf;
162192      p->iCookie = rbuGetU32(&pBuf[24]);
162193      p->iWriteVer = pBuf[19];
162194    }
162195  }
162196  return rc;
162197}
162198
162199/*
162200** Write data to an rbuVfs-file.
162201*/
162202static int rbuVfsWrite(
162203  sqlite3_file *pFile,
162204  const void *zBuf,
162205  int iAmt,
162206  sqlite_int64 iOfst
162207){
162208  rbu_file *p = (rbu_file*)pFile;
162209  sqlite3rbu *pRbu = p->pRbu;
162210  int rc;
162211
162212  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
162213    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
162214    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
162215  }else{
162216    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
162217     && (p->openFlags & SQLITE_OPEN_WAL)
162218     && iOfst>=pRbu->iOalSz
162219    ){
162220      pRbu->iOalSz = iAmt + iOfst;
162221    }
162222    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
162223    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
162224      /* These look like magic numbers. But they are stable, as they are part
162225      ** of the definition of the SQLite file format, which may not change. */
162226      u8 *pBuf = (u8*)zBuf;
162227      p->iCookie = rbuGetU32(&pBuf[24]);
162228      p->iWriteVer = pBuf[19];
162229    }
162230  }
162231  return rc;
162232}
162233
162234/*
162235** Truncate an rbuVfs-file.
162236*/
162237static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
162238  rbu_file *p = (rbu_file*)pFile;
162239  return p->pReal->pMethods->xTruncate(p->pReal, size);
162240}
162241
162242/*
162243** Sync an rbuVfs-file.
162244*/
162245static int rbuVfsSync(sqlite3_file *pFile, int flags){
162246  rbu_file *p = (rbu_file *)pFile;
162247  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
162248    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
162249      return SQLITE_INTERNAL;
162250    }
162251    return SQLITE_OK;
162252  }
162253  return p->pReal->pMethods->xSync(p->pReal, flags);
162254}
162255
162256/*
162257** Return the current file-size of an rbuVfs-file.
162258*/
162259static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
162260  rbu_file *p = (rbu_file *)pFile;
162261  return p->pReal->pMethods->xFileSize(p->pReal, pSize);
162262}
162263
162264/*
162265** Lock an rbuVfs-file.
162266*/
162267static int rbuVfsLock(sqlite3_file *pFile, int eLock){
162268  rbu_file *p = (rbu_file*)pFile;
162269  sqlite3rbu *pRbu = p->pRbu;
162270  int rc = SQLITE_OK;
162271
162272  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162273  if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
162274    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
162275    ** prevents it from checkpointing the database from sqlite3_close(). */
162276    rc = SQLITE_BUSY;
162277  }else{
162278    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
162279  }
162280
162281  return rc;
162282}
162283
162284/*
162285** Unlock an rbuVfs-file.
162286*/
162287static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
162288  rbu_file *p = (rbu_file *)pFile;
162289  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
162290}
162291
162292/*
162293** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
162294*/
162295static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
162296  rbu_file *p = (rbu_file *)pFile;
162297  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
162298}
162299
162300/*
162301** File control method. For custom operations on an rbuVfs-file.
162302*/
162303static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
162304  rbu_file *p = (rbu_file *)pFile;
162305  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
162306  int rc;
162307
162308  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
162309       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
162310  );
162311  if( op==SQLITE_FCNTL_RBU ){
162312    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
162313
162314    /* First try to find another RBU vfs lower down in the vfs stack. If
162315    ** one is found, this vfs will operate in pass-through mode. The lower
162316    ** level vfs will do the special RBU handling.  */
162317    rc = xControl(p->pReal, op, pArg);
162318
162319    if( rc==SQLITE_NOTFOUND ){
162320      /* Now search for a zipvfs instance lower down in the VFS stack. If
162321      ** one is found, this is an error.  */
162322      void *dummy = 0;
162323      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
162324      if( rc==SQLITE_OK ){
162325        rc = SQLITE_ERROR;
162326        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
162327      }else if( rc==SQLITE_NOTFOUND ){
162328        pRbu->pTargetFd = p;
162329        p->pRbu = pRbu;
162330        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
162331        rc = SQLITE_OK;
162332      }
162333    }
162334    return rc;
162335  }
162336
162337  rc = xControl(p->pReal, op, pArg);
162338  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
162339    rbu_vfs *pRbuVfs = p->pRbuVfs;
162340    char *zIn = *(char**)pArg;
162341    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
162342    *(char**)pArg = zOut;
162343    if( zOut==0 ) rc = SQLITE_NOMEM;
162344  }
162345
162346  return rc;
162347}
162348
162349/*
162350** Return the sector-size in bytes for an rbuVfs-file.
162351*/
162352static int rbuVfsSectorSize(sqlite3_file *pFile){
162353  rbu_file *p = (rbu_file *)pFile;
162354  return p->pReal->pMethods->xSectorSize(p->pReal);
162355}
162356
162357/*
162358** Return the device characteristic flags supported by an rbuVfs-file.
162359*/
162360static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
162361  rbu_file *p = (rbu_file *)pFile;
162362  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
162363}
162364
162365/*
162366** Take or release a shared-memory lock.
162367*/
162368static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
162369  rbu_file *p = (rbu_file*)pFile;
162370  sqlite3rbu *pRbu = p->pRbu;
162371  int rc = SQLITE_OK;
162372
162373#ifdef SQLITE_AMALGAMATION
162374    assert( WAL_CKPT_LOCK==1 );
162375#endif
162376
162377  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162378  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
162379    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
162380    ** taking this lock also prevents any checkpoints from occurring.
162381    ** todo: really, it's not clear why this might occur, as
162382    ** wal_autocheckpoint ought to be turned off.  */
162383    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
162384  }else{
162385    int bCapture = 0;
162386    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
162387     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
162388     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
162389    ){
162390      bCapture = 1;
162391    }
162392
162393    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
162394      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
162395      if( bCapture && rc==SQLITE_OK ){
162396        pRbu->mLock |= (1 << ofst);
162397      }
162398    }
162399  }
162400
162401  return rc;
162402}
162403
162404/*
162405** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
162406*/
162407static int rbuVfsShmMap(
162408  sqlite3_file *pFile,
162409  int iRegion,
162410  int szRegion,
162411  int isWrite,
162412  void volatile **pp
162413){
162414  rbu_file *p = (rbu_file*)pFile;
162415  int rc = SQLITE_OK;
162416  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
162417
162418  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
162419  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
162420  ** instead of a file on disk.  */
162421  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162422  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
162423    if( iRegion<=p->nShm ){
162424      int nByte = (iRegion+1) * sizeof(char*);
162425      char **apNew = (char**)sqlite3_realloc(p->apShm, nByte);
162426      if( apNew==0 ){
162427        rc = SQLITE_NOMEM;
162428      }else{
162429        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
162430        p->apShm = apNew;
162431        p->nShm = iRegion+1;
162432      }
162433    }
162434
162435    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
162436      char *pNew = (char*)sqlite3_malloc(szRegion);
162437      if( pNew==0 ){
162438        rc = SQLITE_NOMEM;
162439      }else{
162440        memset(pNew, 0, szRegion);
162441        p->apShm[iRegion] = pNew;
162442      }
162443    }
162444
162445    if( rc==SQLITE_OK ){
162446      *pp = p->apShm[iRegion];
162447    }else{
162448      *pp = 0;
162449    }
162450  }else{
162451    assert( p->apShm==0 );
162452    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
162453  }
162454
162455  return rc;
162456}
162457
162458/*
162459** Memory barrier.
162460*/
162461static void rbuVfsShmBarrier(sqlite3_file *pFile){
162462  rbu_file *p = (rbu_file *)pFile;
162463  p->pReal->pMethods->xShmBarrier(p->pReal);
162464}
162465
162466/*
162467** The xShmUnmap method.
162468*/
162469static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
162470  rbu_file *p = (rbu_file*)pFile;
162471  int rc = SQLITE_OK;
162472  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
162473
162474  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162475  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
162476    /* no-op */
162477  }else{
162478    /* Release the checkpointer and writer locks */
162479    rbuUnlockShm(p);
162480    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
162481  }
162482  return rc;
162483}
162484
162485/*
162486** Given that zWal points to a buffer containing a wal file name passed to
162487** either the xOpen() or xAccess() VFS method, return a pointer to the
162488** file-handle opened by the same database connection on the corresponding
162489** database file.
162490*/
162491static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
162492  rbu_file *pDb;
162493  sqlite3_mutex_enter(pRbuVfs->mutex);
162494  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext);
162495  sqlite3_mutex_leave(pRbuVfs->mutex);
162496  return pDb;
162497}
162498
162499/*
162500** Open an rbu file handle.
162501*/
162502static int rbuVfsOpen(
162503  sqlite3_vfs *pVfs,
162504  const char *zName,
162505  sqlite3_file *pFile,
162506  int flags,
162507  int *pOutFlags
162508){
162509  static sqlite3_io_methods rbuvfs_io_methods = {
162510    2,                            /* iVersion */
162511    rbuVfsClose,                  /* xClose */
162512    rbuVfsRead,                   /* xRead */
162513    rbuVfsWrite,                  /* xWrite */
162514    rbuVfsTruncate,               /* xTruncate */
162515    rbuVfsSync,                   /* xSync */
162516    rbuVfsFileSize,               /* xFileSize */
162517    rbuVfsLock,                   /* xLock */
162518    rbuVfsUnlock,                 /* xUnlock */
162519    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
162520    rbuVfsFileControl,            /* xFileControl */
162521    rbuVfsSectorSize,             /* xSectorSize */
162522    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
162523    rbuVfsShmMap,                 /* xShmMap */
162524    rbuVfsShmLock,                /* xShmLock */
162525    rbuVfsShmBarrier,             /* xShmBarrier */
162526    rbuVfsShmUnmap,               /* xShmUnmap */
162527    0, 0                          /* xFetch, xUnfetch */
162528  };
162529  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
162530  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
162531  rbu_file *pFd = (rbu_file *)pFile;
162532  int rc = SQLITE_OK;
162533  const char *zOpen = zName;
162534
162535  memset(pFd, 0, sizeof(rbu_file));
162536  pFd->pReal = (sqlite3_file*)&pFd[1];
162537  pFd->pRbuVfs = pRbuVfs;
162538  pFd->openFlags = flags;
162539  if( zName ){
162540    if( flags & SQLITE_OPEN_MAIN_DB ){
162541      /* A main database has just been opened. The following block sets
162542      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
162543      ** the name of the *-wal file this db connection will use. SQLite
162544      ** happens to pass a pointer to this buffer when using xAccess()
162545      ** or xOpen() to operate on the *-wal file.  */
162546      int n = strlen(zName);
162547      const char *z = &zName[n];
162548      if( flags & SQLITE_OPEN_URI ){
162549        int odd = 0;
162550        while( 1 ){
162551          if( z[0]==0 ){
162552            odd = 1 - odd;
162553            if( odd && z[1]==0 ) break;
162554          }
162555          z++;
162556        }
162557        z += 2;
162558      }else{
162559        while( *z==0 ) z++;
162560      }
162561      z += (n + 8 + 1);
162562      pFd->zWal = z;
162563    }
162564    else if( flags & SQLITE_OPEN_WAL ){
162565      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
162566      if( pDb ){
162567        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
162568          /* This call is to open a *-wal file. Intead, open the *-oal. This
162569          ** code ensures that the string passed to xOpen() is terminated by a
162570          ** pair of '\0' bytes in case the VFS attempts to extract a URI
162571          ** parameter from it.  */
162572          int nCopy = strlen(zName);
162573          char *zCopy = sqlite3_malloc(nCopy+2);
162574          if( zCopy ){
162575            memcpy(zCopy, zName, nCopy);
162576            zCopy[nCopy-3] = 'o';
162577            zCopy[nCopy] = '\0';
162578            zCopy[nCopy+1] = '\0';
162579            zOpen = (const char*)(pFd->zDel = zCopy);
162580          }else{
162581            rc = SQLITE_NOMEM;
162582          }
162583          pFd->pRbu = pDb->pRbu;
162584        }
162585        pDb->pWalFd = pFd;
162586      }
162587    }
162588  }
162589
162590  if( rc==SQLITE_OK ){
162591    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
162592  }
162593  if( pFd->pReal->pMethods ){
162594    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
162595    ** pointer and, if the file is a main database file, link it into the
162596    ** mutex protected linked list of all such files.  */
162597    pFile->pMethods = &rbuvfs_io_methods;
162598    if( flags & SQLITE_OPEN_MAIN_DB ){
162599      sqlite3_mutex_enter(pRbuVfs->mutex);
162600      pFd->pMainNext = pRbuVfs->pMain;
162601      pRbuVfs->pMain = pFd;
162602      sqlite3_mutex_leave(pRbuVfs->mutex);
162603    }
162604  }else{
162605    sqlite3_free(pFd->zDel);
162606  }
162607
162608  return rc;
162609}
162610
162611/*
162612** Delete the file located at zPath.
162613*/
162614static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
162615  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162616  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
162617}
162618
162619/*
162620** Test for access permissions. Return true if the requested permission
162621** is available, or false otherwise.
162622*/
162623static int rbuVfsAccess(
162624  sqlite3_vfs *pVfs,
162625  const char *zPath,
162626  int flags,
162627  int *pResOut
162628){
162629  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
162630  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
162631  int rc;
162632
162633  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
162634
162635  /* If this call is to check if a *-wal file associated with an RBU target
162636  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
162637  ** the following special handling is activated:
162638  **
162639  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
162640  **      ensures that the RBU extension never tries to update a database
162641  **      in wal mode, even if the first page of the database file has
162642  **      been damaged.
162643  **
162644  **   b) if the *-wal file does not exist, claim that it does anyway,
162645  **      causing SQLite to call xOpen() to open it. This call will also
162646  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
162647  **      file opened instead.
162648  */
162649  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
162650    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
162651    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
162652      if( *pResOut ){
162653        rc = SQLITE_CANTOPEN;
162654      }else{
162655        *pResOut = 1;
162656      }
162657    }
162658  }
162659
162660  return rc;
162661}
162662
162663/*
162664** Populate buffer zOut with the full canonical pathname corresponding
162665** to the pathname in zPath. zOut is guaranteed to point to a buffer
162666** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
162667*/
162668static int rbuVfsFullPathname(
162669  sqlite3_vfs *pVfs,
162670  const char *zPath,
162671  int nOut,
162672  char *zOut
162673){
162674  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162675  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
162676}
162677
162678#ifndef SQLITE_OMIT_LOAD_EXTENSION
162679/*
162680** Open the dynamic library located at zPath and return a handle.
162681*/
162682static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
162683  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162684  return pRealVfs->xDlOpen(pRealVfs, zPath);
162685}
162686
162687/*
162688** Populate the buffer zErrMsg (size nByte bytes) with a human readable
162689** utf-8 string describing the most recent error encountered associated
162690** with dynamic libraries.
162691*/
162692static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
162693  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162694  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
162695}
162696
162697/*
162698** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
162699*/
162700static void (*rbuVfsDlSym(
162701  sqlite3_vfs *pVfs,
162702  void *pArg,
162703  const char *zSym
162704))(void){
162705  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162706  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
162707}
162708
162709/*
162710** Close the dynamic library handle pHandle.
162711*/
162712static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
162713  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162714  pRealVfs->xDlClose(pRealVfs, pHandle);
162715}
162716#endif /* SQLITE_OMIT_LOAD_EXTENSION */
162717
162718/*
162719** Populate the buffer pointed to by zBufOut with nByte bytes of
162720** random data.
162721*/
162722static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
162723  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162724  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
162725}
162726
162727/*
162728** Sleep for nMicro microseconds. Return the number of microseconds
162729** actually slept.
162730*/
162731static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
162732  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162733  return pRealVfs->xSleep(pRealVfs, nMicro);
162734}
162735
162736/*
162737** Return the current time as a Julian Day number in *pTimeOut.
162738*/
162739static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
162740  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162741  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
162742}
162743
162744/*
162745** No-op.
162746*/
162747static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
162748  return 0;
162749}
162750
162751/*
162752** Deregister and destroy an RBU vfs created by an earlier call to
162753** sqlite3rbu_create_vfs().
162754*/
162755SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
162756  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
162757  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
162758    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
162759    sqlite3_vfs_unregister(pVfs);
162760    sqlite3_free(pVfs);
162761  }
162762}
162763
162764/*
162765** Create an RBU VFS named zName that accesses the underlying file-system
162766** via existing VFS zParent. The new object is registered as a non-default
162767** VFS with SQLite before returning.
162768*/
162769SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
162770
162771  /* Template for VFS */
162772  static sqlite3_vfs vfs_template = {
162773    1,                            /* iVersion */
162774    0,                            /* szOsFile */
162775    0,                            /* mxPathname */
162776    0,                            /* pNext */
162777    0,                            /* zName */
162778    0,                            /* pAppData */
162779    rbuVfsOpen,                   /* xOpen */
162780    rbuVfsDelete,                 /* xDelete */
162781    rbuVfsAccess,                 /* xAccess */
162782    rbuVfsFullPathname,           /* xFullPathname */
162783
162784#ifndef SQLITE_OMIT_LOAD_EXTENSION
162785    rbuVfsDlOpen,                 /* xDlOpen */
162786    rbuVfsDlError,                /* xDlError */
162787    rbuVfsDlSym,                  /* xDlSym */
162788    rbuVfsDlClose,                /* xDlClose */
162789#else
162790    0, 0, 0, 0,
162791#endif
162792
162793    rbuVfsRandomness,             /* xRandomness */
162794    rbuVfsSleep,                  /* xSleep */
162795    rbuVfsCurrentTime,            /* xCurrentTime */
162796    rbuVfsGetLastError,           /* xGetLastError */
162797    0,                            /* xCurrentTimeInt64 (version 2) */
162798    0, 0, 0                       /* Unimplemented version 3 methods */
162799  };
162800
162801  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
162802  int nName;
162803  int rc = SQLITE_OK;
162804
162805  int nByte;
162806  nName = strlen(zName);
162807  nByte = sizeof(rbu_vfs) + nName + 1;
162808  pNew = (rbu_vfs*)sqlite3_malloc(nByte);
162809  if( pNew==0 ){
162810    rc = SQLITE_NOMEM;
162811  }else{
162812    sqlite3_vfs *pParent;           /* Parent VFS */
162813    memset(pNew, 0, nByte);
162814    pParent = sqlite3_vfs_find(zParent);
162815    if( pParent==0 ){
162816      rc = SQLITE_NOTFOUND;
162817    }else{
162818      char *zSpace;
162819      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
162820      pNew->base.mxPathname = pParent->mxPathname;
162821      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
162822      pNew->pRealVfs = pParent;
162823      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
162824      memcpy(zSpace, zName, nName);
162825
162826      /* Allocate the mutex and register the new VFS (not as the default) */
162827      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
162828      if( pNew->mutex==0 ){
162829        rc = SQLITE_NOMEM;
162830      }else{
162831        rc = sqlite3_vfs_register(&pNew->base, 0);
162832      }
162833    }
162834
162835    if( rc!=SQLITE_OK ){
162836      sqlite3_mutex_free(pNew->mutex);
162837      sqlite3_free(pNew);
162838    }
162839  }
162840
162841  return rc;
162842}
162843
162844
162845/**************************************************************************/
162846
162847#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
162848
162849/************** End of sqlite3rbu.c ******************************************/
162850/************** Begin file dbstat.c ******************************************/
162851/*
162852** 2010 July 12
162853**
162854** The author disclaims copyright to this source code.  In place of
162855** a legal notice, here is a blessing:
162856**
162857**    May you do good and not evil.
162858**    May you find forgiveness for yourself and forgive others.
162859**    May you share freely, never taking more than you give.
162860**
162861******************************************************************************
162862**
162863** This file contains an implementation of the "dbstat" virtual table.
162864**
162865** The dbstat virtual table is used to extract low-level formatting
162866** information from an SQLite database in order to implement the
162867** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
162868** for an example implementation.
162869**
162870** Additional information is available on the "dbstat.html" page of the
162871** official SQLite documentation.
162872*/
162873
162874/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
162875#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
162876    && !defined(SQLITE_OMIT_VIRTUALTABLE)
162877
162878/*
162879** Page paths:
162880**
162881**   The value of the 'path' column describes the path taken from the
162882**   root-node of the b-tree structure to each page. The value of the
162883**   root-node path is '/'.
162884**
162885**   The value of the path for the left-most child page of the root of
162886**   a b-tree is '/000/'. (Btrees store content ordered from left to right
162887**   so the pages to the left have smaller keys than the pages to the right.)
162888**   The next to left-most child of the root page is
162889**   '/001', and so on, each sibling page identified by a 3-digit hex
162890**   value. The children of the 451st left-most sibling have paths such
162891**   as '/1c2/000/, '/1c2/001/' etc.
162892**
162893**   Overflow pages are specified by appending a '+' character and a
162894**   six-digit hexadecimal value to the path to the cell they are linked
162895**   from. For example, the three overflow pages in a chain linked from
162896**   the left-most cell of the 450th child of the root page are identified
162897**   by the paths:
162898**
162899**      '/1c2/000+000000'         // First page in overflow chain
162900**      '/1c2/000+000001'         // Second page in overflow chain
162901**      '/1c2/000+000002'         // Third page in overflow chain
162902**
162903**   If the paths are sorted using the BINARY collation sequence, then
162904**   the overflow pages associated with a cell will appear earlier in the
162905**   sort-order than its child page:
162906**
162907**      '/1c2/000/'               // Left-most child of 451st child of root
162908*/
162909#define VTAB_SCHEMA                                                         \
162910  "CREATE TABLE xx( "                                                       \
162911  "  name       STRING,           /* Name of table or index */"             \
162912  "  path       INTEGER,          /* Path to page from root */"             \
162913  "  pageno     INTEGER,          /* Page number */"                        \
162914  "  pagetype   STRING,           /* 'internal', 'leaf' or 'overflow' */"   \
162915  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
162916  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
162917  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
162918  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
162919  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
162920  "  pgsize     INTEGER,          /* Size of the page */"                   \
162921  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
162922  ");"
162923
162924
162925typedef struct StatTable StatTable;
162926typedef struct StatCursor StatCursor;
162927typedef struct StatPage StatPage;
162928typedef struct StatCell StatCell;
162929
162930struct StatCell {
162931  int nLocal;                     /* Bytes of local payload */
162932  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
162933  int nOvfl;                      /* Entries in aOvfl[] */
162934  u32 *aOvfl;                     /* Array of overflow page numbers */
162935  int nLastOvfl;                  /* Bytes of payload on final overflow page */
162936  int iOvfl;                      /* Iterates through aOvfl[] */
162937};
162938
162939struct StatPage {
162940  u32 iPgno;
162941  DbPage *pPg;
162942  int iCell;
162943
162944  char *zPath;                    /* Path to this page */
162945
162946  /* Variables populated by statDecodePage(): */
162947  u8 flags;                       /* Copy of flags byte */
162948  int nCell;                      /* Number of cells on page */
162949  int nUnused;                    /* Number of unused bytes on page */
162950  StatCell *aCell;                /* Array of parsed cells */
162951  u32 iRightChildPg;              /* Right-child page number (or 0) */
162952  int nMxPayload;                 /* Largest payload of any cell on this page */
162953};
162954
162955struct StatCursor {
162956  sqlite3_vtab_cursor base;
162957  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
162958  int isEof;                      /* After pStmt has returned SQLITE_DONE */
162959  int iDb;                        /* Schema used for this query */
162960
162961  StatPage aPage[32];
162962  int iPage;                      /* Current entry in aPage[] */
162963
162964  /* Values to return. */
162965  char *zName;                    /* Value of 'name' column */
162966  char *zPath;                    /* Value of 'path' column */
162967  u32 iPageno;                    /* Value of 'pageno' column */
162968  char *zPagetype;                /* Value of 'pagetype' column */
162969  int nCell;                      /* Value of 'ncell' column */
162970  int nPayload;                   /* Value of 'payload' column */
162971  int nUnused;                    /* Value of 'unused' column */
162972  int nMxPayload;                 /* Value of 'mx_payload' column */
162973  i64 iOffset;                    /* Value of 'pgOffset' column */
162974  int szPage;                     /* Value of 'pgSize' column */
162975};
162976
162977struct StatTable {
162978  sqlite3_vtab base;
162979  sqlite3 *db;
162980  int iDb;                        /* Index of database to analyze */
162981};
162982
162983#ifndef get2byte
162984# define get2byte(x)   ((x)[0]<<8 | (x)[1])
162985#endif
162986
162987/*
162988** Connect to or create a statvfs virtual table.
162989*/
162990static int statConnect(
162991  sqlite3 *db,
162992  void *pAux,
162993  int argc, const char *const*argv,
162994  sqlite3_vtab **ppVtab,
162995  char **pzErr
162996){
162997  StatTable *pTab = 0;
162998  int rc = SQLITE_OK;
162999  int iDb;
163000
163001  if( argc>=4 ){
163002    iDb = sqlite3FindDbName(db, argv[3]);
163003    if( iDb<0 ){
163004      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
163005      return SQLITE_ERROR;
163006    }
163007  }else{
163008    iDb = 0;
163009  }
163010  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
163011  if( rc==SQLITE_OK ){
163012    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
163013    if( pTab==0 ) rc = SQLITE_NOMEM;
163014  }
163015
163016  assert( rc==SQLITE_OK || pTab==0 );
163017  if( rc==SQLITE_OK ){
163018    memset(pTab, 0, sizeof(StatTable));
163019    pTab->db = db;
163020    pTab->iDb = iDb;
163021  }
163022
163023  *ppVtab = (sqlite3_vtab*)pTab;
163024  return rc;
163025}
163026
163027/*
163028** Disconnect from or destroy a statvfs virtual table.
163029*/
163030static int statDisconnect(sqlite3_vtab *pVtab){
163031  sqlite3_free(pVtab);
163032  return SQLITE_OK;
163033}
163034
163035/*
163036** There is no "best-index". This virtual table always does a linear
163037** scan.  However, a schema=? constraint should cause this table to
163038** operate on a different database schema, so check for it.
163039**
163040** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
163041*/
163042static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
163043  int i;
163044
163045  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
163046
163047  /* Look for a valid schema=? constraint.  If found, change the idxNum to
163048  ** 1 and request the value of that constraint be sent to xFilter.  And
163049  ** lower the cost estimate to encourage the constrained version to be
163050  ** used.
163051  */
163052  for(i=0; i<pIdxInfo->nConstraint; i++){
163053    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
163054    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
163055    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
163056    pIdxInfo->idxNum = 1;
163057    pIdxInfo->estimatedCost = 1.0;
163058    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
163059    pIdxInfo->aConstraintUsage[i].omit = 1;
163060    break;
163061  }
163062
163063
163064  /* Records are always returned in ascending order of (name, path).
163065  ** If this will satisfy the client, set the orderByConsumed flag so that
163066  ** SQLite does not do an external sort.
163067  */
163068  if( ( pIdxInfo->nOrderBy==1
163069     && pIdxInfo->aOrderBy[0].iColumn==0
163070     && pIdxInfo->aOrderBy[0].desc==0
163071     ) ||
163072      ( pIdxInfo->nOrderBy==2
163073     && pIdxInfo->aOrderBy[0].iColumn==0
163074     && pIdxInfo->aOrderBy[0].desc==0
163075     && pIdxInfo->aOrderBy[1].iColumn==1
163076     && pIdxInfo->aOrderBy[1].desc==0
163077     )
163078  ){
163079    pIdxInfo->orderByConsumed = 1;
163080  }
163081
163082  return SQLITE_OK;
163083}
163084
163085/*
163086** Open a new statvfs cursor.
163087*/
163088static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
163089  StatTable *pTab = (StatTable *)pVTab;
163090  StatCursor *pCsr;
163091
163092  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
163093  if( pCsr==0 ){
163094    return SQLITE_NOMEM;
163095  }else{
163096    memset(pCsr, 0, sizeof(StatCursor));
163097    pCsr->base.pVtab = pVTab;
163098    pCsr->iDb = pTab->iDb;
163099  }
163100
163101  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
163102  return SQLITE_OK;
163103}
163104
163105static void statClearPage(StatPage *p){
163106  int i;
163107  if( p->aCell ){
163108    for(i=0; i<p->nCell; i++){
163109      sqlite3_free(p->aCell[i].aOvfl);
163110    }
163111    sqlite3_free(p->aCell);
163112  }
163113  sqlite3PagerUnref(p->pPg);
163114  sqlite3_free(p->zPath);
163115  memset(p, 0, sizeof(StatPage));
163116}
163117
163118static void statResetCsr(StatCursor *pCsr){
163119  int i;
163120  sqlite3_reset(pCsr->pStmt);
163121  for(i=0; i<ArraySize(pCsr->aPage); i++){
163122    statClearPage(&pCsr->aPage[i]);
163123  }
163124  pCsr->iPage = 0;
163125  sqlite3_free(pCsr->zPath);
163126  pCsr->zPath = 0;
163127  pCsr->isEof = 0;
163128}
163129
163130/*
163131** Close a statvfs cursor.
163132*/
163133static int statClose(sqlite3_vtab_cursor *pCursor){
163134  StatCursor *pCsr = (StatCursor *)pCursor;
163135  statResetCsr(pCsr);
163136  sqlite3_finalize(pCsr->pStmt);
163137  sqlite3_free(pCsr);
163138  return SQLITE_OK;
163139}
163140
163141static void getLocalPayload(
163142  int nUsable,                    /* Usable bytes per page */
163143  u8 flags,                       /* Page flags */
163144  int nTotal,                     /* Total record (payload) size */
163145  int *pnLocal                    /* OUT: Bytes stored locally */
163146){
163147  int nLocal;
163148  int nMinLocal;
163149  int nMaxLocal;
163150
163151  if( flags==0x0D ){              /* Table leaf node */
163152    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
163153    nMaxLocal = nUsable - 35;
163154  }else{                          /* Index interior and leaf nodes */
163155    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
163156    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
163157  }
163158
163159  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
163160  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
163161  *pnLocal = nLocal;
163162}
163163
163164static int statDecodePage(Btree *pBt, StatPage *p){
163165  int nUnused;
163166  int iOff;
163167  int nHdr;
163168  int isLeaf;
163169  int szPage;
163170
163171  u8 *aData = sqlite3PagerGetData(p->pPg);
163172  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
163173
163174  p->flags = aHdr[0];
163175  p->nCell = get2byte(&aHdr[3]);
163176  p->nMxPayload = 0;
163177
163178  isLeaf = (p->flags==0x0A || p->flags==0x0D);
163179  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
163180
163181  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
163182  nUnused += (int)aHdr[7];
163183  iOff = get2byte(&aHdr[1]);
163184  while( iOff ){
163185    nUnused += get2byte(&aData[iOff+2]);
163186    iOff = get2byte(&aData[iOff]);
163187  }
163188  p->nUnused = nUnused;
163189  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
163190  szPage = sqlite3BtreeGetPageSize(pBt);
163191
163192  if( p->nCell ){
163193    int i;                        /* Used to iterate through cells */
163194    int nUsable;                  /* Usable bytes per page */
163195
163196    sqlite3BtreeEnter(pBt);
163197    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
163198    sqlite3BtreeLeave(pBt);
163199    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
163200    if( p->aCell==0 ) return SQLITE_NOMEM;
163201    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
163202
163203    for(i=0; i<p->nCell; i++){
163204      StatCell *pCell = &p->aCell[i];
163205
163206      iOff = get2byte(&aData[nHdr+i*2]);
163207      if( !isLeaf ){
163208        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
163209        iOff += 4;
163210      }
163211      if( p->flags==0x05 ){
163212        /* A table interior node. nPayload==0. */
163213      }else{
163214        u32 nPayload;             /* Bytes of payload total (local+overflow) */
163215        int nLocal;               /* Bytes of payload stored locally */
163216        iOff += getVarint32(&aData[iOff], nPayload);
163217        if( p->flags==0x0D ){
163218          u64 dummy;
163219          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
163220        }
163221        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
163222        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
163223        pCell->nLocal = nLocal;
163224        assert( nLocal>=0 );
163225        assert( nPayload>=(u32)nLocal );
163226        assert( nLocal<=(nUsable-35) );
163227        if( nPayload>(u32)nLocal ){
163228          int j;
163229          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
163230          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
163231          pCell->nOvfl = nOvfl;
163232          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
163233          if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
163234          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
163235          for(j=1; j<nOvfl; j++){
163236            int rc;
163237            u32 iPrev = pCell->aOvfl[j-1];
163238            DbPage *pPg = 0;
163239            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
163240            if( rc!=SQLITE_OK ){
163241              assert( pPg==0 );
163242              return rc;
163243            }
163244            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
163245            sqlite3PagerUnref(pPg);
163246          }
163247        }
163248      }
163249    }
163250  }
163251
163252  return SQLITE_OK;
163253}
163254
163255/*
163256** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
163257** the current value of pCsr->iPageno.
163258*/
163259static void statSizeAndOffset(StatCursor *pCsr){
163260  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
163261  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
163262  Pager *pPager = sqlite3BtreePager(pBt);
163263  sqlite3_file *fd;
163264  sqlite3_int64 x[2];
163265
163266  /* The default page size and offset */
163267  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
163268  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
163269
163270  /* If connected to a ZIPVFS backend, override the page size and
163271  ** offset with actual values obtained from ZIPVFS.
163272  */
163273  fd = sqlite3PagerFile(pPager);
163274  x[0] = pCsr->iPageno;
163275  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
163276    pCsr->iOffset = x[0];
163277    pCsr->szPage = (int)x[1];
163278  }
163279}
163280
163281/*
163282** Move a statvfs cursor to the next entry in the file.
163283*/
163284static int statNext(sqlite3_vtab_cursor *pCursor){
163285  int rc;
163286  int nPayload;
163287  char *z;
163288  StatCursor *pCsr = (StatCursor *)pCursor;
163289  StatTable *pTab = (StatTable *)pCursor->pVtab;
163290  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
163291  Pager *pPager = sqlite3BtreePager(pBt);
163292
163293  sqlite3_free(pCsr->zPath);
163294  pCsr->zPath = 0;
163295
163296statNextRestart:
163297  if( pCsr->aPage[0].pPg==0 ){
163298    rc = sqlite3_step(pCsr->pStmt);
163299    if( rc==SQLITE_ROW ){
163300      int nPage;
163301      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
163302      sqlite3PagerPagecount(pPager, &nPage);
163303      if( nPage==0 ){
163304        pCsr->isEof = 1;
163305        return sqlite3_reset(pCsr->pStmt);
163306      }
163307      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
163308      pCsr->aPage[0].iPgno = iRoot;
163309      pCsr->aPage[0].iCell = 0;
163310      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
163311      pCsr->iPage = 0;
163312      if( z==0 ) rc = SQLITE_NOMEM;
163313    }else{
163314      pCsr->isEof = 1;
163315      return sqlite3_reset(pCsr->pStmt);
163316    }
163317  }else{
163318
163319    /* Page p itself has already been visited. */
163320    StatPage *p = &pCsr->aPage[pCsr->iPage];
163321
163322    while( p->iCell<p->nCell ){
163323      StatCell *pCell = &p->aCell[p->iCell];
163324      if( pCell->iOvfl<pCell->nOvfl ){
163325        int nUsable;
163326        sqlite3BtreeEnter(pBt);
163327        nUsable = sqlite3BtreeGetPageSize(pBt) -
163328                        sqlite3BtreeGetReserveNoMutex(pBt);
163329        sqlite3BtreeLeave(pBt);
163330        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
163331        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
163332        pCsr->zPagetype = "overflow";
163333        pCsr->nCell = 0;
163334        pCsr->nMxPayload = 0;
163335        pCsr->zPath = z = sqlite3_mprintf(
163336            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
163337        );
163338        if( pCell->iOvfl<pCell->nOvfl-1 ){
163339          pCsr->nUnused = 0;
163340          pCsr->nPayload = nUsable - 4;
163341        }else{
163342          pCsr->nPayload = pCell->nLastOvfl;
163343          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
163344        }
163345        pCell->iOvfl++;
163346        statSizeAndOffset(pCsr);
163347        return z==0 ? SQLITE_NOMEM : SQLITE_OK;
163348      }
163349      if( p->iRightChildPg ) break;
163350      p->iCell++;
163351    }
163352
163353    if( !p->iRightChildPg || p->iCell>p->nCell ){
163354      statClearPage(p);
163355      if( pCsr->iPage==0 ) return statNext(pCursor);
163356      pCsr->iPage--;
163357      goto statNextRestart; /* Tail recursion */
163358    }
163359    pCsr->iPage++;
163360    assert( p==&pCsr->aPage[pCsr->iPage-1] );
163361
163362    if( p->iCell==p->nCell ){
163363      p[1].iPgno = p->iRightChildPg;
163364    }else{
163365      p[1].iPgno = p->aCell[p->iCell].iChildPg;
163366    }
163367    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
163368    p[1].iCell = 0;
163369    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
163370    p->iCell++;
163371    if( z==0 ) rc = SQLITE_NOMEM;
163372  }
163373
163374
163375  /* Populate the StatCursor fields with the values to be returned
163376  ** by the xColumn() and xRowid() methods.
163377  */
163378  if( rc==SQLITE_OK ){
163379    int i;
163380    StatPage *p = &pCsr->aPage[pCsr->iPage];
163381    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
163382    pCsr->iPageno = p->iPgno;
163383
163384    rc = statDecodePage(pBt, p);
163385    if( rc==SQLITE_OK ){
163386      statSizeAndOffset(pCsr);
163387
163388      switch( p->flags ){
163389        case 0x05:             /* table internal */
163390        case 0x02:             /* index internal */
163391          pCsr->zPagetype = "internal";
163392          break;
163393        case 0x0D:             /* table leaf */
163394        case 0x0A:             /* index leaf */
163395          pCsr->zPagetype = "leaf";
163396          break;
163397        default:
163398          pCsr->zPagetype = "corrupted";
163399          break;
163400      }
163401      pCsr->nCell = p->nCell;
163402      pCsr->nUnused = p->nUnused;
163403      pCsr->nMxPayload = p->nMxPayload;
163404      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
163405      if( z==0 ) rc = SQLITE_NOMEM;
163406      nPayload = 0;
163407      for(i=0; i<p->nCell; i++){
163408        nPayload += p->aCell[i].nLocal;
163409      }
163410      pCsr->nPayload = nPayload;
163411    }
163412  }
163413
163414  return rc;
163415}
163416
163417static int statEof(sqlite3_vtab_cursor *pCursor){
163418  StatCursor *pCsr = (StatCursor *)pCursor;
163419  return pCsr->isEof;
163420}
163421
163422static int statFilter(
163423  sqlite3_vtab_cursor *pCursor,
163424  int idxNum, const char *idxStr,
163425  int argc, sqlite3_value **argv
163426){
163427  StatCursor *pCsr = (StatCursor *)pCursor;
163428  StatTable *pTab = (StatTable*)(pCursor->pVtab);
163429  char *zSql;
163430  int rc = SQLITE_OK;
163431  char *zMaster;
163432
163433  if( idxNum==1 ){
163434    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
163435    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
163436    if( pCsr->iDb<0 ){
163437      sqlite3_free(pCursor->pVtab->zErrMsg);
163438      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
163439      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
163440    }
163441  }else{
163442    pCsr->iDb = pTab->iDb;
163443  }
163444  statResetCsr(pCsr);
163445  sqlite3_finalize(pCsr->pStmt);
163446  pCsr->pStmt = 0;
163447  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
163448  zSql = sqlite3_mprintf(
163449      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
163450      "  UNION ALL  "
163451      "SELECT name, rootpage, type"
163452      "  FROM \"%w\".%s WHERE rootpage!=0"
163453      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
163454  if( zSql==0 ){
163455    return SQLITE_NOMEM;
163456  }else{
163457    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
163458    sqlite3_free(zSql);
163459  }
163460
163461  if( rc==SQLITE_OK ){
163462    rc = statNext(pCursor);
163463  }
163464  return rc;
163465}
163466
163467static int statColumn(
163468  sqlite3_vtab_cursor *pCursor,
163469  sqlite3_context *ctx,
163470  int i
163471){
163472  StatCursor *pCsr = (StatCursor *)pCursor;
163473  switch( i ){
163474    case 0:            /* name */
163475      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
163476      break;
163477    case 1:            /* path */
163478      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
163479      break;
163480    case 2:            /* pageno */
163481      sqlite3_result_int64(ctx, pCsr->iPageno);
163482      break;
163483    case 3:            /* pagetype */
163484      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
163485      break;
163486    case 4:            /* ncell */
163487      sqlite3_result_int(ctx, pCsr->nCell);
163488      break;
163489    case 5:            /* payload */
163490      sqlite3_result_int(ctx, pCsr->nPayload);
163491      break;
163492    case 6:            /* unused */
163493      sqlite3_result_int(ctx, pCsr->nUnused);
163494      break;
163495    case 7:            /* mx_payload */
163496      sqlite3_result_int(ctx, pCsr->nMxPayload);
163497      break;
163498    case 8:            /* pgoffset */
163499      sqlite3_result_int64(ctx, pCsr->iOffset);
163500      break;
163501    case 9:            /* pgsize */
163502      sqlite3_result_int(ctx, pCsr->szPage);
163503      break;
163504    default: {          /* schema */
163505      sqlite3 *db = sqlite3_context_db_handle(ctx);
163506      int iDb = pCsr->iDb;
163507      sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
163508      break;
163509    }
163510  }
163511  return SQLITE_OK;
163512}
163513
163514static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
163515  StatCursor *pCsr = (StatCursor *)pCursor;
163516  *pRowid = pCsr->iPageno;
163517  return SQLITE_OK;
163518}
163519
163520/*
163521** Invoke this routine to register the "dbstat" virtual table module
163522*/
163523SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
163524  static sqlite3_module dbstat_module = {
163525    0,                            /* iVersion */
163526    statConnect,                  /* xCreate */
163527    statConnect,                  /* xConnect */
163528    statBestIndex,                /* xBestIndex */
163529    statDisconnect,               /* xDisconnect */
163530    statDisconnect,               /* xDestroy */
163531    statOpen,                     /* xOpen - open a cursor */
163532    statClose,                    /* xClose - close a cursor */
163533    statFilter,                   /* xFilter - configure scan constraints */
163534    statNext,                     /* xNext - advance a cursor */
163535    statEof,                      /* xEof - check for end of scan */
163536    statColumn,                   /* xColumn - read data */
163537    statRowid,                    /* xRowid - read data */
163538    0,                            /* xUpdate */
163539    0,                            /* xBegin */
163540    0,                            /* xSync */
163541    0,                            /* xCommit */
163542    0,                            /* xRollback */
163543    0,                            /* xFindMethod */
163544    0,                            /* xRename */
163545  };
163546  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
163547}
163548#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
163549SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
163550#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
163551
163552/************** End of dbstat.c **********************************************/
163553/************** Begin file json1.c *******************************************/
163554/*
163555** 2015-08-12
163556**
163557** The author disclaims copyright to this source code.  In place of
163558** a legal notice, here is a blessing:
163559**
163560**    May you do good and not evil.
163561**    May you find forgiveness for yourself and forgive others.
163562**    May you share freely, never taking more than you give.
163563**
163564******************************************************************************
163565**
163566** This SQLite extension implements JSON functions.  The interface is
163567** modeled after MySQL JSON functions:
163568**
163569**     https://dev.mysql.com/doc/refman/5.7/en/json.html
163570**
163571** For the time being, all JSON is stored as pure text.  (We might add
163572** a JSONB type in the future which stores a binary encoding of JSON in
163573** a BLOB, but there is no support for JSONB in the current implementation.
163574** This implementation parses JSON text at 250 MB/s, so it is hard to see
163575** how JSONB might improve on that.)
163576*/
163577#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
163578#if !defined(_SQLITEINT_H_)
163579/* #include "sqlite3ext.h" */
163580#endif
163581SQLITE_EXTENSION_INIT1
163582/* #include <assert.h> */
163583/* #include <string.h> */
163584/* #include <stdlib.h> */
163585/* #include <stdarg.h> */
163586
163587#define UNUSED_PARAM(X)  (void)(X)
163588
163589#ifndef LARGEST_INT64
163590# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
163591# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
163592#endif
163593
163594/*
163595** Versions of isspace(), isalnum() and isdigit() to which it is safe
163596** to pass signed char values.
163597*/
163598#ifdef sqlite3Isdigit
163599   /* Use the SQLite core versions if this routine is part of the
163600   ** SQLite amalgamation */
163601#  define safe_isdigit(x) sqlite3Isdigit(x)
163602#  define safe_isalnum(x) sqlite3Isalnum(x)
163603#else
163604   /* Use the standard library for separate compilation */
163605#include <ctype.h>  /* amalgamator: keep */
163606#  define safe_isdigit(x) isdigit((unsigned char)(x))
163607#  define safe_isalnum(x) isalnum((unsigned char)(x))
163608#endif
163609
163610/*
163611** Growing our own isspace() routine this way is twice as fast as
163612** the library isspace() function, resulting in a 7% overall performance
163613** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
163614*/
163615static const char jsonIsSpace[] = {
163616  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
163617  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163618  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163619  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163620  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163621  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163622  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163623  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163624  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163625  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163626  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163627  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163628  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163629  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163630  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163631  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163632};
163633#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
163634
163635#ifndef SQLITE_AMALGAMATION
163636  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
163637  ** but the definitions need to be repeated for separate compilation. */
163638  typedef sqlite3_uint64 u64;
163639  typedef unsigned int u32;
163640  typedef unsigned char u8;
163641#endif
163642
163643/* Objects */
163644typedef struct JsonString JsonString;
163645typedef struct JsonNode JsonNode;
163646typedef struct JsonParse JsonParse;
163647
163648/* An instance of this object represents a JSON string
163649** under construction.  Really, this is a generic string accumulator
163650** that can be and is used to create strings other than JSON.
163651*/
163652struct JsonString {
163653  sqlite3_context *pCtx;   /* Function context - put error messages here */
163654  char *zBuf;              /* Append JSON content here */
163655  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
163656  u64 nUsed;               /* Bytes of zBuf[] currently used */
163657  u8 bStatic;              /* True if zBuf is static space */
163658  u8 bErr;                 /* True if an error has been encountered */
163659  char zSpace[100];        /* Initial static space */
163660};
163661
163662/* JSON type values
163663*/
163664#define JSON_NULL     0
163665#define JSON_TRUE     1
163666#define JSON_FALSE    2
163667#define JSON_INT      3
163668#define JSON_REAL     4
163669#define JSON_STRING   5
163670#define JSON_ARRAY    6
163671#define JSON_OBJECT   7
163672
163673/* The "subtype" set for JSON values */
163674#define JSON_SUBTYPE  74    /* Ascii for "J" */
163675
163676/*
163677** Names of the various JSON types:
163678*/
163679static const char * const jsonType[] = {
163680  "null", "true", "false", "integer", "real", "text", "array", "object"
163681};
163682
163683/* Bit values for the JsonNode.jnFlag field
163684*/
163685#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
163686#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
163687#define JNODE_REMOVE  0x04         /* Do not output */
163688#define JNODE_REPLACE 0x08         /* Replace with JsonNode.iVal */
163689#define JNODE_APPEND  0x10         /* More ARRAY/OBJECT entries at u.iAppend */
163690#define JNODE_LABEL   0x20         /* Is a label of an object */
163691
163692
163693/* A single node of parsed JSON
163694*/
163695struct JsonNode {
163696  u8 eType;              /* One of the JSON_ type values */
163697  u8 jnFlags;            /* JNODE flags */
163698  u8 iVal;               /* Replacement value when JNODE_REPLACE */
163699  u32 n;                 /* Bytes of content, or number of sub-nodes */
163700  union {
163701    const char *zJContent; /* Content for INT, REAL, and STRING */
163702    u32 iAppend;           /* More terms for ARRAY and OBJECT */
163703    u32 iKey;              /* Key for ARRAY objects in json_tree() */
163704  } u;
163705};
163706
163707/* A completely parsed JSON string
163708*/
163709struct JsonParse {
163710  u32 nNode;         /* Number of slots of aNode[] used */
163711  u32 nAlloc;        /* Number of slots of aNode[] allocated */
163712  JsonNode *aNode;   /* Array of nodes containing the parse */
163713  const char *zJson; /* Original JSON string */
163714  u32 *aUp;          /* Index of parent of each node */
163715  u8 oom;            /* Set to true if out of memory */
163716  u8 nErr;           /* Number of errors seen */
163717};
163718
163719/**************************************************************************
163720** Utility routines for dealing with JsonString objects
163721**************************************************************************/
163722
163723/* Set the JsonString object to an empty string
163724*/
163725static void jsonZero(JsonString *p){
163726  p->zBuf = p->zSpace;
163727  p->nAlloc = sizeof(p->zSpace);
163728  p->nUsed = 0;
163729  p->bStatic = 1;
163730}
163731
163732/* Initialize the JsonString object
163733*/
163734static void jsonInit(JsonString *p, sqlite3_context *pCtx){
163735  p->pCtx = pCtx;
163736  p->bErr = 0;
163737  jsonZero(p);
163738}
163739
163740
163741/* Free all allocated memory and reset the JsonString object back to its
163742** initial state.
163743*/
163744static void jsonReset(JsonString *p){
163745  if( !p->bStatic ) sqlite3_free(p->zBuf);
163746  jsonZero(p);
163747}
163748
163749
163750/* Report an out-of-memory (OOM) condition
163751*/
163752static void jsonOom(JsonString *p){
163753  p->bErr = 1;
163754  sqlite3_result_error_nomem(p->pCtx);
163755  jsonReset(p);
163756}
163757
163758/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
163759** Return zero on success.  Return non-zero on an OOM error
163760*/
163761static int jsonGrow(JsonString *p, u32 N){
163762  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
163763  char *zNew;
163764  if( p->bStatic ){
163765    if( p->bErr ) return 1;
163766    zNew = sqlite3_malloc64(nTotal);
163767    if( zNew==0 ){
163768      jsonOom(p);
163769      return SQLITE_NOMEM;
163770    }
163771    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
163772    p->zBuf = zNew;
163773    p->bStatic = 0;
163774  }else{
163775    zNew = sqlite3_realloc64(p->zBuf, nTotal);
163776    if( zNew==0 ){
163777      jsonOom(p);
163778      return SQLITE_NOMEM;
163779    }
163780    p->zBuf = zNew;
163781  }
163782  p->nAlloc = nTotal;
163783  return SQLITE_OK;
163784}
163785
163786/* Append N bytes from zIn onto the end of the JsonString string.
163787*/
163788static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
163789  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
163790  memcpy(p->zBuf+p->nUsed, zIn, N);
163791  p->nUsed += N;
163792}
163793
163794/* Append formatted text (not to exceed N bytes) to the JsonString.
163795*/
163796static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
163797  va_list ap;
163798  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
163799  va_start(ap, zFormat);
163800  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
163801  va_end(ap);
163802  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
163803}
163804
163805/* Append a single character
163806*/
163807static void jsonAppendChar(JsonString *p, char c){
163808  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
163809  p->zBuf[p->nUsed++] = c;
163810}
163811
163812/* Append a comma separator to the output buffer, if the previous
163813** character is not '[' or '{'.
163814*/
163815static void jsonAppendSeparator(JsonString *p){
163816  char c;
163817  if( p->nUsed==0 ) return;
163818  c = p->zBuf[p->nUsed-1];
163819  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
163820}
163821
163822/* Append the N-byte string in zIn to the end of the JsonString string
163823** under construction.  Enclose the string in "..." and escape
163824** any double-quotes or backslash characters contained within the
163825** string.
163826*/
163827static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
163828  u32 i;
163829  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
163830  p->zBuf[p->nUsed++] = '"';
163831  for(i=0; i<N; i++){
163832    char c = zIn[i];
163833    if( c=='"' || c=='\\' ){
163834      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
163835      p->zBuf[p->nUsed++] = '\\';
163836    }
163837    p->zBuf[p->nUsed++] = c;
163838  }
163839  p->zBuf[p->nUsed++] = '"';
163840  assert( p->nUsed<p->nAlloc );
163841}
163842
163843/*
163844** Append a function parameter value to the JSON string under
163845** construction.
163846*/
163847static void jsonAppendValue(
163848  JsonString *p,                 /* Append to this JSON string */
163849  sqlite3_value *pValue          /* Value to append */
163850){
163851  switch( sqlite3_value_type(pValue) ){
163852    case SQLITE_NULL: {
163853      jsonAppendRaw(p, "null", 4);
163854      break;
163855    }
163856    case SQLITE_INTEGER:
163857    case SQLITE_FLOAT: {
163858      const char *z = (const char*)sqlite3_value_text(pValue);
163859      u32 n = (u32)sqlite3_value_bytes(pValue);
163860      jsonAppendRaw(p, z, n);
163861      break;
163862    }
163863    case SQLITE_TEXT: {
163864      const char *z = (const char*)sqlite3_value_text(pValue);
163865      u32 n = (u32)sqlite3_value_bytes(pValue);
163866      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
163867        jsonAppendRaw(p, z, n);
163868      }else{
163869        jsonAppendString(p, z, n);
163870      }
163871      break;
163872    }
163873    default: {
163874      if( p->bErr==0 ){
163875        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
163876        p->bErr = 1;
163877        jsonReset(p);
163878      }
163879      break;
163880    }
163881  }
163882}
163883
163884
163885/* Make the JSON in p the result of the SQL function.
163886*/
163887static void jsonResult(JsonString *p){
163888  if( p->bErr==0 ){
163889    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
163890                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
163891                          SQLITE_UTF8);
163892    jsonZero(p);
163893  }
163894  assert( p->bStatic );
163895}
163896
163897/**************************************************************************
163898** Utility routines for dealing with JsonNode and JsonParse objects
163899**************************************************************************/
163900
163901/*
163902** Return the number of consecutive JsonNode slots need to represent
163903** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
163904** OBJECT types, the number might be larger.
163905**
163906** Appended elements are not counted.  The value returned is the number
163907** by which the JsonNode counter should increment in order to go to the
163908** next peer value.
163909*/
163910static u32 jsonNodeSize(JsonNode *pNode){
163911  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
163912}
163913
163914/*
163915** Reclaim all memory allocated by a JsonParse object.  But do not
163916** delete the JsonParse object itself.
163917*/
163918static void jsonParseReset(JsonParse *pParse){
163919  sqlite3_free(pParse->aNode);
163920  pParse->aNode = 0;
163921  pParse->nNode = 0;
163922  pParse->nAlloc = 0;
163923  sqlite3_free(pParse->aUp);
163924  pParse->aUp = 0;
163925}
163926
163927/*
163928** Convert the JsonNode pNode into a pure JSON string and
163929** append to pOut.  Subsubstructure is also included.  Return
163930** the number of JsonNode objects that are encoded.
163931*/
163932static void jsonRenderNode(
163933  JsonNode *pNode,               /* The node to render */
163934  JsonString *pOut,              /* Write JSON here */
163935  sqlite3_value **aReplace       /* Replacement values */
163936){
163937  switch( pNode->eType ){
163938    default: {
163939      assert( pNode->eType==JSON_NULL );
163940      jsonAppendRaw(pOut, "null", 4);
163941      break;
163942    }
163943    case JSON_TRUE: {
163944      jsonAppendRaw(pOut, "true", 4);
163945      break;
163946    }
163947    case JSON_FALSE: {
163948      jsonAppendRaw(pOut, "false", 5);
163949      break;
163950    }
163951    case JSON_STRING: {
163952      if( pNode->jnFlags & JNODE_RAW ){
163953        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
163954        break;
163955      }
163956      /* Fall through into the next case */
163957    }
163958    case JSON_REAL:
163959    case JSON_INT: {
163960      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
163961      break;
163962    }
163963    case JSON_ARRAY: {
163964      u32 j = 1;
163965      jsonAppendChar(pOut, '[');
163966      for(;;){
163967        while( j<=pNode->n ){
163968          if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
163969            if( pNode[j].jnFlags & JNODE_REPLACE ){
163970              jsonAppendSeparator(pOut);
163971              jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
163972            }
163973          }else{
163974            jsonAppendSeparator(pOut);
163975            jsonRenderNode(&pNode[j], pOut, aReplace);
163976          }
163977          j += jsonNodeSize(&pNode[j]);
163978        }
163979        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
163980        pNode = &pNode[pNode->u.iAppend];
163981        j = 1;
163982      }
163983      jsonAppendChar(pOut, ']');
163984      break;
163985    }
163986    case JSON_OBJECT: {
163987      u32 j = 1;
163988      jsonAppendChar(pOut, '{');
163989      for(;;){
163990        while( j<=pNode->n ){
163991          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
163992            jsonAppendSeparator(pOut);
163993            jsonRenderNode(&pNode[j], pOut, aReplace);
163994            jsonAppendChar(pOut, ':');
163995            if( pNode[j+1].jnFlags & JNODE_REPLACE ){
163996              jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
163997            }else{
163998              jsonRenderNode(&pNode[j+1], pOut, aReplace);
163999            }
164000          }
164001          j += 1 + jsonNodeSize(&pNode[j+1]);
164002        }
164003        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
164004        pNode = &pNode[pNode->u.iAppend];
164005        j = 1;
164006      }
164007      jsonAppendChar(pOut, '}');
164008      break;
164009    }
164010  }
164011}
164012
164013/*
164014** Return a JsonNode and all its descendents as a JSON string.
164015*/
164016static void jsonReturnJson(
164017  JsonNode *pNode,            /* Node to return */
164018  sqlite3_context *pCtx,      /* Return value for this function */
164019  sqlite3_value **aReplace    /* Array of replacement values */
164020){
164021  JsonString s;
164022  jsonInit(&s, pCtx);
164023  jsonRenderNode(pNode, &s, aReplace);
164024  jsonResult(&s);
164025  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
164026}
164027
164028/*
164029** Make the JsonNode the return value of the function.
164030*/
164031static void jsonReturn(
164032  JsonNode *pNode,            /* Node to return */
164033  sqlite3_context *pCtx,      /* Return value for this function */
164034  sqlite3_value **aReplace    /* Array of replacement values */
164035){
164036  switch( pNode->eType ){
164037    default: {
164038      assert( pNode->eType==JSON_NULL );
164039      sqlite3_result_null(pCtx);
164040      break;
164041    }
164042    case JSON_TRUE: {
164043      sqlite3_result_int(pCtx, 1);
164044      break;
164045    }
164046    case JSON_FALSE: {
164047      sqlite3_result_int(pCtx, 0);
164048      break;
164049    }
164050    case JSON_INT: {
164051      sqlite3_int64 i = 0;
164052      const char *z = pNode->u.zJContent;
164053      if( z[0]=='-' ){ z++; }
164054      while( z[0]>='0' && z[0]<='9' ){
164055        unsigned v = *(z++) - '0';
164056        if( i>=LARGEST_INT64/10 ){
164057          if( i>LARGEST_INT64/10 ) goto int_as_real;
164058          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
164059          if( v==9 ) goto int_as_real;
164060          if( v==8 ){
164061            if( pNode->u.zJContent[0]=='-' ){
164062              sqlite3_result_int64(pCtx, SMALLEST_INT64);
164063              goto int_done;
164064            }else{
164065              goto int_as_real;
164066            }
164067          }
164068        }
164069        i = i*10 + v;
164070      }
164071      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
164072      sqlite3_result_int64(pCtx, i);
164073      int_done:
164074      break;
164075      int_as_real: /* fall through to real */;
164076    }
164077    case JSON_REAL: {
164078      double r;
164079#ifdef SQLITE_AMALGAMATION
164080      const char *z = pNode->u.zJContent;
164081      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
164082#else
164083      r = strtod(pNode->u.zJContent, 0);
164084#endif
164085      sqlite3_result_double(pCtx, r);
164086      break;
164087    }
164088    case JSON_STRING: {
164089#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
164090      ** json_insert() and json_replace() and those routines do not
164091      ** call jsonReturn() */
164092      if( pNode->jnFlags & JNODE_RAW ){
164093        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
164094                            SQLITE_TRANSIENT);
164095      }else
164096#endif
164097      assert( (pNode->jnFlags & JNODE_RAW)==0 );
164098      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
164099        /* JSON formatted without any backslash-escapes */
164100        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
164101                            SQLITE_TRANSIENT);
164102      }else{
164103        /* Translate JSON formatted string into raw text */
164104        u32 i;
164105        u32 n = pNode->n;
164106        const char *z = pNode->u.zJContent;
164107        char *zOut;
164108        u32 j;
164109        zOut = sqlite3_malloc( n+1 );
164110        if( zOut==0 ){
164111          sqlite3_result_error_nomem(pCtx);
164112          break;
164113        }
164114        for(i=1, j=0; i<n-1; i++){
164115          char c = z[i];
164116          if( c!='\\' ){
164117            zOut[j++] = c;
164118          }else{
164119            c = z[++i];
164120            if( c=='u' ){
164121              u32 v = 0, k;
164122              for(k=0; k<4 && i<n-2; i++, k++){
164123                c = z[i+1];
164124                if( c>='0' && c<='9' ) v = v*16 + c - '0';
164125                else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
164126                else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
164127                else break;
164128              }
164129              if( v==0 ) break;
164130              if( v<=0x7f ){
164131                zOut[j++] = (char)v;
164132              }else if( v<=0x7ff ){
164133                zOut[j++] = (char)(0xc0 | (v>>6));
164134                zOut[j++] = 0x80 | (v&0x3f);
164135              }else{
164136                zOut[j++] = (char)(0xe0 | (v>>12));
164137                zOut[j++] = 0x80 | ((v>>6)&0x3f);
164138                zOut[j++] = 0x80 | (v&0x3f);
164139              }
164140            }else{
164141              if( c=='b' ){
164142                c = '\b';
164143              }else if( c=='f' ){
164144                c = '\f';
164145              }else if( c=='n' ){
164146                c = '\n';
164147              }else if( c=='r' ){
164148                c = '\r';
164149              }else if( c=='t' ){
164150                c = '\t';
164151              }
164152              zOut[j++] = c;
164153            }
164154          }
164155        }
164156        zOut[j] = 0;
164157        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
164158      }
164159      break;
164160    }
164161    case JSON_ARRAY:
164162    case JSON_OBJECT: {
164163      jsonReturnJson(pNode, pCtx, aReplace);
164164      break;
164165    }
164166  }
164167}
164168
164169/* Forward reference */
164170static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
164171
164172/*
164173** A macro to hint to the compiler that a function should not be
164174** inlined.
164175*/
164176#if defined(__GNUC__)
164177#  define JSON_NOINLINE  __attribute__((noinline))
164178#elif defined(_MSC_VER) && _MSC_VER>=1310
164179#  define JSON_NOINLINE  __declspec(noinline)
164180#else
164181#  define JSON_NOINLINE
164182#endif
164183
164184
164185static JSON_NOINLINE int jsonParseAddNodeExpand(
164186  JsonParse *pParse,        /* Append the node to this object */
164187  u32 eType,                /* Node type */
164188  u32 n,                    /* Content size or sub-node count */
164189  const char *zContent      /* Content */
164190){
164191  u32 nNew;
164192  JsonNode *pNew;
164193  assert( pParse->nNode>=pParse->nAlloc );
164194  if( pParse->oom ) return -1;
164195  nNew = pParse->nAlloc*2 + 10;
164196  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
164197  if( pNew==0 ){
164198    pParse->oom = 1;
164199    return -1;
164200  }
164201  pParse->nAlloc = nNew;
164202  pParse->aNode = pNew;
164203  assert( pParse->nNode<pParse->nAlloc );
164204  return jsonParseAddNode(pParse, eType, n, zContent);
164205}
164206
164207/*
164208** Create a new JsonNode instance based on the arguments and append that
164209** instance to the JsonParse.  Return the index in pParse->aNode[] of the
164210** new node, or -1 if a memory allocation fails.
164211*/
164212static int jsonParseAddNode(
164213  JsonParse *pParse,        /* Append the node to this object */
164214  u32 eType,                /* Node type */
164215  u32 n,                    /* Content size or sub-node count */
164216  const char *zContent      /* Content */
164217){
164218  JsonNode *p;
164219  if( pParse->nNode>=pParse->nAlloc ){
164220    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
164221  }
164222  p = &pParse->aNode[pParse->nNode];
164223  p->eType = (u8)eType;
164224  p->jnFlags = 0;
164225  p->iVal = 0;
164226  p->n = n;
164227  p->u.zJContent = zContent;
164228  return pParse->nNode++;
164229}
164230
164231/*
164232** Parse a single JSON value which begins at pParse->zJson[i].  Return the
164233** index of the first character past the end of the value parsed.
164234**
164235** Return negative for a syntax error.  Special cases:  return -2 if the
164236** first non-whitespace character is '}' and return -3 if the first
164237** non-whitespace character is ']'.
164238*/
164239static int jsonParseValue(JsonParse *pParse, u32 i){
164240  char c;
164241  u32 j;
164242  int iThis;
164243  int x;
164244  JsonNode *pNode;
164245  while( safe_isspace(pParse->zJson[i]) ){ i++; }
164246  if( (c = pParse->zJson[i])=='{' ){
164247    /* Parse object */
164248    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
164249    if( iThis<0 ) return -1;
164250    for(j=i+1;;j++){
164251      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164252      x = jsonParseValue(pParse, j);
164253      if( x<0 ){
164254        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
164255        return -1;
164256      }
164257      if( pParse->oom ) return -1;
164258      pNode = &pParse->aNode[pParse->nNode-1];
164259      if( pNode->eType!=JSON_STRING ) return -1;
164260      pNode->jnFlags |= JNODE_LABEL;
164261      j = x;
164262      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164263      if( pParse->zJson[j]!=':' ) return -1;
164264      j++;
164265      x = jsonParseValue(pParse, j);
164266      if( x<0 ) return -1;
164267      j = x;
164268      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164269      c = pParse->zJson[j];
164270      if( c==',' ) continue;
164271      if( c!='}' ) return -1;
164272      break;
164273    }
164274    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
164275    return j+1;
164276  }else if( c=='[' ){
164277    /* Parse array */
164278    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
164279    if( iThis<0 ) return -1;
164280    for(j=i+1;;j++){
164281      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164282      x = jsonParseValue(pParse, j);
164283      if( x<0 ){
164284        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
164285        return -1;
164286      }
164287      j = x;
164288      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164289      c = pParse->zJson[j];
164290      if( c==',' ) continue;
164291      if( c!=']' ) return -1;
164292      break;
164293    }
164294    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
164295    return j+1;
164296  }else if( c=='"' ){
164297    /* Parse string */
164298    u8 jnFlags = 0;
164299    j = i+1;
164300    for(;;){
164301      c = pParse->zJson[j];
164302      if( c==0 ) return -1;
164303      if( c=='\\' ){
164304        c = pParse->zJson[++j];
164305        if( c==0 ) return -1;
164306        jnFlags = JNODE_ESCAPE;
164307      }else if( c=='"' ){
164308        break;
164309      }
164310      j++;
164311    }
164312    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
164313    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
164314    return j+1;
164315  }else if( c=='n'
164316         && strncmp(pParse->zJson+i,"null",4)==0
164317         && !safe_isalnum(pParse->zJson[i+4]) ){
164318    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
164319    return i+4;
164320  }else if( c=='t'
164321         && strncmp(pParse->zJson+i,"true",4)==0
164322         && !safe_isalnum(pParse->zJson[i+4]) ){
164323    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
164324    return i+4;
164325  }else if( c=='f'
164326         && strncmp(pParse->zJson+i,"false",5)==0
164327         && !safe_isalnum(pParse->zJson[i+5]) ){
164328    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
164329    return i+5;
164330  }else if( c=='-' || (c>='0' && c<='9') ){
164331    /* Parse number */
164332    u8 seenDP = 0;
164333    u8 seenE = 0;
164334    j = i+1;
164335    for(;; j++){
164336      c = pParse->zJson[j];
164337      if( c>='0' && c<='9' ) continue;
164338      if( c=='.' ){
164339        if( pParse->zJson[j-1]=='-' ) return -1;
164340        if( seenDP ) return -1;
164341        seenDP = 1;
164342        continue;
164343      }
164344      if( c=='e' || c=='E' ){
164345        if( pParse->zJson[j-1]<'0' ) return -1;
164346        if( seenE ) return -1;
164347        seenDP = seenE = 1;
164348        c = pParse->zJson[j+1];
164349        if( c=='+' || c=='-' ){
164350          j++;
164351          c = pParse->zJson[j+1];
164352        }
164353        if( c<'0' || c>'9' ) return -1;
164354        continue;
164355      }
164356      break;
164357    }
164358    if( pParse->zJson[j-1]<'0' ) return -1;
164359    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
164360                        j - i, &pParse->zJson[i]);
164361    return j;
164362  }else if( c=='}' ){
164363    return -2;  /* End of {...} */
164364  }else if( c==']' ){
164365    return -3;  /* End of [...] */
164366  }else if( c==0 ){
164367    return 0;   /* End of file */
164368  }else{
164369    return -1;  /* Syntax error */
164370  }
164371}
164372
164373/*
164374** Parse a complete JSON string.  Return 0 on success or non-zero if there
164375** are any errors.  If an error occurs, free all memory associated with
164376** pParse.
164377**
164378** pParse is uninitialized when this routine is called.
164379*/
164380static int jsonParse(
164381  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
164382  sqlite3_context *pCtx,       /* Report errors here */
164383  const char *zJson            /* Input JSON text to be parsed */
164384){
164385  int i;
164386  memset(pParse, 0, sizeof(*pParse));
164387  if( zJson==0 ) return 1;
164388  pParse->zJson = zJson;
164389  i = jsonParseValue(pParse, 0);
164390  if( pParse->oom ) i = -1;
164391  if( i>0 ){
164392    while( safe_isspace(zJson[i]) ) i++;
164393    if( zJson[i] ) i = -1;
164394  }
164395  if( i<=0 ){
164396    if( pCtx!=0 ){
164397      if( pParse->oom ){
164398        sqlite3_result_error_nomem(pCtx);
164399      }else{
164400        sqlite3_result_error(pCtx, "malformed JSON", -1);
164401      }
164402    }
164403    jsonParseReset(pParse);
164404    return 1;
164405  }
164406  return 0;
164407}
164408
164409/* Mark node i of pParse as being a child of iParent.  Call recursively
164410** to fill in all the descendants of node i.
164411*/
164412static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
164413  JsonNode *pNode = &pParse->aNode[i];
164414  u32 j;
164415  pParse->aUp[i] = iParent;
164416  switch( pNode->eType ){
164417    case JSON_ARRAY: {
164418      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
164419        jsonParseFillInParentage(pParse, i+j, i);
164420      }
164421      break;
164422    }
164423    case JSON_OBJECT: {
164424      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
164425        pParse->aUp[i+j] = i;
164426        jsonParseFillInParentage(pParse, i+j+1, i);
164427      }
164428      break;
164429    }
164430    default: {
164431      break;
164432    }
164433  }
164434}
164435
164436/*
164437** Compute the parentage of all nodes in a completed parse.
164438*/
164439static int jsonParseFindParents(JsonParse *pParse){
164440  u32 *aUp;
164441  assert( pParse->aUp==0 );
164442  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
164443  if( aUp==0 ){
164444    pParse->oom = 1;
164445    return SQLITE_NOMEM;
164446  }
164447  jsonParseFillInParentage(pParse, 0, 0);
164448  return SQLITE_OK;
164449}
164450
164451/*
164452** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
164453** a match.
164454*/
164455static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
164456  if( pNode->jnFlags & JNODE_RAW ){
164457    if( pNode->n!=nKey ) return 0;
164458    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
164459  }else{
164460    if( pNode->n!=nKey+2 ) return 0;
164461    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
164462  }
164463}
164464
164465/* forward declaration */
164466static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
164467
164468/*
164469** Search along zPath to find the node specified.  Return a pointer
164470** to that node, or NULL if zPath is malformed or if there is no such
164471** node.
164472**
164473** If pApnd!=0, then try to append new nodes to complete zPath if it is
164474** possible to do so and if no existing node corresponds to zPath.  If
164475** new nodes are appended *pApnd is set to 1.
164476*/
164477static JsonNode *jsonLookupStep(
164478  JsonParse *pParse,      /* The JSON to search */
164479  u32 iRoot,              /* Begin the search at this node */
164480  const char *zPath,      /* The path to search */
164481  int *pApnd,             /* Append nodes to complete path if not NULL */
164482  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
164483){
164484  u32 i, j, nKey;
164485  const char *zKey;
164486  JsonNode *pRoot = &pParse->aNode[iRoot];
164487  if( zPath[0]==0 ) return pRoot;
164488  if( zPath[0]=='.' ){
164489    if( pRoot->eType!=JSON_OBJECT ) return 0;
164490    zPath++;
164491    if( zPath[0]=='"' ){
164492      zKey = zPath + 1;
164493      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
164494      nKey = i-1;
164495      if( zPath[i] ){
164496        i++;
164497      }else{
164498        *pzErr = zPath;
164499        return 0;
164500      }
164501    }else{
164502      zKey = zPath;
164503      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
164504      nKey = i;
164505    }
164506    if( nKey==0 ){
164507      *pzErr = zPath;
164508      return 0;
164509    }
164510    j = 1;
164511    for(;;){
164512      while( j<=pRoot->n ){
164513        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
164514          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
164515        }
164516        j++;
164517        j += jsonNodeSize(&pRoot[j]);
164518      }
164519      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
164520      iRoot += pRoot->u.iAppend;
164521      pRoot = &pParse->aNode[iRoot];
164522      j = 1;
164523    }
164524    if( pApnd ){
164525      u32 iStart, iLabel;
164526      JsonNode *pNode;
164527      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
164528      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
164529      zPath += i;
164530      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
164531      if( pParse->oom ) return 0;
164532      if( pNode ){
164533        pRoot = &pParse->aNode[iRoot];
164534        pRoot->u.iAppend = iStart - iRoot;
164535        pRoot->jnFlags |= JNODE_APPEND;
164536        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
164537      }
164538      return pNode;
164539    }
164540  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
164541    if( pRoot->eType!=JSON_ARRAY ) return 0;
164542    i = 0;
164543    j = 1;
164544    while( safe_isdigit(zPath[j]) ){
164545      i = i*10 + zPath[j] - '0';
164546      j++;
164547    }
164548    if( zPath[j]!=']' ){
164549      *pzErr = zPath;
164550      return 0;
164551    }
164552    zPath += j + 1;
164553    j = 1;
164554    for(;;){
164555      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
164556        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
164557        j += jsonNodeSize(&pRoot[j]);
164558      }
164559      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
164560      iRoot += pRoot->u.iAppend;
164561      pRoot = &pParse->aNode[iRoot];
164562      j = 1;
164563    }
164564    if( j<=pRoot->n ){
164565      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
164566    }
164567    if( i==0 && pApnd ){
164568      u32 iStart;
164569      JsonNode *pNode;
164570      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
164571      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
164572      if( pParse->oom ) return 0;
164573      if( pNode ){
164574        pRoot = &pParse->aNode[iRoot];
164575        pRoot->u.iAppend = iStart - iRoot;
164576        pRoot->jnFlags |= JNODE_APPEND;
164577      }
164578      return pNode;
164579    }
164580  }else{
164581    *pzErr = zPath;
164582  }
164583  return 0;
164584}
164585
164586/*
164587** Append content to pParse that will complete zPath.  Return a pointer
164588** to the inserted node, or return NULL if the append fails.
164589*/
164590static JsonNode *jsonLookupAppend(
164591  JsonParse *pParse,     /* Append content to the JSON parse */
164592  const char *zPath,     /* Description of content to append */
164593  int *pApnd,            /* Set this flag to 1 */
164594  const char **pzErr     /* Make this point to any syntax error */
164595){
164596  *pApnd = 1;
164597  if( zPath[0]==0 ){
164598    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
164599    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
164600  }
164601  if( zPath[0]=='.' ){
164602    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
164603  }else if( strncmp(zPath,"[0]",3)==0 ){
164604    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
164605  }else{
164606    return 0;
164607  }
164608  if( pParse->oom ) return 0;
164609  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
164610}
164611
164612/*
164613** Return the text of a syntax error message on a JSON path.  Space is
164614** obtained from sqlite3_malloc().
164615*/
164616static char *jsonPathSyntaxError(const char *zErr){
164617  return sqlite3_mprintf("JSON path error near '%q'", zErr);
164618}
164619
164620/*
164621** Do a node lookup using zPath.  Return a pointer to the node on success.
164622** Return NULL if not found or if there is an error.
164623**
164624** On an error, write an error message into pCtx and increment the
164625** pParse->nErr counter.
164626**
164627** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
164628** nodes are appended.
164629*/
164630static JsonNode *jsonLookup(
164631  JsonParse *pParse,      /* The JSON to search */
164632  const char *zPath,      /* The path to search */
164633  int *pApnd,             /* Append nodes to complete path if not NULL */
164634  sqlite3_context *pCtx   /* Report errors here, if not NULL */
164635){
164636  const char *zErr = 0;
164637  JsonNode *pNode = 0;
164638  char *zMsg;
164639
164640  if( zPath==0 ) return 0;
164641  if( zPath[0]!='$' ){
164642    zErr = zPath;
164643    goto lookup_err;
164644  }
164645  zPath++;
164646  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
164647  if( zErr==0 ) return pNode;
164648
164649lookup_err:
164650  pParse->nErr++;
164651  assert( zErr!=0 && pCtx!=0 );
164652  zMsg = jsonPathSyntaxError(zErr);
164653  if( zMsg ){
164654    sqlite3_result_error(pCtx, zMsg, -1);
164655    sqlite3_free(zMsg);
164656  }else{
164657    sqlite3_result_error_nomem(pCtx);
164658  }
164659  return 0;
164660}
164661
164662
164663/*
164664** Report the wrong number of arguments for json_insert(), json_replace()
164665** or json_set().
164666*/
164667static void jsonWrongNumArgs(
164668  sqlite3_context *pCtx,
164669  const char *zFuncName
164670){
164671  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
164672                               zFuncName);
164673  sqlite3_result_error(pCtx, zMsg, -1);
164674  sqlite3_free(zMsg);
164675}
164676
164677
164678/****************************************************************************
164679** SQL functions used for testing and debugging
164680****************************************************************************/
164681
164682#ifdef SQLITE_DEBUG
164683/*
164684** The json_parse(JSON) function returns a string which describes
164685** a parse of the JSON provided.  Or it returns NULL if JSON is not
164686** well-formed.
164687*/
164688static void jsonParseFunc(
164689  sqlite3_context *ctx,
164690  int argc,
164691  sqlite3_value **argv
164692){
164693  JsonString s;       /* Output string - not real JSON */
164694  JsonParse x;        /* The parse */
164695  u32 i;
164696
164697  assert( argc==1 );
164698  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164699  jsonParseFindParents(&x);
164700  jsonInit(&s, ctx);
164701  for(i=0; i<x.nNode; i++){
164702    const char *zType;
164703    if( x.aNode[i].jnFlags & JNODE_LABEL ){
164704      assert( x.aNode[i].eType==JSON_STRING );
164705      zType = "label";
164706    }else{
164707      zType = jsonType[x.aNode[i].eType];
164708    }
164709    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
164710               i, zType, x.aNode[i].n, x.aUp[i]);
164711    if( x.aNode[i].u.zJContent!=0 ){
164712      jsonAppendRaw(&s, " ", 1);
164713      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
164714    }
164715    jsonAppendRaw(&s, "\n", 1);
164716  }
164717  jsonParseReset(&x);
164718  jsonResult(&s);
164719}
164720
164721/*
164722** The json_test1(JSON) function return true (1) if the input is JSON
164723** text generated by another json function.  It returns (0) if the input
164724** is not known to be JSON.
164725*/
164726static void jsonTest1Func(
164727  sqlite3_context *ctx,
164728  int argc,
164729  sqlite3_value **argv
164730){
164731  UNUSED_PARAM(argc);
164732  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
164733}
164734#endif /* SQLITE_DEBUG */
164735
164736/****************************************************************************
164737** SQL function implementations
164738****************************************************************************/
164739
164740/*
164741** Implementation of the json_array(VALUE,...) function.  Return a JSON
164742** array that contains all values given in arguments.  Or if any argument
164743** is a BLOB, throw an error.
164744*/
164745static void jsonArrayFunc(
164746  sqlite3_context *ctx,
164747  int argc,
164748  sqlite3_value **argv
164749){
164750  int i;
164751  JsonString jx;
164752
164753  jsonInit(&jx, ctx);
164754  jsonAppendChar(&jx, '[');
164755  for(i=0; i<argc; i++){
164756    jsonAppendSeparator(&jx);
164757    jsonAppendValue(&jx, argv[i]);
164758  }
164759  jsonAppendChar(&jx, ']');
164760  jsonResult(&jx);
164761  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164762}
164763
164764
164765/*
164766** json_array_length(JSON)
164767** json_array_length(JSON, PATH)
164768**
164769** Return the number of elements in the top-level JSON array.
164770** Return 0 if the input is not a well-formed JSON array.
164771*/
164772static void jsonArrayLengthFunc(
164773  sqlite3_context *ctx,
164774  int argc,
164775  sqlite3_value **argv
164776){
164777  JsonParse x;          /* The parse */
164778  sqlite3_int64 n = 0;
164779  u32 i;
164780  JsonNode *pNode;
164781
164782  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164783  assert( x.nNode );
164784  if( argc==2 ){
164785    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
164786    pNode = jsonLookup(&x, zPath, 0, ctx);
164787  }else{
164788    pNode = x.aNode;
164789  }
164790  if( pNode==0 ){
164791    x.nErr = 1;
164792  }else if( pNode->eType==JSON_ARRAY ){
164793    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
164794    for(i=1; i<=pNode->n; n++){
164795      i += jsonNodeSize(&pNode[i]);
164796    }
164797  }
164798  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
164799  jsonParseReset(&x);
164800}
164801
164802/*
164803** json_extract(JSON, PATH, ...)
164804**
164805** Return the element described by PATH.  Return NULL if there is no
164806** PATH element.  If there are multiple PATHs, then return a JSON array
164807** with the result from each path.  Throw an error if the JSON or any PATH
164808** is malformed.
164809*/
164810static void jsonExtractFunc(
164811  sqlite3_context *ctx,
164812  int argc,
164813  sqlite3_value **argv
164814){
164815  JsonParse x;          /* The parse */
164816  JsonNode *pNode;
164817  const char *zPath;
164818  JsonString jx;
164819  int i;
164820
164821  if( argc<2 ) return;
164822  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164823  jsonInit(&jx, ctx);
164824  jsonAppendChar(&jx, '[');
164825  for(i=1; i<argc; i++){
164826    zPath = (const char*)sqlite3_value_text(argv[i]);
164827    pNode = jsonLookup(&x, zPath, 0, ctx);
164828    if( x.nErr ) break;
164829    if( argc>2 ){
164830      jsonAppendSeparator(&jx);
164831      if( pNode ){
164832        jsonRenderNode(pNode, &jx, 0);
164833      }else{
164834        jsonAppendRaw(&jx, "null", 4);
164835      }
164836    }else if( pNode ){
164837      jsonReturn(pNode, ctx, 0);
164838    }
164839  }
164840  if( argc>2 && i==argc ){
164841    jsonAppendChar(&jx, ']');
164842    jsonResult(&jx);
164843    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164844  }
164845  jsonReset(&jx);
164846  jsonParseReset(&x);
164847}
164848
164849/*
164850** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
164851** object that contains all name/value given in arguments.  Or if any name
164852** is not a string or if any value is a BLOB, throw an error.
164853*/
164854static void jsonObjectFunc(
164855  sqlite3_context *ctx,
164856  int argc,
164857  sqlite3_value **argv
164858){
164859  int i;
164860  JsonString jx;
164861  const char *z;
164862  u32 n;
164863
164864  if( argc&1 ){
164865    sqlite3_result_error(ctx, "json_object() requires an even number "
164866                                  "of arguments", -1);
164867    return;
164868  }
164869  jsonInit(&jx, ctx);
164870  jsonAppendChar(&jx, '{');
164871  for(i=0; i<argc; i+=2){
164872    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
164873      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
164874      jsonReset(&jx);
164875      return;
164876    }
164877    jsonAppendSeparator(&jx);
164878    z = (const char*)sqlite3_value_text(argv[i]);
164879    n = (u32)sqlite3_value_bytes(argv[i]);
164880    jsonAppendString(&jx, z, n);
164881    jsonAppendChar(&jx, ':');
164882    jsonAppendValue(&jx, argv[i+1]);
164883  }
164884  jsonAppendChar(&jx, '}');
164885  jsonResult(&jx);
164886  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164887}
164888
164889
164890/*
164891** json_remove(JSON, PATH, ...)
164892**
164893** Remove the named elements from JSON and return the result.  malformed
164894** JSON or PATH arguments result in an error.
164895*/
164896static void jsonRemoveFunc(
164897  sqlite3_context *ctx,
164898  int argc,
164899  sqlite3_value **argv
164900){
164901  JsonParse x;          /* The parse */
164902  JsonNode *pNode;
164903  const char *zPath;
164904  u32 i;
164905
164906  if( argc<1 ) return;
164907  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164908  assert( x.nNode );
164909  for(i=1; i<(u32)argc; i++){
164910    zPath = (const char*)sqlite3_value_text(argv[i]);
164911    if( zPath==0 ) goto remove_done;
164912    pNode = jsonLookup(&x, zPath, 0, ctx);
164913    if( x.nErr ) goto remove_done;
164914    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
164915  }
164916  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
164917    jsonReturnJson(x.aNode, ctx, 0);
164918  }
164919remove_done:
164920  jsonParseReset(&x);
164921}
164922
164923/*
164924** json_replace(JSON, PATH, VALUE, ...)
164925**
164926** Replace the value at PATH with VALUE.  If PATH does not already exist,
164927** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
164928*/
164929static void jsonReplaceFunc(
164930  sqlite3_context *ctx,
164931  int argc,
164932  sqlite3_value **argv
164933){
164934  JsonParse x;          /* The parse */
164935  JsonNode *pNode;
164936  const char *zPath;
164937  u32 i;
164938
164939  if( argc<1 ) return;
164940  if( (argc&1)==0 ) {
164941    jsonWrongNumArgs(ctx, "replace");
164942    return;
164943  }
164944  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164945  assert( x.nNode );
164946  for(i=1; i<(u32)argc; i+=2){
164947    zPath = (const char*)sqlite3_value_text(argv[i]);
164948    pNode = jsonLookup(&x, zPath, 0, ctx);
164949    if( x.nErr ) goto replace_err;
164950    if( pNode ){
164951      pNode->jnFlags |= (u8)JNODE_REPLACE;
164952      pNode->iVal = (u8)(i+1);
164953    }
164954  }
164955  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
164956    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
164957  }else{
164958    jsonReturnJson(x.aNode, ctx, argv);
164959  }
164960replace_err:
164961  jsonParseReset(&x);
164962}
164963
164964/*
164965** json_set(JSON, PATH, VALUE, ...)
164966**
164967** Set the value at PATH to VALUE.  Create the PATH if it does not already
164968** exist.  Overwrite existing values that do exist.
164969** If JSON or PATH is malformed, throw an error.
164970**
164971** json_insert(JSON, PATH, VALUE, ...)
164972**
164973** Create PATH and initialize it to VALUE.  If PATH already exists, this
164974** routine is a no-op.  If JSON or PATH is malformed, throw an error.
164975*/
164976static void jsonSetFunc(
164977  sqlite3_context *ctx,
164978  int argc,
164979  sqlite3_value **argv
164980){
164981  JsonParse x;          /* The parse */
164982  JsonNode *pNode;
164983  const char *zPath;
164984  u32 i;
164985  int bApnd;
164986  int bIsSet = *(int*)sqlite3_user_data(ctx);
164987
164988  if( argc<1 ) return;
164989  if( (argc&1)==0 ) {
164990    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
164991    return;
164992  }
164993  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164994  assert( x.nNode );
164995  for(i=1; i<(u32)argc; i+=2){
164996    zPath = (const char*)sqlite3_value_text(argv[i]);
164997    bApnd = 0;
164998    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
164999    if( x.oom ){
165000      sqlite3_result_error_nomem(ctx);
165001      goto jsonSetDone;
165002    }else if( x.nErr ){
165003      goto jsonSetDone;
165004    }else if( pNode && (bApnd || bIsSet) ){
165005      pNode->jnFlags |= (u8)JNODE_REPLACE;
165006      pNode->iVal = (u8)(i+1);
165007    }
165008  }
165009  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
165010    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
165011  }else{
165012    jsonReturnJson(x.aNode, ctx, argv);
165013  }
165014jsonSetDone:
165015  jsonParseReset(&x);
165016}
165017
165018/*
165019** json_type(JSON)
165020** json_type(JSON, PATH)
165021**
165022** Return the top-level "type" of a JSON string.  Throw an error if
165023** either the JSON or PATH inputs are not well-formed.
165024*/
165025static void jsonTypeFunc(
165026  sqlite3_context *ctx,
165027  int argc,
165028  sqlite3_value **argv
165029){
165030  JsonParse x;          /* The parse */
165031  const char *zPath;
165032  JsonNode *pNode;
165033
165034  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
165035  assert( x.nNode );
165036  if( argc==2 ){
165037    zPath = (const char*)sqlite3_value_text(argv[1]);
165038    pNode = jsonLookup(&x, zPath, 0, ctx);
165039  }else{
165040    pNode = x.aNode;
165041  }
165042  if( pNode ){
165043    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
165044  }
165045  jsonParseReset(&x);
165046}
165047
165048/*
165049** json_valid(JSON)
165050**
165051** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
165052** Return 0 otherwise.
165053*/
165054static void jsonValidFunc(
165055  sqlite3_context *ctx,
165056  int argc,
165057  sqlite3_value **argv
165058){
165059  JsonParse x;          /* The parse */
165060  int rc = 0;
165061
165062  UNUSED_PARAM(argc);
165063  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
165064    rc = 1;
165065  }
165066  jsonParseReset(&x);
165067  sqlite3_result_int(ctx, rc);
165068}
165069
165070#ifndef SQLITE_OMIT_VIRTUALTABLE
165071/****************************************************************************
165072** The json_each virtual table
165073****************************************************************************/
165074typedef struct JsonEachCursor JsonEachCursor;
165075struct JsonEachCursor {
165076  sqlite3_vtab_cursor base;  /* Base class - must be first */
165077  u32 iRowid;                /* The rowid */
165078  u32 iBegin;                /* The first node of the scan */
165079  u32 i;                     /* Index in sParse.aNode[] of current row */
165080  u32 iEnd;                  /* EOF when i equals or exceeds this value */
165081  u8 eType;                  /* Type of top-level element */
165082  u8 bRecursive;             /* True for json_tree().  False for json_each() */
165083  char *zJson;               /* Input JSON */
165084  char *zRoot;               /* Path by which to filter zJson */
165085  JsonParse sParse;          /* Parse of the input JSON */
165086};
165087
165088/* Constructor for the json_each virtual table */
165089static int jsonEachConnect(
165090  sqlite3 *db,
165091  void *pAux,
165092  int argc, const char *const*argv,
165093  sqlite3_vtab **ppVtab,
165094  char **pzErr
165095){
165096  sqlite3_vtab *pNew;
165097  int rc;
165098
165099/* Column numbers */
165100#define JEACH_KEY     0
165101#define JEACH_VALUE   1
165102#define JEACH_TYPE    2
165103#define JEACH_ATOM    3
165104#define JEACH_ID      4
165105#define JEACH_PARENT  5
165106#define JEACH_FULLKEY 6
165107#define JEACH_PATH    7
165108#define JEACH_JSON    8
165109#define JEACH_ROOT    9
165110
165111  UNUSED_PARAM(pzErr);
165112  UNUSED_PARAM(argv);
165113  UNUSED_PARAM(argc);
165114  UNUSED_PARAM(pAux);
165115  rc = sqlite3_declare_vtab(db,
165116     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
165117                    "json HIDDEN,root HIDDEN)");
165118  if( rc==SQLITE_OK ){
165119    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
165120    if( pNew==0 ) return SQLITE_NOMEM;
165121    memset(pNew, 0, sizeof(*pNew));
165122  }
165123  return rc;
165124}
165125
165126/* destructor for json_each virtual table */
165127static int jsonEachDisconnect(sqlite3_vtab *pVtab){
165128  sqlite3_free(pVtab);
165129  return SQLITE_OK;
165130}
165131
165132/* constructor for a JsonEachCursor object for json_each(). */
165133static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
165134  JsonEachCursor *pCur;
165135
165136  UNUSED_PARAM(p);
165137  pCur = sqlite3_malloc( sizeof(*pCur) );
165138  if( pCur==0 ) return SQLITE_NOMEM;
165139  memset(pCur, 0, sizeof(*pCur));
165140  *ppCursor = &pCur->base;
165141  return SQLITE_OK;
165142}
165143
165144/* constructor for a JsonEachCursor object for json_tree(). */
165145static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
165146  int rc = jsonEachOpenEach(p, ppCursor);
165147  if( rc==SQLITE_OK ){
165148    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
165149    pCur->bRecursive = 1;
165150  }
165151  return rc;
165152}
165153
165154/* Reset a JsonEachCursor back to its original state.  Free any memory
165155** held. */
165156static void jsonEachCursorReset(JsonEachCursor *p){
165157  sqlite3_free(p->zJson);
165158  sqlite3_free(p->zRoot);
165159  jsonParseReset(&p->sParse);
165160  p->iRowid = 0;
165161  p->i = 0;
165162  p->iEnd = 0;
165163  p->eType = 0;
165164  p->zJson = 0;
165165  p->zRoot = 0;
165166}
165167
165168/* Destructor for a jsonEachCursor object */
165169static int jsonEachClose(sqlite3_vtab_cursor *cur){
165170  JsonEachCursor *p = (JsonEachCursor*)cur;
165171  jsonEachCursorReset(p);
165172  sqlite3_free(cur);
165173  return SQLITE_OK;
165174}
165175
165176/* Return TRUE if the jsonEachCursor object has been advanced off the end
165177** of the JSON object */
165178static int jsonEachEof(sqlite3_vtab_cursor *cur){
165179  JsonEachCursor *p = (JsonEachCursor*)cur;
165180  return p->i >= p->iEnd;
165181}
165182
165183/* Advance the cursor to the next element for json_tree() */
165184static int jsonEachNext(sqlite3_vtab_cursor *cur){
165185  JsonEachCursor *p = (JsonEachCursor*)cur;
165186  if( p->bRecursive ){
165187    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
165188    p->i++;
165189    p->iRowid++;
165190    if( p->i<p->iEnd ){
165191      u32 iUp = p->sParse.aUp[p->i];
165192      JsonNode *pUp = &p->sParse.aNode[iUp];
165193      p->eType = pUp->eType;
165194      if( pUp->eType==JSON_ARRAY ){
165195        if( iUp==p->i-1 ){
165196          pUp->u.iKey = 0;
165197        }else{
165198          pUp->u.iKey++;
165199        }
165200      }
165201    }
165202  }else{
165203    switch( p->eType ){
165204      case JSON_ARRAY: {
165205        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
165206        p->iRowid++;
165207        break;
165208      }
165209      case JSON_OBJECT: {
165210        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
165211        p->iRowid++;
165212        break;
165213      }
165214      default: {
165215        p->i = p->iEnd;
165216        break;
165217      }
165218    }
165219  }
165220  return SQLITE_OK;
165221}
165222
165223/* Append the name of the path for element i to pStr
165224*/
165225static void jsonEachComputePath(
165226  JsonEachCursor *p,       /* The cursor */
165227  JsonString *pStr,        /* Write the path here */
165228  u32 i                    /* Path to this element */
165229){
165230  JsonNode *pNode, *pUp;
165231  u32 iUp;
165232  if( i==0 ){
165233    jsonAppendChar(pStr, '$');
165234    return;
165235  }
165236  iUp = p->sParse.aUp[i];
165237  jsonEachComputePath(p, pStr, iUp);
165238  pNode = &p->sParse.aNode[i];
165239  pUp = &p->sParse.aNode[iUp];
165240  if( pUp->eType==JSON_ARRAY ){
165241    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
165242  }else{
165243    assert( pUp->eType==JSON_OBJECT );
165244    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
165245    assert( pNode->eType==JSON_STRING );
165246    assert( pNode->jnFlags & JNODE_LABEL );
165247    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
165248  }
165249}
165250
165251/* Return the value of a column */
165252static int jsonEachColumn(
165253  sqlite3_vtab_cursor *cur,   /* The cursor */
165254  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
165255  int i                       /* Which column to return */
165256){
165257  JsonEachCursor *p = (JsonEachCursor*)cur;
165258  JsonNode *pThis = &p->sParse.aNode[p->i];
165259  switch( i ){
165260    case JEACH_KEY: {
165261      if( p->i==0 ) break;
165262      if( p->eType==JSON_OBJECT ){
165263        jsonReturn(pThis, ctx, 0);
165264      }else if( p->eType==JSON_ARRAY ){
165265        u32 iKey;
165266        if( p->bRecursive ){
165267          if( p->iRowid==0 ) break;
165268          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
165269        }else{
165270          iKey = p->iRowid;
165271        }
165272        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
165273      }
165274      break;
165275    }
165276    case JEACH_VALUE: {
165277      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165278      jsonReturn(pThis, ctx, 0);
165279      break;
165280    }
165281    case JEACH_TYPE: {
165282      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165283      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
165284      break;
165285    }
165286    case JEACH_ATOM: {
165287      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165288      if( pThis->eType>=JSON_ARRAY ) break;
165289      jsonReturn(pThis, ctx, 0);
165290      break;
165291    }
165292    case JEACH_ID: {
165293      sqlite3_result_int64(ctx,
165294         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
165295      break;
165296    }
165297    case JEACH_PARENT: {
165298      if( p->i>p->iBegin && p->bRecursive ){
165299        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
165300      }
165301      break;
165302    }
165303    case JEACH_FULLKEY: {
165304      JsonString x;
165305      jsonInit(&x, ctx);
165306      if( p->bRecursive ){
165307        jsonEachComputePath(p, &x, p->i);
165308      }else{
165309        if( p->zRoot ){
165310          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
165311        }else{
165312          jsonAppendChar(&x, '$');
165313        }
165314        if( p->eType==JSON_ARRAY ){
165315          jsonPrintf(30, &x, "[%d]", p->iRowid);
165316        }else{
165317          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
165318        }
165319      }
165320      jsonResult(&x);
165321      break;
165322    }
165323    case JEACH_PATH: {
165324      if( p->bRecursive ){
165325        JsonString x;
165326        jsonInit(&x, ctx);
165327        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
165328        jsonResult(&x);
165329        break;
165330      }
165331      /* For json_each() path and root are the same so fall through
165332      ** into the root case */
165333    }
165334    case JEACH_ROOT: {
165335      const char *zRoot = p->zRoot;
165336       if( zRoot==0 ) zRoot = "$";
165337      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
165338      break;
165339    }
165340    case JEACH_JSON: {
165341      assert( i==JEACH_JSON );
165342      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
165343      break;
165344    }
165345  }
165346  return SQLITE_OK;
165347}
165348
165349/* Return the current rowid value */
165350static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
165351  JsonEachCursor *p = (JsonEachCursor*)cur;
165352  *pRowid = p->iRowid;
165353  return SQLITE_OK;
165354}
165355
165356/* The query strategy is to look for an equality constraint on the json
165357** column.  Without such a constraint, the table cannot operate.  idxNum is
165358** 1 if the constraint is found, 3 if the constraint and zRoot are found,
165359** and 0 otherwise.
165360*/
165361static int jsonEachBestIndex(
165362  sqlite3_vtab *tab,
165363  sqlite3_index_info *pIdxInfo
165364){
165365  int i;
165366  int jsonIdx = -1;
165367  int rootIdx = -1;
165368  const struct sqlite3_index_constraint *pConstraint;
165369
165370  UNUSED_PARAM(tab);
165371  pConstraint = pIdxInfo->aConstraint;
165372  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
165373    if( pConstraint->usable==0 ) continue;
165374    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
165375    switch( pConstraint->iColumn ){
165376      case JEACH_JSON:   jsonIdx = i;    break;
165377      case JEACH_ROOT:   rootIdx = i;    break;
165378      default:           /* no-op */     break;
165379    }
165380  }
165381  if( jsonIdx<0 ){
165382    pIdxInfo->idxNum = 0;
165383    pIdxInfo->estimatedCost = 1e99;
165384  }else{
165385    pIdxInfo->estimatedCost = 1.0;
165386    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
165387    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
165388    if( rootIdx<0 ){
165389      pIdxInfo->idxNum = 1;
165390    }else{
165391      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
165392      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
165393      pIdxInfo->idxNum = 3;
165394    }
165395  }
165396  return SQLITE_OK;
165397}
165398
165399/* Start a search on a new JSON string */
165400static int jsonEachFilter(
165401  sqlite3_vtab_cursor *cur,
165402  int idxNum, const char *idxStr,
165403  int argc, sqlite3_value **argv
165404){
165405  JsonEachCursor *p = (JsonEachCursor*)cur;
165406  const char *z;
165407  const char *zRoot = 0;
165408  sqlite3_int64 n;
165409
165410  UNUSED_PARAM(idxStr);
165411  UNUSED_PARAM(argc);
165412  jsonEachCursorReset(p);
165413  if( idxNum==0 ) return SQLITE_OK;
165414  z = (const char*)sqlite3_value_text(argv[0]);
165415  if( z==0 ) return SQLITE_OK;
165416  n = sqlite3_value_bytes(argv[0]);
165417  p->zJson = sqlite3_malloc64( n+1 );
165418  if( p->zJson==0 ) return SQLITE_NOMEM;
165419  memcpy(p->zJson, z, (size_t)n+1);
165420  if( jsonParse(&p->sParse, 0, p->zJson) ){
165421    int rc = SQLITE_NOMEM;
165422    if( p->sParse.oom==0 ){
165423      sqlite3_free(cur->pVtab->zErrMsg);
165424      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
165425      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
165426    }
165427    jsonEachCursorReset(p);
165428    return rc;
165429  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
165430    jsonEachCursorReset(p);
165431    return SQLITE_NOMEM;
165432  }else{
165433    JsonNode *pNode = 0;
165434    if( idxNum==3 ){
165435      const char *zErr = 0;
165436      zRoot = (const char*)sqlite3_value_text(argv[1]);
165437      if( zRoot==0 ) return SQLITE_OK;
165438      n = sqlite3_value_bytes(argv[1]);
165439      p->zRoot = sqlite3_malloc64( n+1 );
165440      if( p->zRoot==0 ) return SQLITE_NOMEM;
165441      memcpy(p->zRoot, zRoot, (size_t)n+1);
165442      if( zRoot[0]!='$' ){
165443        zErr = zRoot;
165444      }else{
165445        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
165446      }
165447      if( zErr ){
165448        sqlite3_free(cur->pVtab->zErrMsg);
165449        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
165450        jsonEachCursorReset(p);
165451        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
165452      }else if( pNode==0 ){
165453        return SQLITE_OK;
165454      }
165455    }else{
165456      pNode = p->sParse.aNode;
165457    }
165458    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
165459    p->eType = pNode->eType;
165460    if( p->eType>=JSON_ARRAY ){
165461      pNode->u.iKey = 0;
165462      p->iEnd = p->i + pNode->n + 1;
165463      if( p->bRecursive ){
165464        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
165465        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
165466          p->i--;
165467        }
165468      }else{
165469        p->i++;
165470      }
165471    }else{
165472      p->iEnd = p->i+1;
165473    }
165474  }
165475  return SQLITE_OK;
165476}
165477
165478/* The methods of the json_each virtual table */
165479static sqlite3_module jsonEachModule = {
165480  0,                         /* iVersion */
165481  0,                         /* xCreate */
165482  jsonEachConnect,           /* xConnect */
165483  jsonEachBestIndex,         /* xBestIndex */
165484  jsonEachDisconnect,        /* xDisconnect */
165485  0,                         /* xDestroy */
165486  jsonEachOpenEach,          /* xOpen - open a cursor */
165487  jsonEachClose,             /* xClose - close a cursor */
165488  jsonEachFilter,            /* xFilter - configure scan constraints */
165489  jsonEachNext,              /* xNext - advance a cursor */
165490  jsonEachEof,               /* xEof - check for end of scan */
165491  jsonEachColumn,            /* xColumn - read data */
165492  jsonEachRowid,             /* xRowid - read data */
165493  0,                         /* xUpdate */
165494  0,                         /* xBegin */
165495  0,                         /* xSync */
165496  0,                         /* xCommit */
165497  0,                         /* xRollback */
165498  0,                         /* xFindMethod */
165499  0,                         /* xRename */
165500  0,                         /* xSavepoint */
165501  0,                         /* xRelease */
165502  0                          /* xRollbackTo */
165503};
165504
165505/* The methods of the json_tree virtual table. */
165506static sqlite3_module jsonTreeModule = {
165507  0,                         /* iVersion */
165508  0,                         /* xCreate */
165509  jsonEachConnect,           /* xConnect */
165510  jsonEachBestIndex,         /* xBestIndex */
165511  jsonEachDisconnect,        /* xDisconnect */
165512  0,                         /* xDestroy */
165513  jsonEachOpenTree,          /* xOpen - open a cursor */
165514  jsonEachClose,             /* xClose - close a cursor */
165515  jsonEachFilter,            /* xFilter - configure scan constraints */
165516  jsonEachNext,              /* xNext - advance a cursor */
165517  jsonEachEof,               /* xEof - check for end of scan */
165518  jsonEachColumn,            /* xColumn - read data */
165519  jsonEachRowid,             /* xRowid - read data */
165520  0,                         /* xUpdate */
165521  0,                         /* xBegin */
165522  0,                         /* xSync */
165523  0,                         /* xCommit */
165524  0,                         /* xRollback */
165525  0,                         /* xFindMethod */
165526  0,                         /* xRename */
165527  0,                         /* xSavepoint */
165528  0,                         /* xRelease */
165529  0                          /* xRollbackTo */
165530};
165531#endif /* SQLITE_OMIT_VIRTUALTABLE */
165532
165533/****************************************************************************
165534** The following routines are the only publically visible identifiers in this
165535** file.  Call the following routines in order to register the various SQL
165536** functions and the virtual table implemented by this file.
165537****************************************************************************/
165538
165539SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
165540  int rc = SQLITE_OK;
165541  unsigned int i;
165542  static const struct {
165543     const char *zName;
165544     int nArg;
165545     int flag;
165546     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
165547  } aFunc[] = {
165548    { "json",                 1, 0,   jsonRemoveFunc        },
165549    { "json_array",          -1, 0,   jsonArrayFunc         },
165550    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
165551    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
165552    { "json_extract",        -1, 0,   jsonExtractFunc       },
165553    { "json_insert",         -1, 0,   jsonSetFunc           },
165554    { "json_object",         -1, 0,   jsonObjectFunc        },
165555    { "json_remove",         -1, 0,   jsonRemoveFunc        },
165556    { "json_replace",        -1, 0,   jsonReplaceFunc       },
165557    { "json_set",            -1, 1,   jsonSetFunc           },
165558    { "json_type",            1, 0,   jsonTypeFunc          },
165559    { "json_type",            2, 0,   jsonTypeFunc          },
165560    { "json_valid",           1, 0,   jsonValidFunc         },
165561
165562#if SQLITE_DEBUG
165563    /* DEBUG and TESTING functions */
165564    { "json_parse",           1, 0,   jsonParseFunc         },
165565    { "json_test1",           1, 0,   jsonTest1Func         },
165566#endif
165567  };
165568#ifndef SQLITE_OMIT_VIRTUALTABLE
165569  static const struct {
165570     const char *zName;
165571     sqlite3_module *pModule;
165572  } aMod[] = {
165573    { "json_each",            &jsonEachModule               },
165574    { "json_tree",            &jsonTreeModule               },
165575  };
165576#endif
165577  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
165578    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
165579                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
165580                                 (void*)&aFunc[i].flag,
165581                                 aFunc[i].xFunc, 0, 0);
165582  }
165583#ifndef SQLITE_OMIT_VIRTUALTABLE
165584  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
165585    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
165586  }
165587#endif
165588  return rc;
165589}
165590
165591
165592#ifndef SQLITE_CORE
165593#ifdef _WIN32
165594__declspec(dllexport)
165595#endif
165596SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
165597  sqlite3 *db,
165598  char **pzErrMsg,
165599  const sqlite3_api_routines *pApi
165600){
165601  SQLITE_EXTENSION_INIT2(pApi);
165602  (void)pzErrMsg;  /* Unused parameter */
165603  return sqlite3Json1Init(db);
165604}
165605#endif
165606#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
165607
165608/************** End of json1.c ***********************************************/
165609/************** Begin file fts5.c ********************************************/
165610
165611
165612#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
165613
165614#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
165615# define NDEBUG 1
165616#endif
165617#if defined(NDEBUG) && defined(SQLITE_DEBUG)
165618# undef NDEBUG
165619#endif
165620
165621/*
165622** 2014 May 31
165623**
165624** The author disclaims copyright to this source code.  In place of
165625** a legal notice, here is a blessing:
165626**
165627**    May you do good and not evil.
165628**    May you find forgiveness for yourself and forgive others.
165629**    May you share freely, never taking more than you give.
165630**
165631******************************************************************************
165632**
165633** Interfaces to extend FTS5. Using the interfaces defined in this file,
165634** FTS5 may be extended with:
165635**
165636**     * custom tokenizers, and
165637**     * custom auxiliary functions.
165638*/
165639
165640
165641#ifndef _FTS5_H
165642#define _FTS5_H
165643
165644/* #include "sqlite3.h" */
165645
165646#if 0
165647extern "C" {
165648#endif
165649
165650/*************************************************************************
165651** CUSTOM AUXILIARY FUNCTIONS
165652**
165653** Virtual table implementations may overload SQL functions by implementing
165654** the sqlite3_module.xFindFunction() method.
165655*/
165656
165657typedef struct Fts5ExtensionApi Fts5ExtensionApi;
165658typedef struct Fts5Context Fts5Context;
165659typedef struct Fts5PhraseIter Fts5PhraseIter;
165660
165661typedef void (*fts5_extension_function)(
165662  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
165663  Fts5Context *pFts,              /* First arg to pass to pApi functions */
165664  sqlite3_context *pCtx,          /* Context for returning result/error */
165665  int nVal,                       /* Number of values in apVal[] array */
165666  sqlite3_value **apVal           /* Array of trailing arguments */
165667);
165668
165669struct Fts5PhraseIter {
165670  const unsigned char *a;
165671  const unsigned char *b;
165672};
165673
165674/*
165675** EXTENSION API FUNCTIONS
165676**
165677** xUserData(pFts):
165678**   Return a copy of the context pointer the extension function was
165679**   registered with.
165680**
165681** xColumnTotalSize(pFts, iCol, pnToken):
165682**   If parameter iCol is less than zero, set output variable *pnToken
165683**   to the total number of tokens in the FTS5 table. Or, if iCol is
165684**   non-negative but less than the number of columns in the table, return
165685**   the total number of tokens in column iCol, considering all rows in
165686**   the FTS5 table.
165687**
165688**   If parameter iCol is greater than or equal to the number of columns
165689**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
165690**   an OOM condition or IO error), an appropriate SQLite error code is
165691**   returned.
165692**
165693** xColumnCount(pFts):
165694**   Return the number of columns in the table.
165695**
165696** xColumnSize(pFts, iCol, pnToken):
165697**   If parameter iCol is less than zero, set output variable *pnToken
165698**   to the total number of tokens in the current row. Or, if iCol is
165699**   non-negative but less than the number of columns in the table, set
165700**   *pnToken to the number of tokens in column iCol of the current row.
165701**
165702**   If parameter iCol is greater than or equal to the number of columns
165703**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
165704**   an OOM condition or IO error), an appropriate SQLite error code is
165705**   returned.
165706**
165707** xColumnText:
165708**   This function attempts to retrieve the text of column iCol of the
165709**   current document. If successful, (*pz) is set to point to a buffer
165710**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
165711**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
165712**   if an error occurs, an SQLite error code is returned and the final values
165713**   of (*pz) and (*pn) are undefined.
165714**
165715** xPhraseCount:
165716**   Returns the number of phrases in the current query expression.
165717**
165718** xPhraseSize:
165719**   Returns the number of tokens in phrase iPhrase of the query. Phrases
165720**   are numbered starting from zero.
165721**
165722** xInstCount:
165723**   Set *pnInst to the total number of occurrences of all phrases within
165724**   the query within the current row. Return SQLITE_OK if successful, or
165725**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
165726**
165727** xInst:
165728**   Query for the details of phrase match iIdx within the current row.
165729**   Phrase matches are numbered starting from zero, so the iIdx argument
165730**   should be greater than or equal to zero and smaller than the value
165731**   output by xInstCount().
165732**
165733**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
165734**   if an error occurs.
165735**
165736** xRowid:
165737**   Returns the rowid of the current row.
165738**
165739** xTokenize:
165740**   Tokenize text using the tokenizer belonging to the FTS5 table.
165741**
165742** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
165743**   This API function is used to query the FTS table for phrase iPhrase
165744**   of the current query. Specifically, a query equivalent to:
165745**
165746**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
165747**
165748**   with $p set to a phrase equivalent to the phrase iPhrase of the
165749**   current query is executed. For each row visited, the callback function
165750**   passed as the fourth argument is invoked. The context and API objects
165751**   passed to the callback function may be used to access the properties of
165752**   each matched row. Invoking Api.xUserData() returns a copy of the pointer
165753**   passed as the third argument to pUserData.
165754**
165755**   If the callback function returns any value other than SQLITE_OK, the
165756**   query is abandoned and the xQueryPhrase function returns immediately.
165757**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
165758**   Otherwise, the error code is propagated upwards.
165759**
165760**   If the query runs to completion without incident, SQLITE_OK is returned.
165761**   Or, if some error occurs before the query completes or is aborted by
165762**   the callback, an SQLite error code is returned.
165763**
165764**
165765** xSetAuxdata(pFts5, pAux, xDelete)
165766**
165767**   Save the pointer passed as the second argument as the extension functions
165768**   "auxiliary data". The pointer may then be retrieved by the current or any
165769**   future invocation of the same fts5 extension function made as part of
165770**   of the same MATCH query using the xGetAuxdata() API.
165771**
165772**   Each extension function is allocated a single auxiliary data slot for
165773**   each FTS query (MATCH expression). If the extension function is invoked
165774**   more than once for a single FTS query, then all invocations share a
165775**   single auxiliary data context.
165776**
165777**   If there is already an auxiliary data pointer when this function is
165778**   invoked, then it is replaced by the new pointer. If an xDelete callback
165779**   was specified along with the original pointer, it is invoked at this
165780**   point.
165781**
165782**   The xDelete callback, if one is specified, is also invoked on the
165783**   auxiliary data pointer after the FTS5 query has finished.
165784**
165785**   If an error (e.g. an OOM condition) occurs within this function, an
165786**   the auxiliary data is set to NULL and an error code returned. If the
165787**   xDelete parameter was not NULL, it is invoked on the auxiliary data
165788**   pointer before returning.
165789**
165790**
165791** xGetAuxdata(pFts5, bClear)
165792**
165793**   Returns the current auxiliary data pointer for the fts5 extension
165794**   function. See the xSetAuxdata() method for details.
165795**
165796**   If the bClear argument is non-zero, then the auxiliary data is cleared
165797**   (set to NULL) before this function returns. In this case the xDelete,
165798**   if any, is not invoked.
165799**
165800**
165801** xRowCount(pFts5, pnRow)
165802**
165803**   This function is used to retrieve the total number of rows in the table.
165804**   In other words, the same value that would be returned by:
165805**
165806**        SELECT count(*) FROM ftstable;
165807**
165808** xPhraseFirst()
165809**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
165810**   method, to iterate through all instances of a single query phrase within
165811**   the current row. This is the same information as is accessible via the
165812**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
165813**   to use, this API may be faster under some circumstances. To iterate
165814**   through instances of phrase iPhrase, use the following code:
165815**
165816**       Fts5PhraseIter iter;
165817**       int iCol, iOff;
165818**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
165819**           iOff>=0;
165820**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
165821**       ){
165822**         // An instance of phrase iPhrase at offset iOff of column iCol
165823**       }
165824**
165825**   The Fts5PhraseIter structure is defined above. Applications should not
165826**   modify this structure directly - it should only be used as shown above
165827**   with the xPhraseFirst() and xPhraseNext() API methods.
165828**
165829** xPhraseNext()
165830**   See xPhraseFirst above.
165831*/
165832struct Fts5ExtensionApi {
165833  int iVersion;                   /* Currently always set to 1 */
165834
165835  void *(*xUserData)(Fts5Context*);
165836
165837  int (*xColumnCount)(Fts5Context*);
165838  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
165839  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
165840
165841  int (*xTokenize)(Fts5Context*,
165842    const char *pText, int nText, /* Text to tokenize */
165843    void *pCtx,                   /* Context passed to xToken() */
165844    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
165845  );
165846
165847  int (*xPhraseCount)(Fts5Context*);
165848  int (*xPhraseSize)(Fts5Context*, int iPhrase);
165849
165850  int (*xInstCount)(Fts5Context*, int *pnInst);
165851  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
165852
165853  sqlite3_int64 (*xRowid)(Fts5Context*);
165854  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
165855  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
165856
165857  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
165858    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
165859  );
165860  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
165861  void *(*xGetAuxdata)(Fts5Context*, int bClear);
165862
165863  void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
165864  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
165865};
165866
165867/*
165868** CUSTOM AUXILIARY FUNCTIONS
165869*************************************************************************/
165870
165871/*************************************************************************
165872** CUSTOM TOKENIZERS
165873**
165874** Applications may also register custom tokenizer types. A tokenizer
165875** is registered by providing fts5 with a populated instance of the
165876** following structure. All structure methods must be defined, setting
165877** any member of the fts5_tokenizer struct to NULL leads to undefined
165878** behaviour. The structure methods are expected to function as follows:
165879**
165880** xCreate:
165881**   This function is used to allocate and inititalize a tokenizer instance.
165882**   A tokenizer instance is required to actually tokenize text.
165883**
165884**   The first argument passed to this function is a copy of the (void*)
165885**   pointer provided by the application when the fts5_tokenizer object
165886**   was registered with FTS5 (the third argument to xCreateTokenizer()).
165887**   The second and third arguments are an array of nul-terminated strings
165888**   containing the tokenizer arguments, if any, specified following the
165889**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
165890**   to create the FTS5 table.
165891**
165892**   The final argument is an output variable. If successful, (*ppOut)
165893**   should be set to point to the new tokenizer handle and SQLITE_OK
165894**   returned. If an error occurs, some value other than SQLITE_OK should
165895**   be returned. In this case, fts5 assumes that the final value of *ppOut
165896**   is undefined.
165897**
165898** xDelete:
165899**   This function is invoked to delete a tokenizer handle previously
165900**   allocated using xCreate(). Fts5 guarantees that this function will
165901**   be invoked exactly once for each successful call to xCreate().
165902**
165903** xTokenize:
165904**   This function is expected to tokenize the nText byte string indicated
165905**   by argument pText. pText may or may not be nul-terminated. The first
165906**   argument passed to this function is a pointer to an Fts5Tokenizer object
165907**   returned by an earlier call to xCreate().
165908**
165909**   The second argument indicates the reason that FTS5 is requesting
165910**   tokenization of the supplied text. This is always one of the following
165911**   four values:
165912**
165913**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
165914**            or removed from the FTS table. The tokenizer is being invoked to
165915**            determine the set of tokens to add to (or delete from) the
165916**            FTS index.
165917**
165918**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
165919**            against the FTS index. The tokenizer is being called to tokenize
165920**            a bareword or quoted string specified as part of the query.
165921**
165922**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
165923**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
165924**            followed by a "*" character, indicating that the last token
165925**            returned by the tokenizer will be treated as a token prefix.
165926**
165927**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
165928**            satisfy an fts5_api.xTokenize() request made by an auxiliary
165929**            function. Or an fts5_api.xColumnSize() request made by the same
165930**            on a columnsize=0 database.
165931**   </ul>
165932**
165933**   For each token in the input string, the supplied callback xToken() must
165934**   be invoked. The first argument to it should be a copy of the pointer
165935**   passed as the second argument to xTokenize(). The third and fourth
165936**   arguments are a pointer to a buffer containing the token text, and the
165937**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
165938**   of the first byte of and first byte immediately following the text from
165939**   which the token is derived within the input.
165940**
165941**   The second argument passed to the xToken() callback ("tflags") should
165942**   normally be set to 0. The exception is if the tokenizer supports
165943**   synonyms. In this case see the discussion below for details.
165944**
165945**   FTS5 assumes the xToken() callback is invoked for each token in the
165946**   order that they occur within the input text.
165947**
165948**   If an xToken() callback returns any value other than SQLITE_OK, then
165949**   the tokenization should be abandoned and the xTokenize() method should
165950**   immediately return a copy of the xToken() return value. Or, if the
165951**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
165952**   if an error occurs with the xTokenize() implementation itself, it
165953**   may abandon the tokenization and return any error code other than
165954**   SQLITE_OK or SQLITE_DONE.
165955**
165956** SYNONYM SUPPORT
165957**
165958**   Custom tokenizers may also support synonyms. Consider a case in which a
165959**   user wishes to query for a phrase such as "first place". Using the
165960**   built-in tokenizers, the FTS5 query 'first + place' will match instances
165961**   of "first place" within the document set, but not alternative forms
165962**   such as "1st place". In some applications, it would be better to match
165963**   all instances of "first place" or "1st place" regardless of which form
165964**   the user specified in the MATCH query text.
165965**
165966**   There are several ways to approach this in FTS5:
165967**
165968**   <ol><li> By mapping all synonyms to a single token. In this case, the
165969**            In the above example, this means that the tokenizer returns the
165970**            same token for inputs "first" and "1st". Say that token is in
165971**            fact "first", so that when the user inserts the document "I won
165972**            1st place" entries are added to the index for tokens "i", "won",
165973**            "first" and "place". If the user then queries for '1st + place',
165974**            the tokenizer substitutes "first" for "1st" and the query works
165975**            as expected.
165976**
165977**       <li> By adding multiple synonyms for a single term to the FTS index.
165978**            In this case, when tokenizing query text, the tokenizer may
165979**            provide multiple synonyms for a single term within the document.
165980**            FTS5 then queries the index for each synonym individually. For
165981**            example, faced with the query:
165982**
165983**   <codeblock>
165984**     ... MATCH 'first place'</codeblock>
165985**
165986**            the tokenizer offers both "1st" and "first" as synonyms for the
165987**            first token in the MATCH query and FTS5 effectively runs a query
165988**            similar to:
165989**
165990**   <codeblock>
165991**     ... MATCH '(first OR 1st) place'</codeblock>
165992**
165993**            except that, for the purposes of auxiliary functions, the query
165994**            still appears to contain just two phrases - "(first OR 1st)"
165995**            being treated as a single phrase.
165996**
165997**       <li> By adding multiple synonyms for a single term to the FTS index.
165998**            Using this method, when tokenizing document text, the tokenizer
165999**            provides multiple synonyms for each token. So that when a
166000**            document such as "I won first place" is tokenized, entries are
166001**            added to the FTS index for "i", "won", "first", "1st" and
166002**            "place".
166003**
166004**            This way, even if the tokenizer does not provide synonyms
166005**            when tokenizing query text (it should not - to do would be
166006**            inefficient), it doesn't matter if the user queries for
166007**            'first + place' or '1st + place', as there are entires in the
166008**            FTS index corresponding to both forms of the first token.
166009**   </ol>
166010**
166011**   Whether it is parsing document or query text, any call to xToken that
166012**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
166013**   is considered to supply a synonym for the previous token. For example,
166014**   when parsing the document "I won first place", a tokenizer that supports
166015**   synonyms would call xToken() 5 times, as follows:
166016**
166017**   <codeblock>
166018**       xToken(pCtx, 0, "i",                      1,  0,  1);
166019**       xToken(pCtx, 0, "won",                    3,  2,  5);
166020**       xToken(pCtx, 0, "first",                  5,  6, 11);
166021**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
166022**       xToken(pCtx, 0, "place",                  5, 12, 17);
166023**</codeblock>
166024**
166025**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
166026**   xToken() is called. Multiple synonyms may be specified for a single token
166027**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
166028**   There is no limit to the number of synonyms that may be provided for a
166029**   single token.
166030**
166031**   In many cases, method (1) above is the best approach. It does not add
166032**   extra data to the FTS index or require FTS5 to query for multiple terms,
166033**   so it is efficient in terms of disk space and query speed. However, it
166034**   does not support prefix queries very well. If, as suggested above, the
166035**   token "first" is subsituted for "1st" by the tokenizer, then the query:
166036**
166037**   <codeblock>
166038**     ... MATCH '1s*'</codeblock>
166039**
166040**   will not match documents that contain the token "1st" (as the tokenizer
166041**   will probably not map "1s" to any prefix of "first").
166042**
166043**   For full prefix support, method (3) may be preferred. In this case,
166044**   because the index contains entries for both "first" and "1st", prefix
166045**   queries such as 'fi*' or '1s*' will match correctly. However, because
166046**   extra entries are added to the FTS index, this method uses more space
166047**   within the database.
166048**
166049**   Method (2) offers a midpoint between (1) and (3). Using this method,
166050**   a query such as '1s*' will match documents that contain the literal
166051**   token "1st", but not "first" (assuming the tokenizer is not able to
166052**   provide synonyms for prefixes). However, a non-prefix query like '1st'
166053**   will match against "1st" and "first". This method does not require
166054**   extra disk space, as no extra entries are added to the FTS index.
166055**   On the other hand, it may require more CPU cycles to run MATCH queries,
166056**   as separate queries of the FTS index are required for each synonym.
166057**
166058**   When using methods (2) or (3), it is important that the tokenizer only
166059**   provide synonyms when tokenizing document text (method (2)) or query
166060**   text (method (3)), not both. Doing so will not cause any errors, but is
166061**   inefficient.
166062*/
166063typedef struct Fts5Tokenizer Fts5Tokenizer;
166064typedef struct fts5_tokenizer fts5_tokenizer;
166065struct fts5_tokenizer {
166066  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
166067  void (*xDelete)(Fts5Tokenizer*);
166068  int (*xTokenize)(Fts5Tokenizer*,
166069      void *pCtx,
166070      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
166071      const char *pText, int nText,
166072      int (*xToken)(
166073        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
166074        int tflags,         /* Mask of FTS5_TOKEN_* flags */
166075        const char *pToken, /* Pointer to buffer containing token */
166076        int nToken,         /* Size of token in bytes */
166077        int iStart,         /* Byte offset of token within input text */
166078        int iEnd            /* Byte offset of end of token within input text */
166079      )
166080  );
166081};
166082
166083/* Flags that may be passed as the third argument to xTokenize() */
166084#define FTS5_TOKENIZE_QUERY     0x0001
166085#define FTS5_TOKENIZE_PREFIX    0x0002
166086#define FTS5_TOKENIZE_DOCUMENT  0x0004
166087#define FTS5_TOKENIZE_AUX       0x0008
166088
166089/* Flags that may be passed by the tokenizer implementation back to FTS5
166090** as the third argument to the supplied xToken callback. */
166091#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
166092
166093/*
166094** END OF CUSTOM TOKENIZERS
166095*************************************************************************/
166096
166097/*************************************************************************
166098** FTS5 EXTENSION REGISTRATION API
166099*/
166100typedef struct fts5_api fts5_api;
166101struct fts5_api {
166102  int iVersion;                   /* Currently always set to 2 */
166103
166104  /* Create a new tokenizer */
166105  int (*xCreateTokenizer)(
166106    fts5_api *pApi,
166107    const char *zName,
166108    void *pContext,
166109    fts5_tokenizer *pTokenizer,
166110    void (*xDestroy)(void*)
166111  );
166112
166113  /* Find an existing tokenizer */
166114  int (*xFindTokenizer)(
166115    fts5_api *pApi,
166116    const char *zName,
166117    void **ppContext,
166118    fts5_tokenizer *pTokenizer
166119  );
166120
166121  /* Create a new auxiliary function */
166122  int (*xCreateFunction)(
166123    fts5_api *pApi,
166124    const char *zName,
166125    void *pContext,
166126    fts5_extension_function xFunction,
166127    void (*xDestroy)(void*)
166128  );
166129};
166130
166131/*
166132** END OF REGISTRATION API
166133*************************************************************************/
166134
166135#if 0
166136}  /* end of the 'extern "C"' block */
166137#endif
166138
166139#endif /* _FTS5_H */
166140
166141
166142/*
166143** 2014 May 31
166144**
166145** The author disclaims copyright to this source code.  In place of
166146** a legal notice, here is a blessing:
166147**
166148**    May you do good and not evil.
166149**    May you find forgiveness for yourself and forgive others.
166150**    May you share freely, never taking more than you give.
166151**
166152******************************************************************************
166153**
166154*/
166155#ifndef _FTS5INT_H
166156#define _FTS5INT_H
166157
166158/* #include "sqlite3ext.h" */
166159SQLITE_EXTENSION_INIT1
166160
166161/* #include <string.h> */
166162/* #include <assert.h> */
166163
166164#ifndef SQLITE_AMALGAMATION
166165
166166typedef unsigned char  u8;
166167typedef unsigned int   u32;
166168typedef unsigned short u16;
166169typedef sqlite3_int64 i64;
166170typedef sqlite3_uint64 u64;
166171
166172#define ArraySize(x) (sizeof(x) / sizeof(x[0]))
166173
166174#define testcase(x)
166175#define ALWAYS(x) 1
166176#define NEVER(x) 0
166177
166178#define MIN(x,y) (((x) < (y)) ? (x) : (y))
166179#define MAX(x,y) (((x) > (y)) ? (x) : (y))
166180
166181/*
166182** Constants for the largest and smallest possible 64-bit signed integers.
166183*/
166184# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
166185# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
166186
166187#endif
166188
166189
166190/*
166191** Maximum number of prefix indexes on single FTS5 table. This must be
166192** less than 32. If it is set to anything large than that, an #error
166193** directive in fts5_index.c will cause the build to fail.
166194*/
166195#define FTS5_MAX_PREFIX_INDEXES 31
166196
166197#define FTS5_DEFAULT_NEARDIST 10
166198#define FTS5_DEFAULT_RANK     "bm25"
166199
166200/* Name of rank and rowid columns */
166201#define FTS5_RANK_NAME "rank"
166202#define FTS5_ROWID_NAME "rowid"
166203
166204#ifdef SQLITE_DEBUG
166205# define FTS5_CORRUPT sqlite3Fts5Corrupt()
166206static int sqlite3Fts5Corrupt(void);
166207#else
166208# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
166209#endif
166210
166211/*
166212** The assert_nc() macro is similar to the assert() macro, except that it
166213** is used for assert() conditions that are true only if it can be
166214** guranteed that the database is not corrupt.
166215*/
166216#ifdef SQLITE_DEBUG
166217SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
166218# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
166219#else
166220# define assert_nc(x) assert(x)
166221#endif
166222
166223typedef struct Fts5Global Fts5Global;
166224typedef struct Fts5Colset Fts5Colset;
166225
166226/* If a NEAR() clump or phrase may only match a specific set of columns,
166227** then an object of the following type is used to record the set of columns.
166228** Each entry in the aiCol[] array is a column that may be matched.
166229**
166230** This object is used by fts5_expr.c and fts5_index.c.
166231*/
166232struct Fts5Colset {
166233  int nCol;
166234  int aiCol[1];
166235};
166236
166237
166238
166239/**************************************************************************
166240** Interface to code in fts5_config.c. fts5_config.c contains contains code
166241** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
166242*/
166243
166244typedef struct Fts5Config Fts5Config;
166245
166246/*
166247** An instance of the following structure encodes all information that can
166248** be gleaned from the CREATE VIRTUAL TABLE statement.
166249**
166250** And all information loaded from the %_config table.
166251**
166252** nAutomerge:
166253**   The minimum number of segments that an auto-merge operation should
166254**   attempt to merge together. A value of 1 sets the object to use the
166255**   compile time default. Zero disables auto-merge altogether.
166256**
166257** zContent:
166258**
166259** zContentRowid:
166260**   The value of the content_rowid= option, if one was specified. Or
166261**   the string "rowid" otherwise. This text is not quoted - if it is
166262**   used as part of an SQL statement it needs to be quoted appropriately.
166263**
166264** zContentExprlist:
166265**
166266** pzErrmsg:
166267**   This exists in order to allow the fts5_index.c module to return a
166268**   decent error message if it encounters a file-format version it does
166269**   not understand.
166270**
166271** bColumnsize:
166272**   True if the %_docsize table is created.
166273**
166274** bPrefixIndex:
166275**   This is only used for debugging. If set to false, any prefix indexes
166276**   are ignored. This value is configured using:
166277**
166278**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
166279**
166280*/
166281struct Fts5Config {
166282  sqlite3 *db;                    /* Database handle */
166283  char *zDb;                      /* Database holding FTS index (e.g. "main") */
166284  char *zName;                    /* Name of FTS index */
166285  int nCol;                       /* Number of columns */
166286  char **azCol;                   /* Column names */
166287  u8 *abUnindexed;                /* True for unindexed columns */
166288  int nPrefix;                    /* Number of prefix indexes */
166289  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
166290  int eContent;                   /* An FTS5_CONTENT value */
166291  char *zContent;                 /* content table */
166292  char *zContentRowid;            /* "content_rowid=" option value */
166293  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
166294  char *zContentExprlist;
166295  Fts5Tokenizer *pTok;
166296  fts5_tokenizer *pTokApi;
166297
166298  /* Values loaded from the %_config table */
166299  int iCookie;                    /* Incremented when %_config is modified */
166300  int pgsz;                       /* Approximate page size used in %_data */
166301  int nAutomerge;                 /* 'automerge' setting */
166302  int nCrisisMerge;               /* Maximum allowed segments per level */
166303  char *zRank;                    /* Name of rank function */
166304  char *zRankArgs;                /* Arguments to rank function */
166305
166306  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
166307  char **pzErrmsg;
166308
166309#ifdef SQLITE_DEBUG
166310  int bPrefixIndex;               /* True to use prefix-indexes */
166311#endif
166312};
166313
166314/* Current expected value of %_config table 'version' field */
166315#define FTS5_CURRENT_VERSION 4
166316
166317#define FTS5_CONTENT_NORMAL   0
166318#define FTS5_CONTENT_NONE     1
166319#define FTS5_CONTENT_EXTERNAL 2
166320
166321
166322
166323
166324static int sqlite3Fts5ConfigParse(
166325    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
166326);
166327static void sqlite3Fts5ConfigFree(Fts5Config*);
166328
166329static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
166330
166331static int sqlite3Fts5Tokenize(
166332  Fts5Config *pConfig,            /* FTS5 Configuration object */
166333  int flags,                      /* FTS5_TOKENIZE_* flags */
166334  const char *pText, int nText,   /* Text to tokenize */
166335  void *pCtx,                     /* Context passed to xToken() */
166336  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
166337);
166338
166339static void sqlite3Fts5Dequote(char *z);
166340
166341/* Load the contents of the %_config table */
166342static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
166343
166344/* Set the value of a single config attribute */
166345static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
166346
166347static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
166348
166349/*
166350** End of interface to code in fts5_config.c.
166351**************************************************************************/
166352
166353/**************************************************************************
166354** Interface to code in fts5_buffer.c.
166355*/
166356
166357/*
166358** Buffer object for the incremental building of string data.
166359*/
166360typedef struct Fts5Buffer Fts5Buffer;
166361struct Fts5Buffer {
166362  u8 *p;
166363  int n;
166364  int nSpace;
166365};
166366
166367static int sqlite3Fts5BufferGrow(int*, Fts5Buffer*, int);
166368static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
166369static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, int, const u8*);
166370static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
166371static void sqlite3Fts5BufferFree(Fts5Buffer*);
166372static void sqlite3Fts5BufferZero(Fts5Buffer*);
166373static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
166374static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
166375static void sqlite3Fts5BufferAppend32(int*, Fts5Buffer*, int);
166376
166377static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
166378
166379#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
166380#define fts5BufferGrow(a,b,c)         sqlite3Fts5BufferGrow(a,b,c)
166381#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
166382#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
166383#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
166384#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
166385#define fts5BufferAppend32(a,b,c)     sqlite3Fts5BufferAppend32(a,b,c)
166386
166387/* Write and decode big-endian 32-bit integer values */
166388static void sqlite3Fts5Put32(u8*, int);
166389static int sqlite3Fts5Get32(const u8*);
166390
166391#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
166392#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
166393
166394typedef struct Fts5PoslistReader Fts5PoslistReader;
166395struct Fts5PoslistReader {
166396  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
166397  const u8 *a;                    /* Position list to iterate through */
166398  int n;                          /* Size of buffer at a[] in bytes */
166399  int i;                          /* Current offset in a[] */
166400
166401  u8 bFlag;                       /* For client use (any custom purpose) */
166402
166403  /* Output variables */
166404  u8 bEof;                        /* Set to true at EOF */
166405  i64 iPos;                       /* (iCol<<32) + iPos */
166406};
166407static int sqlite3Fts5PoslistReaderInit(
166408  const u8 *a, int n,             /* Poslist buffer to iterate through */
166409  Fts5PoslistReader *pIter        /* Iterator object to initialize */
166410);
166411static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
166412
166413typedef struct Fts5PoslistWriter Fts5PoslistWriter;
166414struct Fts5PoslistWriter {
166415  i64 iPrev;
166416};
166417static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
166418
166419static int sqlite3Fts5PoslistNext64(
166420  const u8 *a, int n,             /* Buffer containing poslist */
166421  int *pi,                        /* IN/OUT: Offset within a[] */
166422  i64 *piOff                      /* IN/OUT: Current offset */
166423);
166424
166425/* Malloc utility */
166426static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
166427static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
166428
166429/* Character set tests (like isspace(), isalpha() etc.) */
166430static int sqlite3Fts5IsBareword(char t);
166431
166432/*
166433** End of interface to code in fts5_buffer.c.
166434**************************************************************************/
166435
166436/**************************************************************************
166437** Interface to code in fts5_index.c. fts5_index.c contains contains code
166438** to access the data stored in the %_data table.
166439*/
166440
166441typedef struct Fts5Index Fts5Index;
166442typedef struct Fts5IndexIter Fts5IndexIter;
166443
166444/*
166445** Values used as part of the flags argument passed to IndexQuery().
166446*/
166447#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
166448#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
166449#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
166450#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
166451
166452/*
166453** Create/destroy an Fts5Index object.
166454*/
166455static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
166456static int sqlite3Fts5IndexClose(Fts5Index *p);
166457
166458/*
166459** for(
166460**   sqlite3Fts5IndexQuery(p, "token", 5, 0, 0, &pIter);
166461**   0==sqlite3Fts5IterEof(pIter);
166462**   sqlite3Fts5IterNext(pIter)
166463** ){
166464**   i64 iRowid = sqlite3Fts5IterRowid(pIter);
166465** }
166466*/
166467
166468/*
166469** Open a new iterator to iterate though all rowids that match the
166470** specified token or token prefix.
166471*/
166472static int sqlite3Fts5IndexQuery(
166473  Fts5Index *p,                   /* FTS index to query */
166474  const char *pToken, int nToken, /* Token (or prefix) to query for */
166475  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
166476  Fts5Colset *pColset,            /* Match these columns only */
166477  Fts5IndexIter **ppIter          /* OUT: New iterator object */
166478);
166479
166480/*
166481** The various operations on open token or token prefix iterators opened
166482** using sqlite3Fts5IndexQuery().
166483*/
166484static int sqlite3Fts5IterEof(Fts5IndexIter*);
166485static int sqlite3Fts5IterNext(Fts5IndexIter*);
166486static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
166487static i64 sqlite3Fts5IterRowid(Fts5IndexIter*);
166488static int sqlite3Fts5IterPoslist(Fts5IndexIter*,Fts5Colset*, const u8**, int*, i64*);
166489static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf);
166490
166491/*
166492** Close an iterator opened by sqlite3Fts5IndexQuery().
166493*/
166494static void sqlite3Fts5IterClose(Fts5IndexIter*);
166495
166496/*
166497** This interface is used by the fts5vocab module.
166498*/
166499static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
166500static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
166501
166502
166503/*
166504** Insert or remove data to or from the index. Each time a document is
166505** added to or removed from the index, this function is called one or more
166506** times.
166507**
166508** For an insert, it must be called once for each token in the new document.
166509** If the operation is a delete, it must be called (at least) once for each
166510** unique token in the document with an iCol value less than zero. The iPos
166511** argument is ignored for a delete.
166512*/
166513static int sqlite3Fts5IndexWrite(
166514  Fts5Index *p,                   /* Index to write to */
166515  int iCol,                       /* Column token appears in (-ve -> delete) */
166516  int iPos,                       /* Position of token within column */
166517  const char *pToken, int nToken  /* Token to add or remove to or from index */
166518);
166519
166520/*
166521** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
166522** document iDocid.
166523*/
166524static int sqlite3Fts5IndexBeginWrite(
166525  Fts5Index *p,                   /* Index to write to */
166526  int bDelete,                    /* True if current operation is a delete */
166527  i64 iDocid                      /* Docid to add or remove data from */
166528);
166529
166530/*
166531** Flush any data stored in the in-memory hash tables to the database.
166532** If the bCommit flag is true, also close any open blob handles.
166533*/
166534static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
166535
166536/*
166537** Discard any data stored in the in-memory hash tables. Do not write it
166538** to the database. Additionally, assume that the contents of the %_data
166539** table may have changed on disk. So any in-memory caches of %_data
166540** records must be invalidated.
166541*/
166542static int sqlite3Fts5IndexRollback(Fts5Index *p);
166543
166544/*
166545** Get or set the "averages" values.
166546*/
166547static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
166548static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
166549
166550/*
166551** Functions called by the storage module as part of integrity-check.
166552*/
166553static u64 sqlite3Fts5IndexCksum(Fts5Config*,i64,int,int,const char*,int);
166554static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
166555
166556/*
166557** Called during virtual module initialization to register UDF
166558** fts5_decode() with SQLite
166559*/
166560static int sqlite3Fts5IndexInit(sqlite3*);
166561
166562static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
166563
166564/*
166565** Return the total number of entries read from the %_data table by
166566** this connection since it was created.
166567*/
166568static int sqlite3Fts5IndexReads(Fts5Index *p);
166569
166570static int sqlite3Fts5IndexReinit(Fts5Index *p);
166571static int sqlite3Fts5IndexOptimize(Fts5Index *p);
166572static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
166573
166574static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
166575
166576/*
166577** End of interface to code in fts5_index.c.
166578**************************************************************************/
166579
166580/**************************************************************************
166581** Interface to code in fts5_varint.c.
166582*/
166583static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
166584static int sqlite3Fts5GetVarintLen(u32 iVal);
166585static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
166586static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
166587
166588#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
166589#define fts5GetVarint    sqlite3Fts5GetVarint
166590
166591#define fts5FastGetVarint32(a, iOff, nVal) {      \
166592  nVal = (a)[iOff++];                             \
166593  if( nVal & 0x80 ){                              \
166594    iOff--;                                       \
166595    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
166596  }                                               \
166597}
166598
166599
166600/*
166601** End of interface to code in fts5_varint.c.
166602**************************************************************************/
166603
166604
166605/**************************************************************************
166606** Interface to code in fts5.c.
166607*/
166608
166609static int sqlite3Fts5GetTokenizer(
166610  Fts5Global*,
166611  const char **azArg,
166612  int nArg,
166613  Fts5Tokenizer**,
166614  fts5_tokenizer**,
166615  char **pzErr
166616);
166617
166618static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, int*);
166619
166620/*
166621** End of interface to code in fts5.c.
166622**************************************************************************/
166623
166624/**************************************************************************
166625** Interface to code in fts5_hash.c.
166626*/
166627typedef struct Fts5Hash Fts5Hash;
166628
166629/*
166630** Create a hash table, free a hash table.
166631*/
166632static int sqlite3Fts5HashNew(Fts5Hash**, int *pnSize);
166633static void sqlite3Fts5HashFree(Fts5Hash*);
166634
166635static int sqlite3Fts5HashWrite(
166636  Fts5Hash*,
166637  i64 iRowid,                     /* Rowid for this entry */
166638  int iCol,                       /* Column token appears in (-ve -> delete) */
166639  int iPos,                       /* Position of token within column */
166640  char bByte,
166641  const char *pToken, int nToken  /* Token to add or remove to or from index */
166642);
166643
166644/*
166645** Empty (but do not delete) a hash table.
166646*/
166647static void sqlite3Fts5HashClear(Fts5Hash*);
166648
166649static int sqlite3Fts5HashQuery(
166650  Fts5Hash*,                      /* Hash table to query */
166651  const char *pTerm, int nTerm,   /* Query term */
166652  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
166653  int *pnDoclist                  /* OUT: Size of doclist in bytes */
166654);
166655
166656static int sqlite3Fts5HashScanInit(
166657  Fts5Hash*,                      /* Hash table to query */
166658  const char *pTerm, int nTerm    /* Query prefix */
166659);
166660static void sqlite3Fts5HashScanNext(Fts5Hash*);
166661static int sqlite3Fts5HashScanEof(Fts5Hash*);
166662static void sqlite3Fts5HashScanEntry(Fts5Hash *,
166663  const char **pzTerm,            /* OUT: term (nul-terminated) */
166664  const u8 **ppDoclist,           /* OUT: pointer to doclist */
166665  int *pnDoclist                  /* OUT: size of doclist in bytes */
166666);
166667
166668
166669/*
166670** End of interface to code in fts5_hash.c.
166671**************************************************************************/
166672
166673/**************************************************************************
166674** Interface to code in fts5_storage.c. fts5_storage.c contains contains
166675** code to access the data stored in the %_content and %_docsize tables.
166676*/
166677
166678#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
166679#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
166680#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
166681
166682typedef struct Fts5Storage Fts5Storage;
166683
166684static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
166685static int sqlite3Fts5StorageClose(Fts5Storage *p);
166686static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
166687
166688static int sqlite3Fts5DropAll(Fts5Config*);
166689static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
166690
166691static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64);
166692static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
166693static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
166694
166695static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
166696
166697static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
166698static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
166699
166700static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
166701static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
166702static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
166703
166704static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
166705static int sqlite3Fts5StorageRollback(Fts5Storage *p);
166706
166707static int sqlite3Fts5StorageConfigValue(
166708    Fts5Storage *p, const char*, sqlite3_value*, int
166709);
166710
166711static int sqlite3Fts5StorageSpecialDelete(Fts5Storage *p, i64 iDel, sqlite3_value**);
166712
166713static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
166714static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
166715static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
166716static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
166717
166718/*
166719** End of interface to code in fts5_storage.c.
166720**************************************************************************/
166721
166722
166723/**************************************************************************
166724** Interface to code in fts5_expr.c.
166725*/
166726typedef struct Fts5Expr Fts5Expr;
166727typedef struct Fts5ExprNode Fts5ExprNode;
166728typedef struct Fts5Parse Fts5Parse;
166729typedef struct Fts5Token Fts5Token;
166730typedef struct Fts5ExprPhrase Fts5ExprPhrase;
166731typedef struct Fts5ExprNearset Fts5ExprNearset;
166732
166733struct Fts5Token {
166734  const char *p;                  /* Token text (not NULL terminated) */
166735  int n;                          /* Size of buffer p in bytes */
166736};
166737
166738/* Parse a MATCH expression. */
166739static int sqlite3Fts5ExprNew(
166740  Fts5Config *pConfig,
166741  const char *zExpr,
166742  Fts5Expr **ppNew,
166743  char **pzErr
166744);
166745
166746/*
166747** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
166748**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
166749**     rc = sqlite3Fts5ExprNext(pExpr)
166750** ){
166751**   // The document with rowid iRowid matches the expression!
166752**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
166753** }
166754*/
166755static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
166756static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
166757static int sqlite3Fts5ExprEof(Fts5Expr*);
166758static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
166759
166760static void sqlite3Fts5ExprFree(Fts5Expr*);
166761
166762/* Called during startup to register a UDF with SQLite */
166763static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
166764
166765static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
166766static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
166767static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
166768
166769static int sqlite3Fts5ExprClonePhrase(Fts5Config*, Fts5Expr*, int, Fts5Expr**);
166770
166771/*******************************************
166772** The fts5_expr.c API above this point is used by the other hand-written
166773** C code in this module. The interfaces below this point are called by
166774** the parser code in fts5parse.y.  */
166775
166776static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
166777
166778static Fts5ExprNode *sqlite3Fts5ParseNode(
166779  Fts5Parse *pParse,
166780  int eType,
166781  Fts5ExprNode *pLeft,
166782  Fts5ExprNode *pRight,
166783  Fts5ExprNearset *pNear
166784);
166785
166786static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
166787  Fts5Parse *pParse,
166788  Fts5ExprPhrase *pPhrase,
166789  Fts5Token *pToken,
166790  int bPrefix
166791);
166792
166793static Fts5ExprNearset *sqlite3Fts5ParseNearset(
166794  Fts5Parse*,
166795  Fts5ExprNearset*,
166796  Fts5ExprPhrase*
166797);
166798
166799static Fts5Colset *sqlite3Fts5ParseColset(
166800  Fts5Parse*,
166801  Fts5Colset*,
166802  Fts5Token *
166803);
166804
166805static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
166806static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
166807static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
166808
166809static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
166810static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
166811static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
166812static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
166813
166814/*
166815** End of interface to code in fts5_expr.c.
166816**************************************************************************/
166817
166818
166819
166820/**************************************************************************
166821** Interface to code in fts5_aux.c.
166822*/
166823
166824static int sqlite3Fts5AuxInit(fts5_api*);
166825/*
166826** End of interface to code in fts5_aux.c.
166827**************************************************************************/
166828
166829/**************************************************************************
166830** Interface to code in fts5_tokenizer.c.
166831*/
166832
166833static int sqlite3Fts5TokenizerInit(fts5_api*);
166834/*
166835** End of interface to code in fts5_tokenizer.c.
166836**************************************************************************/
166837
166838/**************************************************************************
166839** Interface to code in fts5_vocab.c.
166840*/
166841
166842static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
166843
166844/*
166845** End of interface to code in fts5_vocab.c.
166846**************************************************************************/
166847
166848
166849/**************************************************************************
166850** Interface to automatically generated code in fts5_unicode2.c.
166851*/
166852static int sqlite3Fts5UnicodeIsalnum(int c);
166853static int sqlite3Fts5UnicodeIsdiacritic(int c);
166854static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
166855/*
166856** End of interface to code in fts5_unicode2.c.
166857**************************************************************************/
166858
166859#endif
166860
166861#define FTS5_OR                               1
166862#define FTS5_AND                              2
166863#define FTS5_NOT                              3
166864#define FTS5_TERM                             4
166865#define FTS5_COLON                            5
166866#define FTS5_LP                               6
166867#define FTS5_RP                               7
166868#define FTS5_LCP                              8
166869#define FTS5_RCP                              9
166870#define FTS5_STRING                          10
166871#define FTS5_COMMA                           11
166872#define FTS5_PLUS                            12
166873#define FTS5_STAR                            13
166874
166875/* Driver template for the LEMON parser generator.
166876** The author disclaims copyright to this source code.
166877**
166878** This version of "lempar.c" is modified, slightly, for use by SQLite.
166879** The only modifications are the addition of a couple of NEVER()
166880** macros to disable tests that are needed in the case of a general
166881** LALR(1) grammar but which are always false in the
166882** specific grammar used by SQLite.
166883*/
166884/* First off, code is included that follows the "include" declaration
166885** in the input grammar file. */
166886/* #include <stdio.h> */
166887
166888
166889/*
166890** Disable all error recovery processing in the parser push-down
166891** automaton.
166892*/
166893#define fts5YYNOERRORRECOVERY 1
166894
166895/*
166896** Make fts5yytestcase() the same as testcase()
166897*/
166898#define fts5yytestcase(X) testcase(X)
166899
166900/* Next is all token values, in a form suitable for use by makeheaders.
166901** This section will be null unless lemon is run with the -m switch.
166902*/
166903/*
166904** These constants (all generated automatically by the parser generator)
166905** specify the various kinds of tokens (terminals) that the parser
166906** understands.
166907**
166908** Each symbol here is a terminal symbol in the grammar.
166909*/
166910/* Make sure the INTERFACE macro is defined.
166911*/
166912#ifndef INTERFACE
166913# define INTERFACE 1
166914#endif
166915/* The next thing included is series of defines which control
166916** various aspects of the generated parser.
166917**    fts5YYCODETYPE         is the data type used for storing terminal
166918**                       and nonterminal numbers.  "unsigned char" is
166919**                       used if there are fewer than 250 terminals
166920**                       and nonterminals.  "int" is used otherwise.
166921**    fts5YYNOCODE           is a number of type fts5YYCODETYPE which corresponds
166922**                       to no legal terminal or nonterminal number.  This
166923**                       number is used to fill in empty slots of the hash
166924**                       table.
166925**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
166926**                       have fall-back values which should be used if the
166927**                       original value of the token will not parse.
166928**    fts5YYACTIONTYPE       is the data type used for storing terminal
166929**                       and nonterminal numbers.  "unsigned char" is
166930**                       used if there are fewer than 250 rules and
166931**                       states combined.  "int" is used otherwise.
166932**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor tokens given
166933**                       directly to the parser from the tokenizer.
166934**    fts5YYMINORTYPE        is the data type used for all minor tokens.
166935**                       This is typically a union of many types, one of
166936**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
166937**                       for base tokens is called "fts5yy0".
166938**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
166939**                       zero the stack is dynamically sized using realloc()
166940**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
166941**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
166942**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
166943**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
166944**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
166945**                       defined, then do no error processing.
166946**    fts5YYNSTATE           the combined number of states.
166947**    fts5YYNRULE            the number of rules in the grammar
166948**    fts5YY_MAX_SHIFT       Maximum value for shift actions
166949**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
166950**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
166951**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
166952**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
166953**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
166954**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
166955*/
166956#define fts5YYCODETYPE unsigned char
166957#define fts5YYNOCODE 27
166958#define fts5YYACTIONTYPE unsigned char
166959#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
166960typedef union {
166961  int fts5yyinit;
166962  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
166963  Fts5Colset* fts5yy3;
166964  Fts5ExprPhrase* fts5yy11;
166965  Fts5ExprNode* fts5yy18;
166966  int fts5yy20;
166967  Fts5ExprNearset* fts5yy26;
166968} fts5YYMINORTYPE;
166969#ifndef fts5YYSTACKDEPTH
166970#define fts5YYSTACKDEPTH 100
166971#endif
166972#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
166973#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
166974#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
166975#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
166976#define fts5YYNSTATE             26
166977#define fts5YYNRULE              24
166978#define fts5YY_MAX_SHIFT         25
166979#define fts5YY_MIN_SHIFTREDUCE   40
166980#define fts5YY_MAX_SHIFTREDUCE   63
166981#define fts5YY_MIN_REDUCE        64
166982#define fts5YY_MAX_REDUCE        87
166983#define fts5YY_ERROR_ACTION      88
166984#define fts5YY_ACCEPT_ACTION     89
166985#define fts5YY_NO_ACTION         90
166986
166987/* The fts5yyzerominor constant is used to initialize instances of
166988** fts5YYMINORTYPE objects to zero. */
166989static const fts5YYMINORTYPE fts5yyzerominor = { 0 };
166990
166991/* Define the fts5yytestcase() macro to be a no-op if is not already defined
166992** otherwise.
166993**
166994** Applications can choose to define fts5yytestcase() in the %include section
166995** to a macro that can assist in verifying code coverage.  For production
166996** code the fts5yytestcase() macro should be turned off.  But it is useful
166997** for testing.
166998*/
166999#ifndef fts5yytestcase
167000# define fts5yytestcase(X)
167001#endif
167002
167003
167004/* Next are the tables used to determine what action to take based on the
167005** current state and lookahead token.  These tables are used to implement
167006** functions that take a state number and lookahead value and return an
167007** action integer.
167008**
167009** Suppose the action integer is N.  Then the action is determined as
167010** follows
167011**
167012**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
167013**                                      token onto the stack and goto state N.
167014**
167015**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
167016**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
167017**
167018**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
167019**     and fts5YY_MAX_REDUCE
167020
167021**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
167022**
167023**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
167024**
167025**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
167026**                                      slots in the fts5yy_action[] table.
167027**
167028** The action table is constructed as a single large table named fts5yy_action[].
167029** Given state S and lookahead X, the action is computed as
167030**
167031**      fts5yy_action[ fts5yy_shift_ofst[S] + X ]
167032**
167033** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
167034** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
167035** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
167036** and that fts5yy_default[S] should be used instead.
167037**
167038** The formula above is for computing the action when the lookahead is
167039** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
167040** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
167041** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
167042** fts5YY_SHIFT_USE_DFLT.
167043**
167044** The following are the tables generated in this section:
167045**
167046**  fts5yy_action[]        A single table containing all actions.
167047**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
167048**                     fts5yy_action.  Used to detect hash collisions.
167049**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
167050**                     shifting terminals.
167051**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
167052**                     shifting non-terminals after a reduce.
167053**  fts5yy_default[]       Default action for each state.
167054*/
167055#define fts5YY_ACTTAB_COUNT (78)
167056static const fts5YYACTIONTYPE fts5yy_action[] = {
167057 /*     0 */    89,   15,   46,    5,   48,   24,   12,   19,   23,   14,
167058 /*    10 */    46,    5,   48,   24,   20,   21,   23,   43,   46,    5,
167059 /*    20 */    48,   24,    6,   18,   23,   17,   46,    5,   48,   24,
167060 /*    30 */    75,    7,   23,   25,   46,    5,   48,   24,   62,   47,
167061 /*    40 */    23,   48,   24,    7,   11,   23,    9,    3,    4,    2,
167062 /*    50 */    62,   50,   52,   44,   64,    3,    4,    2,   49,    4,
167063 /*    60 */     2,    1,   23,   11,   16,    9,   12,    2,   10,   61,
167064 /*    70 */    53,   59,   62,   60,   22,   13,   55,    8,
167065};
167066static const fts5YYCODETYPE fts5yy_lookahead[] = {
167067 /*     0 */    15,   16,   17,   18,   19,   20,   10,   11,   23,   16,
167068 /*    10 */    17,   18,   19,   20,   23,   24,   23,   16,   17,   18,
167069 /*    20 */    19,   20,   22,   23,   23,   16,   17,   18,   19,   20,
167070 /*    30 */     5,    6,   23,   16,   17,   18,   19,   20,   13,   17,
167071 /*    40 */    23,   19,   20,    6,    8,   23,   10,    1,    2,    3,
167072 /*    50 */    13,    9,   10,    7,    0,    1,    2,    3,   19,    2,
167073 /*    60 */     3,    6,   23,    8,   21,   10,   10,    3,   10,   25,
167074 /*    70 */    10,   10,   13,   25,   12,   10,    7,    5,
167075};
167076#define fts5YY_SHIFT_USE_DFLT (-5)
167077#define fts5YY_SHIFT_COUNT (25)
167078#define fts5YY_SHIFT_MIN   (-4)
167079#define fts5YY_SHIFT_MAX   (72)
167080static const signed char fts5yy_shift_ofst[] = {
167081 /*     0 */    55,   55,   55,   55,   55,   36,   -4,   56,   58,   25,
167082 /*    10 */    37,   60,   59,   59,   46,   54,   42,   57,   62,   61,
167083 /*    20 */    62,   69,   65,   62,   72,   64,
167084};
167085#define fts5YY_REDUCE_USE_DFLT (-16)
167086#define fts5YY_REDUCE_COUNT (13)
167087#define fts5YY_REDUCE_MIN   (-15)
167088#define fts5YY_REDUCE_MAX   (48)
167089static const signed char fts5yy_reduce_ofst[] = {
167090 /*     0 */   -15,   -7,    1,    9,   17,   22,   -9,    0,   39,   44,
167091 /*    10 */    44,   43,   44,   48,
167092};
167093static const fts5YYACTIONTYPE fts5yy_default[] = {
167094 /*     0 */    88,   88,   88,   88,   88,   69,   82,   88,   88,   87,
167095 /*    10 */    87,   88,   87,   87,   88,   88,   88,   66,   80,   88,
167096 /*    20 */    81,   88,   88,   78,   88,   65,
167097};
167098
167099/* The next table maps tokens into fallback tokens.  If a construct
167100** like the following:
167101**
167102**      %fallback ID X Y Z.
167103**
167104** appears in the grammar, then ID becomes a fallback token for X, Y,
167105** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
167106** but it does not parse, the type of the token is changed to ID and
167107** the parse is retried before an error is thrown.
167108*/
167109#ifdef fts5YYFALLBACK
167110static const fts5YYCODETYPE fts5yyFallback[] = {
167111};
167112#endif /* fts5YYFALLBACK */
167113
167114/* The following structure represents a single element of the
167115** parser's stack.  Information stored includes:
167116**
167117**   +  The state number for the parser at this level of the stack.
167118**
167119**   +  The value of the token stored at this level of the stack.
167120**      (In other words, the "major" token.)
167121**
167122**   +  The semantic value stored at this level of the stack.  This is
167123**      the information used by the action routines in the grammar.
167124**      It is sometimes called the "minor" token.
167125**
167126** After the "shift" half of a SHIFTREDUCE action, the stateno field
167127** actually contains the reduce action for the second half of the
167128** SHIFTREDUCE.
167129*/
167130struct fts5yyStackEntry {
167131  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
167132  fts5YYCODETYPE major;      /* The major token value.  This is the code
167133                         ** number for the token at this stack level */
167134  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
167135                         ** is the value of the token  */
167136};
167137typedef struct fts5yyStackEntry fts5yyStackEntry;
167138
167139/* The state of the parser is completely contained in an instance of
167140** the following structure */
167141struct fts5yyParser {
167142  int fts5yyidx;                    /* Index of top element in stack */
167143#ifdef fts5YYTRACKMAXSTACKDEPTH
167144  int fts5yyidxMax;                 /* Maximum value of fts5yyidx */
167145#endif
167146  int fts5yyerrcnt;                 /* Shifts left before out of the error */
167147  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
167148#if fts5YYSTACKDEPTH<=0
167149  int fts5yystksz;                  /* Current side of the stack */
167150  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
167151#else
167152  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
167153#endif
167154};
167155typedef struct fts5yyParser fts5yyParser;
167156
167157#ifndef NDEBUG
167158/* #include <stdio.h> */
167159static FILE *fts5yyTraceFILE = 0;
167160static char *fts5yyTracePrompt = 0;
167161#endif /* NDEBUG */
167162
167163#ifndef NDEBUG
167164/*
167165** Turn parser tracing on by giving a stream to which to write the trace
167166** and a prompt to preface each trace message.  Tracing is turned off
167167** by making either argument NULL
167168**
167169** Inputs:
167170** <ul>
167171** <li> A FILE* to which trace output should be written.
167172**      If NULL, then tracing is turned off.
167173** <li> A prefix string written at the beginning of every
167174**      line of trace output.  If NULL, then tracing is
167175**      turned off.
167176** </ul>
167177**
167178** Outputs:
167179** None.
167180*/
167181static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
167182  fts5yyTraceFILE = TraceFILE;
167183  fts5yyTracePrompt = zTracePrompt;
167184  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
167185  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
167186}
167187#endif /* NDEBUG */
167188
167189#ifndef NDEBUG
167190/* For tracing shifts, the names of all terminals and nonterminals
167191** are required.  The following table supplies these names */
167192static const char *const fts5yyTokenName[] = {
167193  "$",             "OR",            "AND",           "NOT",
167194  "TERM",          "COLON",         "LP",            "RP",
167195  "LCP",           "RCP",           "STRING",        "COMMA",
167196  "PLUS",          "STAR",          "error",         "input",
167197  "expr",          "cnearset",      "exprlist",      "nearset",
167198  "colset",        "colsetlist",    "nearphrases",   "phrase",
167199  "neardist_opt",  "star_opt",
167200};
167201#endif /* NDEBUG */
167202
167203#ifndef NDEBUG
167204/* For tracing reduce actions, the names of all rules are required.
167205*/
167206static const char *const fts5yyRuleName[] = {
167207 /*   0 */ "input ::= expr",
167208 /*   1 */ "expr ::= expr AND expr",
167209 /*   2 */ "expr ::= expr OR expr",
167210 /*   3 */ "expr ::= expr NOT expr",
167211 /*   4 */ "expr ::= LP expr RP",
167212 /*   5 */ "expr ::= exprlist",
167213 /*   6 */ "exprlist ::= cnearset",
167214 /*   7 */ "exprlist ::= exprlist cnearset",
167215 /*   8 */ "cnearset ::= nearset",
167216 /*   9 */ "cnearset ::= colset COLON nearset",
167217 /*  10 */ "colset ::= LCP colsetlist RCP",
167218 /*  11 */ "colset ::= STRING",
167219 /*  12 */ "colsetlist ::= colsetlist STRING",
167220 /*  13 */ "colsetlist ::= STRING",
167221 /*  14 */ "nearset ::= phrase",
167222 /*  15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
167223 /*  16 */ "nearphrases ::= phrase",
167224 /*  17 */ "nearphrases ::= nearphrases phrase",
167225 /*  18 */ "neardist_opt ::=",
167226 /*  19 */ "neardist_opt ::= COMMA STRING",
167227 /*  20 */ "phrase ::= phrase PLUS STRING star_opt",
167228 /*  21 */ "phrase ::= STRING star_opt",
167229 /*  22 */ "star_opt ::= STAR",
167230 /*  23 */ "star_opt ::=",
167231};
167232#endif /* NDEBUG */
167233
167234
167235#if fts5YYSTACKDEPTH<=0
167236/*
167237** Try to increase the size of the parser stack.
167238*/
167239static void fts5yyGrowStack(fts5yyParser *p){
167240  int newSize;
167241  fts5yyStackEntry *pNew;
167242
167243  newSize = p->fts5yystksz*2 + 100;
167244  pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
167245  if( pNew ){
167246    p->fts5yystack = pNew;
167247    p->fts5yystksz = newSize;
167248#ifndef NDEBUG
167249    if( fts5yyTraceFILE ){
167250      fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
167251              fts5yyTracePrompt, p->fts5yystksz);
167252    }
167253#endif
167254  }
167255}
167256#endif
167257
167258/*
167259** This function allocates a new parser.
167260** The only argument is a pointer to a function which works like
167261** malloc.
167262**
167263** Inputs:
167264** A pointer to the function used to allocate memory.
167265**
167266** Outputs:
167267** A pointer to a parser.  This pointer is used in subsequent calls
167268** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
167269*/
167270static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)){
167271  fts5yyParser *pParser;
167272  pParser = (fts5yyParser*)(*mallocProc)( (u64)sizeof(fts5yyParser) );
167273  if( pParser ){
167274    pParser->fts5yyidx = -1;
167275#ifdef fts5YYTRACKMAXSTACKDEPTH
167276    pParser->fts5yyidxMax = 0;
167277#endif
167278#if fts5YYSTACKDEPTH<=0
167279    pParser->fts5yystack = NULL;
167280    pParser->fts5yystksz = 0;
167281    fts5yyGrowStack(pParser);
167282#endif
167283  }
167284  return pParser;
167285}
167286
167287/* The following function deletes the value associated with a
167288** symbol.  The symbol can be either a terminal or nonterminal.
167289** "fts5yymajor" is the symbol code, and "fts5yypminor" is a pointer to
167290** the value.
167291*/
167292static void fts5yy_destructor(
167293  fts5yyParser *fts5yypParser,    /* The parser */
167294  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
167295  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
167296){
167297  sqlite3Fts5ParserARG_FETCH;
167298  switch( fts5yymajor ){
167299    /* Here is inserted the actions which take place when a
167300    ** terminal or non-terminal is destroyed.  This can happen
167301    ** when the symbol is popped from the stack during a
167302    ** reduce or during error processing or when a parser is
167303    ** being destroyed before it is finished parsing.
167304    **
167305    ** Note: during a reduce, the only symbols destroyed are those
167306    ** which appear on the RHS of the rule, but which are not used
167307    ** inside the C code.
167308    */
167309    case 15: /* input */
167310{
167311 (void)pParse;
167312}
167313      break;
167314    case 16: /* expr */
167315    case 17: /* cnearset */
167316    case 18: /* exprlist */
167317{
167318 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
167319}
167320      break;
167321    case 19: /* nearset */
167322    case 22: /* nearphrases */
167323{
167324 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
167325}
167326      break;
167327    case 20: /* colset */
167328    case 21: /* colsetlist */
167329{
167330 sqlite3_free((fts5yypminor->fts5yy3));
167331}
167332      break;
167333    case 23: /* phrase */
167334{
167335 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
167336}
167337      break;
167338    default:  break;   /* If no destructor action specified: do nothing */
167339  }
167340}
167341
167342/*
167343** Pop the parser's stack once.
167344**
167345** If there is a destructor routine associated with the token which
167346** is popped from the stack, then call it.
167347**
167348** Return the major token number for the symbol popped.
167349*/
167350static int fts5yy_pop_parser_stack(fts5yyParser *pParser){
167351  fts5YYCODETYPE fts5yymajor;
167352  fts5yyStackEntry *fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx];
167353
167354  /* There is no mechanism by which the parser stack can be popped below
167355  ** empty in SQLite.  */
167356  assert( pParser->fts5yyidx>=0 );
167357#ifndef NDEBUG
167358  if( fts5yyTraceFILE && pParser->fts5yyidx>=0 ){
167359    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
167360      fts5yyTracePrompt,
167361      fts5yyTokenName[fts5yytos->major]);
167362  }
167363#endif
167364  fts5yymajor = fts5yytos->major;
167365  fts5yy_destructor(pParser, fts5yymajor, &fts5yytos->minor);
167366  pParser->fts5yyidx--;
167367  return fts5yymajor;
167368}
167369
167370/*
167371** Deallocate and destroy a parser.  Destructors are all called for
167372** all stack elements before shutting the parser down.
167373**
167374** Inputs:
167375** <ul>
167376** <li>  A pointer to the parser.  This should be a pointer
167377**       obtained from sqlite3Fts5ParserAlloc.
167378** <li>  A pointer to a function used to reclaim memory obtained
167379**       from malloc.
167380** </ul>
167381*/
167382static void sqlite3Fts5ParserFree(
167383  void *p,                    /* The parser to be deleted */
167384  void (*freeProc)(void*)     /* Function used to reclaim memory */
167385){
167386  fts5yyParser *pParser = (fts5yyParser*)p;
167387  /* In SQLite, we never try to destroy a parser that was not successfully
167388  ** created in the first place. */
167389  if( NEVER(pParser==0) ) return;
167390  while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
167391#if fts5YYSTACKDEPTH<=0
167392  free(pParser->fts5yystack);
167393#endif
167394  (*freeProc)((void*)pParser);
167395}
167396
167397/*
167398** Return the peak depth of the stack for a parser.
167399*/
167400#ifdef fts5YYTRACKMAXSTACKDEPTH
167401static int sqlite3Fts5ParserStackPeak(void *p){
167402  fts5yyParser *pParser = (fts5yyParser*)p;
167403  return pParser->fts5yyidxMax;
167404}
167405#endif
167406
167407/*
167408** Find the appropriate action for a parser given the terminal
167409** look-ahead token iLookAhead.
167410**
167411** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
167412** independent of the look-ahead.  If it is, return the action, otherwise
167413** return fts5YY_NO_ACTION.
167414*/
167415static int fts5yy_find_shift_action(
167416  fts5yyParser *pParser,        /* The parser */
167417  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
167418){
167419  int i;
167420  int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
167421
167422  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
167423  assert( stateno <= fts5YY_SHIFT_COUNT );
167424  i = fts5yy_shift_ofst[stateno];
167425  if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
167426  assert( iLookAhead!=fts5YYNOCODE );
167427  i += iLookAhead;
167428  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
167429    if( iLookAhead>0 ){
167430#ifdef fts5YYFALLBACK
167431      fts5YYCODETYPE iFallback;            /* Fallback token */
167432      if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
167433             && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
167434#ifndef NDEBUG
167435        if( fts5yyTraceFILE ){
167436          fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
167437             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
167438        }
167439#endif
167440        return fts5yy_find_shift_action(pParser, iFallback);
167441      }
167442#endif
167443#ifdef fts5YYWILDCARD
167444      {
167445        int j = i - iLookAhead + fts5YYWILDCARD;
167446        if(
167447#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
167448          j>=0 &&
167449#endif
167450#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
167451          j<fts5YY_ACTTAB_COUNT &&
167452#endif
167453          fts5yy_lookahead[j]==fts5YYWILDCARD
167454        ){
167455#ifndef NDEBUG
167456          if( fts5yyTraceFILE ){
167457            fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
167458               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[fts5YYWILDCARD]);
167459          }
167460#endif /* NDEBUG */
167461          return fts5yy_action[j];
167462        }
167463      }
167464#endif /* fts5YYWILDCARD */
167465    }
167466    return fts5yy_default[stateno];
167467  }else{
167468    return fts5yy_action[i];
167469  }
167470}
167471
167472/*
167473** Find the appropriate action for a parser given the non-terminal
167474** look-ahead token iLookAhead.
167475**
167476** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
167477** independent of the look-ahead.  If it is, return the action, otherwise
167478** return fts5YY_NO_ACTION.
167479*/
167480static int fts5yy_find_reduce_action(
167481  int stateno,              /* Current state number */
167482  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
167483){
167484  int i;
167485#ifdef fts5YYERRORSYMBOL
167486  if( stateno>fts5YY_REDUCE_COUNT ){
167487    return fts5yy_default[stateno];
167488  }
167489#else
167490  assert( stateno<=fts5YY_REDUCE_COUNT );
167491#endif
167492  i = fts5yy_reduce_ofst[stateno];
167493  assert( i!=fts5YY_REDUCE_USE_DFLT );
167494  assert( iLookAhead!=fts5YYNOCODE );
167495  i += iLookAhead;
167496#ifdef fts5YYERRORSYMBOL
167497  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
167498    return fts5yy_default[stateno];
167499  }
167500#else
167501  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
167502  assert( fts5yy_lookahead[i]==iLookAhead );
167503#endif
167504  return fts5yy_action[i];
167505}
167506
167507/*
167508** The following routine is called if the stack overflows.
167509*/
167510static void fts5yyStackOverflow(fts5yyParser *fts5yypParser, fts5YYMINORTYPE *fts5yypMinor){
167511   sqlite3Fts5ParserARG_FETCH;
167512   fts5yypParser->fts5yyidx--;
167513#ifndef NDEBUG
167514   if( fts5yyTraceFILE ){
167515     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
167516   }
167517#endif
167518   while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167519   /* Here code is inserted which will execute if the parser
167520   ** stack every overflows */
167521
167522  assert( 0 );
167523   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
167524}
167525
167526/*
167527** Print tracing information for a SHIFT action
167528*/
167529#ifndef NDEBUG
167530static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
167531  if( fts5yyTraceFILE ){
167532    int i;
167533    if( fts5yyNewState<fts5YYNSTATE ){
167534      fprintf(fts5yyTraceFILE,"%sShift %d\n",fts5yyTracePrompt,fts5yyNewState);
167535      fprintf(fts5yyTraceFILE,"%sStack:",fts5yyTracePrompt);
167536      for(i=1; i<=fts5yypParser->fts5yyidx; i++)
167537        fprintf(fts5yyTraceFILE," %s",fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
167538      fprintf(fts5yyTraceFILE,"\n");
167539    }else{
167540      fprintf(fts5yyTraceFILE,"%sShift *\n",fts5yyTracePrompt);
167541    }
167542  }
167543}
167544#else
167545# define fts5yyTraceShift(X,Y)
167546#endif
167547
167548/*
167549** Perform a shift action.  Return the number of errors.
167550*/
167551static void fts5yy_shift(
167552  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
167553  int fts5yyNewState,               /* The new state to shift in */
167554  int fts5yyMajor,                  /* The major token to shift in */
167555  fts5YYMINORTYPE *fts5yypMinor         /* Pointer to the minor token to shift in */
167556){
167557  fts5yyStackEntry *fts5yytos;
167558  fts5yypParser->fts5yyidx++;
167559#ifdef fts5YYTRACKMAXSTACKDEPTH
167560  if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
167561    fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
167562  }
167563#endif
167564#if fts5YYSTACKDEPTH>0
167565  if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
167566    fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
167567    return;
167568  }
167569#else
167570  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
167571    fts5yyGrowStack(fts5yypParser);
167572    if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
167573      fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
167574      return;
167575    }
167576  }
167577#endif
167578  fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
167579  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
167580  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
167581  fts5yytos->minor = *fts5yypMinor;
167582  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
167583}
167584
167585/* The following table contains information about every rule that
167586** is used during the reduce.
167587*/
167588static const struct {
167589  fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
167590  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
167591} fts5yyRuleInfo[] = {
167592  { 15, 1 },
167593  { 16, 3 },
167594  { 16, 3 },
167595  { 16, 3 },
167596  { 16, 3 },
167597  { 16, 1 },
167598  { 18, 1 },
167599  { 18, 2 },
167600  { 17, 1 },
167601  { 17, 3 },
167602  { 20, 3 },
167603  { 20, 1 },
167604  { 21, 2 },
167605  { 21, 1 },
167606  { 19, 1 },
167607  { 19, 5 },
167608  { 22, 1 },
167609  { 22, 2 },
167610  { 24, 0 },
167611  { 24, 2 },
167612  { 23, 4 },
167613  { 23, 2 },
167614  { 25, 1 },
167615  { 25, 0 },
167616};
167617
167618static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
167619
167620/*
167621** Perform a reduce action and the shift that must immediately
167622** follow the reduce.
167623*/
167624static void fts5yy_reduce(
167625  fts5yyParser *fts5yypParser,         /* The parser */
167626  int fts5yyruleno                 /* Number of the rule by which to reduce */
167627){
167628  int fts5yygoto;                     /* The next state */
167629  int fts5yyact;                      /* The next action */
167630  fts5YYMINORTYPE fts5yygotominor;        /* The LHS of the rule reduced */
167631  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
167632  int fts5yysize;                     /* Amount to pop the stack */
167633  sqlite3Fts5ParserARG_FETCH;
167634  fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
167635#ifndef NDEBUG
167636  if( fts5yyTraceFILE && fts5yyruleno>=0
167637        && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
167638    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
167639    fprintf(fts5yyTraceFILE, "%sReduce [%s] -> state %d.\n", fts5yyTracePrompt,
167640      fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
167641  }
167642#endif /* NDEBUG */
167643
167644  /* Silence complaints from purify about fts5yygotominor being uninitialized
167645  ** in some cases when it is copied into the stack after the following
167646  ** switch.  fts5yygotominor is uninitialized when a rule reduces that does
167647  ** not set the value of its left-hand side nonterminal.  Leaving the
167648  ** value of the nonterminal uninitialized is utterly harmless as long
167649  ** as the value is never used.  So really the only thing this code
167650  ** accomplishes is to quieten purify.
167651  **
167652  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
167653  ** without this code, their parser segfaults.  I'm not sure what there
167654  ** parser is doing to make this happen.  This is the second bug report
167655  ** from wireshark this week.  Clearly they are stressing Lemon in ways
167656  ** that it has not been previously stressed...  (SQLite ticket #2172)
167657  */
167658  /*memset(&fts5yygotominor, 0, sizeof(fts5yygotominor));*/
167659  fts5yygotominor = fts5yyzerominor;
167660
167661
167662  switch( fts5yyruleno ){
167663  /* Beginning here are the reduction cases.  A typical example
167664  ** follows:
167665  **   case 0:
167666  **  #line <lineno> <grammarfile>
167667  **     { ... }           // User supplied code
167668  **  #line <lineno> <thisfile>
167669  **     break;
167670  */
167671      case 0: /* input ::= expr */
167672{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
167673        break;
167674      case 1: /* expr ::= expr AND expr */
167675{
167676  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167677}
167678        break;
167679      case 2: /* expr ::= expr OR expr */
167680{
167681  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167682}
167683        break;
167684      case 3: /* expr ::= expr NOT expr */
167685{
167686  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167687}
167688        break;
167689      case 4: /* expr ::= LP expr RP */
167690{fts5yygotominor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
167691        break;
167692      case 5: /* expr ::= exprlist */
167693      case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
167694{fts5yygotominor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
167695        break;
167696      case 7: /* exprlist ::= exprlist cnearset */
167697{
167698  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167699}
167700        break;
167701      case 8: /* cnearset ::= nearset */
167702{
167703  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
167704}
167705        break;
167706      case 9: /* cnearset ::= colset COLON nearset */
167707{
167708  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
167709  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
167710}
167711        break;
167712      case 10: /* colset ::= LCP colsetlist RCP */
167713{ fts5yygotominor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
167714        break;
167715      case 11: /* colset ::= STRING */
167716{
167717  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
167718}
167719        break;
167720      case 12: /* colsetlist ::= colsetlist STRING */
167721{
167722  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
167723        break;
167724      case 13: /* colsetlist ::= STRING */
167725{
167726  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
167727}
167728        break;
167729      case 14: /* nearset ::= phrase */
167730{ fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
167731        break;
167732      case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
167733{
167734  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
167735  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
167736  fts5yygotominor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
167737}
167738        break;
167739      case 16: /* nearphrases ::= phrase */
167740{
167741  fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
167742}
167743        break;
167744      case 17: /* nearphrases ::= nearphrases phrase */
167745{
167746  fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
167747}
167748        break;
167749      case 18: /* neardist_opt ::= */
167750{ fts5yygotominor.fts5yy0.p = 0; fts5yygotominor.fts5yy0.n = 0; }
167751        break;
167752      case 19: /* neardist_opt ::= COMMA STRING */
167753{ fts5yygotominor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
167754        break;
167755      case 20: /* phrase ::= phrase PLUS STRING star_opt */
167756{
167757  fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
167758}
167759        break;
167760      case 21: /* phrase ::= STRING star_opt */
167761{
167762  fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
167763}
167764        break;
167765      case 22: /* star_opt ::= STAR */
167766{ fts5yygotominor.fts5yy20 = 1; }
167767        break;
167768      case 23: /* star_opt ::= */
167769{ fts5yygotominor.fts5yy20 = 0; }
167770        break;
167771      default:
167772        break;
167773  };
167774  assert( fts5yyruleno>=0 && fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
167775  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
167776  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
167777  fts5yypParser->fts5yyidx -= fts5yysize;
167778  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
167779  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
167780    if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
167781    /* If the reduce action popped at least
167782    ** one element off the stack, then we can push the new element back
167783    ** onto the stack here, and skip the stack overflow test in fts5yy_shift().
167784    ** That gives a significant speed improvement. */
167785    if( fts5yysize ){
167786      fts5yypParser->fts5yyidx++;
167787      fts5yymsp -= fts5yysize-1;
167788      fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
167789      fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
167790      fts5yymsp->minor = fts5yygotominor;
167791      fts5yyTraceShift(fts5yypParser, fts5yyact);
167792    }else{
167793      fts5yy_shift(fts5yypParser,fts5yyact,fts5yygoto,&fts5yygotominor);
167794    }
167795  }else{
167796    assert( fts5yyact == fts5YY_ACCEPT_ACTION );
167797    fts5yy_accept(fts5yypParser);
167798  }
167799}
167800
167801/*
167802** The following code executes when the parse fails
167803*/
167804#ifndef fts5YYNOERRORRECOVERY
167805static void fts5yy_parse_failed(
167806  fts5yyParser *fts5yypParser           /* The parser */
167807){
167808  sqlite3Fts5ParserARG_FETCH;
167809#ifndef NDEBUG
167810  if( fts5yyTraceFILE ){
167811    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
167812  }
167813#endif
167814  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167815  /* Here code is inserted which will be executed whenever the
167816  ** parser fails */
167817  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167818}
167819#endif /* fts5YYNOERRORRECOVERY */
167820
167821/*
167822** The following code executes when a syntax error first occurs.
167823*/
167824static void fts5yy_syntax_error(
167825  fts5yyParser *fts5yypParser,           /* The parser */
167826  int fts5yymajor,                   /* The major type of the error token */
167827  fts5YYMINORTYPE fts5yyminor            /* The minor type of the error token */
167828){
167829  sqlite3Fts5ParserARG_FETCH;
167830#define FTS5TOKEN (fts5yyminor.fts5yy0)
167831
167832  sqlite3Fts5ParseError(
167833    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
167834  );
167835  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167836}
167837
167838/*
167839** The following is executed when the parser accepts
167840*/
167841static void fts5yy_accept(
167842  fts5yyParser *fts5yypParser           /* The parser */
167843){
167844  sqlite3Fts5ParserARG_FETCH;
167845#ifndef NDEBUG
167846  if( fts5yyTraceFILE ){
167847    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
167848  }
167849#endif
167850  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167851  /* Here code is inserted which will be executed whenever the
167852  ** parser accepts */
167853  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167854}
167855
167856/* The main parser program.
167857** The first argument is a pointer to a structure obtained from
167858** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
167859** The second argument is the major token number.  The third is
167860** the minor token.  The fourth optional argument is whatever the
167861** user wants (and specified in the grammar) and is available for
167862** use by the action routines.
167863**
167864** Inputs:
167865** <ul>
167866** <li> A pointer to the parser (an opaque structure.)
167867** <li> The major token number.
167868** <li> The minor token number.
167869** <li> An option argument of a grammar-specified type.
167870** </ul>
167871**
167872** Outputs:
167873** None.
167874*/
167875static void sqlite3Fts5Parser(
167876  void *fts5yyp,                   /* The parser */
167877  int fts5yymajor,                 /* The major token code number */
167878  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
167879  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
167880){
167881  fts5YYMINORTYPE fts5yyminorunion;
167882  int fts5yyact;            /* The parser action. */
167883#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
167884  int fts5yyendofinput;     /* True if we are at the end of input */
167885#endif
167886#ifdef fts5YYERRORSYMBOL
167887  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
167888#endif
167889  fts5yyParser *fts5yypParser;  /* The parser */
167890
167891  /* (re)initialize the parser, if necessary */
167892  fts5yypParser = (fts5yyParser*)fts5yyp;
167893  if( fts5yypParser->fts5yyidx<0 ){
167894#if fts5YYSTACKDEPTH<=0
167895    if( fts5yypParser->fts5yystksz <=0 ){
167896      /*memset(&fts5yyminorunion, 0, sizeof(fts5yyminorunion));*/
167897      fts5yyminorunion = fts5yyzerominor;
167898      fts5yyStackOverflow(fts5yypParser, &fts5yyminorunion);
167899      return;
167900    }
167901#endif
167902    fts5yypParser->fts5yyidx = 0;
167903    fts5yypParser->fts5yyerrcnt = -1;
167904    fts5yypParser->fts5yystack[0].stateno = 0;
167905    fts5yypParser->fts5yystack[0].major = 0;
167906  }
167907  fts5yyminorunion.fts5yy0 = fts5yyminor;
167908#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
167909  fts5yyendofinput = (fts5yymajor==0);
167910#endif
167911  sqlite3Fts5ParserARG_STORE;
167912
167913#ifndef NDEBUG
167914  if( fts5yyTraceFILE ){
167915    fprintf(fts5yyTraceFILE,"%sInput %s\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
167916  }
167917#endif
167918
167919  do{
167920    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
167921    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
167922      if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
167923      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,&fts5yyminorunion);
167924      fts5yypParser->fts5yyerrcnt--;
167925      fts5yymajor = fts5YYNOCODE;
167926    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
167927      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
167928    }else{
167929      assert( fts5yyact == fts5YY_ERROR_ACTION );
167930#ifdef fts5YYERRORSYMBOL
167931      int fts5yymx;
167932#endif
167933#ifndef NDEBUG
167934      if( fts5yyTraceFILE ){
167935        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
167936      }
167937#endif
167938#ifdef fts5YYERRORSYMBOL
167939      /* A syntax error has occurred.
167940      ** The response to an error depends upon whether or not the
167941      ** grammar defines an error token "ERROR".
167942      **
167943      ** This is what we do if the grammar does define ERROR:
167944      **
167945      **  * Call the %syntax_error function.
167946      **
167947      **  * Begin popping the stack until we enter a state where
167948      **    it is legal to shift the error symbol, then shift
167949      **    the error symbol.
167950      **
167951      **  * Set the error count to three.
167952      **
167953      **  * Begin accepting and shifting new tokens.  No new error
167954      **    processing will occur until three tokens have been
167955      **    shifted successfully.
167956      **
167957      */
167958      if( fts5yypParser->fts5yyerrcnt<0 ){
167959        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
167960      }
167961      fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
167962      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
167963#ifndef NDEBUG
167964        if( fts5yyTraceFILE ){
167965          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
167966             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
167967        }
167968#endif
167969        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
167970        fts5yymajor = fts5YYNOCODE;
167971      }else{
167972         while(
167973          fts5yypParser->fts5yyidx >= 0 &&
167974          fts5yymx != fts5YYERRORSYMBOL &&
167975          (fts5yyact = fts5yy_find_reduce_action(
167976                        fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
167977                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
167978        ){
167979          fts5yy_pop_parser_stack(fts5yypParser);
167980        }
167981        if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
167982          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
167983          fts5yy_parse_failed(fts5yypParser);
167984          fts5yymajor = fts5YYNOCODE;
167985        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
167986          fts5YYMINORTYPE u2;
167987          u2.fts5YYERRSYMDT = 0;
167988          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,&u2);
167989        }
167990      }
167991      fts5yypParser->fts5yyerrcnt = 3;
167992      fts5yyerrorhit = 1;
167993#elif defined(fts5YYNOERRORRECOVERY)
167994      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
167995      ** do any kind of error recovery.  Instead, simply invoke the syntax
167996      ** error routine and continue going as if nothing had happened.
167997      **
167998      ** Applications can set this macro (for example inside %include) if
167999      ** they intend to abandon the parse upon the first syntax error seen.
168000      */
168001      fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
168002      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168003      fts5yymajor = fts5YYNOCODE;
168004
168005#else  /* fts5YYERRORSYMBOL is not defined */
168006      /* This is what we do if the grammar does not define ERROR:
168007      **
168008      **  * Report an error message, and throw away the input token.
168009      **
168010      **  * If the input token is $, then fail the parse.
168011      **
168012      ** As before, subsequent error messages are suppressed until
168013      ** three input tokens have been successfully shifted.
168014      */
168015      if( fts5yypParser->fts5yyerrcnt<=0 ){
168016        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
168017      }
168018      fts5yypParser->fts5yyerrcnt = 3;
168019      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168020      if( fts5yyendofinput ){
168021        fts5yy_parse_failed(fts5yypParser);
168022      }
168023      fts5yymajor = fts5YYNOCODE;
168024#endif
168025    }
168026  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
168027#ifndef NDEBUG
168028  if( fts5yyTraceFILE ){
168029    fprintf(fts5yyTraceFILE,"%sReturn\n",fts5yyTracePrompt);
168030  }
168031#endif
168032  return;
168033}
168034
168035/*
168036** 2014 May 31
168037**
168038** The author disclaims copyright to this source code.  In place of
168039** a legal notice, here is a blessing:
168040**
168041**    May you do good and not evil.
168042**    May you find forgiveness for yourself and forgive others.
168043**    May you share freely, never taking more than you give.
168044**
168045******************************************************************************
168046*/
168047
168048
168049#include <math.h>                 /* amalgamator: keep */
168050
168051/*
168052** Object used to iterate through all "coalesced phrase instances" in
168053** a single column of the current row. If the phrase instances in the
168054** column being considered do not overlap, this object simply iterates
168055** through them. Or, if they do overlap (share one or more tokens in
168056** common), each set of overlapping instances is treated as a single
168057** match. See documentation for the highlight() auxiliary function for
168058** details.
168059**
168060** Usage is:
168061**
168062**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
168063**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
168064**      rc = fts5CInstIterNext(&iter)
168065**   ){
168066**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
168067**   }
168068**
168069*/
168070typedef struct CInstIter CInstIter;
168071struct CInstIter {
168072  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
168073  Fts5Context *pFts;              /* First arg to pass to pApi functions */
168074  int iCol;                       /* Column to search */
168075  int iInst;                      /* Next phrase instance index */
168076  int nInst;                      /* Total number of phrase instances */
168077
168078  /* Output variables */
168079  int iStart;                     /* First token in coalesced phrase instance */
168080  int iEnd;                       /* Last token in coalesced phrase instance */
168081};
168082
168083/*
168084** Advance the iterator to the next coalesced phrase instance. Return
168085** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
168086*/
168087static int fts5CInstIterNext(CInstIter *pIter){
168088  int rc = SQLITE_OK;
168089  pIter->iStart = -1;
168090  pIter->iEnd = -1;
168091
168092  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
168093    int ip; int ic; int io;
168094    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
168095    if( rc==SQLITE_OK ){
168096      if( ic==pIter->iCol ){
168097        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
168098        if( pIter->iStart<0 ){
168099          pIter->iStart = io;
168100          pIter->iEnd = iEnd;
168101        }else if( io<=pIter->iEnd ){
168102          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
168103        }else{
168104          break;
168105        }
168106      }
168107      pIter->iInst++;
168108    }
168109  }
168110
168111  return rc;
168112}
168113
168114/*
168115** Initialize the iterator object indicated by the final parameter to
168116** iterate through coalesced phrase instances in column iCol.
168117*/
168118static int fts5CInstIterInit(
168119  const Fts5ExtensionApi *pApi,
168120  Fts5Context *pFts,
168121  int iCol,
168122  CInstIter *pIter
168123){
168124  int rc;
168125
168126  memset(pIter, 0, sizeof(CInstIter));
168127  pIter->pApi = pApi;
168128  pIter->pFts = pFts;
168129  pIter->iCol = iCol;
168130  rc = pApi->xInstCount(pFts, &pIter->nInst);
168131
168132  if( rc==SQLITE_OK ){
168133    rc = fts5CInstIterNext(pIter);
168134  }
168135
168136  return rc;
168137}
168138
168139
168140
168141/*************************************************************************
168142** Start of highlight() implementation.
168143*/
168144typedef struct HighlightContext HighlightContext;
168145struct HighlightContext {
168146  CInstIter iter;                 /* Coalesced Instance Iterator */
168147  int iPos;                       /* Current token offset in zIn[] */
168148  int iRangeStart;                /* First token to include */
168149  int iRangeEnd;                  /* If non-zero, last token to include */
168150  const char *zOpen;              /* Opening highlight */
168151  const char *zClose;             /* Closing highlight */
168152  const char *zIn;                /* Input text */
168153  int nIn;                        /* Size of input text in bytes */
168154  int iOff;                       /* Current offset within zIn[] */
168155  char *zOut;                     /* Output value */
168156};
168157
168158/*
168159** Append text to the HighlightContext output string - p->zOut. Argument
168160** z points to a buffer containing n bytes of text to append. If n is
168161** negative, everything up until the first '\0' is appended to the output.
168162**
168163** If *pRc is set to any value other than SQLITE_OK when this function is
168164** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
168165** *pRc is set to an error code before returning.
168166*/
168167static void fts5HighlightAppend(
168168  int *pRc,
168169  HighlightContext *p,
168170  const char *z, int n
168171){
168172  if( *pRc==SQLITE_OK ){
168173    if( n<0 ) n = strlen(z);
168174    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
168175    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
168176  }
168177}
168178
168179/*
168180** Tokenizer callback used by implementation of highlight() function.
168181*/
168182static int fts5HighlightCb(
168183  void *pContext,                 /* Pointer to HighlightContext object */
168184  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
168185  const char *pToken,             /* Buffer containing token */
168186  int nToken,                     /* Size of token in bytes */
168187  int iStartOff,                  /* Start offset of token */
168188  int iEndOff                     /* End offset of token */
168189){
168190  HighlightContext *p = (HighlightContext*)pContext;
168191  int rc = SQLITE_OK;
168192  int iPos;
168193
168194  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
168195  iPos = p->iPos++;
168196
168197  if( p->iRangeEnd>0 ){
168198    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
168199    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
168200  }
168201
168202  if( iPos==p->iter.iStart ){
168203    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
168204    fts5HighlightAppend(&rc, p, p->zOpen, -1);
168205    p->iOff = iStartOff;
168206  }
168207
168208  if( iPos==p->iter.iEnd ){
168209    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
168210      fts5HighlightAppend(&rc, p, p->zOpen, -1);
168211    }
168212    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
168213    fts5HighlightAppend(&rc, p, p->zClose, -1);
168214    p->iOff = iEndOff;
168215    if( rc==SQLITE_OK ){
168216      rc = fts5CInstIterNext(&p->iter);
168217    }
168218  }
168219
168220  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
168221    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
168222    p->iOff = iEndOff;
168223    if( iPos<p->iter.iEnd ){
168224      fts5HighlightAppend(&rc, p, p->zClose, -1);
168225    }
168226  }
168227
168228  return rc;
168229}
168230
168231/*
168232** Implementation of highlight() function.
168233*/
168234static void fts5HighlightFunction(
168235  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168236  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168237  sqlite3_context *pCtx,          /* Context for returning result/error */
168238  int nVal,                       /* Number of values in apVal[] array */
168239  sqlite3_value **apVal           /* Array of trailing arguments */
168240){
168241  HighlightContext ctx;
168242  int rc;
168243  int iCol;
168244
168245  if( nVal!=3 ){
168246    const char *zErr = "wrong number of arguments to function highlight()";
168247    sqlite3_result_error(pCtx, zErr, -1);
168248    return;
168249  }
168250
168251  iCol = sqlite3_value_int(apVal[0]);
168252  memset(&ctx, 0, sizeof(HighlightContext));
168253  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
168254  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
168255  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
168256
168257  if( ctx.zIn ){
168258    if( rc==SQLITE_OK ){
168259      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
168260    }
168261
168262    if( rc==SQLITE_OK ){
168263      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
168264    }
168265    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
168266
168267    if( rc==SQLITE_OK ){
168268      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
168269    }
168270    sqlite3_free(ctx.zOut);
168271  }
168272  if( rc!=SQLITE_OK ){
168273    sqlite3_result_error_code(pCtx, rc);
168274  }
168275}
168276/*
168277** End of highlight() implementation.
168278**************************************************************************/
168279
168280/*
168281** Implementation of snippet() function.
168282*/
168283static void fts5SnippetFunction(
168284  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168285  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168286  sqlite3_context *pCtx,          /* Context for returning result/error */
168287  int nVal,                       /* Number of values in apVal[] array */
168288  sqlite3_value **apVal           /* Array of trailing arguments */
168289){
168290  HighlightContext ctx;
168291  int rc = SQLITE_OK;             /* Return code */
168292  int iCol;                       /* 1st argument to snippet() */
168293  const char *zEllips;            /* 4th argument to snippet() */
168294  int nToken;                     /* 5th argument to snippet() */
168295  int nInst = 0;                  /* Number of instance matches this row */
168296  int i;                          /* Used to iterate through instances */
168297  int nPhrase;                    /* Number of phrases in query */
168298  unsigned char *aSeen;           /* Array of "seen instance" flags */
168299  int iBestCol;                   /* Column containing best snippet */
168300  int iBestStart = 0;             /* First token of best snippet */
168301  int iBestLast;                  /* Last token of best snippet */
168302  int nBestScore = 0;             /* Score of best snippet */
168303  int nColSize = 0;               /* Total size of iBestCol in tokens */
168304
168305  if( nVal!=5 ){
168306    const char *zErr = "wrong number of arguments to function snippet()";
168307    sqlite3_result_error(pCtx, zErr, -1);
168308    return;
168309  }
168310
168311  memset(&ctx, 0, sizeof(HighlightContext));
168312  iCol = sqlite3_value_int(apVal[0]);
168313  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
168314  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
168315  zEllips = (const char*)sqlite3_value_text(apVal[3]);
168316  nToken = sqlite3_value_int(apVal[4]);
168317  iBestLast = nToken-1;
168318
168319  iBestCol = (iCol>=0 ? iCol : 0);
168320  nPhrase = pApi->xPhraseCount(pFts);
168321  aSeen = sqlite3_malloc(nPhrase);
168322  if( aSeen==0 ){
168323    rc = SQLITE_NOMEM;
168324  }
168325
168326  if( rc==SQLITE_OK ){
168327    rc = pApi->xInstCount(pFts, &nInst);
168328  }
168329  for(i=0; rc==SQLITE_OK && i<nInst; i++){
168330    int ip, iSnippetCol, iStart;
168331    memset(aSeen, 0, nPhrase);
168332    rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
168333    if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
168334      int nScore = 1000;
168335      int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
168336      int j;
168337      aSeen[ip] = 1;
168338
168339      for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
168340        int ic; int io; int iFinal;
168341        rc = pApi->xInst(pFts, j, &ip, &ic, &io);
168342        iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
168343        if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
168344          nScore += aSeen[ip] ? 1000 : 1;
168345          aSeen[ip] = 1;
168346          if( iFinal>iLast ) iLast = iFinal;
168347        }
168348      }
168349
168350      if( rc==SQLITE_OK && nScore>nBestScore ){
168351        iBestCol = iSnippetCol;
168352        iBestStart = iStart;
168353        iBestLast = iLast;
168354        nBestScore = nScore;
168355      }
168356    }
168357  }
168358
168359  if( rc==SQLITE_OK ){
168360    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
168361  }
168362  if( rc==SQLITE_OK ){
168363    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
168364  }
168365  if( ctx.zIn ){
168366    if( rc==SQLITE_OK ){
168367      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
168368    }
168369
168370    if( (iBestStart+nToken-1)>iBestLast ){
168371      iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
168372    }
168373    if( iBestStart+nToken>nColSize ){
168374      iBestStart = nColSize - nToken;
168375    }
168376    if( iBestStart<0 ) iBestStart = 0;
168377
168378    ctx.iRangeStart = iBestStart;
168379    ctx.iRangeEnd = iBestStart + nToken - 1;
168380
168381    if( iBestStart>0 ){
168382      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
168383    }
168384    if( rc==SQLITE_OK ){
168385      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
168386    }
168387    if( ctx.iRangeEnd>=(nColSize-1) ){
168388      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
168389    }else{
168390      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
168391    }
168392
168393    if( rc==SQLITE_OK ){
168394      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
168395    }else{
168396      sqlite3_result_error_code(pCtx, rc);
168397    }
168398    sqlite3_free(ctx.zOut);
168399  }
168400  sqlite3_free(aSeen);
168401}
168402
168403/************************************************************************/
168404
168405/*
168406** The first time the bm25() function is called for a query, an instance
168407** of the following structure is allocated and populated.
168408*/
168409typedef struct Fts5Bm25Data Fts5Bm25Data;
168410struct Fts5Bm25Data {
168411  int nPhrase;                    /* Number of phrases in query */
168412  double avgdl;                   /* Average number of tokens in each row */
168413  double *aIDF;                   /* IDF for each phrase */
168414  double *aFreq;                  /* Array used to calculate phrase freq. */
168415};
168416
168417/*
168418** Callback used by fts5Bm25GetData() to count the number of rows in the
168419** table matched by each individual phrase within the query.
168420*/
168421static int fts5CountCb(
168422  const Fts5ExtensionApi *pApi,
168423  Fts5Context *pFts,
168424  void *pUserData                 /* Pointer to sqlite3_int64 variable */
168425){
168426  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
168427  (*pn)++;
168428  return SQLITE_OK;
168429}
168430
168431/*
168432** Set *ppData to point to the Fts5Bm25Data object for the current query.
168433** If the object has not already been allocated, allocate and populate it
168434** now.
168435*/
168436static int fts5Bm25GetData(
168437  const Fts5ExtensionApi *pApi,
168438  Fts5Context *pFts,
168439  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
168440){
168441  int rc = SQLITE_OK;             /* Return code */
168442  Fts5Bm25Data *p;                /* Object to return */
168443
168444  p = pApi->xGetAuxdata(pFts, 0);
168445  if( p==0 ){
168446    int nPhrase;                  /* Number of phrases in query */
168447    sqlite3_int64 nRow = 0;       /* Number of rows in table */
168448    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
168449    int nByte;                    /* Bytes of space to allocate */
168450    int i;
168451
168452    /* Allocate the Fts5Bm25Data object */
168453    nPhrase = pApi->xPhraseCount(pFts);
168454    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
168455    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
168456    if( p==0 ){
168457      rc = SQLITE_NOMEM;
168458    }else{
168459      memset(p, 0, nByte);
168460      p->nPhrase = nPhrase;
168461      p->aIDF = (double*)&p[1];
168462      p->aFreq = &p->aIDF[nPhrase];
168463    }
168464
168465    /* Calculate the average document length for this FTS5 table */
168466    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
168467    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
168468    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
168469
168470    /* Calculate an IDF for each phrase in the query */
168471    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
168472      sqlite3_int64 nHit = 0;
168473      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
168474      if( rc==SQLITE_OK ){
168475        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
168476        ** This is done using the standard BM25 formula as found on wikipedia:
168477        **
168478        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
168479        **
168480        ** where "N" is the total number of documents in the set and nHit
168481        ** is the number that contain at least one instance of the phrase
168482        ** under consideration.
168483        **
168484        ** The problem with this is that if (N < 2*nHit), the IDF is
168485        ** negative. Which is undesirable. So the mimimum allowable IDF is
168486        ** (1e-6) - roughly the same as a term that appears in just over
168487        ** half of set of 5,000,000 documents.  */
168488        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
168489        if( idf<=0.0 ) idf = 1e-6;
168490        p->aIDF[i] = idf;
168491      }
168492    }
168493
168494    if( rc!=SQLITE_OK ){
168495      sqlite3_free(p);
168496    }else{
168497      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
168498    }
168499    if( rc!=SQLITE_OK ) p = 0;
168500  }
168501  *ppData = p;
168502  return rc;
168503}
168504
168505/*
168506** Implementation of bm25() function.
168507*/
168508static void fts5Bm25Function(
168509  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168510  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168511  sqlite3_context *pCtx,          /* Context for returning result/error */
168512  int nVal,                       /* Number of values in apVal[] array */
168513  sqlite3_value **apVal           /* Array of trailing arguments */
168514){
168515  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
168516  const double b = 0.75;          /* Constant "b" from BM25 formula */
168517  int rc = SQLITE_OK;             /* Error code */
168518  double score = 0.0;             /* SQL function return value */
168519  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
168520  int i;                          /* Iterator variable */
168521  int nInst = 0;                  /* Value returned by xInstCount() */
168522  double D = 0.0;                 /* Total number of tokens in row */
168523  double *aFreq = 0;              /* Array of phrase freq. for current row */
168524
168525  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
168526  ** for each phrase in the query for the current row. */
168527  rc = fts5Bm25GetData(pApi, pFts, &pData);
168528  if( rc==SQLITE_OK ){
168529    aFreq = pData->aFreq;
168530    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
168531    rc = pApi->xInstCount(pFts, &nInst);
168532  }
168533  for(i=0; rc==SQLITE_OK && i<nInst; i++){
168534    int ip; int ic; int io;
168535    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
168536    if( rc==SQLITE_OK ){
168537      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
168538      aFreq[ip] += w;
168539    }
168540  }
168541
168542  /* Figure out the total size of the current row in tokens. */
168543  if( rc==SQLITE_OK ){
168544    int nTok;
168545    rc = pApi->xColumnSize(pFts, -1, &nTok);
168546    D = (double)nTok;
168547  }
168548
168549  /* Determine the BM25 score for the current row. */
168550  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
168551    score += pData->aIDF[i] * (
168552      ( aFreq[i] * (k1 + 1.0) ) /
168553      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
168554    );
168555  }
168556
168557  /* If no error has occurred, return the calculated score. Otherwise,
168558  ** throw an SQL exception.  */
168559  if( rc==SQLITE_OK ){
168560    sqlite3_result_double(pCtx, -1.0 * score);
168561  }else{
168562    sqlite3_result_error_code(pCtx, rc);
168563  }
168564}
168565
168566static int sqlite3Fts5AuxInit(fts5_api *pApi){
168567  struct Builtin {
168568    const char *zFunc;            /* Function name (nul-terminated) */
168569    void *pUserData;              /* User-data pointer */
168570    fts5_extension_function xFunc;/* Callback function */
168571    void (*xDestroy)(void*);      /* Destructor function */
168572  } aBuiltin [] = {
168573    { "snippet",   0, fts5SnippetFunction, 0 },
168574    { "highlight", 0, fts5HighlightFunction, 0 },
168575    { "bm25",      0, fts5Bm25Function,    0 },
168576  };
168577  int rc = SQLITE_OK;             /* Return code */
168578  int i;                          /* To iterate through builtin functions */
168579
168580  for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
168581    rc = pApi->xCreateFunction(pApi,
168582        aBuiltin[i].zFunc,
168583        aBuiltin[i].pUserData,
168584        aBuiltin[i].xFunc,
168585        aBuiltin[i].xDestroy
168586    );
168587  }
168588
168589  return rc;
168590}
168591
168592
168593
168594/*
168595** 2014 May 31
168596**
168597** The author disclaims copyright to this source code.  In place of
168598** a legal notice, here is a blessing:
168599**
168600**    May you do good and not evil.
168601**    May you find forgiveness for yourself and forgive others.
168602**    May you share freely, never taking more than you give.
168603**
168604******************************************************************************
168605*/
168606
168607
168608
168609
168610static int sqlite3Fts5BufferGrow(int *pRc, Fts5Buffer *pBuf, int nByte){
168611
168612  if( (pBuf->n + nByte) > pBuf->nSpace ){
168613    u8 *pNew;
168614    int nNew = pBuf->nSpace ? pBuf->nSpace*2 : 64;
168615
168616    /* A no-op if an error has already occurred */
168617    if( *pRc ) return 1;
168618
168619    while( nNew<(pBuf->n + nByte) ){
168620      nNew = nNew * 2;
168621    }
168622    pNew = sqlite3_realloc(pBuf->p, nNew);
168623    if( pNew==0 ){
168624      *pRc = SQLITE_NOMEM;
168625      return 1;
168626    }else{
168627      pBuf->nSpace = nNew;
168628      pBuf->p = pNew;
168629    }
168630  }
168631  return 0;
168632}
168633
168634/*
168635** Encode value iVal as an SQLite varint and append it to the buffer object
168636** pBuf. If an OOM error occurs, set the error code in p.
168637*/
168638static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
168639  if( sqlite3Fts5BufferGrow(pRc, pBuf, 9) ) return;
168640  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
168641}
168642
168643static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
168644  aBuf[0] = (iVal>>24) & 0x00FF;
168645  aBuf[1] = (iVal>>16) & 0x00FF;
168646  aBuf[2] = (iVal>> 8) & 0x00FF;
168647  aBuf[3] = (iVal>> 0) & 0x00FF;
168648}
168649
168650static int sqlite3Fts5Get32(const u8 *aBuf){
168651  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
168652}
168653
168654static void sqlite3Fts5BufferAppend32(int *pRc, Fts5Buffer *pBuf, int iVal){
168655  if( sqlite3Fts5BufferGrow(pRc, pBuf, 4) ) return;
168656  sqlite3Fts5Put32(&pBuf->p[pBuf->n], iVal);
168657  pBuf->n += 4;
168658}
168659
168660/*
168661** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
168662** the error code in p. If an error has already occurred when this function
168663** is called, it is a no-op.
168664*/
168665static void sqlite3Fts5BufferAppendBlob(
168666  int *pRc,
168667  Fts5Buffer *pBuf,
168668  int nData,
168669  const u8 *pData
168670){
168671  assert( *pRc || nData>=0 );
168672  if( sqlite3Fts5BufferGrow(pRc, pBuf, nData) ) return;
168673  memcpy(&pBuf->p[pBuf->n], pData, nData);
168674  pBuf->n += nData;
168675}
168676
168677/*
168678** Append the nul-terminated string zStr to the buffer pBuf. This function
168679** ensures that the byte following the buffer data is set to 0x00, even
168680** though this byte is not included in the pBuf->n count.
168681*/
168682static void sqlite3Fts5BufferAppendString(
168683  int *pRc,
168684  Fts5Buffer *pBuf,
168685  const char *zStr
168686){
168687  int nStr = strlen(zStr);
168688  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
168689  pBuf->n--;
168690}
168691
168692/*
168693** Argument zFmt is a printf() style format string. This function performs
168694** the printf() style processing, then appends the results to buffer pBuf.
168695**
168696** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
168697** following the buffer data is set to 0x00, even though this byte is not
168698** included in the pBuf->n count.
168699*/
168700static void sqlite3Fts5BufferAppendPrintf(
168701  int *pRc,
168702  Fts5Buffer *pBuf,
168703  char *zFmt, ...
168704){
168705  if( *pRc==SQLITE_OK ){
168706    char *zTmp;
168707    va_list ap;
168708    va_start(ap, zFmt);
168709    zTmp = sqlite3_vmprintf(zFmt, ap);
168710    va_end(ap);
168711
168712    if( zTmp==0 ){
168713      *pRc = SQLITE_NOMEM;
168714    }else{
168715      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
168716      sqlite3_free(zTmp);
168717    }
168718  }
168719}
168720
168721static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
168722  char *zRet = 0;
168723  if( *pRc==SQLITE_OK ){
168724    va_list ap;
168725    va_start(ap, zFmt);
168726    zRet = sqlite3_vmprintf(zFmt, ap);
168727    va_end(ap);
168728    if( zRet==0 ){
168729      *pRc = SQLITE_NOMEM;
168730    }
168731  }
168732  return zRet;
168733}
168734
168735
168736/*
168737** Free any buffer allocated by pBuf. Zero the structure before returning.
168738*/
168739static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
168740  sqlite3_free(pBuf->p);
168741  memset(pBuf, 0, sizeof(Fts5Buffer));
168742}
168743
168744/*
168745** Zero the contents of the buffer object. But do not free the associated
168746** memory allocation.
168747*/
168748static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
168749  pBuf->n = 0;
168750}
168751
168752/*
168753** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
168754** the error code in p. If an error has already occurred when this function
168755** is called, it is a no-op.
168756*/
168757static void sqlite3Fts5BufferSet(
168758  int *pRc,
168759  Fts5Buffer *pBuf,
168760  int nData,
168761  const u8 *pData
168762){
168763  pBuf->n = 0;
168764  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
168765}
168766
168767static int sqlite3Fts5PoslistNext64(
168768  const u8 *a, int n,             /* Buffer containing poslist */
168769  int *pi,                        /* IN/OUT: Offset within a[] */
168770  i64 *piOff                      /* IN/OUT: Current offset */
168771){
168772  int i = *pi;
168773  if( i>=n ){
168774    /* EOF */
168775    *piOff = -1;
168776    return 1;
168777  }else{
168778    i64 iOff = *piOff;
168779    int iVal;
168780    fts5FastGetVarint32(a, i, iVal);
168781    if( iVal==1 ){
168782      fts5FastGetVarint32(a, i, iVal);
168783      iOff = ((i64)iVal) << 32;
168784      fts5FastGetVarint32(a, i, iVal);
168785    }
168786    *piOff = iOff + (iVal-2);
168787    *pi = i;
168788    return 0;
168789  }
168790}
168791
168792
168793/*
168794** Advance the iterator object passed as the only argument. Return true
168795** if the iterator reaches EOF, or false otherwise.
168796*/
168797static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
168798  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
168799    pIter->bEof = 1;
168800  }
168801  return pIter->bEof;
168802}
168803
168804static int sqlite3Fts5PoslistReaderInit(
168805  const u8 *a, int n,             /* Poslist buffer to iterate through */
168806  Fts5PoslistReader *pIter        /* Iterator object to initialize */
168807){
168808  memset(pIter, 0, sizeof(*pIter));
168809  pIter->a = a;
168810  pIter->n = n;
168811  sqlite3Fts5PoslistReaderNext(pIter);
168812  return pIter->bEof;
168813}
168814
168815static int sqlite3Fts5PoslistWriterAppend(
168816  Fts5Buffer *pBuf,
168817  Fts5PoslistWriter *pWriter,
168818  i64 iPos
168819){
168820  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
168821  int rc = SQLITE_OK;
168822  if( 0==sqlite3Fts5BufferGrow(&rc, pBuf, 5+5+5) ){
168823    if( (iPos & colmask) != (pWriter->iPrev & colmask) ){
168824      pBuf->p[pBuf->n++] = 1;
168825      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
168826      pWriter->iPrev = (iPos & colmask);
168827    }
168828    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-pWriter->iPrev)+2);
168829    pWriter->iPrev = iPos;
168830  }
168831  return rc;
168832}
168833
168834static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
168835  void *pRet = 0;
168836  if( *pRc==SQLITE_OK ){
168837    pRet = sqlite3_malloc(nByte);
168838    if( pRet==0 && nByte>0 ){
168839      *pRc = SQLITE_NOMEM;
168840    }else{
168841      memset(pRet, 0, nByte);
168842    }
168843  }
168844  return pRet;
168845}
168846
168847/*
168848** Return a nul-terminated copy of the string indicated by pIn. If nIn
168849** is non-negative, then it is the length of the string in bytes. Otherwise,
168850** the length of the string is determined using strlen().
168851**
168852** It is the responsibility of the caller to eventually free the returned
168853** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
168854*/
168855static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
168856  char *zRet = 0;
168857  if( *pRc==SQLITE_OK ){
168858    if( nIn<0 ){
168859      nIn = strlen(pIn);
168860    }
168861    zRet = (char*)sqlite3_malloc(nIn+1);
168862    if( zRet ){
168863      memcpy(zRet, pIn, nIn);
168864      zRet[nIn] = '\0';
168865    }else{
168866      *pRc = SQLITE_NOMEM;
168867    }
168868  }
168869  return zRet;
168870}
168871
168872
168873/*
168874** Return true if character 't' may be part of an FTS5 bareword, or false
168875** otherwise. Characters that may be part of barewords:
168876**
168877**   * All non-ASCII characters,
168878**   * The 52 upper and lower case ASCII characters, and
168879**   * The 10 integer ASCII characters.
168880**   * The underscore character "_" (0x5F).
168881**   * The unicode "subsitute" character (0x1A).
168882*/
168883static int sqlite3Fts5IsBareword(char t){
168884  u8 aBareword[128] = {
168885    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
168886    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
168887    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
168888    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
168889    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
168890    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
168891    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
168892    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
168893  };
168894
168895  return (t & 0x80) || aBareword[(int)t];
168896}
168897
168898
168899
168900/*
168901** 2014 Jun 09
168902**
168903** The author disclaims copyright to this source code.  In place of
168904** a legal notice, here is a blessing:
168905**
168906**    May you do good and not evil.
168907**    May you find forgiveness for yourself and forgive others.
168908**    May you share freely, never taking more than you give.
168909**
168910******************************************************************************
168911**
168912** This is an SQLite module implementing full-text search.
168913*/
168914
168915
168916
168917
168918#define FTS5_DEFAULT_PAGE_SIZE   4050
168919#define FTS5_DEFAULT_AUTOMERGE      4
168920#define FTS5_DEFAULT_CRISISMERGE   16
168921
168922/* Maximum allowed page size */
168923#define FTS5_MAX_PAGE_SIZE (128*1024)
168924
168925static int fts5_iswhitespace(char x){
168926  return (x==' ');
168927}
168928
168929static int fts5_isopenquote(char x){
168930  return (x=='"' || x=='\'' || x=='[' || x=='`');
168931}
168932
168933/*
168934** Argument pIn points to a character that is part of a nul-terminated
168935** string. Return a pointer to the first character following *pIn in
168936** the string that is not a white-space character.
168937*/
168938static const char *fts5ConfigSkipWhitespace(const char *pIn){
168939  const char *p = pIn;
168940  if( p ){
168941    while( fts5_iswhitespace(*p) ){ p++; }
168942  }
168943  return p;
168944}
168945
168946/*
168947** Argument pIn points to a character that is part of a nul-terminated
168948** string. Return a pointer to the first character following *pIn in
168949** the string that is not a "bareword" character.
168950*/
168951static const char *fts5ConfigSkipBareword(const char *pIn){
168952  const char *p = pIn;
168953  while ( sqlite3Fts5IsBareword(*p) ) p++;
168954  if( p==pIn ) p = 0;
168955  return p;
168956}
168957
168958static int fts5_isdigit(char a){
168959  return (a>='0' && a<='9');
168960}
168961
168962
168963
168964static const char *fts5ConfigSkipLiteral(const char *pIn){
168965  const char *p = pIn;
168966  switch( *p ){
168967    case 'n': case 'N':
168968      if( sqlite3_strnicmp("null", p, 4)==0 ){
168969        p = &p[4];
168970      }else{
168971        p = 0;
168972      }
168973      break;
168974
168975    case 'x': case 'X':
168976      p++;
168977      if( *p=='\'' ){
168978        p++;
168979        while( (*p>='a' && *p<='f')
168980            || (*p>='A' && *p<='F')
168981            || (*p>='0' && *p<='9')
168982            ){
168983          p++;
168984        }
168985        if( *p=='\'' && 0==((p-pIn)%2) ){
168986          p++;
168987        }else{
168988          p = 0;
168989        }
168990      }else{
168991        p = 0;
168992      }
168993      break;
168994
168995    case '\'':
168996      p++;
168997      while( p ){
168998        if( *p=='\'' ){
168999          p++;
169000          if( *p!='\'' ) break;
169001        }
169002        p++;
169003        if( *p==0 ) p = 0;
169004      }
169005      break;
169006
169007    default:
169008      /* maybe a number */
169009      if( *p=='+' || *p=='-' ) p++;
169010      while( fts5_isdigit(*p) ) p++;
169011
169012      /* At this point, if the literal was an integer, the parse is
169013      ** finished. Or, if it is a floating point value, it may continue
169014      ** with either a decimal point or an 'E' character. */
169015      if( *p=='.' && fts5_isdigit(p[1]) ){
169016        p += 2;
169017        while( fts5_isdigit(*p) ) p++;
169018      }
169019      if( p==pIn ) p = 0;
169020
169021      break;
169022  }
169023
169024  return p;
169025}
169026
169027/*
169028** The first character of the string pointed to by argument z is guaranteed
169029** to be an open-quote character (see function fts5_isopenquote()).
169030**
169031** This function searches for the corresponding close-quote character within
169032** the string and, if found, dequotes the string in place and adds a new
169033** nul-terminator byte.
169034**
169035** If the close-quote is found, the value returned is the byte offset of
169036** the character immediately following it. Or, if the close-quote is not
169037** found, -1 is returned. If -1 is returned, the buffer is left in an
169038** undefined state.
169039*/
169040static int fts5Dequote(char *z){
169041  char q;
169042  int iIn = 1;
169043  int iOut = 0;
169044  q = z[0];
169045
169046  /* Set stack variable q to the close-quote character */
169047  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
169048  if( q=='[' ) q = ']';
169049
169050  while( ALWAYS(z[iIn]) ){
169051    if( z[iIn]==q ){
169052      if( z[iIn+1]!=q ){
169053        /* Character iIn was the close quote. */
169054        iIn++;
169055        break;
169056      }else{
169057        /* Character iIn and iIn+1 form an escaped quote character. Skip
169058        ** the input cursor past both and copy a single quote character
169059        ** to the output buffer. */
169060        iIn += 2;
169061        z[iOut++] = q;
169062      }
169063    }else{
169064      z[iOut++] = z[iIn++];
169065    }
169066  }
169067
169068  z[iOut] = '\0';
169069  return iIn;
169070}
169071
169072/*
169073** Convert an SQL-style quoted string into a normal string by removing
169074** the quote characters.  The conversion is done in-place.  If the
169075** input does not begin with a quote character, then this routine
169076** is a no-op.
169077**
169078** Examples:
169079**
169080**     "abc"   becomes   abc
169081**     'xyz'   becomes   xyz
169082**     [pqr]   becomes   pqr
169083**     `mno`   becomes   mno
169084*/
169085static void sqlite3Fts5Dequote(char *z){
169086  char quote;                     /* Quote character (if any ) */
169087
169088  assert( 0==fts5_iswhitespace(z[0]) );
169089  quote = z[0];
169090  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
169091    fts5Dequote(z);
169092  }
169093}
169094
169095/*
169096** Parse a "special" CREATE VIRTUAL TABLE directive and update
169097** configuration object pConfig as appropriate.
169098**
169099** If successful, object pConfig is updated and SQLITE_OK returned. If
169100** an error occurs, an SQLite error code is returned and an error message
169101** may be left in *pzErr. It is the responsibility of the caller to
169102** eventually free any such error message using sqlite3_free().
169103*/
169104static int fts5ConfigParseSpecial(
169105  Fts5Global *pGlobal,
169106  Fts5Config *pConfig,            /* Configuration object to update */
169107  const char *zCmd,               /* Special command to parse */
169108  const char *zArg,               /* Argument to parse */
169109  char **pzErr                    /* OUT: Error message */
169110){
169111  int rc = SQLITE_OK;
169112  int nCmd = strlen(zCmd);
169113  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
169114    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
169115    const char *p;
169116    if( pConfig->aPrefix ){
169117      *pzErr = sqlite3_mprintf("multiple prefix=... directives");
169118      rc = SQLITE_ERROR;
169119    }else{
169120      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
169121    }
169122    p = zArg;
169123    while( rc==SQLITE_OK && p[0] ){
169124      int nPre = 0;
169125      while( p[0]==' ' ) p++;
169126      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
169127        nPre = nPre*10 + (p[0] - '0');
169128        p++;
169129      }
169130      while( p[0]==' ' ) p++;
169131      if( p[0]==',' ){
169132        p++;
169133      }else if( p[0] ){
169134        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
169135        rc = SQLITE_ERROR;
169136      }
169137      if( rc==SQLITE_OK && (nPre==0 || nPre>=1000) ){
169138        *pzErr = sqlite3_mprintf("prefix length out of range: %d", nPre);
169139        rc = SQLITE_ERROR;
169140      }
169141      pConfig->aPrefix[pConfig->nPrefix] = nPre;
169142      pConfig->nPrefix++;
169143    }
169144    return rc;
169145  }
169146
169147  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
169148    const char *p = (const char*)zArg;
169149    int nArg = strlen(zArg) + 1;
169150    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
169151    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
169152    char *pSpace = pDel;
169153
169154    if( azArg && pSpace ){
169155      if( pConfig->pTok ){
169156        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
169157        rc = SQLITE_ERROR;
169158      }else{
169159        for(nArg=0; p && *p; nArg++){
169160          const char *p2 = fts5ConfigSkipWhitespace(p);
169161          if( *p2=='\'' ){
169162            p = fts5ConfigSkipLiteral(p2);
169163          }else{
169164            p = fts5ConfigSkipBareword(p2);
169165          }
169166          if( p ){
169167            memcpy(pSpace, p2, p-p2);
169168            azArg[nArg] = pSpace;
169169            sqlite3Fts5Dequote(pSpace);
169170            pSpace += (p - p2) + 1;
169171            p = fts5ConfigSkipWhitespace(p);
169172          }
169173        }
169174        if( p==0 ){
169175          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
169176          rc = SQLITE_ERROR;
169177        }else{
169178          rc = sqlite3Fts5GetTokenizer(pGlobal,
169179              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
169180              pzErr
169181          );
169182        }
169183      }
169184    }
169185
169186    sqlite3_free(azArg);
169187    sqlite3_free(pDel);
169188    return rc;
169189  }
169190
169191  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
169192    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
169193      *pzErr = sqlite3_mprintf("multiple content=... directives");
169194      rc = SQLITE_ERROR;
169195    }else{
169196      if( zArg[0] ){
169197        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
169198        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
169199      }else{
169200        pConfig->eContent = FTS5_CONTENT_NONE;
169201      }
169202    }
169203    return rc;
169204  }
169205
169206  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
169207    if( pConfig->zContentRowid ){
169208      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
169209      rc = SQLITE_ERROR;
169210    }else{
169211      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
169212    }
169213    return rc;
169214  }
169215
169216  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
169217    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
169218      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
169219      rc = SQLITE_ERROR;
169220    }else{
169221      pConfig->bColumnsize = (zArg[0]=='1');
169222    }
169223    return rc;
169224  }
169225
169226  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
169227  return SQLITE_ERROR;
169228}
169229
169230/*
169231** Allocate an instance of the default tokenizer ("simple") at
169232** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
169233** code if an error occurs.
169234*/
169235static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
169236  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
169237  return sqlite3Fts5GetTokenizer(
169238      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
169239  );
169240}
169241
169242/*
169243** Gobble up the first bareword or quoted word from the input buffer zIn.
169244** Return a pointer to the character immediately following the last in
169245** the gobbled word if successful, or a NULL pointer otherwise (failed
169246** to find close-quote character).
169247**
169248** Before returning, set pzOut to point to a new buffer containing a
169249** nul-terminated, dequoted copy of the gobbled word. If the word was
169250** quoted, *pbQuoted is also set to 1 before returning.
169251**
169252** If *pRc is other than SQLITE_OK when this function is called, it is
169253** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
169254** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
169255** set if a parse error (failed to find close quote) occurs.
169256*/
169257static const char *fts5ConfigGobbleWord(
169258  int *pRc,                       /* IN/OUT: Error code */
169259  const char *zIn,                /* Buffer to gobble string/bareword from */
169260  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
169261  int *pbQuoted                   /* OUT: Set to true if dequoting required */
169262){
169263  const char *zRet = 0;
169264
169265  int nIn = strlen(zIn);
169266  char *zOut = sqlite3_malloc(nIn+1);
169267
169268  assert( *pRc==SQLITE_OK );
169269  *pbQuoted = 0;
169270  *pzOut = 0;
169271
169272  if( zOut==0 ){
169273    *pRc = SQLITE_NOMEM;
169274  }else{
169275    memcpy(zOut, zIn, nIn+1);
169276    if( fts5_isopenquote(zOut[0]) ){
169277      int ii = fts5Dequote(zOut);
169278      zRet = &zIn[ii];
169279      *pbQuoted = 1;
169280    }else{
169281      zRet = fts5ConfigSkipBareword(zIn);
169282      zOut[zRet-zIn] = '\0';
169283    }
169284  }
169285
169286  if( zRet==0 ){
169287    sqlite3_free(zOut);
169288  }else{
169289    *pzOut = zOut;
169290  }
169291
169292  return zRet;
169293}
169294
169295static int fts5ConfigParseColumn(
169296  Fts5Config *p,
169297  char *zCol,
169298  char *zArg,
169299  char **pzErr
169300){
169301  int rc = SQLITE_OK;
169302  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
169303   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
169304  ){
169305    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
169306    rc = SQLITE_ERROR;
169307  }else if( zArg ){
169308    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
169309      p->abUnindexed[p->nCol] = 1;
169310    }else{
169311      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
169312      rc = SQLITE_ERROR;
169313    }
169314  }
169315
169316  p->azCol[p->nCol++] = zCol;
169317  return rc;
169318}
169319
169320/*
169321** Populate the Fts5Config.zContentExprlist string.
169322*/
169323static int fts5ConfigMakeExprlist(Fts5Config *p){
169324  int i;
169325  int rc = SQLITE_OK;
169326  Fts5Buffer buf = {0, 0, 0};
169327
169328  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
169329  if( p->eContent!=FTS5_CONTENT_NONE ){
169330    for(i=0; i<p->nCol; i++){
169331      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
169332        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
169333      }else{
169334        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
169335      }
169336    }
169337  }
169338
169339  assert( p->zContentExprlist==0 );
169340  p->zContentExprlist = (char*)buf.p;
169341  return rc;
169342}
169343
169344/*
169345** Arguments nArg/azArg contain the string arguments passed to the xCreate
169346** or xConnect method of the virtual table. This function attempts to
169347** allocate an instance of Fts5Config containing the results of parsing
169348** those arguments.
169349**
169350** If successful, SQLITE_OK is returned and *ppOut is set to point to the
169351** new Fts5Config object. If an error occurs, an SQLite error code is
169352** returned, *ppOut is set to NULL and an error message may be left in
169353** *pzErr. It is the responsibility of the caller to eventually free any
169354** such error message using sqlite3_free().
169355*/
169356static int sqlite3Fts5ConfigParse(
169357  Fts5Global *pGlobal,
169358  sqlite3 *db,
169359  int nArg,                       /* Number of arguments */
169360  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
169361  Fts5Config **ppOut,             /* OUT: Results of parse */
169362  char **pzErr                    /* OUT: Error message */
169363){
169364  int rc = SQLITE_OK;             /* Return code */
169365  Fts5Config *pRet;               /* New object to return */
169366  int i;
169367  int nByte;
169368
169369  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
169370  if( pRet==0 ) return SQLITE_NOMEM;
169371  memset(pRet, 0, sizeof(Fts5Config));
169372  pRet->db = db;
169373  pRet->iCookie = -1;
169374
169375  nByte = nArg * (sizeof(char*) + sizeof(u8));
169376  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
169377  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
169378  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
169379  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
169380  pRet->bColumnsize = 1;
169381#ifdef SQLITE_DEBUG
169382  pRet->bPrefixIndex = 1;
169383#endif
169384  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
169385    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
169386    rc = SQLITE_ERROR;
169387  }
169388
169389  for(i=3; rc==SQLITE_OK && i<nArg; i++){
169390    const char *zOrig = azArg[i];
169391    const char *z;
169392    char *zOne = 0;
169393    char *zTwo = 0;
169394    int bOption = 0;
169395    int bMustBeCol = 0;
169396
169397    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
169398    z = fts5ConfigSkipWhitespace(z);
169399    if( z && *z=='=' ){
169400      bOption = 1;
169401      z++;
169402      if( bMustBeCol ) z = 0;
169403    }
169404    z = fts5ConfigSkipWhitespace(z);
169405    if( z && z[0] ){
169406      int bDummy;
169407      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
169408      if( z && z[0] ) z = 0;
169409    }
169410
169411    if( rc==SQLITE_OK ){
169412      if( z==0 ){
169413        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
169414        rc = SQLITE_ERROR;
169415      }else{
169416        if( bOption ){
169417          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
169418        }else{
169419          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
169420          zOne = 0;
169421        }
169422      }
169423    }
169424
169425    sqlite3_free(zOne);
169426    sqlite3_free(zTwo);
169427  }
169428
169429  /* If a tokenizer= option was successfully parsed, the tokenizer has
169430  ** already been allocated. Otherwise, allocate an instance of the default
169431  ** tokenizer (unicode61) now.  */
169432  if( rc==SQLITE_OK && pRet->pTok==0 ){
169433    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
169434  }
169435
169436  /* If no zContent option was specified, fill in the default values. */
169437  if( rc==SQLITE_OK && pRet->zContent==0 ){
169438    const char *zTail = 0;
169439    assert( pRet->eContent==FTS5_CONTENT_NORMAL
169440         || pRet->eContent==FTS5_CONTENT_NONE
169441    );
169442    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
169443      zTail = "content";
169444    }else if( pRet->bColumnsize ){
169445      zTail = "docsize";
169446    }
169447
169448    if( zTail ){
169449      pRet->zContent = sqlite3Fts5Mprintf(
169450          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
169451      );
169452    }
169453  }
169454
169455  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
169456    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
169457  }
169458
169459  /* Formulate the zContentExprlist text */
169460  if( rc==SQLITE_OK ){
169461    rc = fts5ConfigMakeExprlist(pRet);
169462  }
169463
169464  if( rc!=SQLITE_OK ){
169465    sqlite3Fts5ConfigFree(pRet);
169466    *ppOut = 0;
169467  }
169468  return rc;
169469}
169470
169471/*
169472** Free the configuration object passed as the only argument.
169473*/
169474static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
169475  if( pConfig ){
169476    int i;
169477    if( pConfig->pTok ){
169478      pConfig->pTokApi->xDelete(pConfig->pTok);
169479    }
169480    sqlite3_free(pConfig->zDb);
169481    sqlite3_free(pConfig->zName);
169482    for(i=0; i<pConfig->nCol; i++){
169483      sqlite3_free(pConfig->azCol[i]);
169484    }
169485    sqlite3_free(pConfig->azCol);
169486    sqlite3_free(pConfig->aPrefix);
169487    sqlite3_free(pConfig->zRank);
169488    sqlite3_free(pConfig->zRankArgs);
169489    sqlite3_free(pConfig->zContent);
169490    sqlite3_free(pConfig->zContentRowid);
169491    sqlite3_free(pConfig->zContentExprlist);
169492    sqlite3_free(pConfig);
169493  }
169494}
169495
169496/*
169497** Call sqlite3_declare_vtab() based on the contents of the configuration
169498** object passed as the only argument. Return SQLITE_OK if successful, or
169499** an SQLite error code if an error occurs.
169500*/
169501static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
169502  int i;
169503  int rc = SQLITE_OK;
169504  char *zSql;
169505
169506  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
169507  for(i=0; zSql && i<pConfig->nCol; i++){
169508    const char *zSep = (i==0?"":", ");
169509    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
169510  }
169511  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
169512      zSql, pConfig->zName, FTS5_RANK_NAME
169513  );
169514
169515  assert( zSql || rc==SQLITE_NOMEM );
169516  if( zSql ){
169517    rc = sqlite3_declare_vtab(pConfig->db, zSql);
169518    sqlite3_free(zSql);
169519  }
169520
169521  return rc;
169522}
169523
169524/*
169525** Tokenize the text passed via the second and third arguments.
169526**
169527** The callback is invoked once for each token in the input text. The
169528** arguments passed to it are, in order:
169529**
169530**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
169531**     const char *pToken  // Pointer to buffer containing token
169532**     int nToken          // Size of token in bytes
169533**     int iStart          // Byte offset of start of token within input text
169534**     int iEnd            // Byte offset of end of token within input text
169535**     int iPos            // Position of token in input (first token is 0)
169536**
169537** If the callback returns a non-zero value the tokenization is abandoned
169538** and no further callbacks are issued.
169539**
169540** This function returns SQLITE_OK if successful or an SQLite error code
169541** if an error occurs. If the tokenization was abandoned early because
169542** the callback returned SQLITE_DONE, this is not an error and this function
169543** still returns SQLITE_OK. Or, if the tokenization was abandoned early
169544** because the callback returned another non-zero value, it is assumed
169545** to be an SQLite error code and returned to the caller.
169546*/
169547static int sqlite3Fts5Tokenize(
169548  Fts5Config *pConfig,            /* FTS5 Configuration object */
169549  int flags,                      /* FTS5_TOKENIZE_* flags */
169550  const char *pText, int nText,   /* Text to tokenize */
169551  void *pCtx,                     /* Context passed to xToken() */
169552  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
169553){
169554  if( pText==0 ) return SQLITE_OK;
169555  return pConfig->pTokApi->xTokenize(
169556      pConfig->pTok, pCtx, flags, pText, nText, xToken
169557  );
169558}
169559
169560/*
169561** Argument pIn points to the first character in what is expected to be
169562** a comma-separated list of SQL literals followed by a ')' character.
169563** If it actually is this, return a pointer to the ')'. Otherwise, return
169564** NULL to indicate a parse error.
169565*/
169566static const char *fts5ConfigSkipArgs(const char *pIn){
169567  const char *p = pIn;
169568
169569  while( 1 ){
169570    p = fts5ConfigSkipWhitespace(p);
169571    p = fts5ConfigSkipLiteral(p);
169572    p = fts5ConfigSkipWhitespace(p);
169573    if( p==0 || *p==')' ) break;
169574    if( *p!=',' ){
169575      p = 0;
169576      break;
169577    }
169578    p++;
169579  }
169580
169581  return p;
169582}
169583
169584/*
169585** Parameter zIn contains a rank() function specification. The format of
169586** this is:
169587**
169588**   + Bareword (function name)
169589**   + Open parenthesis - "("
169590**   + Zero or more SQL literals in a comma separated list
169591**   + Close parenthesis - ")"
169592*/
169593static int sqlite3Fts5ConfigParseRank(
169594  const char *zIn,                /* Input string */
169595  char **pzRank,                  /* OUT: Rank function name */
169596  char **pzRankArgs               /* OUT: Rank function arguments */
169597){
169598  const char *p = zIn;
169599  const char *pRank;
169600  char *zRank = 0;
169601  char *zRankArgs = 0;
169602  int rc = SQLITE_OK;
169603
169604  *pzRank = 0;
169605  *pzRankArgs = 0;
169606
169607  p = fts5ConfigSkipWhitespace(p);
169608  pRank = p;
169609  p = fts5ConfigSkipBareword(p);
169610
169611  if( p ){
169612    zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
169613    if( zRank ) memcpy(zRank, pRank, p-pRank);
169614  }else{
169615    rc = SQLITE_ERROR;
169616  }
169617
169618  if( rc==SQLITE_OK ){
169619    p = fts5ConfigSkipWhitespace(p);
169620    if( *p!='(' ) rc = SQLITE_ERROR;
169621    p++;
169622  }
169623  if( rc==SQLITE_OK ){
169624    const char *pArgs;
169625    p = fts5ConfigSkipWhitespace(p);
169626    pArgs = p;
169627    if( *p!=')' ){
169628      p = fts5ConfigSkipArgs(p);
169629      if( p==0 ){
169630        rc = SQLITE_ERROR;
169631      }else{
169632        zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
169633        if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
169634      }
169635    }
169636  }
169637
169638  if( rc!=SQLITE_OK ){
169639    sqlite3_free(zRank);
169640    assert( zRankArgs==0 );
169641  }else{
169642    *pzRank = zRank;
169643    *pzRankArgs = zRankArgs;
169644  }
169645  return rc;
169646}
169647
169648static int sqlite3Fts5ConfigSetValue(
169649  Fts5Config *pConfig,
169650  const char *zKey,
169651  sqlite3_value *pVal,
169652  int *pbBadkey
169653){
169654  int rc = SQLITE_OK;
169655
169656  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
169657    int pgsz = 0;
169658    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169659      pgsz = sqlite3_value_int(pVal);
169660    }
169661    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
169662      *pbBadkey = 1;
169663    }else{
169664      pConfig->pgsz = pgsz;
169665    }
169666  }
169667
169668  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
169669    int nAutomerge = -1;
169670    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169671      nAutomerge = sqlite3_value_int(pVal);
169672    }
169673    if( nAutomerge<0 || nAutomerge>64 ){
169674      *pbBadkey = 1;
169675    }else{
169676      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
169677      pConfig->nAutomerge = nAutomerge;
169678    }
169679  }
169680
169681  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
169682    int nCrisisMerge = -1;
169683    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169684      nCrisisMerge = sqlite3_value_int(pVal);
169685    }
169686    if( nCrisisMerge<0 ){
169687      *pbBadkey = 1;
169688    }else{
169689      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
169690      pConfig->nCrisisMerge = nCrisisMerge;
169691    }
169692  }
169693
169694  else if( 0==sqlite3_stricmp(zKey, "rank") ){
169695    const char *zIn = (const char*)sqlite3_value_text(pVal);
169696    char *zRank;
169697    char *zRankArgs;
169698    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
169699    if( rc==SQLITE_OK ){
169700      sqlite3_free(pConfig->zRank);
169701      sqlite3_free(pConfig->zRankArgs);
169702      pConfig->zRank = zRank;
169703      pConfig->zRankArgs = zRankArgs;
169704    }else if( rc==SQLITE_ERROR ){
169705      rc = SQLITE_OK;
169706      *pbBadkey = 1;
169707    }
169708  }else{
169709    *pbBadkey = 1;
169710  }
169711  return rc;
169712}
169713
169714/*
169715** Load the contents of the %_config table into memory.
169716*/
169717static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
169718  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
169719  char *zSql;
169720  sqlite3_stmt *p = 0;
169721  int rc = SQLITE_OK;
169722  int iVersion = 0;
169723
169724  /* Set default values */
169725  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
169726  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
169727  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
169728
169729  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
169730  if( zSql ){
169731    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
169732    sqlite3_free(zSql);
169733  }
169734
169735  assert( rc==SQLITE_OK || p==0 );
169736  if( rc==SQLITE_OK ){
169737    while( SQLITE_ROW==sqlite3_step(p) ){
169738      const char *zK = (const char*)sqlite3_column_text(p, 0);
169739      sqlite3_value *pVal = sqlite3_column_value(p, 1);
169740      if( 0==sqlite3_stricmp(zK, "version") ){
169741        iVersion = sqlite3_value_int(pVal);
169742      }else{
169743        int bDummy = 0;
169744        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
169745      }
169746    }
169747    rc = sqlite3_finalize(p);
169748  }
169749
169750  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
169751    rc = SQLITE_ERROR;
169752    if( pConfig->pzErrmsg ){
169753      assert( 0==*pConfig->pzErrmsg );
169754      *pConfig->pzErrmsg = sqlite3_mprintf(
169755          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
169756          iVersion, FTS5_CURRENT_VERSION
169757      );
169758    }
169759  }
169760
169761  if( rc==SQLITE_OK ){
169762    pConfig->iCookie = iCookie;
169763  }
169764  return rc;
169765}
169766
169767
169768/*
169769** 2014 May 31
169770**
169771** The author disclaims copyright to this source code.  In place of
169772** a legal notice, here is a blessing:
169773**
169774**    May you do good and not evil.
169775**    May you find forgiveness for yourself and forgive others.
169776**    May you share freely, never taking more than you give.
169777**
169778******************************************************************************
169779**
169780*/
169781
169782
169783
169784
169785/*
169786** All token types in the generated fts5parse.h file are greater than 0.
169787*/
169788#define FTS5_EOF 0
169789
169790#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
169791
169792typedef struct Fts5ExprTerm Fts5ExprTerm;
169793
169794/*
169795** Functions generated by lemon from fts5parse.y.
169796*/
169797static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
169798static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
169799static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
169800#ifndef NDEBUG
169801/* #include <stdio.h> */
169802static void sqlite3Fts5ParserTrace(FILE*, char*);
169803#endif
169804
169805
169806struct Fts5Expr {
169807  Fts5Index *pIndex;
169808  Fts5ExprNode *pRoot;
169809  int bDesc;                      /* Iterate in descending rowid order */
169810  int nPhrase;                    /* Number of phrases in expression */
169811  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
169812};
169813
169814/*
169815** eType:
169816**   Expression node type. Always one of:
169817**
169818**       FTS5_AND                 (nChild, apChild valid)
169819**       FTS5_OR                  (nChild, apChild valid)
169820**       FTS5_NOT                 (nChild, apChild valid)
169821**       FTS5_STRING              (pNear valid)
169822**       FTS5_TERM                (pNear valid)
169823*/
169824struct Fts5ExprNode {
169825  int eType;                      /* Node type */
169826  int bEof;                       /* True at EOF */
169827  int bNomatch;                   /* True if entry is not a match */
169828
169829  i64 iRowid;                     /* Current rowid */
169830  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
169831
169832  /* Child nodes. For a NOT node, this array always contains 2 entries. For
169833  ** AND or OR nodes, it contains 2 or more entries.  */
169834  int nChild;                     /* Number of child nodes */
169835  Fts5ExprNode *apChild[1];       /* Array of child nodes */
169836};
169837
169838#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
169839
169840/*
169841** An instance of the following structure represents a single search term
169842** or term prefix.
169843*/
169844struct Fts5ExprTerm {
169845  int bPrefix;                    /* True for a prefix term */
169846  char *zTerm;                    /* nul-terminated term */
169847  Fts5IndexIter *pIter;           /* Iterator for this term */
169848  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
169849};
169850
169851/*
169852** A phrase. One or more terms that must appear in a contiguous sequence
169853** within a document for it to match.
169854*/
169855struct Fts5ExprPhrase {
169856  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
169857  Fts5Buffer poslist;             /* Current position list */
169858  int nTerm;                      /* Number of entries in aTerm[] */
169859  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
169860};
169861
169862/*
169863** One or more phrases that must appear within a certain token distance of
169864** each other within each matching document.
169865*/
169866struct Fts5ExprNearset {
169867  int nNear;                      /* NEAR parameter */
169868  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
169869  int nPhrase;                    /* Number of entries in aPhrase[] array */
169870  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
169871};
169872
169873
169874/*
169875** Parse context.
169876*/
169877struct Fts5Parse {
169878  Fts5Config *pConfig;
169879  char *zErr;
169880  int rc;
169881  int nPhrase;                    /* Size of apPhrase array */
169882  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
169883  Fts5ExprNode *pExpr;            /* Result of a successful parse */
169884};
169885
169886static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
169887  va_list ap;
169888  va_start(ap, zFmt);
169889  if( pParse->rc==SQLITE_OK ){
169890    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
169891    pParse->rc = SQLITE_ERROR;
169892  }
169893  va_end(ap);
169894}
169895
169896static int fts5ExprIsspace(char t){
169897  return t==' ' || t=='\t' || t=='\n' || t=='\r';
169898}
169899
169900/*
169901** Read the first token from the nul-terminated string at *pz.
169902*/
169903static int fts5ExprGetToken(
169904  Fts5Parse *pParse,
169905  const char **pz,                /* IN/OUT: Pointer into buffer */
169906  Fts5Token *pToken
169907){
169908  const char *z = *pz;
169909  int tok;
169910
169911  /* Skip past any whitespace */
169912  while( fts5ExprIsspace(*z) ) z++;
169913
169914  pToken->p = z;
169915  pToken->n = 1;
169916  switch( *z ){
169917    case '(':  tok = FTS5_LP;    break;
169918    case ')':  tok = FTS5_RP;    break;
169919    case '{':  tok = FTS5_LCP;   break;
169920    case '}':  tok = FTS5_RCP;   break;
169921    case ':':  tok = FTS5_COLON; break;
169922    case ',':  tok = FTS5_COMMA; break;
169923    case '+':  tok = FTS5_PLUS;  break;
169924    case '*':  tok = FTS5_STAR;  break;
169925    case '\0': tok = FTS5_EOF;   break;
169926
169927    case '"': {
169928      const char *z2;
169929      tok = FTS5_STRING;
169930
169931      for(z2=&z[1]; 1; z2++){
169932        if( z2[0]=='"' ){
169933          z2++;
169934          if( z2[0]!='"' ) break;
169935        }
169936        if( z2[0]=='\0' ){
169937          sqlite3Fts5ParseError(pParse, "unterminated string");
169938          return FTS5_EOF;
169939        }
169940      }
169941      pToken->n = (z2 - z);
169942      break;
169943    }
169944
169945    default: {
169946      const char *z2;
169947      if( sqlite3Fts5IsBareword(z[0])==0 ){
169948        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
169949        return FTS5_EOF;
169950      }
169951      tok = FTS5_STRING;
169952      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
169953      pToken->n = (z2 - z);
169954      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
169955      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
169956      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
169957      break;
169958    }
169959  }
169960
169961  *pz = &pToken->p[pToken->n];
169962  return tok;
169963}
169964
169965static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
169966static void fts5ParseFree(void *p){ sqlite3_free(p); }
169967
169968static int sqlite3Fts5ExprNew(
169969  Fts5Config *pConfig,            /* FTS5 Configuration */
169970  const char *zExpr,              /* Expression text */
169971  Fts5Expr **ppNew,
169972  char **pzErr
169973){
169974  Fts5Parse sParse;
169975  Fts5Token token;
169976  const char *z = zExpr;
169977  int t;                          /* Next token type */
169978  void *pEngine;
169979  Fts5Expr *pNew;
169980
169981  *ppNew = 0;
169982  *pzErr = 0;
169983  memset(&sParse, 0, sizeof(sParse));
169984  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
169985  if( pEngine==0 ){ return SQLITE_NOMEM; }
169986  sParse.pConfig = pConfig;
169987
169988  do {
169989    t = fts5ExprGetToken(&sParse, &z, &token);
169990    sqlite3Fts5Parser(pEngine, t, token, &sParse);
169991  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
169992  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
169993
169994  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
169995  if( sParse.rc==SQLITE_OK ){
169996    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
169997    if( pNew==0 ){
169998      sParse.rc = SQLITE_NOMEM;
169999      sqlite3Fts5ParseNodeFree(sParse.pExpr);
170000    }else{
170001      pNew->pRoot = sParse.pExpr;
170002      pNew->pIndex = 0;
170003      pNew->apExprPhrase = sParse.apPhrase;
170004      pNew->nPhrase = sParse.nPhrase;
170005      sParse.apPhrase = 0;
170006    }
170007  }
170008
170009  sqlite3_free(sParse.apPhrase);
170010  *pzErr = sParse.zErr;
170011  return sParse.rc;
170012}
170013
170014/*
170015** Free the expression node object passed as the only argument.
170016*/
170017static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
170018  if( p ){
170019    int i;
170020    for(i=0; i<p->nChild; i++){
170021      sqlite3Fts5ParseNodeFree(p->apChild[i]);
170022    }
170023    sqlite3Fts5ParseNearsetFree(p->pNear);
170024    sqlite3_free(p);
170025  }
170026}
170027
170028/*
170029** Free the expression object passed as the only argument.
170030*/
170031static void sqlite3Fts5ExprFree(Fts5Expr *p){
170032  if( p ){
170033    sqlite3Fts5ParseNodeFree(p->pRoot);
170034    sqlite3_free(p->apExprPhrase);
170035    sqlite3_free(p);
170036  }
170037}
170038
170039/*
170040** Argument pTerm must be a synonym iterator. Return the current rowid
170041** that it points to.
170042*/
170043static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
170044  i64 iRet = 0;
170045  int bRetValid = 0;
170046  Fts5ExprTerm *p;
170047
170048  assert( pTerm->pSynonym );
170049  assert( bDesc==0 || bDesc==1 );
170050  for(p=pTerm; p; p=p->pSynonym){
170051    if( 0==sqlite3Fts5IterEof(p->pIter) ){
170052      i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
170053      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
170054        iRet = iRowid;
170055        bRetValid = 1;
170056      }
170057    }
170058  }
170059
170060  if( pbEof && bRetValid==0 ) *pbEof = 1;
170061  return iRet;
170062}
170063
170064/*
170065** Argument pTerm must be a synonym iterator.
170066*/
170067static int fts5ExprSynonymPoslist(
170068  Fts5ExprTerm *pTerm,
170069  Fts5Colset *pColset,
170070  i64 iRowid,
170071  int *pbDel,                     /* OUT: Caller should sqlite3_free(*pa) */
170072  u8 **pa, int *pn
170073){
170074  Fts5PoslistReader aStatic[4];
170075  Fts5PoslistReader *aIter = aStatic;
170076  int nIter = 0;
170077  int nAlloc = 4;
170078  int rc = SQLITE_OK;
170079  Fts5ExprTerm *p;
170080
170081  assert( pTerm->pSynonym );
170082  for(p=pTerm; p; p=p->pSynonym){
170083    Fts5IndexIter *pIter = p->pIter;
170084    if( sqlite3Fts5IterEof(pIter)==0 && sqlite3Fts5IterRowid(pIter)==iRowid ){
170085      const u8 *a;
170086      int n;
170087      i64 dummy;
170088      rc = sqlite3Fts5IterPoslist(pIter, pColset, &a, &n, &dummy);
170089      if( rc!=SQLITE_OK ) goto synonym_poslist_out;
170090      if( nIter==nAlloc ){
170091        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
170092        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
170093        if( aNew==0 ){
170094          rc = SQLITE_NOMEM;
170095          goto synonym_poslist_out;
170096        }
170097        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
170098        nAlloc = nAlloc*2;
170099        if( aIter!=aStatic ) sqlite3_free(aIter);
170100        aIter = aNew;
170101      }
170102      sqlite3Fts5PoslistReaderInit(a, n, &aIter[nIter]);
170103      assert( aIter[nIter].bEof==0 );
170104      nIter++;
170105    }
170106  }
170107
170108  assert( *pbDel==0 );
170109  if( nIter==1 ){
170110    *pa = (u8*)aIter[0].a;
170111    *pn = aIter[0].n;
170112  }else{
170113    Fts5PoslistWriter writer = {0};
170114    Fts5Buffer buf = {0,0,0};
170115    i64 iPrev = -1;
170116    while( 1 ){
170117      int i;
170118      i64 iMin = FTS5_LARGEST_INT64;
170119      for(i=0; i<nIter; i++){
170120        if( aIter[i].bEof==0 ){
170121          if( aIter[i].iPos==iPrev ){
170122            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
170123          }
170124          if( aIter[i].iPos<iMin ){
170125            iMin = aIter[i].iPos;
170126          }
170127        }
170128      }
170129      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
170130      rc = sqlite3Fts5PoslistWriterAppend(&buf, &writer, iMin);
170131      iPrev = iMin;
170132    }
170133    if( rc ){
170134      sqlite3_free(buf.p);
170135    }else{
170136      *pa = buf.p;
170137      *pn = buf.n;
170138      *pbDel = 1;
170139    }
170140  }
170141
170142 synonym_poslist_out:
170143  if( aIter!=aStatic ) sqlite3_free(aIter);
170144  return rc;
170145}
170146
170147
170148/*
170149** All individual term iterators in pPhrase are guaranteed to be valid and
170150** pointing to the same rowid when this function is called. This function
170151** checks if the current rowid really is a match, and if so populates
170152** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
170153** is set to true if this is really a match, or false otherwise.
170154**
170155** SQLITE_OK is returned if an error occurs, or an SQLite error code
170156** otherwise. It is not considered an error code if the current rowid is
170157** not a match.
170158*/
170159static int fts5ExprPhraseIsMatch(
170160  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
170161  Fts5Colset *pColset,            /* Restrict matches to these columns */
170162  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
170163  int *pbMatch                    /* OUT: Set to true if really a match */
170164){
170165  Fts5PoslistWriter writer = {0};
170166  Fts5PoslistReader aStatic[4];
170167  Fts5PoslistReader *aIter = aStatic;
170168  int i;
170169  int rc = SQLITE_OK;
170170
170171  fts5BufferZero(&pPhrase->poslist);
170172
170173  /* If the aStatic[] array is not large enough, allocate a large array
170174  ** using sqlite3_malloc(). This approach could be improved upon. */
170175  if( pPhrase->nTerm>(sizeof(aStatic) / sizeof(aStatic[0])) ){
170176    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
170177    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
170178    if( !aIter ) return SQLITE_NOMEM;
170179  }
170180  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
170181
170182  /* Initialize a term iterator for each term in the phrase */
170183  for(i=0; i<pPhrase->nTerm; i++){
170184    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
170185    i64 dummy;
170186    int n = 0;
170187    int bFlag = 0;
170188    const u8 *a = 0;
170189    if( pTerm->pSynonym ){
170190      rc = fts5ExprSynonymPoslist(
170191          pTerm, pColset, pNode->iRowid, &bFlag, (u8**)&a, &n
170192      );
170193    }else{
170194      rc = sqlite3Fts5IterPoslist(pTerm->pIter, pColset, &a, &n, &dummy);
170195    }
170196    if( rc!=SQLITE_OK ) goto ismatch_out;
170197    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
170198    aIter[i].bFlag = bFlag;
170199    if( aIter[i].bEof ) goto ismatch_out;
170200  }
170201
170202  while( 1 ){
170203    int bMatch;
170204    i64 iPos = aIter[0].iPos;
170205    do {
170206      bMatch = 1;
170207      for(i=0; i<pPhrase->nTerm; i++){
170208        Fts5PoslistReader *pPos = &aIter[i];
170209        i64 iAdj = iPos + i;
170210        if( pPos->iPos!=iAdj ){
170211          bMatch = 0;
170212          while( pPos->iPos<iAdj ){
170213            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
170214          }
170215          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
170216        }
170217      }
170218    }while( bMatch==0 );
170219
170220    /* Append position iPos to the output */
170221    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
170222    if( rc!=SQLITE_OK ) goto ismatch_out;
170223
170224    for(i=0; i<pPhrase->nTerm; i++){
170225      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
170226    }
170227  }
170228
170229 ismatch_out:
170230  *pbMatch = (pPhrase->poslist.n>0);
170231  for(i=0; i<pPhrase->nTerm; i++){
170232    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
170233  }
170234  if( aIter!=aStatic ) sqlite3_free(aIter);
170235  return rc;
170236}
170237
170238typedef struct Fts5LookaheadReader Fts5LookaheadReader;
170239struct Fts5LookaheadReader {
170240  const u8 *a;                    /* Buffer containing position list */
170241  int n;                          /* Size of buffer a[] in bytes */
170242  int i;                          /* Current offset in position list */
170243  i64 iPos;                       /* Current position */
170244  i64 iLookahead;                 /* Next position */
170245};
170246
170247#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
170248
170249static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
170250  p->iPos = p->iLookahead;
170251  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
170252    p->iLookahead = FTS5_LOOKAHEAD_EOF;
170253  }
170254  return (p->iPos==FTS5_LOOKAHEAD_EOF);
170255}
170256
170257static int fts5LookaheadReaderInit(
170258  const u8 *a, int n,             /* Buffer to read position list from */
170259  Fts5LookaheadReader *p          /* Iterator object to initialize */
170260){
170261  memset(p, 0, sizeof(Fts5LookaheadReader));
170262  p->a = a;
170263  p->n = n;
170264  fts5LookaheadReaderNext(p);
170265  return fts5LookaheadReaderNext(p);
170266}
170267
170268#if 0
170269static int fts5LookaheadReaderEof(Fts5LookaheadReader *p){
170270  return (p->iPos==FTS5_LOOKAHEAD_EOF);
170271}
170272#endif
170273
170274typedef struct Fts5NearTrimmer Fts5NearTrimmer;
170275struct Fts5NearTrimmer {
170276  Fts5LookaheadReader reader;     /* Input iterator */
170277  Fts5PoslistWriter writer;       /* Writer context */
170278  Fts5Buffer *pOut;               /* Output poslist */
170279};
170280
170281/*
170282** The near-set object passed as the first argument contains more than
170283** one phrase. All phrases currently point to the same row. The
170284** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
170285** tests if the current row contains instances of each phrase sufficiently
170286** close together to meet the NEAR constraint. Non-zero is returned if it
170287** does, or zero otherwise.
170288**
170289** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
170290** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
170291** occurs within this function (*pRc) is set accordingly before returning.
170292** The return value is undefined in both these cases.
170293**
170294** If no error occurs and non-zero (a match) is returned, the position-list
170295** of each phrase object is edited to contain only those entries that
170296** meet the constraint before returning.
170297*/
170298static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
170299  Fts5NearTrimmer aStatic[4];
170300  Fts5NearTrimmer *a = aStatic;
170301  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
170302
170303  int i;
170304  int rc = *pRc;
170305  int bMatch;
170306
170307  assert( pNear->nPhrase>1 );
170308
170309  /* If the aStatic[] array is not large enough, allocate a large array
170310  ** using sqlite3_malloc(). This approach could be improved upon. */
170311  if( pNear->nPhrase>(sizeof(aStatic) / sizeof(aStatic[0])) ){
170312    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
170313    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
170314  }else{
170315    memset(aStatic, 0, sizeof(aStatic));
170316  }
170317  if( rc!=SQLITE_OK ){
170318    *pRc = rc;
170319    return 0;
170320  }
170321
170322  /* Initialize a lookahead iterator for each phrase. After passing the
170323  ** buffer and buffer size to the lookaside-reader init function, zero
170324  ** the phrase poslist buffer. The new poslist for the phrase (containing
170325  ** the same entries as the original with some entries removed on account
170326  ** of the NEAR constraint) is written over the original even as it is
170327  ** being read. This is safe as the entries for the new poslist are a
170328  ** subset of the old, so it is not possible for data yet to be read to
170329  ** be overwritten.  */
170330  for(i=0; i<pNear->nPhrase; i++){
170331    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
170332    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
170333    pPoslist->n = 0;
170334    a[i].pOut = pPoslist;
170335  }
170336
170337  while( 1 ){
170338    int iAdv;
170339    i64 iMin;
170340    i64 iMax;
170341
170342    /* This block advances the phrase iterators until they point to a set of
170343    ** entries that together comprise a match.  */
170344    iMax = a[0].reader.iPos;
170345    do {
170346      bMatch = 1;
170347      for(i=0; i<pNear->nPhrase; i++){
170348        Fts5LookaheadReader *pPos = &a[i].reader;
170349        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
170350        if( pPos->iPos<iMin || pPos->iPos>iMax ){
170351          bMatch = 0;
170352          while( pPos->iPos<iMin ){
170353            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
170354          }
170355          if( pPos->iPos>iMax ) iMax = pPos->iPos;
170356        }
170357      }
170358    }while( bMatch==0 );
170359
170360    /* Add an entry to each output position list */
170361    for(i=0; i<pNear->nPhrase; i++){
170362      i64 iPos = a[i].reader.iPos;
170363      Fts5PoslistWriter *pWriter = &a[i].writer;
170364      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
170365        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
170366      }
170367    }
170368
170369    iAdv = 0;
170370    iMin = a[0].reader.iLookahead;
170371    for(i=0; i<pNear->nPhrase; i++){
170372      if( a[i].reader.iLookahead < iMin ){
170373        iMin = a[i].reader.iLookahead;
170374        iAdv = i;
170375      }
170376    }
170377    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
170378  }
170379
170380  ismatch_out: {
170381    int bRet = a[0].pOut->n>0;
170382    *pRc = rc;
170383    if( a!=aStatic ) sqlite3_free(a);
170384    return bRet;
170385  }
170386}
170387
170388/*
170389** Advance the first term iterator in the first phrase of pNear. Set output
170390** variable *pbEof to true if it reaches EOF or if an error occurs.
170391**
170392** Return SQLITE_OK if successful, or an SQLite error code if an error
170393** occurs.
170394*/
170395static int fts5ExprNearAdvanceFirst(
170396  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170397  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
170398  int bFromValid,
170399  i64 iFrom
170400){
170401  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
170402  int rc = SQLITE_OK;
170403
170404  if( pTerm->pSynonym ){
170405    int bEof = 1;
170406    Fts5ExprTerm *p;
170407
170408    /* Find the firstest rowid any synonym points to. */
170409    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
170410
170411    /* Advance each iterator that currently points to iRowid. Or, if iFrom
170412    ** is valid - each iterator that points to a rowid before iFrom.  */
170413    for(p=pTerm; p; p=p->pSynonym){
170414      if( sqlite3Fts5IterEof(p->pIter)==0 ){
170415        i64 ii = sqlite3Fts5IterRowid(p->pIter);
170416        if( ii==iRowid
170417         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
170418        ){
170419          if( bFromValid ){
170420            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
170421          }else{
170422            rc = sqlite3Fts5IterNext(p->pIter);
170423          }
170424          if( rc!=SQLITE_OK ) break;
170425          if( sqlite3Fts5IterEof(p->pIter)==0 ){
170426            bEof = 0;
170427          }
170428        }else{
170429          bEof = 0;
170430        }
170431      }
170432    }
170433
170434    /* Set the EOF flag if either all synonym iterators are at EOF or an
170435    ** error has occurred.  */
170436    pNode->bEof = (rc || bEof);
170437  }else{
170438    Fts5IndexIter *pIter = pTerm->pIter;
170439
170440    assert( Fts5NodeIsString(pNode) );
170441    if( bFromValid ){
170442      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
170443    }else{
170444      rc = sqlite3Fts5IterNext(pIter);
170445    }
170446
170447    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
170448  }
170449
170450  return rc;
170451}
170452
170453/*
170454** Advance iterator pIter until it points to a value equal to or laster
170455** than the initial value of *piLast. If this means the iterator points
170456** to a value laster than *piLast, update *piLast to the new lastest value.
170457**
170458** If the iterator reaches EOF, set *pbEof to true before returning. If
170459** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
170460** are set, return a non-zero value. Otherwise, return zero.
170461*/
170462static int fts5ExprAdvanceto(
170463  Fts5IndexIter *pIter,           /* Iterator to advance */
170464  int bDesc,                      /* True if iterator is "rowid DESC" */
170465  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
170466  int *pRc,                       /* OUT: Error code */
170467  int *pbEof                      /* OUT: Set to true if EOF */
170468){
170469  i64 iLast = *piLast;
170470  i64 iRowid;
170471
170472  iRowid = sqlite3Fts5IterRowid(pIter);
170473  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
170474    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
170475    if( rc || sqlite3Fts5IterEof(pIter) ){
170476      *pRc = rc;
170477      *pbEof = 1;
170478      return 1;
170479    }
170480    iRowid = sqlite3Fts5IterRowid(pIter);
170481    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
170482  }
170483  *piLast = iRowid;
170484
170485  return 0;
170486}
170487
170488static int fts5ExprSynonymAdvanceto(
170489  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
170490  int bDesc,                      /* True if iterator is "rowid DESC" */
170491  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
170492  int *pRc                        /* OUT: Error code */
170493){
170494  int rc = SQLITE_OK;
170495  i64 iLast = *piLast;
170496  Fts5ExprTerm *p;
170497  int bEof = 0;
170498
170499  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
170500    if( sqlite3Fts5IterEof(p->pIter)==0 ){
170501      i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
170502      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
170503        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
170504      }
170505    }
170506  }
170507
170508  if( rc!=SQLITE_OK ){
170509    *pRc = rc;
170510    bEof = 1;
170511  }else{
170512    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
170513  }
170514  return bEof;
170515}
170516
170517
170518static int fts5ExprNearTest(
170519  int *pRc,
170520  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
170521  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
170522){
170523  Fts5ExprNearset *pNear = pNode->pNear;
170524  int rc = *pRc;
170525  int i;
170526
170527  /* Check that each phrase in the nearset matches the current row.
170528  ** Populate the pPhrase->poslist buffers at the same time. If any
170529  ** phrase is not a match, break out of the loop early.  */
170530  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
170531    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170532    if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
170533      int bMatch = 0;
170534      rc = fts5ExprPhraseIsMatch(pNode, pNear->pColset, pPhrase, &bMatch);
170535      if( bMatch==0 ) break;
170536    }else{
170537      rc = sqlite3Fts5IterPoslistBuffer(
170538          pPhrase->aTerm[0].pIter, &pPhrase->poslist
170539      );
170540    }
170541  }
170542
170543  *pRc = rc;
170544  if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
170545    return 1;
170546  }
170547
170548  return 0;
170549}
170550
170551static int fts5ExprTokenTest(
170552  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
170553  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
170554){
170555  /* As this "NEAR" object is actually a single phrase that consists
170556  ** of a single term only, grab pointers into the poslist managed by the
170557  ** fts5_index.c iterator object. This is much faster than synthesizing
170558  ** a new poslist the way we have to for more complicated phrase or NEAR
170559  ** expressions.  */
170560  Fts5ExprNearset *pNear = pNode->pNear;
170561  Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
170562  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
170563  Fts5Colset *pColset = pNear->pColset;
170564  int rc;
170565
170566  assert( pNode->eType==FTS5_TERM );
170567  assert( pNear->nPhrase==1 && pPhrase->nTerm==1 );
170568  assert( pPhrase->aTerm[0].pSynonym==0 );
170569
170570  rc = sqlite3Fts5IterPoslist(pIter, pColset,
170571      (const u8**)&pPhrase->poslist.p, &pPhrase->poslist.n, &pNode->iRowid
170572  );
170573  pNode->bNomatch = (pPhrase->poslist.n==0);
170574  return rc;
170575}
170576
170577/*
170578** All individual term iterators in pNear are guaranteed to be valid when
170579** this function is called. This function checks if all term iterators
170580** point to the same rowid, and if not, advances them until they do.
170581** If an EOF is reached before this happens, *pbEof is set to true before
170582** returning.
170583**
170584** SQLITE_OK is returned if an error occurs, or an SQLite error code
170585** otherwise. It is not considered an error code if an iterator reaches
170586** EOF.
170587*/
170588static int fts5ExprNearNextMatch(
170589  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170590  Fts5ExprNode *pNode
170591){
170592  Fts5ExprNearset *pNear = pNode->pNear;
170593  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
170594  int rc = SQLITE_OK;
170595  i64 iLast;                      /* Lastest rowid any iterator points to */
170596  int i, j;                       /* Phrase and token index, respectively */
170597  int bMatch;                     /* True if all terms are at the same rowid */
170598  const int bDesc = pExpr->bDesc;
170599
170600  /* Check that this node should not be FTS5_TERM */
170601  assert( pNear->nPhrase>1
170602       || pNear->apPhrase[0]->nTerm>1
170603       || pNear->apPhrase[0]->aTerm[0].pSynonym
170604  );
170605
170606  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
170607  ** iterator skips through rowids in the default ascending order, this means
170608  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
170609  ** means the minimum rowid.  */
170610  if( pLeft->aTerm[0].pSynonym ){
170611    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
170612  }else{
170613    iLast = sqlite3Fts5IterRowid(pLeft->aTerm[0].pIter);
170614  }
170615
170616  do {
170617    bMatch = 1;
170618    for(i=0; i<pNear->nPhrase; i++){
170619      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170620      for(j=0; j<pPhrase->nTerm; j++){
170621        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
170622        if( pTerm->pSynonym ){
170623          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
170624          if( iRowid==iLast ) continue;
170625          bMatch = 0;
170626          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
170627            pNode->bEof = 1;
170628            return rc;
170629          }
170630        }else{
170631          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
170632          i64 iRowid = sqlite3Fts5IterRowid(pIter);
170633          if( iRowid==iLast ) continue;
170634          bMatch = 0;
170635          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
170636            return rc;
170637          }
170638        }
170639      }
170640    }
170641  }while( bMatch==0 );
170642
170643  pNode->iRowid = iLast;
170644  pNode->bNomatch = (0==fts5ExprNearTest(&rc, pExpr, pNode));
170645
170646  return rc;
170647}
170648
170649/*
170650** Initialize all term iterators in the pNear object. If any term is found
170651** to match no documents at all, return immediately without initializing any
170652** further iterators.
170653*/
170654static int fts5ExprNearInitAll(
170655  Fts5Expr *pExpr,
170656  Fts5ExprNode *pNode
170657){
170658  Fts5ExprNearset *pNear = pNode->pNear;
170659  int i, j;
170660  int rc = SQLITE_OK;
170661
170662  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
170663    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170664    for(j=0; j<pPhrase->nTerm; j++){
170665      Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
170666      Fts5ExprTerm *p;
170667      int bEof = 1;
170668
170669      for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
170670        if( p->pIter ){
170671          sqlite3Fts5IterClose(p->pIter);
170672          p->pIter = 0;
170673        }
170674        rc = sqlite3Fts5IndexQuery(
170675            pExpr->pIndex, p->zTerm, strlen(p->zTerm),
170676            (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
170677            (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
170678            pNear->pColset,
170679            &p->pIter
170680        );
170681        assert( rc==SQLITE_OK || p->pIter==0 );
170682        if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
170683          bEof = 0;
170684        }
170685      }
170686
170687      if( bEof ){
170688        pNode->bEof = 1;
170689        return rc;
170690      }
170691    }
170692  }
170693
170694  return rc;
170695}
170696
170697/* fts5ExprNodeNext() calls fts5ExprNodeNextMatch(). And vice-versa. */
170698static int fts5ExprNodeNextMatch(Fts5Expr*, Fts5ExprNode*);
170699
170700
170701/*
170702** If pExpr is an ASC iterator, this function returns a value with the
170703** same sign as:
170704**
170705**   (iLhs - iRhs)
170706**
170707** Otherwise, if this is a DESC iterator, the opposite is returned:
170708**
170709**   (iRhs - iLhs)
170710*/
170711static int fts5RowidCmp(
170712  Fts5Expr *pExpr,
170713  i64 iLhs,
170714  i64 iRhs
170715){
170716  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
170717  if( pExpr->bDesc==0 ){
170718    if( iLhs<iRhs ) return -1;
170719    return (iLhs > iRhs);
170720  }else{
170721    if( iLhs>iRhs ) return -1;
170722    return (iLhs < iRhs);
170723  }
170724}
170725
170726static void fts5ExprSetEof(Fts5ExprNode *pNode){
170727  int i;
170728  pNode->bEof = 1;
170729  for(i=0; i<pNode->nChild; i++){
170730    fts5ExprSetEof(pNode->apChild[i]);
170731  }
170732}
170733
170734static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
170735  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
170736    Fts5ExprNearset *pNear = pNode->pNear;
170737    int i;
170738    for(i=0; i<pNear->nPhrase; i++){
170739      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170740      pPhrase->poslist.n = 0;
170741    }
170742  }else{
170743    int i;
170744    for(i=0; i<pNode->nChild; i++){
170745      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
170746    }
170747  }
170748}
170749
170750
170751static int fts5ExprNodeNext(Fts5Expr*, Fts5ExprNode*, int, i64);
170752
170753/*
170754** Argument pNode is an FTS5_AND node.
170755*/
170756static int fts5ExprAndNextRowid(
170757  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170758  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
170759){
170760  int iChild;
170761  i64 iLast = pAnd->iRowid;
170762  int rc = SQLITE_OK;
170763  int bMatch;
170764
170765  assert( pAnd->bEof==0 );
170766  do {
170767    pAnd->bNomatch = 0;
170768    bMatch = 1;
170769    for(iChild=0; iChild<pAnd->nChild; iChild++){
170770      Fts5ExprNode *pChild = pAnd->apChild[iChild];
170771      if( 0 && pChild->eType==FTS5_STRING ){
170772        /* TODO */
170773      }else{
170774        int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
170775        if( cmp>0 ){
170776          /* Advance pChild until it points to iLast or laster */
170777          rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
170778          if( rc!=SQLITE_OK ) return rc;
170779        }
170780      }
170781
170782      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
170783      ** the child node is guaranteed to have advanced at least as far as
170784      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
170785      ** new lastest rowid seen so far.  */
170786      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
170787      if( pChild->bEof ){
170788        fts5ExprSetEof(pAnd);
170789        bMatch = 1;
170790        break;
170791      }else if( iLast!=pChild->iRowid ){
170792        bMatch = 0;
170793        iLast = pChild->iRowid;
170794      }
170795
170796      if( pChild->bNomatch ){
170797        pAnd->bNomatch = 1;
170798      }
170799    }
170800  }while( bMatch==0 );
170801
170802  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
170803    fts5ExprNodeZeroPoslist(pAnd);
170804  }
170805  pAnd->iRowid = iLast;
170806  return SQLITE_OK;
170807}
170808
170809
170810/*
170811** Compare the values currently indicated by the two nodes as follows:
170812**
170813**    res = (*p1) - (*p2)
170814**
170815** Nodes that point to values that come later in the iteration order are
170816** considered to be larger. Nodes at EOF are the largest of all.
170817**
170818** This means that if the iteration order is ASC, then numerically larger
170819** rowids are considered larger. Or if it is the default DESC, numerically
170820** smaller rowids are larger.
170821*/
170822static int fts5NodeCompare(
170823  Fts5Expr *pExpr,
170824  Fts5ExprNode *p1,
170825  Fts5ExprNode *p2
170826){
170827  if( p2->bEof ) return -1;
170828  if( p1->bEof ) return +1;
170829  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
170830}
170831
170832/*
170833** Advance node iterator pNode, part of expression pExpr. If argument
170834** bFromValid is zero, then pNode is advanced exactly once. Or, if argument
170835** bFromValid is non-zero, then pNode is advanced until it is at or past
170836** rowid value iFrom. Whether "past" means "less than" or "greater than"
170837** depends on whether this is an ASC or DESC iterator.
170838*/
170839static int fts5ExprNodeNext(
170840  Fts5Expr *pExpr,
170841  Fts5ExprNode *pNode,
170842  int bFromValid,
170843  i64 iFrom
170844){
170845  int rc = SQLITE_OK;
170846
170847  if( pNode->bEof==0 ){
170848    switch( pNode->eType ){
170849      case FTS5_STRING: {
170850        rc = fts5ExprNearAdvanceFirst(pExpr, pNode, bFromValid, iFrom);
170851        break;
170852      };
170853
170854      case FTS5_TERM: {
170855        Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
170856        if( bFromValid ){
170857          rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
170858        }else{
170859          rc = sqlite3Fts5IterNext(pIter);
170860        }
170861        if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
170862          assert( rc==SQLITE_OK );
170863          rc = fts5ExprTokenTest(pExpr, pNode);
170864        }else{
170865          pNode->bEof = 1;
170866        }
170867        return rc;
170868      };
170869
170870      case FTS5_AND: {
170871        Fts5ExprNode *pLeft = pNode->apChild[0];
170872        rc = fts5ExprNodeNext(pExpr, pLeft, bFromValid, iFrom);
170873        break;
170874      }
170875
170876      case FTS5_OR: {
170877        int i;
170878        i64 iLast = pNode->iRowid;
170879
170880        for(i=0; rc==SQLITE_OK && i<pNode->nChild; i++){
170881          Fts5ExprNode *p1 = pNode->apChild[i];
170882          assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
170883          if( p1->bEof==0 ){
170884            if( (p1->iRowid==iLast)
170885             || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
170886            ){
170887              rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
170888            }
170889          }
170890        }
170891
170892        break;
170893      }
170894
170895      default: assert( pNode->eType==FTS5_NOT ); {
170896        assert( pNode->nChild==2 );
170897        rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
170898        break;
170899      }
170900    }
170901
170902    if( rc==SQLITE_OK ){
170903      rc = fts5ExprNodeNextMatch(pExpr, pNode);
170904    }
170905  }
170906
170907  /* Assert that if bFromValid was true, either:
170908  **
170909  **   a) an error occurred, or
170910  **   b) the node is now at EOF, or
170911  **   c) the node is now at or past rowid iFrom.
170912  */
170913  assert( bFromValid==0
170914      || rc!=SQLITE_OK                                                  /* a */
170915      || pNode->bEof                                                    /* b */
170916      || pNode->iRowid==iFrom || pExpr->bDesc==(pNode->iRowid<iFrom)    /* c */
170917  );
170918
170919  return rc;
170920}
170921
170922
170923/*
170924** If pNode currently points to a match, this function returns SQLITE_OK
170925** without modifying it. Otherwise, pNode is advanced until it does point
170926** to a match or EOF is reached.
170927*/
170928static int fts5ExprNodeNextMatch(
170929  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
170930  Fts5ExprNode *pNode             /* Expression node to test */
170931){
170932  int rc = SQLITE_OK;
170933  if( pNode->bEof==0 ){
170934    switch( pNode->eType ){
170935
170936      case FTS5_STRING: {
170937        /* Advance the iterators until they all point to the same rowid */
170938        rc = fts5ExprNearNextMatch(pExpr, pNode);
170939        break;
170940      }
170941
170942      case FTS5_TERM: {
170943        rc = fts5ExprTokenTest(pExpr, pNode);
170944        break;
170945      }
170946
170947      case FTS5_AND: {
170948        rc = fts5ExprAndNextRowid(pExpr, pNode);
170949        break;
170950      }
170951
170952      case FTS5_OR: {
170953        Fts5ExprNode *pNext = pNode->apChild[0];
170954        int i;
170955
170956        for(i=1; i<pNode->nChild; i++){
170957          Fts5ExprNode *pChild = pNode->apChild[i];
170958          int cmp = fts5NodeCompare(pExpr, pNext, pChild);
170959          if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
170960            pNext = pChild;
170961          }
170962        }
170963        pNode->iRowid = pNext->iRowid;
170964        pNode->bEof = pNext->bEof;
170965        pNode->bNomatch = pNext->bNomatch;
170966        break;
170967      }
170968
170969      default: assert( pNode->eType==FTS5_NOT ); {
170970        Fts5ExprNode *p1 = pNode->apChild[0];
170971        Fts5ExprNode *p2 = pNode->apChild[1];
170972        assert( pNode->nChild==2 );
170973
170974        while( rc==SQLITE_OK && p1->bEof==0 ){
170975          int cmp = fts5NodeCompare(pExpr, p1, p2);
170976          if( cmp>0 ){
170977            rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
170978            cmp = fts5NodeCompare(pExpr, p1, p2);
170979          }
170980          assert( rc!=SQLITE_OK || cmp<=0 );
170981          if( cmp || p2->bNomatch ) break;
170982          rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
170983        }
170984        pNode->bEof = p1->bEof;
170985        pNode->iRowid = p1->iRowid;
170986        break;
170987      }
170988    }
170989  }
170990  return rc;
170991}
170992
170993
170994/*
170995** Set node pNode, which is part of expression pExpr, to point to the first
170996** match. If there are no matches, set the Node.bEof flag to indicate EOF.
170997**
170998** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
170999** It is not an error if there are no matches.
171000*/
171001static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
171002  int rc = SQLITE_OK;
171003  pNode->bEof = 0;
171004
171005  if( Fts5NodeIsString(pNode) ){
171006    /* Initialize all term iterators in the NEAR object. */
171007    rc = fts5ExprNearInitAll(pExpr, pNode);
171008  }else{
171009    int i;
171010    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
171011      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
171012    }
171013    pNode->iRowid = pNode->apChild[0]->iRowid;
171014  }
171015
171016  if( rc==SQLITE_OK ){
171017    rc = fts5ExprNodeNextMatch(pExpr, pNode);
171018  }
171019  return rc;
171020}
171021
171022
171023/*
171024** Begin iterating through the set of documents in index pIdx matched by
171025** the MATCH expression passed as the first argument. If the "bDesc"
171026** parameter is passed a non-zero value, iteration is in descending rowid
171027** order. Or, if it is zero, in ascending order.
171028**
171029** If iterating in ascending rowid order (bDesc==0), the first document
171030** visited is that with the smallest rowid that is larger than or equal
171031** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
171032** then the first document visited must have a rowid smaller than or
171033** equal to iFirst.
171034**
171035** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
171036** is not considered an error if the query does not match any documents.
171037*/
171038static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
171039  Fts5ExprNode *pRoot = p->pRoot;
171040  int rc = SQLITE_OK;
171041  if( pRoot ){
171042    p->pIndex = pIdx;
171043    p->bDesc = bDesc;
171044    rc = fts5ExprNodeFirst(p, pRoot);
171045
171046    /* If not at EOF but the current rowid occurs earlier than iFirst in
171047    ** the iteration order, move to document iFirst or later. */
171048    if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
171049      rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
171050    }
171051
171052    /* If the iterator is not at a real match, skip forward until it is. */
171053    while( pRoot->bNomatch && rc==SQLITE_OK && pRoot->bEof==0 ){
171054      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
171055    }
171056  }
171057  return rc;
171058}
171059
171060/*
171061** Move to the next document
171062**
171063** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
171064** is not considered an error if the query does not match any documents.
171065*/
171066static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
171067  int rc;
171068  Fts5ExprNode *pRoot = p->pRoot;
171069  do {
171070    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
171071  }while( pRoot->bNomatch && pRoot->bEof==0 && rc==SQLITE_OK );
171072  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
171073    pRoot->bEof = 1;
171074  }
171075  return rc;
171076}
171077
171078static int sqlite3Fts5ExprEof(Fts5Expr *p){
171079  return (p->pRoot==0 || p->pRoot->bEof);
171080}
171081
171082static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
171083  return p->pRoot->iRowid;
171084}
171085
171086static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
171087  int rc = SQLITE_OK;
171088  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
171089  return rc;
171090}
171091
171092/*
171093** Free the phrase object passed as the only argument.
171094*/
171095static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
171096  if( pPhrase ){
171097    int i;
171098    for(i=0; i<pPhrase->nTerm; i++){
171099      Fts5ExprTerm *pSyn;
171100      Fts5ExprTerm *pNext;
171101      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
171102      sqlite3_free(pTerm->zTerm);
171103      sqlite3Fts5IterClose(pTerm->pIter);
171104
171105      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
171106        pNext = pSyn->pSynonym;
171107        sqlite3Fts5IterClose(pSyn->pIter);
171108        sqlite3_free(pSyn);
171109      }
171110    }
171111    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
171112    sqlite3_free(pPhrase);
171113  }
171114}
171115
171116/*
171117** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
171118** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
171119** appended to it and the results returned.
171120**
171121** If an OOM error occurs, both the pNear and pPhrase objects are freed and
171122** NULL returned.
171123*/
171124static Fts5ExprNearset *sqlite3Fts5ParseNearset(
171125  Fts5Parse *pParse,              /* Parse context */
171126  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
171127  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
171128){
171129  const int SZALLOC = 8;
171130  Fts5ExprNearset *pRet = 0;
171131
171132  if( pParse->rc==SQLITE_OK ){
171133    if( pPhrase==0 ){
171134      return pNear;
171135    }
171136    if( pNear==0 ){
171137      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
171138      pRet = sqlite3_malloc(nByte);
171139      if( pRet==0 ){
171140        pParse->rc = SQLITE_NOMEM;
171141      }else{
171142        memset(pRet, 0, nByte);
171143      }
171144    }else if( (pNear->nPhrase % SZALLOC)==0 ){
171145      int nNew = pNear->nPhrase + SZALLOC;
171146      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
171147
171148      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
171149      if( pRet==0 ){
171150        pParse->rc = SQLITE_NOMEM;
171151      }
171152    }else{
171153      pRet = pNear;
171154    }
171155  }
171156
171157  if( pRet==0 ){
171158    assert( pParse->rc!=SQLITE_OK );
171159    sqlite3Fts5ParseNearsetFree(pNear);
171160    sqlite3Fts5ParsePhraseFree(pPhrase);
171161  }else{
171162    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
171163  }
171164  return pRet;
171165}
171166
171167typedef struct TokenCtx TokenCtx;
171168struct TokenCtx {
171169  Fts5ExprPhrase *pPhrase;
171170  int rc;
171171};
171172
171173/*
171174** Callback for tokenizing terms used by ParseTerm().
171175*/
171176static int fts5ParseTokenize(
171177  void *pContext,                 /* Pointer to Fts5InsertCtx object */
171178  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
171179  const char *pToken,             /* Buffer containing token */
171180  int nToken,                     /* Size of token in bytes */
171181  int iUnused1,                   /* Start offset of token */
171182  int iUnused2                    /* End offset of token */
171183){
171184  int rc = SQLITE_OK;
171185  const int SZALLOC = 8;
171186  TokenCtx *pCtx = (TokenCtx*)pContext;
171187  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
171188
171189  /* If an error has already occurred, this is a no-op */
171190  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
171191
171192  assert( pPhrase==0 || pPhrase->nTerm>0 );
171193  if( pPhrase && (tflags & FTS5_TOKEN_COLOCATED) ){
171194    Fts5ExprTerm *pSyn;
171195    int nByte = sizeof(Fts5ExprTerm) + nToken+1;
171196    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
171197    if( pSyn==0 ){
171198      rc = SQLITE_NOMEM;
171199    }else{
171200      memset(pSyn, 0, nByte);
171201      pSyn->zTerm = (char*)&pSyn[1];
171202      memcpy(pSyn->zTerm, pToken, nToken);
171203      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
171204      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
171205    }
171206  }else{
171207    Fts5ExprTerm *pTerm;
171208    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
171209      Fts5ExprPhrase *pNew;
171210      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
171211
171212      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
171213          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
171214      );
171215      if( pNew==0 ){
171216        rc = SQLITE_NOMEM;
171217      }else{
171218        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
171219        pCtx->pPhrase = pPhrase = pNew;
171220        pNew->nTerm = nNew - SZALLOC;
171221      }
171222    }
171223
171224    if( rc==SQLITE_OK ){
171225      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
171226      memset(pTerm, 0, sizeof(Fts5ExprTerm));
171227      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
171228    }
171229  }
171230
171231  pCtx->rc = rc;
171232  return rc;
171233}
171234
171235
171236/*
171237** Free the phrase object passed as the only argument.
171238*/
171239static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
171240  fts5ExprPhraseFree(pPhrase);
171241}
171242
171243/*
171244** Free the phrase object passed as the second argument.
171245*/
171246static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
171247  if( pNear ){
171248    int i;
171249    for(i=0; i<pNear->nPhrase; i++){
171250      fts5ExprPhraseFree(pNear->apPhrase[i]);
171251    }
171252    sqlite3_free(pNear->pColset);
171253    sqlite3_free(pNear);
171254  }
171255}
171256
171257static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
171258  assert( pParse->pExpr==0 );
171259  pParse->pExpr = p;
171260}
171261
171262/*
171263** This function is called by the parser to process a string token. The
171264** string may or may not be quoted. In any case it is tokenized and a
171265** phrase object consisting of all tokens returned.
171266*/
171267static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
171268  Fts5Parse *pParse,              /* Parse context */
171269  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
171270  Fts5Token *pToken,              /* String to tokenize */
171271  int bPrefix                     /* True if there is a trailing "*" */
171272){
171273  Fts5Config *pConfig = pParse->pConfig;
171274  TokenCtx sCtx;                  /* Context object passed to callback */
171275  int rc;                         /* Tokenize return code */
171276  char *z = 0;
171277
171278  memset(&sCtx, 0, sizeof(TokenCtx));
171279  sCtx.pPhrase = pAppend;
171280
171281  rc = fts5ParseStringFromToken(pToken, &z);
171282  if( rc==SQLITE_OK ){
171283    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
171284    int n;
171285    sqlite3Fts5Dequote(z);
171286    n = strlen(z);
171287    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
171288  }
171289  sqlite3_free(z);
171290  if( rc || (rc = sCtx.rc) ){
171291    pParse->rc = rc;
171292    fts5ExprPhraseFree(sCtx.pPhrase);
171293    sCtx.pPhrase = 0;
171294  }else if( sCtx.pPhrase ){
171295
171296    if( pAppend==0 ){
171297      if( (pParse->nPhrase % 8)==0 ){
171298        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
171299        Fts5ExprPhrase **apNew;
171300        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
171301        if( apNew==0 ){
171302          pParse->rc = SQLITE_NOMEM;
171303          fts5ExprPhraseFree(sCtx.pPhrase);
171304          return 0;
171305        }
171306        pParse->apPhrase = apNew;
171307      }
171308      pParse->nPhrase++;
171309    }
171310
171311    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
171312    assert( sCtx.pPhrase->nTerm>0 );
171313    sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
171314  }
171315
171316  return sCtx.pPhrase;
171317}
171318
171319/*
171320** Create a new FTS5 expression by cloning phrase iPhrase of the
171321** expression passed as the second argument.
171322*/
171323static int sqlite3Fts5ExprClonePhrase(
171324  Fts5Config *pConfig,
171325  Fts5Expr *pExpr,
171326  int iPhrase,
171327  Fts5Expr **ppNew
171328){
171329  int rc = SQLITE_OK;             /* Return code */
171330  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
171331  int i;                          /* Used to iterate through phrase terms */
171332
171333  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
171334
171335  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
171336
171337
171338  pOrig = pExpr->apExprPhrase[iPhrase];
171339
171340  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
171341  if( rc==SQLITE_OK ){
171342    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
171343        sizeof(Fts5ExprPhrase*));
171344  }
171345  if( rc==SQLITE_OK ){
171346    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
171347        sizeof(Fts5ExprNode));
171348  }
171349  if( rc==SQLITE_OK ){
171350    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
171351        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
171352  }
171353
171354  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
171355    int tflags = 0;
171356    Fts5ExprTerm *p;
171357    for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
171358      const char *zTerm = p->zTerm;
171359      rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, strlen(zTerm), 0, 0);
171360      tflags = FTS5_TOKEN_COLOCATED;
171361    }
171362    if( rc==SQLITE_OK ){
171363      sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
171364    }
171365  }
171366
171367  if( rc==SQLITE_OK ){
171368    /* All the allocations succeeded. Put the expression object together. */
171369    pNew->pIndex = pExpr->pIndex;
171370    pNew->nPhrase = 1;
171371    pNew->apExprPhrase[0] = sCtx.pPhrase;
171372    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
171373    pNew->pRoot->pNear->nPhrase = 1;
171374    sCtx.pPhrase->pNode = pNew->pRoot;
171375
171376    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
171377      pNew->pRoot->eType = FTS5_TERM;
171378    }else{
171379      pNew->pRoot->eType = FTS5_STRING;
171380    }
171381  }else{
171382    sqlite3Fts5ExprFree(pNew);
171383    fts5ExprPhraseFree(sCtx.pPhrase);
171384    pNew = 0;
171385  }
171386
171387  *ppNew = pNew;
171388  return rc;
171389}
171390
171391
171392/*
171393** Token pTok has appeared in a MATCH expression where the NEAR operator
171394** is expected. If token pTok does not contain "NEAR", store an error
171395** in the pParse object.
171396*/
171397static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
171398  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
171399    sqlite3Fts5ParseError(
171400        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
171401    );
171402  }
171403}
171404
171405static void sqlite3Fts5ParseSetDistance(
171406  Fts5Parse *pParse,
171407  Fts5ExprNearset *pNear,
171408  Fts5Token *p
171409){
171410  int nNear = 0;
171411  int i;
171412  if( p->n ){
171413    for(i=0; i<p->n; i++){
171414      char c = (char)p->p[i];
171415      if( c<'0' || c>'9' ){
171416        sqlite3Fts5ParseError(
171417            pParse, "expected integer, got \"%.*s\"", p->n, p->p
171418        );
171419        return;
171420      }
171421      nNear = nNear * 10 + (p->p[i] - '0');
171422    }
171423  }else{
171424    nNear = FTS5_DEFAULT_NEARDIST;
171425  }
171426  pNear->nNear = nNear;
171427}
171428
171429/*
171430** The second argument passed to this function may be NULL, or it may be
171431** an existing Fts5Colset object. This function returns a pointer to
171432** a new colset object containing the contents of (p) with new value column
171433** number iCol appended.
171434**
171435** If an OOM error occurs, store an error code in pParse and return NULL.
171436** The old colset object (if any) is not freed in this case.
171437*/
171438static Fts5Colset *fts5ParseColset(
171439  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
171440  Fts5Colset *p,                  /* Existing colset object */
171441  int iCol                        /* New column to add to colset object */
171442){
171443  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
171444  Fts5Colset *pNew;               /* New colset object to return */
171445
171446  assert( pParse->rc==SQLITE_OK );
171447  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
171448
171449  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
171450  if( pNew==0 ){
171451    pParse->rc = SQLITE_NOMEM;
171452  }else{
171453    int *aiCol = pNew->aiCol;
171454    int i, j;
171455    for(i=0; i<nCol; i++){
171456      if( aiCol[i]==iCol ) return pNew;
171457      if( aiCol[i]>iCol ) break;
171458    }
171459    for(j=nCol; j>i; j--){
171460      aiCol[j] = aiCol[j-1];
171461    }
171462    aiCol[i] = iCol;
171463    pNew->nCol = nCol+1;
171464
171465#ifndef NDEBUG
171466    /* Check that the array is in order and contains no duplicate entries. */
171467    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
171468#endif
171469  }
171470
171471  return pNew;
171472}
171473
171474static Fts5Colset *sqlite3Fts5ParseColset(
171475  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
171476  Fts5Colset *pColset,            /* Existing colset object */
171477  Fts5Token *p
171478){
171479  Fts5Colset *pRet = 0;
171480  int iCol;
171481  char *z;                        /* Dequoted copy of token p */
171482
171483  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
171484  if( pParse->rc==SQLITE_OK ){
171485    Fts5Config *pConfig = pParse->pConfig;
171486    sqlite3Fts5Dequote(z);
171487    for(iCol=0; iCol<pConfig->nCol; iCol++){
171488      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
171489    }
171490    if( iCol==pConfig->nCol ){
171491      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
171492    }else{
171493      pRet = fts5ParseColset(pParse, pColset, iCol);
171494    }
171495    sqlite3_free(z);
171496  }
171497
171498  if( pRet==0 ){
171499    assert( pParse->rc!=SQLITE_OK );
171500    sqlite3_free(pColset);
171501  }
171502
171503  return pRet;
171504}
171505
171506static void sqlite3Fts5ParseSetColset(
171507  Fts5Parse *pParse,
171508  Fts5ExprNearset *pNear,
171509  Fts5Colset *pColset
171510){
171511  if( pNear ){
171512    pNear->pColset = pColset;
171513  }else{
171514    sqlite3_free(pColset);
171515  }
171516}
171517
171518static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
171519  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
171520    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
171521    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
171522    p->nChild += pSub->nChild;
171523    sqlite3_free(pSub);
171524  }else{
171525    p->apChild[p->nChild++] = pSub;
171526  }
171527}
171528
171529/*
171530** Allocate and return a new expression object. If anything goes wrong (i.e.
171531** OOM error), leave an error code in pParse and return NULL.
171532*/
171533static Fts5ExprNode *sqlite3Fts5ParseNode(
171534  Fts5Parse *pParse,              /* Parse context */
171535  int eType,                      /* FTS5_STRING, AND, OR or NOT */
171536  Fts5ExprNode *pLeft,            /* Left hand child expression */
171537  Fts5ExprNode *pRight,           /* Right hand child expression */
171538  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
171539){
171540  Fts5ExprNode *pRet = 0;
171541
171542  if( pParse->rc==SQLITE_OK ){
171543    int nChild = 0;               /* Number of children of returned node */
171544    int nByte;                    /* Bytes of space to allocate for this node */
171545
171546    assert( (eType!=FTS5_STRING && !pNear)
171547         || (eType==FTS5_STRING && !pLeft && !pRight)
171548    );
171549    if( eType==FTS5_STRING && pNear==0 ) return 0;
171550    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
171551    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
171552
171553    if( eType==FTS5_NOT ){
171554      nChild = 2;
171555    }else if( eType==FTS5_AND || eType==FTS5_OR ){
171556      nChild = 2;
171557      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
171558      if( pRight->eType==eType ) nChild += pRight->nChild-1;
171559    }
171560
171561    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
171562    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
171563
171564    if( pRet ){
171565      pRet->eType = eType;
171566      pRet->pNear = pNear;
171567      if( eType==FTS5_STRING ){
171568        int iPhrase;
171569        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
171570          pNear->apPhrase[iPhrase]->pNode = pRet;
171571        }
171572        if( pNear->nPhrase==1
171573         && pNear->apPhrase[0]->nTerm==1
171574         && pNear->apPhrase[0]->aTerm[0].pSynonym==0
171575        ){
171576          pRet->eType = FTS5_TERM;
171577        }
171578      }else{
171579        fts5ExprAddChildren(pRet, pLeft);
171580        fts5ExprAddChildren(pRet, pRight);
171581      }
171582    }
171583  }
171584
171585  if( pRet==0 ){
171586    assert( pParse->rc!=SQLITE_OK );
171587    sqlite3Fts5ParseNodeFree(pLeft);
171588    sqlite3Fts5ParseNodeFree(pRight);
171589    sqlite3Fts5ParseNearsetFree(pNear);
171590  }
171591  return pRet;
171592}
171593
171594static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
171595  int nByte = 0;
171596  Fts5ExprTerm *p;
171597  char *zQuoted;
171598
171599  /* Determine the maximum amount of space required. */
171600  for(p=pTerm; p; p=p->pSynonym){
171601    nByte += strlen(pTerm->zTerm) * 2 + 3 + 2;
171602  }
171603  zQuoted = sqlite3_malloc(nByte);
171604
171605  if( zQuoted ){
171606    int i = 0;
171607    for(p=pTerm; p; p=p->pSynonym){
171608      char *zIn = p->zTerm;
171609      zQuoted[i++] = '"';
171610      while( *zIn ){
171611        if( *zIn=='"' ) zQuoted[i++] = '"';
171612        zQuoted[i++] = *zIn++;
171613      }
171614      zQuoted[i++] = '"';
171615      if( p->pSynonym ) zQuoted[i++] = '|';
171616    }
171617    if( pTerm->bPrefix ){
171618      zQuoted[i++] = ' ';
171619      zQuoted[i++] = '*';
171620    }
171621    zQuoted[i++] = '\0';
171622  }
171623  return zQuoted;
171624}
171625
171626static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
171627  char *zNew;
171628  va_list ap;
171629  va_start(ap, zFmt);
171630  zNew = sqlite3_vmprintf(zFmt, ap);
171631  va_end(ap);
171632  if( zApp && zNew ){
171633    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
171634    sqlite3_free(zNew);
171635    zNew = zNew2;
171636  }
171637  sqlite3_free(zApp);
171638  return zNew;
171639}
171640
171641/*
171642** Compose a tcl-readable representation of expression pExpr. Return a
171643** pointer to a buffer containing that representation. It is the
171644** responsibility of the caller to at some point free the buffer using
171645** sqlite3_free().
171646*/
171647static char *fts5ExprPrintTcl(
171648  Fts5Config *pConfig,
171649  const char *zNearsetCmd,
171650  Fts5ExprNode *pExpr
171651){
171652  char *zRet = 0;
171653  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
171654    Fts5ExprNearset *pNear = pExpr->pNear;
171655    int i;
171656    int iTerm;
171657
171658    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
171659    if( zRet==0 ) return 0;
171660    if( pNear->pColset ){
171661      int *aiCol = pNear->pColset->aiCol;
171662      int nCol = pNear->pColset->nCol;
171663      if( nCol==1 ){
171664        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
171665      }else{
171666        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
171667        for(i=1; i<pNear->pColset->nCol; i++){
171668          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
171669        }
171670        zRet = fts5PrintfAppend(zRet, "} ");
171671      }
171672      if( zRet==0 ) return 0;
171673    }
171674
171675    if( pNear->nPhrase>1 ){
171676      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
171677      if( zRet==0 ) return 0;
171678    }
171679
171680    zRet = fts5PrintfAppend(zRet, "--");
171681    if( zRet==0 ) return 0;
171682
171683    for(i=0; i<pNear->nPhrase; i++){
171684      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
171685
171686      zRet = fts5PrintfAppend(zRet, " {");
171687      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
171688        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
171689        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
171690      }
171691
171692      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
171693      if( zRet==0 ) return 0;
171694    }
171695
171696  }else{
171697    char const *zOp = 0;
171698    int i;
171699    switch( pExpr->eType ){
171700      case FTS5_AND: zOp = "AND"; break;
171701      case FTS5_NOT: zOp = "NOT"; break;
171702      default:
171703        assert( pExpr->eType==FTS5_OR );
171704        zOp = "OR";
171705        break;
171706    }
171707
171708    zRet = sqlite3_mprintf("%s", zOp);
171709    for(i=0; zRet && i<pExpr->nChild; i++){
171710      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
171711      if( !z ){
171712        sqlite3_free(zRet);
171713        zRet = 0;
171714      }else{
171715        zRet = fts5PrintfAppend(zRet, " [%z]", z);
171716      }
171717    }
171718  }
171719
171720  return zRet;
171721}
171722
171723static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
171724  char *zRet = 0;
171725  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
171726    Fts5ExprNearset *pNear = pExpr->pNear;
171727    int i;
171728    int iTerm;
171729
171730    if( pNear->pColset ){
171731      int iCol = pNear->pColset->aiCol[0];
171732      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
171733      if( zRet==0 ) return 0;
171734    }
171735
171736    if( pNear->nPhrase>1 ){
171737      zRet = fts5PrintfAppend(zRet, "NEAR(");
171738      if( zRet==0 ) return 0;
171739    }
171740
171741    for(i=0; i<pNear->nPhrase; i++){
171742      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
171743      if( i!=0 ){
171744        zRet = fts5PrintfAppend(zRet, " ");
171745        if( zRet==0 ) return 0;
171746      }
171747      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
171748        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
171749        if( zTerm ){
171750          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
171751          sqlite3_free(zTerm);
171752        }
171753        if( zTerm==0 || zRet==0 ){
171754          sqlite3_free(zRet);
171755          return 0;
171756        }
171757      }
171758    }
171759
171760    if( pNear->nPhrase>1 ){
171761      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
171762      if( zRet==0 ) return 0;
171763    }
171764
171765  }else{
171766    char const *zOp = 0;
171767    int i;
171768
171769    switch( pExpr->eType ){
171770      case FTS5_AND: zOp = " AND "; break;
171771      case FTS5_NOT: zOp = " NOT "; break;
171772      default:
171773        assert( pExpr->eType==FTS5_OR );
171774        zOp = " OR ";
171775        break;
171776    }
171777
171778    for(i=0; i<pExpr->nChild; i++){
171779      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
171780      if( z==0 ){
171781        sqlite3_free(zRet);
171782        zRet = 0;
171783      }else{
171784        int e = pExpr->apChild[i]->eType;
171785        int b = (e!=FTS5_STRING && e!=FTS5_TERM);
171786        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
171787            (i==0 ? "" : zOp),
171788            (b?"(":""), z, (b?")":"")
171789        );
171790      }
171791      if( zRet==0 ) break;
171792    }
171793  }
171794
171795  return zRet;
171796}
171797
171798/*
171799** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
171800** and fts5_expr_tcl() (bTcl!=0).
171801*/
171802static void fts5ExprFunction(
171803  sqlite3_context *pCtx,          /* Function call context */
171804  int nArg,                       /* Number of args */
171805  sqlite3_value **apVal,          /* Function arguments */
171806  int bTcl
171807){
171808  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
171809  sqlite3 *db = sqlite3_context_db_handle(pCtx);
171810  const char *zExpr = 0;
171811  char *zErr = 0;
171812  Fts5Expr *pExpr = 0;
171813  int rc;
171814  int i;
171815
171816  const char **azConfig;          /* Array of arguments for Fts5Config */
171817  const char *zNearsetCmd = "nearset";
171818  int nConfig;                    /* Size of azConfig[] */
171819  Fts5Config *pConfig = 0;
171820  int iArg = 1;
171821
171822  if( nArg<1 ){
171823    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
171824        bTcl ? "fts5_expr_tcl" : "fts5_expr"
171825    );
171826    sqlite3_result_error(pCtx, zErr, -1);
171827    sqlite3_free(zErr);
171828    return;
171829  }
171830
171831  if( bTcl && nArg>1 ){
171832    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
171833    iArg = 2;
171834  }
171835
171836  nConfig = 3 + (nArg-iArg);
171837  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
171838  if( azConfig==0 ){
171839    sqlite3_result_error_nomem(pCtx);
171840    return;
171841  }
171842  azConfig[0] = 0;
171843  azConfig[1] = "main";
171844  azConfig[2] = "tbl";
171845  for(i=3; iArg<nArg; iArg++){
171846    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
171847  }
171848
171849  zExpr = (const char*)sqlite3_value_text(apVal[0]);
171850
171851  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
171852  if( rc==SQLITE_OK ){
171853    rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
171854  }
171855  if( rc==SQLITE_OK ){
171856    char *zText;
171857    if( pExpr->pRoot==0 ){
171858      zText = sqlite3_mprintf("");
171859    }else if( bTcl ){
171860      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
171861    }else{
171862      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
171863    }
171864    if( zText==0 ){
171865      rc = SQLITE_NOMEM;
171866    }else{
171867      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
171868      sqlite3_free(zText);
171869    }
171870  }
171871
171872  if( rc!=SQLITE_OK ){
171873    if( zErr ){
171874      sqlite3_result_error(pCtx, zErr, -1);
171875      sqlite3_free(zErr);
171876    }else{
171877      sqlite3_result_error_code(pCtx, rc);
171878    }
171879  }
171880  sqlite3_free((void *)azConfig);
171881  sqlite3Fts5ConfigFree(pConfig);
171882  sqlite3Fts5ExprFree(pExpr);
171883}
171884
171885static void fts5ExprFunctionHr(
171886  sqlite3_context *pCtx,          /* Function call context */
171887  int nArg,                       /* Number of args */
171888  sqlite3_value **apVal           /* Function arguments */
171889){
171890  fts5ExprFunction(pCtx, nArg, apVal, 0);
171891}
171892static void fts5ExprFunctionTcl(
171893  sqlite3_context *pCtx,          /* Function call context */
171894  int nArg,                       /* Number of args */
171895  sqlite3_value **apVal           /* Function arguments */
171896){
171897  fts5ExprFunction(pCtx, nArg, apVal, 1);
171898}
171899
171900/*
171901** The implementation of an SQLite user-defined-function that accepts a
171902** single integer as an argument. If the integer is an alpha-numeric
171903** unicode code point, 1 is returned. Otherwise 0.
171904*/
171905static void fts5ExprIsAlnum(
171906  sqlite3_context *pCtx,          /* Function call context */
171907  int nArg,                       /* Number of args */
171908  sqlite3_value **apVal           /* Function arguments */
171909){
171910  int iCode;
171911  if( nArg!=1 ){
171912    sqlite3_result_error(pCtx,
171913        "wrong number of arguments to function fts5_isalnum", -1
171914    );
171915    return;
171916  }
171917  iCode = sqlite3_value_int(apVal[0]);
171918  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
171919}
171920
171921static void fts5ExprFold(
171922  sqlite3_context *pCtx,          /* Function call context */
171923  int nArg,                       /* Number of args */
171924  sqlite3_value **apVal           /* Function arguments */
171925){
171926  if( nArg!=1 && nArg!=2 ){
171927    sqlite3_result_error(pCtx,
171928        "wrong number of arguments to function fts5_fold", -1
171929    );
171930  }else{
171931    int iCode;
171932    int bRemoveDiacritics = 0;
171933    iCode = sqlite3_value_int(apVal[0]);
171934    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
171935    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
171936  }
171937}
171938
171939/*
171940** This is called during initialization to register the fts5_expr() scalar
171941** UDF with the SQLite handle passed as the only argument.
171942*/
171943static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
171944  struct Fts5ExprFunc {
171945    const char *z;
171946    void (*x)(sqlite3_context*,int,sqlite3_value**);
171947  } aFunc[] = {
171948    { "fts5_expr",     fts5ExprFunctionHr },
171949    { "fts5_expr_tcl", fts5ExprFunctionTcl },
171950    { "fts5_isalnum",  fts5ExprIsAlnum },
171951    { "fts5_fold",     fts5ExprFold },
171952  };
171953  int i;
171954  int rc = SQLITE_OK;
171955  void *pCtx = (void*)pGlobal;
171956
171957  for(i=0; rc==SQLITE_OK && i<(sizeof(aFunc) / sizeof(aFunc[0])); i++){
171958    struct Fts5ExprFunc *p = &aFunc[i];
171959    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
171960  }
171961
171962  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
171963#ifndef NDEBUG
171964  (void)sqlite3Fts5ParserTrace;
171965#endif
171966
171967  return rc;
171968}
171969
171970/*
171971** Return the number of phrases in expression pExpr.
171972*/
171973static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
171974  return (pExpr ? pExpr->nPhrase : 0);
171975}
171976
171977/*
171978** Return the number of terms in the iPhrase'th phrase in pExpr.
171979*/
171980static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
171981  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
171982  return pExpr->apExprPhrase[iPhrase]->nTerm;
171983}
171984
171985/*
171986** This function is used to access the current position list for phrase
171987** iPhrase.
171988*/
171989static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
171990  int nRet;
171991  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
171992  Fts5ExprNode *pNode = pPhrase->pNode;
171993  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
171994    *pa = pPhrase->poslist.p;
171995    nRet = pPhrase->poslist.n;
171996  }else{
171997    *pa = 0;
171998    nRet = 0;
171999  }
172000  return nRet;
172001}
172002
172003/*
172004** 2014 August 11
172005**
172006** The author disclaims copyright to this source code.  In place of
172007** a legal notice, here is a blessing:
172008**
172009**    May you do good and not evil.
172010**    May you find forgiveness for yourself and forgive others.
172011**    May you share freely, never taking more than you give.
172012**
172013******************************************************************************
172014**
172015*/
172016
172017
172018
172019
172020typedef struct Fts5HashEntry Fts5HashEntry;
172021
172022/*
172023** This file contains the implementation of an in-memory hash table used
172024** to accumuluate "term -> doclist" content before it is flused to a level-0
172025** segment.
172026*/
172027
172028
172029struct Fts5Hash {
172030  int *pnByte;                    /* Pointer to bytes counter */
172031  int nEntry;                     /* Number of entries currently in hash */
172032  int nSlot;                      /* Size of aSlot[] array */
172033  Fts5HashEntry *pScan;           /* Current ordered scan item */
172034  Fts5HashEntry **aSlot;          /* Array of hash slots */
172035};
172036
172037/*
172038** Each entry in the hash table is represented by an object of the
172039** following type. Each object, its key (zKey[]) and its current data
172040** are stored in a single memory allocation. The position list data
172041** immediately follows the key data in memory.
172042**
172043** The data that follows the key is in a similar, but not identical format
172044** to the doclist data stored in the database. It is:
172045**
172046**   * Rowid, as a varint
172047**   * Position list, without 0x00 terminator.
172048**   * Size of previous position list and rowid, as a 4 byte
172049**     big-endian integer.
172050**
172051** iRowidOff:
172052**   Offset of last rowid written to data area. Relative to first byte of
172053**   structure.
172054**
172055** nData:
172056**   Bytes of data written since iRowidOff.
172057*/
172058struct Fts5HashEntry {
172059  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
172060  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
172061
172062  int nAlloc;                     /* Total size of allocation */
172063  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
172064  int nData;                      /* Total bytes of data (incl. structure) */
172065  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
172066
172067  int iCol;                       /* Column of last value written */
172068  int iPos;                       /* Position of last value written */
172069  i64 iRowid;                     /* Rowid of last value written */
172070  char zKey[8];                   /* Nul-terminated entry key */
172071};
172072
172073/*
172074** Size of Fts5HashEntry without the zKey[] array.
172075*/
172076#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
172077
172078
172079
172080/*
172081** Allocate a new hash table.
172082*/
172083static int sqlite3Fts5HashNew(Fts5Hash **ppNew, int *pnByte){
172084  int rc = SQLITE_OK;
172085  Fts5Hash *pNew;
172086
172087  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
172088  if( pNew==0 ){
172089    rc = SQLITE_NOMEM;
172090  }else{
172091    int nByte;
172092    memset(pNew, 0, sizeof(Fts5Hash));
172093    pNew->pnByte = pnByte;
172094
172095    pNew->nSlot = 1024;
172096    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
172097    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
172098    if( pNew->aSlot==0 ){
172099      sqlite3_free(pNew);
172100      *ppNew = 0;
172101      rc = SQLITE_NOMEM;
172102    }else{
172103      memset(pNew->aSlot, 0, nByte);
172104    }
172105  }
172106  return rc;
172107}
172108
172109/*
172110** Free a hash table object.
172111*/
172112static void sqlite3Fts5HashFree(Fts5Hash *pHash){
172113  if( pHash ){
172114    sqlite3Fts5HashClear(pHash);
172115    sqlite3_free(pHash->aSlot);
172116    sqlite3_free(pHash);
172117  }
172118}
172119
172120/*
172121** Empty (but do not delete) a hash table.
172122*/
172123static void sqlite3Fts5HashClear(Fts5Hash *pHash){
172124  int i;
172125  for(i=0; i<pHash->nSlot; i++){
172126    Fts5HashEntry *pNext;
172127    Fts5HashEntry *pSlot;
172128    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
172129      pNext = pSlot->pHashNext;
172130      sqlite3_free(pSlot);
172131    }
172132  }
172133  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
172134  pHash->nEntry = 0;
172135}
172136
172137static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
172138  int i;
172139  unsigned int h = 13;
172140  for(i=n-1; i>=0; i--){
172141    h = (h << 3) ^ h ^ p[i];
172142  }
172143  return (h % nSlot);
172144}
172145
172146static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
172147  int i;
172148  unsigned int h = 13;
172149  for(i=n-1; i>=0; i--){
172150    h = (h << 3) ^ h ^ p[i];
172151  }
172152  h = (h << 3) ^ h ^ b;
172153  return (h % nSlot);
172154}
172155
172156/*
172157** Resize the hash table by doubling the number of slots.
172158*/
172159static int fts5HashResize(Fts5Hash *pHash){
172160  int nNew = pHash->nSlot*2;
172161  int i;
172162  Fts5HashEntry **apNew;
172163  Fts5HashEntry **apOld = pHash->aSlot;
172164
172165  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
172166  if( !apNew ) return SQLITE_NOMEM;
172167  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
172168
172169  for(i=0; i<pHash->nSlot; i++){
172170    while( apOld[i] ){
172171      int iHash;
172172      Fts5HashEntry *p = apOld[i];
172173      apOld[i] = p->pHashNext;
172174      iHash = fts5HashKey(nNew, (u8*)p->zKey, strlen(p->zKey));
172175      p->pHashNext = apNew[iHash];
172176      apNew[iHash] = p;
172177    }
172178  }
172179
172180  sqlite3_free(apOld);
172181  pHash->nSlot = nNew;
172182  pHash->aSlot = apNew;
172183  return SQLITE_OK;
172184}
172185
172186static void fts5HashAddPoslistSize(Fts5HashEntry *p){
172187  if( p->iSzPoslist ){
172188    u8 *pPtr = (u8*)p;
172189    int nSz = (p->nData - p->iSzPoslist - 1);         /* Size in bytes */
172190    int nPos = nSz*2 + p->bDel;                       /* Value of nPos field */
172191
172192    assert( p->bDel==0 || p->bDel==1 );
172193    if( nPos<=127 ){
172194      pPtr[p->iSzPoslist] = nPos;
172195    }else{
172196      int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
172197      memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
172198      sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
172199      p->nData += (nByte-1);
172200    }
172201    p->bDel = 0;
172202    p->iSzPoslist = 0;
172203  }
172204}
172205
172206static int sqlite3Fts5HashWrite(
172207  Fts5Hash *pHash,
172208  i64 iRowid,                     /* Rowid for this entry */
172209  int iCol,                       /* Column token appears in (-ve -> delete) */
172210  int iPos,                       /* Position of token within column */
172211  char bByte,                     /* First byte of token */
172212  const char *pToken, int nToken  /* Token to add or remove to or from index */
172213){
172214  unsigned int iHash;
172215  Fts5HashEntry *p;
172216  u8 *pPtr;
172217  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
172218
172219  /* Attempt to locate an existing hash entry */
172220  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
172221  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
172222    if( p->zKey[0]==bByte
172223     && memcmp(&p->zKey[1], pToken, nToken)==0
172224     && p->zKey[nToken+1]==0
172225    ){
172226      break;
172227    }
172228  }
172229
172230  /* If an existing hash entry cannot be found, create a new one. */
172231  if( p==0 ){
172232    int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
172233    if( nByte<128 ) nByte = 128;
172234
172235    if( (pHash->nEntry*2)>=pHash->nSlot ){
172236      int rc = fts5HashResize(pHash);
172237      if( rc!=SQLITE_OK ) return rc;
172238      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
172239    }
172240
172241    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
172242    if( !p ) return SQLITE_NOMEM;
172243    memset(p, 0, FTS5_HASHENTRYSIZE);
172244    p->nAlloc = nByte;
172245    p->zKey[0] = bByte;
172246    memcpy(&p->zKey[1], pToken, nToken);
172247    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
172248    p->zKey[nToken+1] = '\0';
172249    p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
172250    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
172251    p->iSzPoslist = p->nData;
172252    p->nData += 1;
172253    p->iRowid = iRowid;
172254    p->pHashNext = pHash->aSlot[iHash];
172255    pHash->aSlot[iHash] = p;
172256    pHash->nEntry++;
172257    nIncr += p->nData;
172258  }
172259
172260  /* Check there is enough space to append a new entry. Worst case scenario
172261  ** is:
172262  **
172263  **     + 9 bytes for a new rowid,
172264  **     + 4 byte reserved for the "poslist size" varint.
172265  **     + 1 byte for a "new column" byte,
172266  **     + 3 bytes for a new column number (16-bit max) as a varint,
172267  **     + 5 bytes for the new position offset (32-bit max).
172268  */
172269  if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
172270    int nNew = p->nAlloc * 2;
172271    Fts5HashEntry *pNew;
172272    Fts5HashEntry **pp;
172273    pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
172274    if( pNew==0 ) return SQLITE_NOMEM;
172275    pNew->nAlloc = nNew;
172276    for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
172277    *pp = pNew;
172278    p = pNew;
172279  }
172280  pPtr = (u8*)p;
172281  nIncr -= p->nData;
172282
172283  /* If this is a new rowid, append the 4-byte size field for the previous
172284  ** entry, and the new rowid for this entry.  */
172285  if( iRowid!=p->iRowid ){
172286    fts5HashAddPoslistSize(p);
172287    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
172288    p->iSzPoslist = p->nData;
172289    p->nData += 1;
172290    p->iCol = 0;
172291    p->iPos = 0;
172292    p->iRowid = iRowid;
172293  }
172294
172295  if( iCol>=0 ){
172296    /* Append a new column value, if necessary */
172297    assert( iCol>=p->iCol );
172298    if( iCol!=p->iCol ){
172299      pPtr[p->nData++] = 0x01;
172300      p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
172301      p->iCol = iCol;
172302      p->iPos = 0;
172303    }
172304
172305    /* Append the new position offset */
172306    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
172307    p->iPos = iPos;
172308  }else{
172309    /* This is a delete. Set the delete flag. */
172310    p->bDel = 1;
172311  }
172312  nIncr += p->nData;
172313
172314  *pHash->pnByte += nIncr;
172315  return SQLITE_OK;
172316}
172317
172318
172319/*
172320** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
172321** each sorted in key order. This function merges the two lists into a
172322** single list and returns a pointer to its first element.
172323*/
172324static Fts5HashEntry *fts5HashEntryMerge(
172325  Fts5HashEntry *pLeft,
172326  Fts5HashEntry *pRight
172327){
172328  Fts5HashEntry *p1 = pLeft;
172329  Fts5HashEntry *p2 = pRight;
172330  Fts5HashEntry *pRet = 0;
172331  Fts5HashEntry **ppOut = &pRet;
172332
172333  while( p1 || p2 ){
172334    if( p1==0 ){
172335      *ppOut = p2;
172336      p2 = 0;
172337    }else if( p2==0 ){
172338      *ppOut = p1;
172339      p1 = 0;
172340    }else{
172341      int i = 0;
172342      while( p1->zKey[i]==p2->zKey[i] ) i++;
172343
172344      if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
172345        /* p2 is smaller */
172346        *ppOut = p2;
172347        ppOut = &p2->pScanNext;
172348        p2 = p2->pScanNext;
172349      }else{
172350        /* p1 is smaller */
172351        *ppOut = p1;
172352        ppOut = &p1->pScanNext;
172353        p1 = p1->pScanNext;
172354      }
172355      *ppOut = 0;
172356    }
172357  }
172358
172359  return pRet;
172360}
172361
172362/*
172363** Extract all tokens from hash table iHash and link them into a list
172364** in sorted order. The hash table is cleared before returning. It is
172365** the responsibility of the caller to free the elements of the returned
172366** list.
172367*/
172368static int fts5HashEntrySort(
172369  Fts5Hash *pHash,
172370  const char *pTerm, int nTerm,   /* Query prefix, if any */
172371  Fts5HashEntry **ppSorted
172372){
172373  const int nMergeSlot = 32;
172374  Fts5HashEntry **ap;
172375  Fts5HashEntry *pList;
172376  int iSlot;
172377  int i;
172378
172379  *ppSorted = 0;
172380  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
172381  if( !ap ) return SQLITE_NOMEM;
172382  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
172383
172384  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
172385    Fts5HashEntry *pIter;
172386    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
172387      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
172388        Fts5HashEntry *pEntry = pIter;
172389        pEntry->pScanNext = 0;
172390        for(i=0; ap[i]; i++){
172391          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
172392          ap[i] = 0;
172393        }
172394        ap[i] = pEntry;
172395      }
172396    }
172397  }
172398
172399  pList = 0;
172400  for(i=0; i<nMergeSlot; i++){
172401    pList = fts5HashEntryMerge(pList, ap[i]);
172402  }
172403
172404  pHash->nEntry = 0;
172405  sqlite3_free(ap);
172406  *ppSorted = pList;
172407  return SQLITE_OK;
172408}
172409
172410/*
172411** Query the hash table for a doclist associated with term pTerm/nTerm.
172412*/
172413static int sqlite3Fts5HashQuery(
172414  Fts5Hash *pHash,                /* Hash table to query */
172415  const char *pTerm, int nTerm,   /* Query term */
172416  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
172417  int *pnDoclist                  /* OUT: Size of doclist in bytes */
172418){
172419  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
172420  Fts5HashEntry *p;
172421
172422  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
172423    if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
172424  }
172425
172426  if( p ){
172427    fts5HashAddPoslistSize(p);
172428    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
172429    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
172430  }else{
172431    *ppDoclist = 0;
172432    *pnDoclist = 0;
172433  }
172434
172435  return SQLITE_OK;
172436}
172437
172438static int sqlite3Fts5HashScanInit(
172439  Fts5Hash *p,                    /* Hash table to query */
172440  const char *pTerm, int nTerm    /* Query prefix */
172441){
172442  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
172443}
172444
172445static void sqlite3Fts5HashScanNext(Fts5Hash *p){
172446  assert( !sqlite3Fts5HashScanEof(p) );
172447  p->pScan = p->pScan->pScanNext;
172448}
172449
172450static int sqlite3Fts5HashScanEof(Fts5Hash *p){
172451  return (p->pScan==0);
172452}
172453
172454static void sqlite3Fts5HashScanEntry(
172455  Fts5Hash *pHash,
172456  const char **pzTerm,            /* OUT: term (nul-terminated) */
172457  const u8 **ppDoclist,           /* OUT: pointer to doclist */
172458  int *pnDoclist                  /* OUT: size of doclist in bytes */
172459){
172460  Fts5HashEntry *p;
172461  if( (p = pHash->pScan) ){
172462    int nTerm = strlen(p->zKey);
172463    fts5HashAddPoslistSize(p);
172464    *pzTerm = p->zKey;
172465    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
172466    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
172467  }else{
172468    *pzTerm = 0;
172469    *ppDoclist = 0;
172470    *pnDoclist = 0;
172471  }
172472}
172473
172474
172475/*
172476** 2014 May 31
172477**
172478** The author disclaims copyright to this source code.  In place of
172479** a legal notice, here is a blessing:
172480**
172481**    May you do good and not evil.
172482**    May you find forgiveness for yourself and forgive others.
172483**    May you share freely, never taking more than you give.
172484**
172485******************************************************************************
172486**
172487** Low level access to the FTS index stored in the database file. The
172488** routines in this file file implement all read and write access to the
172489** %_data table. Other parts of the system access this functionality via
172490** the interface defined in fts5Int.h.
172491*/
172492
172493
172494
172495/*
172496** Overview:
172497**
172498** The %_data table contains all the FTS indexes for an FTS5 virtual table.
172499** As well as the main term index, there may be up to 31 prefix indexes.
172500** The format is similar to FTS3/4, except that:
172501**
172502**   * all segment b-tree leaf data is stored in fixed size page records
172503**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
172504**     taken to ensure it is possible to iterate in either direction through
172505**     the entries in a doclist, or to seek to a specific entry within a
172506**     doclist, without loading it into memory.
172507**
172508**   * large doclists that span many pages have associated "doclist index"
172509**     records that contain a copy of the first rowid on each page spanned by
172510**     the doclist. This is used to speed up seek operations, and merges of
172511**     large doclists with very small doclists.
172512**
172513**   * extra fields in the "structure record" record the state of ongoing
172514**     incremental merge operations.
172515**
172516*/
172517
172518
172519#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
172520#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
172521
172522#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
172523
172524#define FTS5_MAIN_PREFIX '0'
172525
172526#if FTS5_MAX_PREFIX_INDEXES > 31
172527# error "FTS5_MAX_PREFIX_INDEXES is too large"
172528#endif
172529
172530/*
172531** Details:
172532**
172533** The %_data table managed by this module,
172534**
172535**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
172536**
172537** , contains the following 5 types of records. See the comments surrounding
172538** the FTS5_*_ROWID macros below for a description of how %_data rowids are
172539** assigned to each fo them.
172540**
172541** 1. Structure Records:
172542**
172543**   The set of segments that make up an index - the index structure - are
172544**   recorded in a single record within the %_data table. The record consists
172545**   of a single 32-bit configuration cookie value followed by a list of
172546**   SQLite varints. If the FTS table features more than one index (because
172547**   there are one or more prefix indexes), it is guaranteed that all share
172548**   the same cookie value.
172549**
172550**   Immediately following the configuration cookie, the record begins with
172551**   three varints:
172552**
172553**     + number of levels,
172554**     + total number of segments on all levels,
172555**     + value of write counter.
172556**
172557**   Then, for each level from 0 to nMax:
172558**
172559**     + number of input segments in ongoing merge.
172560**     + total number of segments in level.
172561**     + for each segment from oldest to newest:
172562**         + segment id (always > 0)
172563**         + first leaf page number (often 1, always greater than 0)
172564**         + final leaf page number
172565**
172566** 2. The Averages Record:
172567**
172568**   A single record within the %_data table. The data is a list of varints.
172569**   The first value is the number of rows in the index. Then, for each column
172570**   from left to right, the total number of tokens in the column for all
172571**   rows of the table.
172572**
172573** 3. Segment leaves:
172574**
172575**   TERM/DOCLIST FORMAT:
172576**
172577**     Most of each segment leaf is taken up by term/doclist data. The
172578**     general format of term/doclist, starting with the first term
172579**     on the leaf page, is:
172580**
172581**         varint : size of first term
172582**         blob:    first term data
172583**         doclist: first doclist
172584**         zero-or-more {
172585**           varint:  number of bytes in common with previous term
172586**           varint:  number of bytes of new term data (nNew)
172587**           blob:    nNew bytes of new term data
172588**           doclist: next doclist
172589**         }
172590**
172591**     doclist format:
172592**
172593**         varint:  first rowid
172594**         poslist: first poslist
172595**         zero-or-more {
172596**           varint:  rowid delta (always > 0)
172597**           poslist: next poslist
172598**         }
172599**
172600**     poslist format:
172601**
172602**         varint: size of poslist in bytes multiplied by 2, not including
172603**                 this field. Plus 1 if this entry carries the "delete" flag.
172604**         collist: collist for column 0
172605**         zero-or-more {
172606**           0x01 byte
172607**           varint: column number (I)
172608**           collist: collist for column I
172609**         }
172610**
172611**     collist format:
172612**
172613**         varint: first offset + 2
172614**         zero-or-more {
172615**           varint: offset delta + 2
172616**         }
172617**
172618**   PAGE FORMAT
172619**
172620**     Each leaf page begins with a 4-byte header containing 2 16-bit
172621**     unsigned integer fields in big-endian format. They are:
172622**
172623**       * The byte offset of the first rowid on the page, if it exists
172624**         and occurs before the first term (otherwise 0).
172625**
172626**       * The byte offset of the start of the page footer. If the page
172627**         footer is 0 bytes in size, then this field is the same as the
172628**         size of the leaf page in bytes.
172629**
172630**     The page footer consists of a single varint for each term located
172631**     on the page. Each varint is the byte offset of the current term
172632**     within the page, delta-compressed against the previous value. In
172633**     other words, the first varint in the footer is the byte offset of
172634**     the first term, the second is the byte offset of the second less that
172635**     of the first, and so on.
172636**
172637**     The term/doclist format described above is accurate if the entire
172638**     term/doclist data fits on a single leaf page. If this is not the case,
172639**     the format is changed in two ways:
172640**
172641**       + if the first rowid on a page occurs before the first term, it
172642**         is stored as a literal value:
172643**
172644**             varint:  first rowid
172645**
172646**       + the first term on each page is stored in the same way as the
172647**         very first term of the segment:
172648**
172649**             varint : size of first term
172650**             blob:    first term data
172651**
172652** 5. Segment doclist indexes:
172653**
172654**   Doclist indexes are themselves b-trees, however they usually consist of
172655**   a single leaf record only. The format of each doclist index leaf page
172656**   is:
172657**
172658**     * Flags byte. Bits are:
172659**         0x01: Clear if leaf is also the root page, otherwise set.
172660**
172661**     * Page number of fts index leaf page. As a varint.
172662**
172663**     * First rowid on page indicated by previous field. As a varint.
172664**
172665**     * A list of varints, one for each subsequent termless page. A
172666**       positive delta if the termless page contains at least one rowid,
172667**       or an 0x00 byte otherwise.
172668**
172669**   Internal doclist index nodes are:
172670**
172671**     * Flags byte. Bits are:
172672**         0x01: Clear for root page, otherwise set.
172673**
172674**     * Page number of first child page. As a varint.
172675**
172676**     * Copy of first rowid on page indicated by previous field. As a varint.
172677**
172678**     * A list of delta-encoded varints - the first rowid on each subsequent
172679**       child page.
172680**
172681*/
172682
172683/*
172684** Rowids for the averages and structure records in the %_data table.
172685*/
172686#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
172687#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
172688
172689/*
172690** Macros determining the rowids used by segment leaves and dlidx leaves
172691** and nodes. All nodes and leaves are stored in the %_data table with large
172692** positive rowids.
172693**
172694** Each segment has a unique non-zero 16-bit id.
172695**
172696** The rowid for each segment leaf is found by passing the segment id and
172697** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
172698** sequentially starting from 1.
172699*/
172700#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
172701#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
172702#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
172703#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
172704
172705#define fts5_dri(segid, dlidx, height, pgno) (                                 \
172706 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
172707 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
172708 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
172709 ((i64)(pgno))                                                                 \
172710)
172711
172712#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
172713#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
172714
172715/*
172716** Maximum segments permitted in a single index
172717*/
172718#define FTS5_MAX_SEGMENT 2000
172719
172720#ifdef SQLITE_DEBUG
172721static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
172722#endif
172723
172724
172725/*
172726** Each time a blob is read from the %_data table, it is padded with this
172727** many zero bytes. This makes it easier to decode the various record formats
172728** without overreading if the records are corrupt.
172729*/
172730#define FTS5_DATA_ZERO_PADDING 8
172731#define FTS5_DATA_PADDING 20
172732
172733typedef struct Fts5Data Fts5Data;
172734typedef struct Fts5DlidxIter Fts5DlidxIter;
172735typedef struct Fts5DlidxLvl Fts5DlidxLvl;
172736typedef struct Fts5DlidxWriter Fts5DlidxWriter;
172737typedef struct Fts5PageWriter Fts5PageWriter;
172738typedef struct Fts5SegIter Fts5SegIter;
172739typedef struct Fts5DoclistIter Fts5DoclistIter;
172740typedef struct Fts5SegWriter Fts5SegWriter;
172741typedef struct Fts5Structure Fts5Structure;
172742typedef struct Fts5StructureLevel Fts5StructureLevel;
172743typedef struct Fts5StructureSegment Fts5StructureSegment;
172744
172745struct Fts5Data {
172746  u8 *p;                          /* Pointer to buffer containing record */
172747  int nn;                         /* Size of record in bytes */
172748  int szLeaf;                     /* Size of leaf without page-index */
172749};
172750
172751/*
172752** One object per %_data table.
172753*/
172754struct Fts5Index {
172755  Fts5Config *pConfig;            /* Virtual table configuration */
172756  char *zDataTbl;                 /* Name of %_data table */
172757  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
172758
172759  /*
172760  ** Variables related to the accumulation of tokens and doclists within the
172761  ** in-memory hash tables before they are flushed to disk.
172762  */
172763  Fts5Hash *pHash;                /* Hash table for in-memory data */
172764  int nMaxPendingData;            /* Max pending data before flush to disk */
172765  int nPendingData;               /* Current bytes of pending data */
172766  i64 iWriteRowid;                /* Rowid for current doc being written */
172767  int bDelete;                    /* Current write is a delete */
172768
172769  /* Error state. */
172770  int rc;                         /* Current error code */
172771
172772  /* State used by the fts5DataXXX() functions. */
172773  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
172774  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
172775  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
172776  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
172777  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
172778  sqlite3_stmt *pIdxSelect;
172779  int nRead;                      /* Total number of blocks read */
172780};
172781
172782struct Fts5DoclistIter {
172783  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
172784
172785  /* Output variables. aPoslist==0 at EOF */
172786  i64 iRowid;
172787  u8 *aPoslist;
172788  int nPoslist;
172789  int nSize;
172790};
172791
172792/*
172793** The contents of the "structure" record for each index are represented
172794** using an Fts5Structure record in memory. Which uses instances of the
172795** other Fts5StructureXXX types as components.
172796*/
172797struct Fts5StructureSegment {
172798  int iSegid;                     /* Segment id */
172799  int pgnoFirst;                  /* First leaf page number in segment */
172800  int pgnoLast;                   /* Last leaf page number in segment */
172801};
172802struct Fts5StructureLevel {
172803  int nMerge;                     /* Number of segments in incr-merge */
172804  int nSeg;                       /* Total number of segments on level */
172805  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
172806};
172807struct Fts5Structure {
172808  int nRef;                       /* Object reference count */
172809  u64 nWriteCounter;              /* Total leaves written to level 0 */
172810  int nSegment;                   /* Total segments in this structure */
172811  int nLevel;                     /* Number of levels in this index */
172812  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
172813};
172814
172815/*
172816** An object of type Fts5SegWriter is used to write to segments.
172817*/
172818struct Fts5PageWriter {
172819  int pgno;                       /* Page number for this page */
172820  int iPrevPgidx;                 /* Previous value written into pgidx */
172821  Fts5Buffer buf;                 /* Buffer containing leaf data */
172822  Fts5Buffer pgidx;               /* Buffer containing page-index */
172823  Fts5Buffer term;                /* Buffer containing previous term on page */
172824};
172825struct Fts5DlidxWriter {
172826  int pgno;                       /* Page number for this page */
172827  int bPrevValid;                 /* True if iPrev is valid */
172828  i64 iPrev;                      /* Previous rowid value written to page */
172829  Fts5Buffer buf;                 /* Buffer containing page data */
172830};
172831struct Fts5SegWriter {
172832  int iSegid;                     /* Segid to write to */
172833  Fts5PageWriter writer;          /* PageWriter object */
172834  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
172835  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
172836  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
172837  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
172838  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
172839  int nLeafWritten;               /* Number of leaf pages written */
172840  int nEmpty;                     /* Number of contiguous term-less nodes */
172841
172842  int nDlidx;                     /* Allocated size of aDlidx[] array */
172843  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
172844
172845  /* Values to insert into the %_idx table */
172846  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
172847  int iBtPage;                    /* Page number corresponding to btterm */
172848};
172849
172850/*
172851** Object for iterating through the merged results of one or more segments,
172852** visiting each term/rowid pair in the merged data.
172853**
172854** nSeg is always a power of two greater than or equal to the number of
172855** segments that this object is merging data from. Both the aSeg[] and
172856** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
172857** with zeroed objects - these are handled as if they were iterators opened
172858** on empty segments.
172859**
172860** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
172861** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
172862** comparison in this context is the index of the iterator that currently
172863** points to the smaller term/rowid combination. Iterators at EOF are
172864** considered to be greater than all other iterators.
172865**
172866** aFirst[1] contains the index in aSeg[] of the iterator that points to
172867** the smallest key overall. aFirst[0] is unused.
172868*/
172869
172870typedef struct Fts5CResult Fts5CResult;
172871struct Fts5CResult {
172872  u16 iFirst;                     /* aSeg[] index of firstest iterator */
172873  u8 bTermEq;                     /* True if the terms are equal */
172874};
172875
172876/*
172877** Object for iterating through a single segment, visiting each term/rowid
172878** pair in the segment.
172879**
172880** pSeg:
172881**   The segment to iterate through.
172882**
172883** iLeafPgno:
172884**   Current leaf page number within segment.
172885**
172886** iLeafOffset:
172887**   Byte offset within the current leaf that is the first byte of the
172888**   position list data (one byte passed the position-list size field).
172889**   rowid field of the current entry. Usually this is the size field of the
172890**   position list data. The exception is if the rowid for the current entry
172891**   is the last thing on the leaf page.
172892**
172893** pLeaf:
172894**   Buffer containing current leaf page data. Set to NULL at EOF.
172895**
172896** iTermLeafPgno, iTermLeafOffset:
172897**   Leaf page number containing the last term read from the segment. And
172898**   the offset immediately following the term data.
172899**
172900** flags:
172901**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
172902**
172903**   FTS5_SEGITER_ONETERM:
172904**     If set, set the iterator to point to EOF after the current doclist
172905**     has been exhausted. Do not proceed to the next term in the segment.
172906**
172907**   FTS5_SEGITER_REVERSE:
172908**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
172909**     it is set, iterate through rowid in descending order instead of the
172910**     default ascending order.
172911**
172912** iRowidOffset/nRowidOffset/aRowidOffset:
172913**     These are used if the FTS5_SEGITER_REVERSE flag is set.
172914**
172915**     For each rowid on the page corresponding to the current term, the
172916**     corresponding aRowidOffset[] entry is set to the byte offset of the
172917**     start of the "position-list-size" field within the page.
172918**
172919** iTermIdx:
172920**     Index of current term on iTermLeafPgno.
172921*/
172922struct Fts5SegIter {
172923  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
172924  int flags;                      /* Mask of configuration flags */
172925  int iLeafPgno;                  /* Current leaf page number */
172926  Fts5Data *pLeaf;                /* Current leaf data */
172927  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
172928  int iLeafOffset;                /* Byte offset within current leaf */
172929
172930  /* The page and offset from which the current term was read. The offset
172931  ** is the offset of the first rowid in the current doclist.  */
172932  int iTermLeafPgno;
172933  int iTermLeafOffset;
172934
172935  int iPgidxOff;                  /* Next offset in pgidx */
172936  int iEndofDoclist;
172937
172938  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
172939  int iRowidOffset;               /* Current entry in aRowidOffset[] */
172940  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
172941  int *aRowidOffset;              /* Array of offset to rowid fields */
172942
172943  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
172944
172945  /* Variables populated based on current entry. */
172946  Fts5Buffer term;                /* Current term */
172947  i64 iRowid;                     /* Current rowid */
172948  int nPos;                       /* Number of bytes in current position list */
172949  int bDel;                       /* True if the delete flag is set */
172950};
172951
172952/*
172953** Argument is a pointer to an Fts5Data structure that contains a
172954** leaf page.
172955*/
172956#define ASSERT_SZLEAF_OK(x) assert( \
172957    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
172958)
172959
172960#define FTS5_SEGITER_ONETERM 0x01
172961#define FTS5_SEGITER_REVERSE 0x02
172962
172963
172964/*
172965** Argument is a pointer to an Fts5Data structure that contains a leaf
172966** page. This macro evaluates to true if the leaf contains no terms, or
172967** false if it contains at least one term.
172968*/
172969#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
172970
172971#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
172972
172973#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
172974
172975/*
172976** poslist:
172977**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
172978**   There is no way to tell if this is populated or not.
172979*/
172980struct Fts5IndexIter {
172981  Fts5Index *pIndex;              /* Index that owns this iterator */
172982  Fts5Structure *pStruct;         /* Database structure for this iterator */
172983  Fts5Buffer poslist;             /* Buffer containing current poslist */
172984
172985  int nSeg;                       /* Size of aSeg[] array */
172986  int bRev;                       /* True to iterate in reverse order */
172987  u8 bSkipEmpty;                  /* True to skip deleted entries */
172988  u8 bEof;                        /* True at EOF */
172989  u8 bFiltered;                   /* True if column-filter already applied */
172990
172991  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
172992  Fts5CResult *aFirst;            /* Current merge state (see above) */
172993  Fts5SegIter aSeg[1];            /* Array of segment iterators */
172994};
172995
172996
172997/*
172998** An instance of the following type is used to iterate through the contents
172999** of a doclist-index record.
173000**
173001** pData:
173002**   Record containing the doclist-index data.
173003**
173004** bEof:
173005**   Set to true once iterator has reached EOF.
173006**
173007** iOff:
173008**   Set to the current offset within record pData.
173009*/
173010struct Fts5DlidxLvl {
173011  Fts5Data *pData;              /* Data for current page of this level */
173012  int iOff;                     /* Current offset into pData */
173013  int bEof;                     /* At EOF already */
173014  int iFirstOff;                /* Used by reverse iterators */
173015
173016  /* Output variables */
173017  int iLeafPgno;                /* Page number of current leaf page */
173018  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
173019};
173020struct Fts5DlidxIter {
173021  int nLvl;
173022  int iSegid;
173023  Fts5DlidxLvl aLvl[1];
173024};
173025
173026static void fts5PutU16(u8 *aOut, u16 iVal){
173027  aOut[0] = (iVal>>8);
173028  aOut[1] = (iVal&0xFF);
173029}
173030
173031static u16 fts5GetU16(const u8 *aIn){
173032  return ((u16)aIn[0] << 8) + aIn[1];
173033}
173034
173035/*
173036** Allocate and return a buffer at least nByte bytes in size.
173037**
173038** If an OOM error is encountered, return NULL and set the error code in
173039** the Fts5Index handle passed as the first argument.
173040*/
173041static void *fts5IdxMalloc(Fts5Index *p, int nByte){
173042  return sqlite3Fts5MallocZero(&p->rc, nByte);
173043}
173044
173045/*
173046** Compare the contents of the pLeft buffer with the pRight/nRight blob.
173047**
173048** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
173049** +ve if pRight is smaller than pLeft. In other words:
173050**
173051**     res = *pLeft - *pRight
173052*/
173053#ifdef SQLITE_DEBUG
173054static int fts5BufferCompareBlob(
173055  Fts5Buffer *pLeft,              /* Left hand side of comparison */
173056  const u8 *pRight, int nRight    /* Right hand side of comparison */
173057){
173058  int nCmp = MIN(pLeft->n, nRight);
173059  int res = memcmp(pLeft->p, pRight, nCmp);
173060  return (res==0 ? (pLeft->n - nRight) : res);
173061}
173062#endif
173063
173064/*
173065** Compare the contents of the two buffers using memcmp(). If one buffer
173066** is a prefix of the other, it is considered the lesser.
173067**
173068** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
173069** +ve if pRight is smaller than pLeft. In other words:
173070**
173071**     res = *pLeft - *pRight
173072*/
173073static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
173074  int nCmp = MIN(pLeft->n, pRight->n);
173075  int res = memcmp(pLeft->p, pRight->p, nCmp);
173076  return (res==0 ? (pLeft->n - pRight->n) : res);
173077}
173078
173079#ifdef SQLITE_DEBUG
173080static int fts5BlobCompare(
173081  const u8 *pLeft, int nLeft,
173082  const u8 *pRight, int nRight
173083){
173084  int nCmp = MIN(nLeft, nRight);
173085  int res = memcmp(pLeft, pRight, nCmp);
173086  return (res==0 ? (nLeft - nRight) : res);
173087}
173088#endif
173089
173090static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
173091  int ret;
173092  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
173093  return ret;
173094}
173095
173096/*
173097** Close the read-only blob handle, if it is open.
173098*/
173099static void fts5CloseReader(Fts5Index *p){
173100  if( p->pReader ){
173101    sqlite3_blob *pReader = p->pReader;
173102    p->pReader = 0;
173103    sqlite3_blob_close(pReader);
173104  }
173105}
173106
173107
173108/*
173109** Retrieve a record from the %_data table.
173110**
173111** If an error occurs, NULL is returned and an error left in the
173112** Fts5Index object.
173113*/
173114static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
173115  Fts5Data *pRet = 0;
173116  if( p->rc==SQLITE_OK ){
173117    int rc = SQLITE_OK;
173118
173119    if( p->pReader ){
173120      /* This call may return SQLITE_ABORT if there has been a savepoint
173121      ** rollback since it was last used. In this case a new blob handle
173122      ** is required.  */
173123      sqlite3_blob *pBlob = p->pReader;
173124      p->pReader = 0;
173125      rc = sqlite3_blob_reopen(pBlob, iRowid);
173126      assert( p->pReader==0 );
173127      p->pReader = pBlob;
173128      if( rc!=SQLITE_OK ){
173129        fts5CloseReader(p);
173130      }
173131      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
173132    }
173133
173134    /* If the blob handle is not open at this point, open it and seek
173135    ** to the requested entry.  */
173136    if( p->pReader==0 && rc==SQLITE_OK ){
173137      Fts5Config *pConfig = p->pConfig;
173138      rc = sqlite3_blob_open(pConfig->db,
173139          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
173140      );
173141    }
173142
173143    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
173144    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
173145    ** All the reasons those functions might return SQLITE_ERROR - missing
173146    ** table, missing row, non-blob/text in block column - indicate
173147    ** backing store corruption.  */
173148    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
173149
173150    if( rc==SQLITE_OK ){
173151      u8 *aOut = 0;               /* Read blob data into this buffer */
173152      int nByte = sqlite3_blob_bytes(p->pReader);
173153      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
173154      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
173155      if( pRet ){
173156        pRet->nn = nByte;
173157        aOut = pRet->p = (u8*)&pRet[1];
173158      }else{
173159        rc = SQLITE_NOMEM;
173160      }
173161
173162      if( rc==SQLITE_OK ){
173163        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
173164      }
173165      if( rc!=SQLITE_OK ){
173166        sqlite3_free(pRet);
173167        pRet = 0;
173168      }else{
173169        /* TODO1: Fix this */
173170        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
173171      }
173172    }
173173    p->rc = rc;
173174    p->nRead++;
173175  }
173176
173177  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
173178  return pRet;
173179}
173180
173181/*
173182** Release a reference to data record returned by an earlier call to
173183** fts5DataRead().
173184*/
173185static void fts5DataRelease(Fts5Data *pData){
173186  sqlite3_free(pData);
173187}
173188
173189static int fts5IndexPrepareStmt(
173190  Fts5Index *p,
173191  sqlite3_stmt **ppStmt,
173192  char *zSql
173193){
173194  if( p->rc==SQLITE_OK ){
173195    if( zSql ){
173196      p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
173197    }else{
173198      p->rc = SQLITE_NOMEM;
173199    }
173200  }
173201  sqlite3_free(zSql);
173202  return p->rc;
173203}
173204
173205
173206/*
173207** INSERT OR REPLACE a record into the %_data table.
173208*/
173209static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
173210  if( p->rc!=SQLITE_OK ) return;
173211
173212  if( p->pWriter==0 ){
173213    Fts5Config *pConfig = p->pConfig;
173214    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
173215          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
173216          pConfig->zDb, pConfig->zName
173217    ));
173218    if( p->rc ) return;
173219  }
173220
173221  sqlite3_bind_int64(p->pWriter, 1, iRowid);
173222  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
173223  sqlite3_step(p->pWriter);
173224  p->rc = sqlite3_reset(p->pWriter);
173225}
173226
173227/*
173228** Execute the following SQL:
173229**
173230**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
173231*/
173232static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
173233  if( p->rc!=SQLITE_OK ) return;
173234
173235  if( p->pDeleter==0 ){
173236    int rc;
173237    Fts5Config *pConfig = p->pConfig;
173238    char *zSql = sqlite3_mprintf(
173239        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
173240          pConfig->zDb, pConfig->zName
173241    );
173242    if( zSql==0 ){
173243      rc = SQLITE_NOMEM;
173244    }else{
173245      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
173246      sqlite3_free(zSql);
173247    }
173248    if( rc!=SQLITE_OK ){
173249      p->rc = rc;
173250      return;
173251    }
173252  }
173253
173254  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
173255  sqlite3_bind_int64(p->pDeleter, 2, iLast);
173256  sqlite3_step(p->pDeleter);
173257  p->rc = sqlite3_reset(p->pDeleter);
173258}
173259
173260/*
173261** Remove all records associated with segment iSegid.
173262*/
173263static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
173264  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
173265  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
173266  fts5DataDelete(p, iFirst, iLast);
173267  if( p->pIdxDeleter==0 ){
173268    Fts5Config *pConfig = p->pConfig;
173269    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
173270          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
173271          pConfig->zDb, pConfig->zName
173272    ));
173273  }
173274  if( p->rc==SQLITE_OK ){
173275    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
173276    sqlite3_step(p->pIdxDeleter);
173277    p->rc = sqlite3_reset(p->pIdxDeleter);
173278  }
173279}
173280
173281/*
173282** Release a reference to an Fts5Structure object returned by an earlier
173283** call to fts5StructureRead() or fts5StructureDecode().
173284*/
173285static void fts5StructureRelease(Fts5Structure *pStruct){
173286  if( pStruct && 0>=(--pStruct->nRef) ){
173287    int i;
173288    assert( pStruct->nRef==0 );
173289    for(i=0; i<pStruct->nLevel; i++){
173290      sqlite3_free(pStruct->aLevel[i].aSeg);
173291    }
173292    sqlite3_free(pStruct);
173293  }
173294}
173295
173296static void fts5StructureRef(Fts5Structure *pStruct){
173297  pStruct->nRef++;
173298}
173299
173300/*
173301** Deserialize and return the structure record currently stored in serialized
173302** form within buffer pData/nData.
173303**
173304** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
173305** are over-allocated by one slot. This allows the structure contents
173306** to be more easily edited.
173307**
173308** If an error occurs, *ppOut is set to NULL and an SQLite error code
173309** returned. Otherwise, *ppOut is set to point to the new object and
173310** SQLITE_OK returned.
173311*/
173312static int fts5StructureDecode(
173313  const u8 *pData,                /* Buffer containing serialized structure */
173314  int nData,                      /* Size of buffer pData in bytes */
173315  int *piCookie,                  /* Configuration cookie value */
173316  Fts5Structure **ppOut           /* OUT: Deserialized object */
173317){
173318  int rc = SQLITE_OK;
173319  int i = 0;
173320  int iLvl;
173321  int nLevel = 0;
173322  int nSegment = 0;
173323  int nByte;                      /* Bytes of space to allocate at pRet */
173324  Fts5Structure *pRet = 0;        /* Structure object to return */
173325
173326  /* Grab the cookie value */
173327  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
173328  i = 4;
173329
173330  /* Read the total number of levels and segments from the start of the
173331  ** structure record.  */
173332  i += fts5GetVarint32(&pData[i], nLevel);
173333  i += fts5GetVarint32(&pData[i], nSegment);
173334  nByte = (
173335      sizeof(Fts5Structure) +                    /* Main structure */
173336      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
173337  );
173338  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
173339
173340  if( pRet ){
173341    pRet->nRef = 1;
173342    pRet->nLevel = nLevel;
173343    pRet->nSegment = nSegment;
173344    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
173345
173346    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
173347      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
173348      int nTotal;
173349      int iSeg;
173350
173351      i += fts5GetVarint32(&pData[i], pLvl->nMerge);
173352      i += fts5GetVarint32(&pData[i], nTotal);
173353      assert( nTotal>=pLvl->nMerge );
173354      pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
173355          nTotal * sizeof(Fts5StructureSegment)
173356      );
173357
173358      if( rc==SQLITE_OK ){
173359        pLvl->nSeg = nTotal;
173360        for(iSeg=0; iSeg<nTotal; iSeg++){
173361          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
173362          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
173363          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
173364        }
173365      }else{
173366        fts5StructureRelease(pRet);
173367        pRet = 0;
173368      }
173369    }
173370  }
173371
173372  *ppOut = pRet;
173373  return rc;
173374}
173375
173376/*
173377**
173378*/
173379static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
173380  if( *pRc==SQLITE_OK ){
173381    Fts5Structure *pStruct = *ppStruct;
173382    int nLevel = pStruct->nLevel;
173383    int nByte = (
173384        sizeof(Fts5Structure) +                  /* Main structure */
173385        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
173386    );
173387
173388    pStruct = sqlite3_realloc(pStruct, nByte);
173389    if( pStruct ){
173390      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
173391      pStruct->nLevel++;
173392      *ppStruct = pStruct;
173393    }else{
173394      *pRc = SQLITE_NOMEM;
173395    }
173396  }
173397}
173398
173399/*
173400** Extend level iLvl so that there is room for at least nExtra more
173401** segments.
173402*/
173403static void fts5StructureExtendLevel(
173404  int *pRc,
173405  Fts5Structure *pStruct,
173406  int iLvl,
173407  int nExtra,
173408  int bInsert
173409){
173410  if( *pRc==SQLITE_OK ){
173411    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
173412    Fts5StructureSegment *aNew;
173413    int nByte;
173414
173415    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
173416    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
173417    if( aNew ){
173418      if( bInsert==0 ){
173419        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
173420      }else{
173421        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
173422        memmove(&aNew[nExtra], aNew, nMove);
173423        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
173424      }
173425      pLvl->aSeg = aNew;
173426    }else{
173427      *pRc = SQLITE_NOMEM;
173428    }
173429  }
173430}
173431
173432/*
173433** Read, deserialize and return the structure record.
173434**
173435** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
173436** are over-allocated as described for function fts5StructureDecode()
173437** above.
173438**
173439** If an error occurs, NULL is returned and an error code left in the
173440** Fts5Index handle. If an error has already occurred when this function
173441** is called, it is a no-op.
173442*/
173443static Fts5Structure *fts5StructureRead(Fts5Index *p){
173444  Fts5Config *pConfig = p->pConfig;
173445  Fts5Structure *pRet = 0;        /* Object to return */
173446  int iCookie;                    /* Configuration cookie */
173447  Fts5Data *pData;
173448
173449  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
173450  if( p->rc ) return 0;
173451  /* TODO: Do we need this if the leaf-index is appended? Probably... */
173452  memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
173453  p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
173454  if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
173455    p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
173456  }
173457
173458  fts5DataRelease(pData);
173459  if( p->rc!=SQLITE_OK ){
173460    fts5StructureRelease(pRet);
173461    pRet = 0;
173462  }
173463  return pRet;
173464}
173465
173466/*
173467** Return the total number of segments in index structure pStruct. This
173468** function is only ever used as part of assert() conditions.
173469*/
173470#ifdef SQLITE_DEBUG
173471static int fts5StructureCountSegments(Fts5Structure *pStruct){
173472  int nSegment = 0;               /* Total number of segments */
173473  if( pStruct ){
173474    int iLvl;                     /* Used to iterate through levels */
173475    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
173476      nSegment += pStruct->aLevel[iLvl].nSeg;
173477    }
173478  }
173479
173480  return nSegment;
173481}
173482#endif
173483
173484/*
173485** Serialize and store the "structure" record.
173486**
173487** If an error occurs, leave an error code in the Fts5Index object. If an
173488** error has already occurred, this function is a no-op.
173489*/
173490static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
173491  if( p->rc==SQLITE_OK ){
173492    Fts5Buffer buf;               /* Buffer to serialize record into */
173493    int iLvl;                     /* Used to iterate through levels */
173494    int iCookie;                  /* Cookie value to store */
173495
173496    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
173497    memset(&buf, 0, sizeof(Fts5Buffer));
173498
173499    /* Append the current configuration cookie */
173500    iCookie = p->pConfig->iCookie;
173501    if( iCookie<0 ) iCookie = 0;
173502    fts5BufferAppend32(&p->rc, &buf, iCookie);
173503
173504    fts5BufferAppendVarint(&p->rc, &buf, pStruct->nLevel);
173505    fts5BufferAppendVarint(&p->rc, &buf, pStruct->nSegment);
173506    fts5BufferAppendVarint(&p->rc, &buf, (i64)pStruct->nWriteCounter);
173507
173508    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
173509      int iSeg;                     /* Used to iterate through segments */
173510      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
173511      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
173512      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
173513      assert( pLvl->nMerge<=pLvl->nSeg );
173514
173515      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
173516        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
173517        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
173518        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
173519      }
173520    }
173521
173522    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
173523    fts5BufferFree(&buf);
173524  }
173525}
173526
173527#if 0
173528static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
173529static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
173530  int rc = SQLITE_OK;
173531  Fts5Buffer buf;
173532  memset(&buf, 0, sizeof(buf));
173533  fts5DebugStructure(&rc, &buf, pStruct);
173534  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
173535  fflush(stdout);
173536  fts5BufferFree(&buf);
173537}
173538#else
173539# define fts5PrintStructure(x,y)
173540#endif
173541
173542static int fts5SegmentSize(Fts5StructureSegment *pSeg){
173543  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
173544}
173545
173546/*
173547** Return a copy of index structure pStruct. Except, promote as many
173548** segments as possible to level iPromote. If an OOM occurs, NULL is
173549** returned.
173550*/
173551static void fts5StructurePromoteTo(
173552  Fts5Index *p,
173553  int iPromote,
173554  int szPromote,
173555  Fts5Structure *pStruct
173556){
173557  int il, is;
173558  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
173559
173560  if( pOut->nMerge==0 ){
173561    for(il=iPromote+1; il<pStruct->nLevel; il++){
173562      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
173563      if( pLvl->nMerge ) return;
173564      for(is=pLvl->nSeg-1; is>=0; is--){
173565        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
173566        if( sz>szPromote ) return;
173567        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
173568        if( p->rc ) return;
173569        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
173570        pOut->nSeg++;
173571        pLvl->nSeg--;
173572      }
173573    }
173574  }
173575}
173576
173577/*
173578** A new segment has just been written to level iLvl of index structure
173579** pStruct. This function determines if any segments should be promoted
173580** as a result. Segments are promoted in two scenarios:
173581**
173582**   a) If the segment just written is smaller than one or more segments
173583**      within the previous populated level, it is promoted to the previous
173584**      populated level.
173585**
173586**   b) If the segment just written is larger than the newest segment on
173587**      the next populated level, then that segment, and any other adjacent
173588**      segments that are also smaller than the one just written, are
173589**      promoted.
173590**
173591** If one or more segments are promoted, the structure object is updated
173592** to reflect this.
173593*/
173594static void fts5StructurePromote(
173595  Fts5Index *p,                   /* FTS5 backend object */
173596  int iLvl,                       /* Index level just updated */
173597  Fts5Structure *pStruct          /* Index structure */
173598){
173599  if( p->rc==SQLITE_OK ){
173600    int iTst;
173601    int iPromote = -1;
173602    int szPromote = 0;            /* Promote anything this size or smaller */
173603    Fts5StructureSegment *pSeg;   /* Segment just written */
173604    int szSeg;                    /* Size of segment just written */
173605    int nSeg = pStruct->aLevel[iLvl].nSeg;
173606
173607    if( nSeg==0 ) return;
173608    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
173609    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
173610
173611    /* Check for condition (a) */
173612    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
173613    if( iTst>=0 ){
173614      int i;
173615      int szMax = 0;
173616      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
173617      assert( pTst->nMerge==0 );
173618      for(i=0; i<pTst->nSeg; i++){
173619        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
173620        if( sz>szMax ) szMax = sz;
173621      }
173622      if( szMax>=szSeg ){
173623        /* Condition (a) is true. Promote the newest segment on level
173624        ** iLvl to level iTst.  */
173625        iPromote = iTst;
173626        szPromote = szMax;
173627      }
173628    }
173629
173630    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
173631    ** is a no-op if it is not.  */
173632    if( iPromote<0 ){
173633      iPromote = iLvl;
173634      szPromote = szSeg;
173635    }
173636    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
173637  }
173638}
173639
173640
173641/*
173642** Advance the iterator passed as the only argument. If the end of the
173643** doclist-index page is reached, return non-zero.
173644*/
173645static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
173646  Fts5Data *pData = pLvl->pData;
173647
173648  if( pLvl->iOff==0 ){
173649    assert( pLvl->bEof==0 );
173650    pLvl->iOff = 1;
173651    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
173652    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
173653    pLvl->iFirstOff = pLvl->iOff;
173654  }else{
173655    int iOff;
173656    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
173657      if( pData->p[iOff] ) break;
173658    }
173659
173660    if( iOff<pData->nn ){
173661      i64 iVal;
173662      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
173663      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
173664      pLvl->iRowid += iVal;
173665      pLvl->iOff = iOff;
173666    }else{
173667      pLvl->bEof = 1;
173668    }
173669  }
173670
173671  return pLvl->bEof;
173672}
173673
173674/*
173675** Advance the iterator passed as the only argument.
173676*/
173677static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
173678  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
173679
173680  assert( iLvl<pIter->nLvl );
173681  if( fts5DlidxLvlNext(pLvl) ){
173682    if( (iLvl+1) < pIter->nLvl ){
173683      fts5DlidxIterNextR(p, pIter, iLvl+1);
173684      if( pLvl[1].bEof==0 ){
173685        fts5DataRelease(pLvl->pData);
173686        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173687        pLvl->pData = fts5DataRead(p,
173688            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
173689        );
173690        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
173691      }
173692    }
173693  }
173694
173695  return pIter->aLvl[0].bEof;
173696}
173697static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
173698  return fts5DlidxIterNextR(p, pIter, 0);
173699}
173700
173701/*
173702** The iterator passed as the first argument has the following fields set
173703** as follows. This function sets up the rest of the iterator so that it
173704** points to the first rowid in the doclist-index.
173705**
173706**   pData:
173707**     pointer to doclist-index record,
173708**
173709** When this function is called pIter->iLeafPgno is the page number the
173710** doclist is associated with (the one featuring the term).
173711*/
173712static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
173713  int i;
173714  for(i=0; i<pIter->nLvl; i++){
173715    fts5DlidxLvlNext(&pIter->aLvl[i]);
173716  }
173717  return pIter->aLvl[0].bEof;
173718}
173719
173720
173721static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
173722  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
173723}
173724
173725static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
173726  int i;
173727
173728  /* Advance each level to the last entry on the last page */
173729  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
173730    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
173731    while( fts5DlidxLvlNext(pLvl)==0 );
173732    pLvl->bEof = 0;
173733
173734    if( i>0 ){
173735      Fts5DlidxLvl *pChild = &pLvl[-1];
173736      fts5DataRelease(pChild->pData);
173737      memset(pChild, 0, sizeof(Fts5DlidxLvl));
173738      pChild->pData = fts5DataRead(p,
173739          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
173740      );
173741    }
173742  }
173743}
173744
173745/*
173746** Move the iterator passed as the only argument to the previous entry.
173747*/
173748static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
173749  int iOff = pLvl->iOff;
173750
173751  assert( pLvl->bEof==0 );
173752  if( iOff<=pLvl->iFirstOff ){
173753    pLvl->bEof = 1;
173754  }else{
173755    u8 *a = pLvl->pData->p;
173756    i64 iVal;
173757    int iLimit;
173758    int ii;
173759    int nZero = 0;
173760
173761    /* Currently iOff points to the first byte of a varint. This block
173762    ** decrements iOff until it points to the first byte of the previous
173763    ** varint. Taking care not to read any memory locations that occur
173764    ** before the buffer in memory.  */
173765    iLimit = (iOff>9 ? iOff-9 : 0);
173766    for(iOff--; iOff>iLimit; iOff--){
173767      if( (a[iOff-1] & 0x80)==0 ) break;
173768    }
173769
173770    fts5GetVarint(&a[iOff], (u64*)&iVal);
173771    pLvl->iRowid -= iVal;
173772    pLvl->iLeafPgno--;
173773
173774    /* Skip backwards past any 0x00 varints. */
173775    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
173776      nZero++;
173777    }
173778    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
173779      /* The byte immediately before the last 0x00 byte has the 0x80 bit
173780      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
173781      ** bytes before a[ii]. */
173782      int bZero = 0;              /* True if last 0x00 counts */
173783      if( (ii-8)>=pLvl->iFirstOff ){
173784        int j;
173785        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
173786        bZero = (j>8);
173787      }
173788      if( bZero==0 ) nZero--;
173789    }
173790    pLvl->iLeafPgno -= nZero;
173791    pLvl->iOff = iOff - nZero;
173792  }
173793
173794  return pLvl->bEof;
173795}
173796
173797static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
173798  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
173799
173800  assert( iLvl<pIter->nLvl );
173801  if( fts5DlidxLvlPrev(pLvl) ){
173802    if( (iLvl+1) < pIter->nLvl ){
173803      fts5DlidxIterPrevR(p, pIter, iLvl+1);
173804      if( pLvl[1].bEof==0 ){
173805        fts5DataRelease(pLvl->pData);
173806        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173807        pLvl->pData = fts5DataRead(p,
173808            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
173809        );
173810        if( pLvl->pData ){
173811          while( fts5DlidxLvlNext(pLvl)==0 );
173812          pLvl->bEof = 0;
173813        }
173814      }
173815    }
173816  }
173817
173818  return pIter->aLvl[0].bEof;
173819}
173820static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
173821  return fts5DlidxIterPrevR(p, pIter, 0);
173822}
173823
173824/*
173825** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
173826*/
173827static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
173828  if( pIter ){
173829    int i;
173830    for(i=0; i<pIter->nLvl; i++){
173831      fts5DataRelease(pIter->aLvl[i].pData);
173832    }
173833    sqlite3_free(pIter);
173834  }
173835}
173836
173837static Fts5DlidxIter *fts5DlidxIterInit(
173838  Fts5Index *p,                   /* Fts5 Backend to iterate within */
173839  int bRev,                       /* True for ORDER BY ASC */
173840  int iSegid,                     /* Segment id */
173841  int iLeafPg                     /* Leaf page number to load dlidx for */
173842){
173843  Fts5DlidxIter *pIter = 0;
173844  int i;
173845  int bDone = 0;
173846
173847  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
173848    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
173849    Fts5DlidxIter *pNew;
173850
173851    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
173852    if( pNew==0 ){
173853      p->rc = SQLITE_NOMEM;
173854    }else{
173855      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
173856      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
173857      pIter = pNew;
173858      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173859      pLvl->pData = fts5DataRead(p, iRowid);
173860      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
173861        bDone = 1;
173862      }
173863      pIter->nLvl = i+1;
173864    }
173865  }
173866
173867  if( p->rc==SQLITE_OK ){
173868    pIter->iSegid = iSegid;
173869    if( bRev==0 ){
173870      fts5DlidxIterFirst(pIter);
173871    }else{
173872      fts5DlidxIterLast(p, pIter);
173873    }
173874  }
173875
173876  if( p->rc!=SQLITE_OK ){
173877    fts5DlidxIterFree(pIter);
173878    pIter = 0;
173879  }
173880
173881  return pIter;
173882}
173883
173884static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
173885  return pIter->aLvl[0].iRowid;
173886}
173887static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
173888  return pIter->aLvl[0].iLeafPgno;
173889}
173890
173891/*
173892** Load the next leaf page into the segment iterator.
173893*/
173894static void fts5SegIterNextPage(
173895  Fts5Index *p,                   /* FTS5 backend object */
173896  Fts5SegIter *pIter              /* Iterator to advance to next page */
173897){
173898  Fts5Data *pLeaf;
173899  Fts5StructureSegment *pSeg = pIter->pSeg;
173900  fts5DataRelease(pIter->pLeaf);
173901  pIter->iLeafPgno++;
173902  if( pIter->pNextLeaf ){
173903    pIter->pLeaf = pIter->pNextLeaf;
173904    pIter->pNextLeaf = 0;
173905  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
173906    pIter->pLeaf = fts5DataRead(p,
173907        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
173908    );
173909  }else{
173910    pIter->pLeaf = 0;
173911  }
173912  pLeaf = pIter->pLeaf;
173913
173914  if( pLeaf ){
173915    pIter->iPgidxOff = pLeaf->szLeaf;
173916    if( fts5LeafIsTermless(pLeaf) ){
173917      pIter->iEndofDoclist = pLeaf->nn+1;
173918    }else{
173919      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
173920          pIter->iEndofDoclist
173921      );
173922    }
173923  }
173924}
173925
173926/*
173927** Argument p points to a buffer containing a varint to be interpreted as a
173928** position list size field. Read the varint and return the number of bytes
173929** read. Before returning, set *pnSz to the number of bytes in the position
173930** list, and *pbDel to true if the delete flag is set, or false otherwise.
173931*/
173932static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
173933  int nSz;
173934  int n = 0;
173935  fts5FastGetVarint32(p, n, nSz);
173936  assert_nc( nSz>=0 );
173937  *pnSz = nSz/2;
173938  *pbDel = nSz & 0x0001;
173939  return n;
173940}
173941
173942/*
173943** Fts5SegIter.iLeafOffset currently points to the first byte of a
173944** position-list size field. Read the value of the field and store it
173945** in the following variables:
173946**
173947**   Fts5SegIter.nPos
173948**   Fts5SegIter.bDel
173949**
173950** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
173951** position list content (if any).
173952*/
173953static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
173954  if( p->rc==SQLITE_OK ){
173955    int iOff = pIter->iLeafOffset;  /* Offset to read at */
173956    int nSz;
173957    ASSERT_SZLEAF_OK(pIter->pLeaf);
173958    fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
173959    pIter->bDel = (nSz & 0x0001);
173960    pIter->nPos = nSz>>1;
173961    pIter->iLeafOffset = iOff;
173962  }
173963}
173964
173965static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
173966  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
173967  int iOff = pIter->iLeafOffset;
173968
173969  ASSERT_SZLEAF_OK(pIter->pLeaf);
173970  if( iOff>=pIter->pLeaf->szLeaf ){
173971    fts5SegIterNextPage(p, pIter);
173972    if( pIter->pLeaf==0 ){
173973      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
173974      return;
173975    }
173976    iOff = 4;
173977    a = pIter->pLeaf->p;
173978  }
173979  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
173980  pIter->iLeafOffset = iOff;
173981}
173982
173983/*
173984** Fts5SegIter.iLeafOffset currently points to the first byte of the
173985** "nSuffix" field of a term. Function parameter nKeep contains the value
173986** of the "nPrefix" field (if there was one - it is passed 0 if this is
173987** the first term in the segment).
173988**
173989** This function populates:
173990**
173991**   Fts5SegIter.term
173992**   Fts5SegIter.rowid
173993**
173994** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
173995** the first position list. The position list belonging to document
173996** (Fts5SegIter.iRowid).
173997*/
173998static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
173999  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
174000  int iOff = pIter->iLeafOffset;  /* Offset to read at */
174001  int nNew;                       /* Bytes of new data */
174002
174003  iOff += fts5GetVarint32(&a[iOff], nNew);
174004  pIter->term.n = nKeep;
174005  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
174006  iOff += nNew;
174007  pIter->iTermLeafOffset = iOff;
174008  pIter->iTermLeafPgno = pIter->iLeafPgno;
174009  pIter->iLeafOffset = iOff;
174010
174011  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
174012    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174013  }else{
174014    int nExtra;
174015    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
174016    pIter->iEndofDoclist += nExtra;
174017  }
174018
174019  fts5SegIterLoadRowid(p, pIter);
174020}
174021
174022/*
174023** Initialize the iterator object pIter to iterate through the entries in
174024** segment pSeg. The iterator is left pointing to the first entry when
174025** this function returns.
174026**
174027** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174028** an error has already occurred when this function is called, it is a no-op.
174029*/
174030static void fts5SegIterInit(
174031  Fts5Index *p,                   /* FTS index object */
174032  Fts5StructureSegment *pSeg,     /* Description of segment */
174033  Fts5SegIter *pIter              /* Object to populate */
174034){
174035  if( pSeg->pgnoFirst==0 ){
174036    /* This happens if the segment is being used as an input to an incremental
174037    ** merge and all data has already been "trimmed". See function
174038    ** fts5TrimSegments() for details. In this case leave the iterator empty.
174039    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
174040    ** at EOF already. */
174041    assert( pIter->pLeaf==0 );
174042    return;
174043  }
174044
174045  if( p->rc==SQLITE_OK ){
174046    memset(pIter, 0, sizeof(*pIter));
174047    pIter->pSeg = pSeg;
174048    pIter->iLeafPgno = pSeg->pgnoFirst-1;
174049    fts5SegIterNextPage(p, pIter);
174050  }
174051
174052  if( p->rc==SQLITE_OK ){
174053    pIter->iLeafOffset = 4;
174054    assert_nc( pIter->pLeaf->nn>4 );
174055    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
174056    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
174057    fts5SegIterLoadTerm(p, pIter, 0);
174058    fts5SegIterLoadNPos(p, pIter);
174059  }
174060}
174061
174062/*
174063** This function is only ever called on iterators created by calls to
174064** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
174065**
174066** The iterator is in an unusual state when this function is called: the
174067** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
174068** the position-list size field for the first relevant rowid on the page.
174069** Fts5SegIter.rowid is set, but nPos and bDel are not.
174070**
174071** This function advances the iterator so that it points to the last
174072** relevant rowid on the page and, if necessary, initializes the
174073** aRowidOffset[] and iRowidOffset variables. At this point the iterator
174074** is in its regular state - Fts5SegIter.iLeafOffset points to the first
174075** byte of the position list content associated with said rowid.
174076*/
174077static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
174078  int n = pIter->pLeaf->szLeaf;
174079  int i = pIter->iLeafOffset;
174080  u8 *a = pIter->pLeaf->p;
174081  int iRowidOffset = 0;
174082
174083  if( n>pIter->iEndofDoclist ){
174084    n = pIter->iEndofDoclist;
174085  }
174086
174087  ASSERT_SZLEAF_OK(pIter->pLeaf);
174088  while( 1 ){
174089    i64 iDelta = 0;
174090    int nPos;
174091    int bDummy;
174092
174093    i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
174094    i += nPos;
174095    if( i>=n ) break;
174096    i += fts5GetVarint(&a[i], (u64*)&iDelta);
174097    pIter->iRowid += iDelta;
174098
174099    if( iRowidOffset>=pIter->nRowidOffset ){
174100      int nNew = pIter->nRowidOffset + 8;
174101      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
174102      if( aNew==0 ){
174103        p->rc = SQLITE_NOMEM;
174104        break;
174105      }
174106      pIter->aRowidOffset = aNew;
174107      pIter->nRowidOffset = nNew;
174108    }
174109
174110    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
174111    pIter->iLeafOffset = i;
174112  }
174113  pIter->iRowidOffset = iRowidOffset;
174114  fts5SegIterLoadNPos(p, pIter);
174115}
174116
174117/*
174118**
174119*/
174120static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
174121  assert( pIter->flags & FTS5_SEGITER_REVERSE );
174122  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174123
174124  fts5DataRelease(pIter->pLeaf);
174125  pIter->pLeaf = 0;
174126  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
174127    Fts5Data *pNew;
174128    pIter->iLeafPgno--;
174129    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
174130          pIter->pSeg->iSegid, pIter->iLeafPgno
174131    ));
174132    if( pNew ){
174133      /* iTermLeafOffset may be equal to szLeaf if the term is the last
174134      ** thing on the page - i.e. the first rowid is on the following page.
174135      ** In this case leaf pIter->pLeaf==0, this iterator is at EOF. */
174136      if( pIter->iLeafPgno==pIter->iTermLeafPgno
174137       && pIter->iTermLeafOffset<pNew->szLeaf
174138      ){
174139        pIter->pLeaf = pNew;
174140        pIter->iLeafOffset = pIter->iTermLeafOffset;
174141      }else{
174142        int iRowidOff;
174143        iRowidOff = fts5LeafFirstRowidOff(pNew);
174144        if( iRowidOff ){
174145          pIter->pLeaf = pNew;
174146          pIter->iLeafOffset = iRowidOff;
174147        }
174148      }
174149
174150      if( pIter->pLeaf ){
174151        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
174152        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
174153        break;
174154      }else{
174155        fts5DataRelease(pNew);
174156      }
174157    }
174158  }
174159
174160  if( pIter->pLeaf ){
174161    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174162    fts5SegIterReverseInitPage(p, pIter);
174163  }
174164}
174165
174166/*
174167** Return true if the iterator passed as the second argument currently
174168** points to a delete marker. A delete marker is an entry with a 0 byte
174169** position-list.
174170*/
174171static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5IndexIter *pIter){
174172  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
174173  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
174174}
174175
174176/*
174177** Advance iterator pIter to the next entry.
174178**
174179** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
174180** is not considered an error if the iterator reaches EOF. If an error has
174181** already occurred when this function is called, it is a no-op.
174182*/
174183static void fts5SegIterNext(
174184  Fts5Index *p,                   /* FTS5 backend object */
174185  Fts5SegIter *pIter,             /* Iterator to advance */
174186  int *pbNewTerm                  /* OUT: Set for new term */
174187){
174188  assert( pbNewTerm==0 || *pbNewTerm==0 );
174189  if( p->rc==SQLITE_OK ){
174190    if( pIter->flags & FTS5_SEGITER_REVERSE ){
174191      assert( pIter->pNextLeaf==0 );
174192      if( pIter->iRowidOffset>0 ){
174193        u8 *a = pIter->pLeaf->p;
174194        int iOff;
174195        int nPos;
174196        int bDummy;
174197        i64 iDelta;
174198
174199        pIter->iRowidOffset--;
174200        pIter->iLeafOffset = iOff = pIter->aRowidOffset[pIter->iRowidOffset];
174201        iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
174202        iOff += nPos;
174203        fts5GetVarint(&a[iOff], (u64*)&iDelta);
174204        pIter->iRowid -= iDelta;
174205        fts5SegIterLoadNPos(p, pIter);
174206      }else{
174207        fts5SegIterReverseNewPage(p, pIter);
174208      }
174209    }else{
174210      Fts5Data *pLeaf = pIter->pLeaf;
174211      int iOff;
174212      int bNewTerm = 0;
174213      int nKeep = 0;
174214
174215      /* Search for the end of the position list within the current page. */
174216      u8 *a = pLeaf->p;
174217      int n = pLeaf->szLeaf;
174218
174219      ASSERT_SZLEAF_OK(pLeaf);
174220      iOff = pIter->iLeafOffset + pIter->nPos;
174221
174222      if( iOff<n ){
174223        /* The next entry is on the current page. */
174224        assert_nc( iOff<=pIter->iEndofDoclist );
174225        if( iOff>=pIter->iEndofDoclist ){
174226          bNewTerm = 1;
174227          if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
174228            iOff += fts5GetVarint32(&a[iOff], nKeep);
174229          }
174230        }else{
174231          u64 iDelta;
174232          iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
174233          pIter->iRowid += iDelta;
174234          assert_nc( iDelta>0 );
174235        }
174236        pIter->iLeafOffset = iOff;
174237
174238      }else if( pIter->pSeg==0 ){
174239        const u8 *pList = 0;
174240        const char *zTerm = 0;
174241        int nList = 0;
174242        if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
174243          sqlite3Fts5HashScanNext(p->pHash);
174244          sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
174245        }
174246        if( pList==0 ){
174247          fts5DataRelease(pIter->pLeaf);
174248          pIter->pLeaf = 0;
174249        }else{
174250          pIter->pLeaf->p = (u8*)pList;
174251          pIter->pLeaf->nn = nList;
174252          pIter->pLeaf->szLeaf = nList;
174253          pIter->iEndofDoclist = nList+1;
174254          sqlite3Fts5BufferSet(&p->rc, &pIter->term, strlen(zTerm), (u8*)zTerm);
174255          pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
174256          if( pbNewTerm ) *pbNewTerm = 1;
174257        }
174258      }else{
174259        iOff = 0;
174260        /* Next entry is not on the current page */
174261        while( iOff==0 ){
174262          fts5SegIterNextPage(p, pIter);
174263          pLeaf = pIter->pLeaf;
174264          if( pLeaf==0 ) break;
174265          ASSERT_SZLEAF_OK(pLeaf);
174266          if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
174267            iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
174268            pIter->iLeafOffset = iOff;
174269
174270            if( pLeaf->nn>pLeaf->szLeaf ){
174271              pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
174272                  &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
174273              );
174274            }
174275
174276          }
174277          else if( pLeaf->nn>pLeaf->szLeaf ){
174278            pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
174279                &pLeaf->p[pLeaf->szLeaf], iOff
174280            );
174281            pIter->iLeafOffset = iOff;
174282            pIter->iEndofDoclist = iOff;
174283            bNewTerm = 1;
174284          }
174285          if( iOff>=pLeaf->szLeaf ){
174286            p->rc = FTS5_CORRUPT;
174287            return;
174288          }
174289        }
174290      }
174291
174292      /* Check if the iterator is now at EOF. If so, return early. */
174293      if( pIter->pLeaf ){
174294        if( bNewTerm ){
174295          if( pIter->flags & FTS5_SEGITER_ONETERM ){
174296            fts5DataRelease(pIter->pLeaf);
174297            pIter->pLeaf = 0;
174298          }else{
174299            fts5SegIterLoadTerm(p, pIter, nKeep);
174300            fts5SegIterLoadNPos(p, pIter);
174301            if( pbNewTerm ) *pbNewTerm = 1;
174302          }
174303        }else{
174304          fts5SegIterLoadNPos(p, pIter);
174305        }
174306      }
174307    }
174308  }
174309}
174310
174311#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
174312
174313/*
174314** Iterator pIter currently points to the first rowid in a doclist. This
174315** function sets the iterator up so that iterates in reverse order through
174316** the doclist.
174317*/
174318static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
174319  Fts5DlidxIter *pDlidx = pIter->pDlidx;
174320  Fts5Data *pLast = 0;
174321  int pgnoLast = 0;
174322
174323  if( pDlidx ){
174324    int iSegid = pIter->pSeg->iSegid;
174325    pgnoLast = fts5DlidxIterPgno(pDlidx);
174326    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
174327  }else{
174328    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
174329
174330    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
174331    ** position-list content for the current rowid. Back it up so that it
174332    ** points to the start of the position-list size field. */
174333    pIter->iLeafOffset -= sqlite3Fts5GetVarintLen(pIter->nPos*2+pIter->bDel);
174334
174335    /* If this condition is true then the largest rowid for the current
174336    ** term may not be stored on the current page. So search forward to
174337    ** see where said rowid really is.  */
174338    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
174339      int pgno;
174340      Fts5StructureSegment *pSeg = pIter->pSeg;
174341
174342      /* The last rowid in the doclist may not be on the current page. Search
174343      ** forward to find the page containing the last rowid.  */
174344      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
174345        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
174346        Fts5Data *pNew = fts5DataRead(p, iAbs);
174347        if( pNew ){
174348          int iRowid, bTermless;
174349          iRowid = fts5LeafFirstRowidOff(pNew);
174350          bTermless = fts5LeafIsTermless(pNew);
174351          if( iRowid ){
174352            SWAPVAL(Fts5Data*, pNew, pLast);
174353            pgnoLast = pgno;
174354          }
174355          fts5DataRelease(pNew);
174356          if( bTermless==0 ) break;
174357        }
174358      }
174359    }
174360  }
174361
174362  /* If pLast is NULL at this point, then the last rowid for this doclist
174363  ** lies on the page currently indicated by the iterator. In this case
174364  ** pIter->iLeafOffset is already set to point to the position-list size
174365  ** field associated with the first relevant rowid on the page.
174366  **
174367  ** Or, if pLast is non-NULL, then it is the page that contains the last
174368  ** rowid. In this case configure the iterator so that it points to the
174369  ** first rowid on this page.
174370  */
174371  if( pLast ){
174372    int iOff;
174373    fts5DataRelease(pIter->pLeaf);
174374    pIter->pLeaf = pLast;
174375    pIter->iLeafPgno = pgnoLast;
174376    iOff = fts5LeafFirstRowidOff(pLast);
174377    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
174378    pIter->iLeafOffset = iOff;
174379
174380    if( fts5LeafIsTermless(pLast) ){
174381      pIter->iEndofDoclist = pLast->nn+1;
174382    }else{
174383      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
174384    }
174385
174386  }
174387
174388  fts5SegIterReverseInitPage(p, pIter);
174389}
174390
174391/*
174392** Iterator pIter currently points to the first rowid of a doclist.
174393** There is a doclist-index associated with the final term on the current
174394** page. If the current term is the last term on the page, load the
174395** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
174396*/
174397static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
174398  int iSeg = pIter->pSeg->iSegid;
174399  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
174400  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
174401
174402  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174403  assert( pIter->pDlidx==0 );
174404
174405  /* Check if the current doclist ends on this page. If it does, return
174406  ** early without loading the doclist-index (as it belongs to a different
174407  ** term. */
174408  if( pIter->iTermLeafPgno==pIter->iLeafPgno
174409   && pIter->iEndofDoclist<pLeaf->szLeaf
174410  ){
174411    return;
174412  }
174413
174414  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
174415}
174416
174417#define fts5IndexSkipVarint(a, iOff) {            \
174418  int iEnd = iOff+9;                              \
174419  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
174420}
174421
174422/*
174423** The iterator object passed as the second argument currently contains
174424** no valid values except for the Fts5SegIter.pLeaf member variable. This
174425** function searches the leaf page for a term matching (pTerm/nTerm).
174426**
174427** If the specified term is found on the page, then the iterator is left
174428** pointing to it. If argument bGe is zero and the term is not found,
174429** the iterator is left pointing at EOF.
174430**
174431** If bGe is non-zero and the specified term is not found, then the
174432** iterator is left pointing to the smallest term in the segment that
174433** is larger than the specified term, even if this term is not on the
174434** current page.
174435*/
174436static void fts5LeafSeek(
174437  Fts5Index *p,                   /* Leave any error code here */
174438  int bGe,                        /* True for a >= search */
174439  Fts5SegIter *pIter,             /* Iterator to seek */
174440  const u8 *pTerm, int nTerm      /* Term to search for */
174441){
174442  int iOff;
174443  const u8 *a = pIter->pLeaf->p;
174444  int szLeaf = pIter->pLeaf->szLeaf;
174445  int n = pIter->pLeaf->nn;
174446
174447  int nMatch = 0;
174448  int nKeep = 0;
174449  int nNew = 0;
174450  int iTermOff;
174451  int iPgidx;                     /* Current offset in pgidx */
174452  int bEndOfPage = 0;
174453
174454  assert( p->rc==SQLITE_OK );
174455
174456  iPgidx = szLeaf;
174457  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
174458  iOff = iTermOff;
174459
174460  while( 1 ){
174461
174462    /* Figure out how many new bytes are in this term */
174463    fts5FastGetVarint32(a, iOff, nNew);
174464    if( nKeep<nMatch ){
174465      goto search_failed;
174466    }
174467
174468    assert( nKeep>=nMatch );
174469    if( nKeep==nMatch ){
174470      int nCmp;
174471      int i;
174472      nCmp = MIN(nNew, nTerm-nMatch);
174473      for(i=0; i<nCmp; i++){
174474        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
174475      }
174476      nMatch += i;
174477
174478      if( nTerm==nMatch ){
174479        if( i==nNew ){
174480          goto search_success;
174481        }else{
174482          goto search_failed;
174483        }
174484      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
174485        goto search_failed;
174486      }
174487    }
174488
174489    if( iPgidx>=n ){
174490      bEndOfPage = 1;
174491      break;
174492    }
174493
174494    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
174495    iTermOff += nKeep;
174496    iOff = iTermOff;
174497
174498    /* Read the nKeep field of the next term. */
174499    fts5FastGetVarint32(a, iOff, nKeep);
174500  }
174501
174502 search_failed:
174503  if( bGe==0 ){
174504    fts5DataRelease(pIter->pLeaf);
174505    pIter->pLeaf = 0;
174506    return;
174507  }else if( bEndOfPage ){
174508    do {
174509      fts5SegIterNextPage(p, pIter);
174510      if( pIter->pLeaf==0 ) return;
174511      a = pIter->pLeaf->p;
174512      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
174513        fts5GetVarint32(&pIter->pLeaf->p[pIter->pLeaf->szLeaf], iOff);
174514        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
174515          p->rc = FTS5_CORRUPT;
174516        }else{
174517          nKeep = 0;
174518          iOff += fts5GetVarint32(&a[iOff], nNew);
174519          break;
174520        }
174521      }
174522    }while( 1 );
174523  }
174524
174525 search_success:
174526
174527  pIter->iLeafOffset = iOff + nNew;
174528  pIter->iTermLeafOffset = pIter->iLeafOffset;
174529  pIter->iTermLeafPgno = pIter->iLeafPgno;
174530
174531  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
174532  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
174533
174534  if( iPgidx>=n ){
174535    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174536  }else{
174537    int nExtra;
174538    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
174539    pIter->iEndofDoclist = iTermOff + nExtra;
174540  }
174541  pIter->iPgidxOff = iPgidx;
174542
174543  fts5SegIterLoadRowid(p, pIter);
174544  fts5SegIterLoadNPos(p, pIter);
174545}
174546
174547/*
174548** Initialize the object pIter to point to term pTerm/nTerm within segment
174549** pSeg. If there is no such term in the index, the iterator is set to EOF.
174550**
174551** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174552** an error has already occurred when this function is called, it is a no-op.
174553*/
174554static void fts5SegIterSeekInit(
174555  Fts5Index *p,                   /* FTS5 backend */
174556  Fts5Buffer *pBuf,               /* Buffer to use for loading pages */
174557  const u8 *pTerm, int nTerm,     /* Term to seek to */
174558  int flags,                      /* Mask of FTS5INDEX_XXX flags */
174559  Fts5StructureSegment *pSeg,     /* Description of segment */
174560  Fts5SegIter *pIter              /* Object to populate */
174561){
174562  int iPg = 1;
174563  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
174564  int bDlidx = 0;                 /* True if there is a doclist-index */
174565
174566  static int nCall = 0;
174567  nCall++;
174568
174569  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
174570  assert( pTerm && nTerm );
174571  memset(pIter, 0, sizeof(*pIter));
174572  pIter->pSeg = pSeg;
174573
174574  /* This block sets stack variable iPg to the leaf page number that may
174575  ** contain term (pTerm/nTerm), if it is present in the segment. */
174576  if( p->pIdxSelect==0 ){
174577    Fts5Config *pConfig = p->pConfig;
174578    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
174579          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
174580          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
174581          pConfig->zDb, pConfig->zName
174582    ));
174583  }
174584  if( p->rc ) return;
174585  sqlite3_bind_int(p->pIdxSelect, 1, pSeg->iSegid);
174586  sqlite3_bind_blob(p->pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
174587  if( SQLITE_ROW==sqlite3_step(p->pIdxSelect) ){
174588    i64 val = sqlite3_column_int(p->pIdxSelect, 0);
174589    iPg = (int)(val>>1);
174590    bDlidx = (val & 0x0001);
174591  }
174592  p->rc = sqlite3_reset(p->pIdxSelect);
174593
174594  if( iPg<pSeg->pgnoFirst ){
174595    iPg = pSeg->pgnoFirst;
174596    bDlidx = 0;
174597  }
174598
174599  pIter->iLeafPgno = iPg - 1;
174600  fts5SegIterNextPage(p, pIter);
174601
174602  if( pIter->pLeaf ){
174603    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
174604  }
174605
174606  if( p->rc==SQLITE_OK && bGe==0 ){
174607    pIter->flags |= FTS5_SEGITER_ONETERM;
174608    if( pIter->pLeaf ){
174609      if( flags & FTS5INDEX_QUERY_DESC ){
174610        pIter->flags |= FTS5_SEGITER_REVERSE;
174611      }
174612      if( bDlidx ){
174613        fts5SegIterLoadDlidx(p, pIter);
174614      }
174615      if( flags & FTS5INDEX_QUERY_DESC ){
174616        fts5SegIterReverse(p, pIter);
174617      }
174618    }
174619  }
174620
174621  /* Either:
174622  **
174623  **   1) an error has occurred, or
174624  **   2) the iterator points to EOF, or
174625  **   3) the iterator points to an entry with term (pTerm/nTerm), or
174626  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
174627  **      to an entry with a term greater than or equal to (pTerm/nTerm).
174628  */
174629  assert( p->rc!=SQLITE_OK                                          /* 1 */
174630   || pIter->pLeaf==0                                               /* 2 */
174631   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
174632   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
174633  );
174634}
174635
174636/*
174637** Initialize the object pIter to point to term pTerm/nTerm within the
174638** in-memory hash table. If there is no such term in the hash-table, the
174639** iterator is set to EOF.
174640**
174641** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174642** an error has already occurred when this function is called, it is a no-op.
174643*/
174644static void fts5SegIterHashInit(
174645  Fts5Index *p,                   /* FTS5 backend */
174646  const u8 *pTerm, int nTerm,     /* Term to seek to */
174647  int flags,                      /* Mask of FTS5INDEX_XXX flags */
174648  Fts5SegIter *pIter              /* Object to populate */
174649){
174650  const u8 *pList = 0;
174651  int nList = 0;
174652  const u8 *z = 0;
174653  int n = 0;
174654
174655  assert( p->pHash );
174656  assert( p->rc==SQLITE_OK );
174657
174658  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
174659    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
174660    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
174661    n = (z ? strlen((const char*)z) : 0);
174662  }else{
174663    pIter->flags |= FTS5_SEGITER_ONETERM;
174664    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
174665    z = pTerm;
174666    n = nTerm;
174667  }
174668
174669  if( pList ){
174670    Fts5Data *pLeaf;
174671    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
174672    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
174673    if( pLeaf==0 ) return;
174674    pLeaf->p = (u8*)pList;
174675    pLeaf->nn = pLeaf->szLeaf = nList;
174676    pIter->pLeaf = pLeaf;
174677    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
174678    pIter->iEndofDoclist = pLeaf->nn+1;
174679
174680    if( flags & FTS5INDEX_QUERY_DESC ){
174681      pIter->flags |= FTS5_SEGITER_REVERSE;
174682      fts5SegIterReverseInitPage(p, pIter);
174683    }else{
174684      fts5SegIterLoadNPos(p, pIter);
174685    }
174686  }
174687}
174688
174689/*
174690** Zero the iterator passed as the only argument.
174691*/
174692static void fts5SegIterClear(Fts5SegIter *pIter){
174693  fts5BufferFree(&pIter->term);
174694  fts5DataRelease(pIter->pLeaf);
174695  fts5DataRelease(pIter->pNextLeaf);
174696  fts5DlidxIterFree(pIter->pDlidx);
174697  sqlite3_free(pIter->aRowidOffset);
174698  memset(pIter, 0, sizeof(Fts5SegIter));
174699}
174700
174701#ifdef SQLITE_DEBUG
174702
174703/*
174704** This function is used as part of the big assert() procedure implemented by
174705** fts5AssertMultiIterSetup(). It ensures that the result currently stored
174706** in *pRes is the correct result of comparing the current positions of the
174707** two iterators.
174708*/
174709static void fts5AssertComparisonResult(
174710  Fts5IndexIter *pIter,
174711  Fts5SegIter *p1,
174712  Fts5SegIter *p2,
174713  Fts5CResult *pRes
174714){
174715  int i1 = p1 - pIter->aSeg;
174716  int i2 = p2 - pIter->aSeg;
174717
174718  if( p1->pLeaf || p2->pLeaf ){
174719    if( p1->pLeaf==0 ){
174720      assert( pRes->iFirst==i2 );
174721    }else if( p2->pLeaf==0 ){
174722      assert( pRes->iFirst==i1 );
174723    }else{
174724      int nMin = MIN(p1->term.n, p2->term.n);
174725      int res = memcmp(p1->term.p, p2->term.p, nMin);
174726      if( res==0 ) res = p1->term.n - p2->term.n;
174727
174728      if( res==0 ){
174729        assert( pRes->bTermEq==1 );
174730        assert( p1->iRowid!=p2->iRowid );
174731        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
174732      }else{
174733        assert( pRes->bTermEq==0 );
174734      }
174735
174736      if( res<0 ){
174737        assert( pRes->iFirst==i1 );
174738      }else{
174739        assert( pRes->iFirst==i2 );
174740      }
174741    }
174742  }
174743}
174744
174745/*
174746** This function is a no-op unless SQLITE_DEBUG is defined when this module
174747** is compiled. In that case, this function is essentially an assert()
174748** statement used to verify that the contents of the pIter->aFirst[] array
174749** are correct.
174750*/
174751static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5IndexIter *pIter){
174752  if( p->rc==SQLITE_OK ){
174753    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
174754    int i;
174755
174756    assert( (pFirst->pLeaf==0)==pIter->bEof );
174757
174758    /* Check that pIter->iSwitchRowid is set correctly. */
174759    for(i=0; i<pIter->nSeg; i++){
174760      Fts5SegIter *p1 = &pIter->aSeg[i];
174761      assert( p1==pFirst
174762           || p1->pLeaf==0
174763           || fts5BufferCompare(&pFirst->term, &p1->term)
174764           || p1->iRowid==pIter->iSwitchRowid
174765           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
174766      );
174767    }
174768
174769    for(i=0; i<pIter->nSeg; i+=2){
174770      Fts5SegIter *p1 = &pIter->aSeg[i];
174771      Fts5SegIter *p2 = &pIter->aSeg[i+1];
174772      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
174773      fts5AssertComparisonResult(pIter, p1, p2, pRes);
174774    }
174775
174776    for(i=1; i<(pIter->nSeg / 2); i+=2){
174777      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
174778      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
174779      Fts5CResult *pRes = &pIter->aFirst[i];
174780      fts5AssertComparisonResult(pIter, p1, p2, pRes);
174781    }
174782  }
174783}
174784#else
174785# define fts5AssertMultiIterSetup(x,y)
174786#endif
174787
174788/*
174789** Do the comparison necessary to populate pIter->aFirst[iOut].
174790**
174791** If the returned value is non-zero, then it is the index of an entry
174792** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
174793** to a key that is a duplicate of another, higher priority,
174794** segment-iterator in the pSeg->aSeg[] array.
174795*/
174796static int fts5MultiIterDoCompare(Fts5IndexIter *pIter, int iOut){
174797  int i1;                         /* Index of left-hand Fts5SegIter */
174798  int i2;                         /* Index of right-hand Fts5SegIter */
174799  int iRes;
174800  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
174801  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
174802  Fts5CResult *pRes = &pIter->aFirst[iOut];
174803
174804  assert( iOut<pIter->nSeg && iOut>0 );
174805  assert( pIter->bRev==0 || pIter->bRev==1 );
174806
174807  if( iOut>=(pIter->nSeg/2) ){
174808    i1 = (iOut - pIter->nSeg/2) * 2;
174809    i2 = i1 + 1;
174810  }else{
174811    i1 = pIter->aFirst[iOut*2].iFirst;
174812    i2 = pIter->aFirst[iOut*2+1].iFirst;
174813  }
174814  p1 = &pIter->aSeg[i1];
174815  p2 = &pIter->aSeg[i2];
174816
174817  pRes->bTermEq = 0;
174818  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
174819    iRes = i2;
174820  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
174821    iRes = i1;
174822  }else{
174823    int res = fts5BufferCompare(&p1->term, &p2->term);
174824    if( res==0 ){
174825      assert( i2>i1 );
174826      assert( i2!=0 );
174827      pRes->bTermEq = 1;
174828      if( p1->iRowid==p2->iRowid ){
174829        p1->bDel = p2->bDel;
174830        return i2;
174831      }
174832      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
174833    }
174834    assert( res!=0 );
174835    if( res<0 ){
174836      iRes = i1;
174837    }else{
174838      iRes = i2;
174839    }
174840  }
174841
174842  pRes->iFirst = iRes;
174843  return 0;
174844}
174845
174846/*
174847** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
174848** It is an error if leaf iLeafPgno does not exist or contains no rowids.
174849*/
174850static void fts5SegIterGotoPage(
174851  Fts5Index *p,                   /* FTS5 backend object */
174852  Fts5SegIter *pIter,             /* Iterator to advance */
174853  int iLeafPgno
174854){
174855  assert( iLeafPgno>pIter->iLeafPgno );
174856
174857  if( iLeafPgno>pIter->pSeg->pgnoLast ){
174858    p->rc = FTS5_CORRUPT;
174859  }else{
174860    fts5DataRelease(pIter->pNextLeaf);
174861    pIter->pNextLeaf = 0;
174862    pIter->iLeafPgno = iLeafPgno-1;
174863    fts5SegIterNextPage(p, pIter);
174864    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
174865
174866    if( p->rc==SQLITE_OK ){
174867      int iOff;
174868      u8 *a = pIter->pLeaf->p;
174869      int n = pIter->pLeaf->szLeaf;
174870
174871      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
174872      if( iOff<4 || iOff>=n ){
174873        p->rc = FTS5_CORRUPT;
174874      }else{
174875        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
174876        pIter->iLeafOffset = iOff;
174877        fts5SegIterLoadNPos(p, pIter);
174878      }
174879    }
174880  }
174881}
174882
174883/*
174884** Advance the iterator passed as the second argument until it is at or
174885** past rowid iFrom. Regardless of the value of iFrom, the iterator is
174886** always advanced at least once.
174887*/
174888static void fts5SegIterNextFrom(
174889  Fts5Index *p,                   /* FTS5 backend object */
174890  Fts5SegIter *pIter,             /* Iterator to advance */
174891  i64 iMatch                      /* Advance iterator at least this far */
174892){
174893  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
174894  Fts5DlidxIter *pDlidx = pIter->pDlidx;
174895  int iLeafPgno = pIter->iLeafPgno;
174896  int bMove = 1;
174897
174898  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174899  assert( pIter->pDlidx );
174900  assert( pIter->pLeaf );
174901
174902  if( bRev==0 ){
174903    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
174904      iLeafPgno = fts5DlidxIterPgno(pDlidx);
174905      fts5DlidxIterNext(p, pDlidx);
174906    }
174907    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
174908    if( iLeafPgno>pIter->iLeafPgno ){
174909      fts5SegIterGotoPage(p, pIter, iLeafPgno);
174910      bMove = 0;
174911    }
174912  }else{
174913    assert( pIter->pNextLeaf==0 );
174914    assert( iMatch<pIter->iRowid );
174915    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
174916      fts5DlidxIterPrev(p, pDlidx);
174917    }
174918    iLeafPgno = fts5DlidxIterPgno(pDlidx);
174919
174920    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
174921
174922    if( iLeafPgno<pIter->iLeafPgno ){
174923      pIter->iLeafPgno = iLeafPgno+1;
174924      fts5SegIterReverseNewPage(p, pIter);
174925      bMove = 0;
174926    }
174927  }
174928
174929  do{
174930    if( bMove ) fts5SegIterNext(p, pIter, 0);
174931    if( pIter->pLeaf==0 ) break;
174932    if( bRev==0 && pIter->iRowid>=iMatch ) break;
174933    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
174934    bMove = 1;
174935  }while( p->rc==SQLITE_OK );
174936}
174937
174938
174939/*
174940** Free the iterator object passed as the second argument.
174941*/
174942static void fts5MultiIterFree(Fts5Index *p, Fts5IndexIter *pIter){
174943  if( pIter ){
174944    int i;
174945    for(i=0; i<pIter->nSeg; i++){
174946      fts5SegIterClear(&pIter->aSeg[i]);
174947    }
174948    fts5StructureRelease(pIter->pStruct);
174949    fts5BufferFree(&pIter->poslist);
174950    sqlite3_free(pIter);
174951  }
174952}
174953
174954static void fts5MultiIterAdvanced(
174955  Fts5Index *p,                   /* FTS5 backend to iterate within */
174956  Fts5IndexIter *pIter,           /* Iterator to update aFirst[] array for */
174957  int iChanged,                   /* Index of sub-iterator just advanced */
174958  int iMinset                     /* Minimum entry in aFirst[] to set */
174959){
174960  int i;
174961  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
174962    int iEq;
174963    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
174964      fts5SegIterNext(p, &pIter->aSeg[iEq], 0);
174965      i = pIter->nSeg + iEq;
174966    }
174967  }
174968}
174969
174970/*
174971** Sub-iterator iChanged of iterator pIter has just been advanced. It still
174972** points to the same term though - just a different rowid. This function
174973** attempts to update the contents of the pIter->aFirst[] accordingly.
174974** If it does so successfully, 0 is returned. Otherwise 1.
174975**
174976** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
174977** on the iterator instead. That function does the same as this one, except
174978** that it deals with more complicated cases as well.
174979*/
174980static int fts5MultiIterAdvanceRowid(
174981  Fts5Index *p,                   /* FTS5 backend to iterate within */
174982  Fts5IndexIter *pIter,           /* Iterator to update aFirst[] array for */
174983  int iChanged                    /* Index of sub-iterator just advanced */
174984){
174985  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
174986
174987  if( pNew->iRowid==pIter->iSwitchRowid
174988   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
174989  ){
174990    int i;
174991    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
174992    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
174993    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
174994      Fts5CResult *pRes = &pIter->aFirst[i];
174995
174996      assert( pNew->pLeaf );
174997      assert( pRes->bTermEq==0 || pOther->pLeaf );
174998
174999      if( pRes->bTermEq ){
175000        if( pNew->iRowid==pOther->iRowid ){
175001          return 1;
175002        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
175003          pIter->iSwitchRowid = pOther->iRowid;
175004          pNew = pOther;
175005        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
175006          pIter->iSwitchRowid = pOther->iRowid;
175007        }
175008      }
175009      pRes->iFirst = (pNew - pIter->aSeg);
175010      if( i==1 ) break;
175011
175012      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
175013    }
175014  }
175015
175016  return 0;
175017}
175018
175019/*
175020** Set the pIter->bEof variable based on the state of the sub-iterators.
175021*/
175022static void fts5MultiIterSetEof(Fts5IndexIter *pIter){
175023  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
175024  pIter->bEof = pSeg->pLeaf==0;
175025  pIter->iSwitchRowid = pSeg->iRowid;
175026}
175027
175028/*
175029** Move the iterator to the next entry.
175030**
175031** If an error occurs, an error code is left in Fts5Index.rc. It is not
175032** considered an error if the iterator reaches EOF, or if it is already at
175033** EOF when this function is called.
175034*/
175035static void fts5MultiIterNext(
175036  Fts5Index *p,
175037  Fts5IndexIter *pIter,
175038  int bFrom,                      /* True if argument iFrom is valid */
175039  i64 iFrom                       /* Advance at least as far as this */
175040){
175041  if( p->rc==SQLITE_OK ){
175042    int bUseFrom = bFrom;
175043    do {
175044      int iFirst = pIter->aFirst[1].iFirst;
175045      int bNewTerm = 0;
175046      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
175047      assert( p->rc==SQLITE_OK );
175048      if( bUseFrom && pSeg->pDlidx ){
175049        fts5SegIterNextFrom(p, pSeg, iFrom);
175050      }else{
175051        fts5SegIterNext(p, pSeg, &bNewTerm);
175052      }
175053
175054      if( pSeg->pLeaf==0 || bNewTerm
175055       || fts5MultiIterAdvanceRowid(p, pIter, iFirst)
175056      ){
175057        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
175058        fts5MultiIterSetEof(pIter);
175059      }
175060      fts5AssertMultiIterSetup(p, pIter);
175061
175062      bUseFrom = 0;
175063    }while( pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter) );
175064  }
175065}
175066
175067static Fts5IndexIter *fts5MultiIterAlloc(
175068  Fts5Index *p,                   /* FTS5 backend to iterate within */
175069  int nSeg
175070){
175071  Fts5IndexIter *pNew;
175072  int nSlot;                      /* Power of two >= nSeg */
175073
175074  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
175075  pNew = fts5IdxMalloc(p,
175076      sizeof(Fts5IndexIter) +             /* pNew */
175077      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
175078      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
175079  );
175080  if( pNew ){
175081    pNew->nSeg = nSlot;
175082    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
175083    pNew->pIndex = p;
175084  }
175085  return pNew;
175086}
175087
175088/*
175089** Allocate a new Fts5IndexIter object.
175090**
175091** The new object will be used to iterate through data in structure pStruct.
175092** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
175093** is zero or greater, data from the first nSegment segments on level iLevel
175094** is merged.
175095**
175096** The iterator initially points to the first term/rowid entry in the
175097** iterated data.
175098*/
175099static void fts5MultiIterNew(
175100  Fts5Index *p,                   /* FTS5 backend to iterate within */
175101  Fts5Structure *pStruct,         /* Structure of specific index */
175102  int bSkipEmpty,                 /* True to ignore delete-keys */
175103  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
175104  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
175105  int iLevel,                     /* Level to iterate (-1 for all) */
175106  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
175107  Fts5IndexIter **ppOut           /* New object */
175108){
175109  int nSeg = 0;                   /* Number of segment-iters in use */
175110  int iIter = 0;                  /* */
175111  int iSeg;                       /* Used to iterate through segments */
175112  Fts5Buffer buf = {0,0,0};       /* Buffer used by fts5SegIterSeekInit() */
175113  Fts5StructureLevel *pLvl;
175114  Fts5IndexIter *pNew;
175115
175116  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
175117
175118  /* Allocate space for the new multi-seg-iterator. */
175119  if( p->rc==SQLITE_OK ){
175120    if( iLevel<0 ){
175121      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
175122      nSeg = pStruct->nSegment;
175123      nSeg += (p->pHash ? 1 : 0);
175124    }else{
175125      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
175126    }
175127  }
175128  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
175129  if( pNew==0 ) return;
175130  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
175131  pNew->bSkipEmpty = bSkipEmpty;
175132  pNew->pStruct = pStruct;
175133  fts5StructureRef(pStruct);
175134
175135  /* Initialize each of the component segment iterators. */
175136  if( iLevel<0 ){
175137    Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
175138    if( p->pHash ){
175139      /* Add a segment iterator for the current contents of the hash table. */
175140      Fts5SegIter *pIter = &pNew->aSeg[iIter++];
175141      fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
175142    }
175143    for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
175144      for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
175145        Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
175146        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
175147        if( pTerm==0 ){
175148          fts5SegIterInit(p, pSeg, pIter);
175149        }else{
175150          fts5SegIterSeekInit(p, &buf, pTerm, nTerm, flags, pSeg, pIter);
175151        }
175152      }
175153    }
175154  }else{
175155    pLvl = &pStruct->aLevel[iLevel];
175156    for(iSeg=nSeg-1; iSeg>=0; iSeg--){
175157      fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
175158    }
175159  }
175160  assert( iIter==nSeg );
175161
175162  /* If the above was successful, each component iterators now points
175163  ** to the first entry in its segment. In this case initialize the
175164  ** aFirst[] array. Or, if an error has occurred, free the iterator
175165  ** object and set the output variable to NULL.  */
175166  if( p->rc==SQLITE_OK ){
175167    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
175168      int iEq;
175169      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
175170        fts5SegIterNext(p, &pNew->aSeg[iEq], 0);
175171        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
175172      }
175173    }
175174    fts5MultiIterSetEof(pNew);
175175    fts5AssertMultiIterSetup(p, pNew);
175176
175177    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
175178      fts5MultiIterNext(p, pNew, 0, 0);
175179    }
175180  }else{
175181    fts5MultiIterFree(p, pNew);
175182    *ppOut = 0;
175183  }
175184  fts5BufferFree(&buf);
175185}
175186
175187/*
175188** Create an Fts5IndexIter that iterates through the doclist provided
175189** as the second argument.
175190*/
175191static void fts5MultiIterNew2(
175192  Fts5Index *p,                   /* FTS5 backend to iterate within */
175193  Fts5Data *pData,                /* Doclist to iterate through */
175194  int bDesc,                      /* True for descending rowid order */
175195  Fts5IndexIter **ppOut           /* New object */
175196){
175197  Fts5IndexIter *pNew;
175198  pNew = fts5MultiIterAlloc(p, 2);
175199  if( pNew ){
175200    Fts5SegIter *pIter = &pNew->aSeg[1];
175201
175202    pNew->bFiltered = 1;
175203    pIter->flags = FTS5_SEGITER_ONETERM;
175204    if( pData->szLeaf>0 ){
175205      pIter->pLeaf = pData;
175206      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
175207      pIter->iEndofDoclist = pData->nn;
175208      pNew->aFirst[1].iFirst = 1;
175209      if( bDesc ){
175210        pNew->bRev = 1;
175211        pIter->flags |= FTS5_SEGITER_REVERSE;
175212        fts5SegIterReverseInitPage(p, pIter);
175213      }else{
175214        fts5SegIterLoadNPos(p, pIter);
175215      }
175216      pData = 0;
175217    }else{
175218      pNew->bEof = 1;
175219    }
175220
175221    *ppOut = pNew;
175222  }
175223
175224  fts5DataRelease(pData);
175225}
175226
175227/*
175228** Return true if the iterator is at EOF or if an error has occurred.
175229** False otherwise.
175230*/
175231static int fts5MultiIterEof(Fts5Index *p, Fts5IndexIter *pIter){
175232  assert( p->rc
175233      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->bEof
175234  );
175235  return (p->rc || pIter->bEof);
175236}
175237
175238/*
175239** Return the rowid of the entry that the iterator currently points
175240** to. If the iterator points to EOF when this function is called the
175241** results are undefined.
175242*/
175243static i64 fts5MultiIterRowid(Fts5IndexIter *pIter){
175244  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
175245  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
175246}
175247
175248/*
175249** Move the iterator to the next entry at or following iMatch.
175250*/
175251static void fts5MultiIterNextFrom(
175252  Fts5Index *p,
175253  Fts5IndexIter *pIter,
175254  i64 iMatch
175255){
175256  while( 1 ){
175257    i64 iRowid;
175258    fts5MultiIterNext(p, pIter, 1, iMatch);
175259    if( fts5MultiIterEof(p, pIter) ) break;
175260    iRowid = fts5MultiIterRowid(pIter);
175261    if( pIter->bRev==0 && iRowid>=iMatch ) break;
175262    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
175263  }
175264}
175265
175266/*
175267** Return a pointer to a buffer containing the term associated with the
175268** entry that the iterator currently points to.
175269*/
175270static const u8 *fts5MultiIterTerm(Fts5IndexIter *pIter, int *pn){
175271  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
175272  *pn = p->term.n;
175273  return p->term.p;
175274}
175275
175276static void fts5ChunkIterate(
175277  Fts5Index *p,                   /* Index object */
175278  Fts5SegIter *pSeg,              /* Poslist of this iterator */
175279  void *pCtx,                     /* Context pointer for xChunk callback */
175280  void (*xChunk)(Fts5Index*, void*, const u8*, int)
175281){
175282  int nRem = pSeg->nPos;          /* Number of bytes still to come */
175283  Fts5Data *pData = 0;
175284  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
175285  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
175286  int pgno = pSeg->iLeafPgno;
175287  int pgnoSave = 0;
175288
175289  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
175290    pgnoSave = pgno+1;
175291  }
175292
175293  while( 1 ){
175294    xChunk(p, pCtx, pChunk, nChunk);
175295    nRem -= nChunk;
175296    fts5DataRelease(pData);
175297    if( nRem<=0 ){
175298      break;
175299    }else{
175300      pgno++;
175301      pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
175302      if( pData==0 ) break;
175303      pChunk = &pData->p[4];
175304      nChunk = MIN(nRem, pData->szLeaf - 4);
175305      if( pgno==pgnoSave ){
175306        assert( pSeg->pNextLeaf==0 );
175307        pSeg->pNextLeaf = pData;
175308        pData = 0;
175309      }
175310    }
175311  }
175312}
175313
175314
175315
175316/*
175317** Allocate a new segment-id for the structure pStruct. The new segment
175318** id must be between 1 and 65335 inclusive, and must not be used by
175319** any currently existing segment. If a free segment id cannot be found,
175320** SQLITE_FULL is returned.
175321**
175322** If an error has already occurred, this function is a no-op. 0 is
175323** returned in this case.
175324*/
175325static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
175326  int iSegid = 0;
175327
175328  if( p->rc==SQLITE_OK ){
175329    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
175330      p->rc = SQLITE_FULL;
175331    }else{
175332      while( iSegid==0 ){
175333        int iLvl, iSeg;
175334        sqlite3_randomness(sizeof(u32), (void*)&iSegid);
175335        iSegid = iSegid & ((1 << FTS5_DATA_ID_B)-1);
175336        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
175337          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
175338            if( iSegid==pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ){
175339              iSegid = 0;
175340            }
175341          }
175342        }
175343      }
175344    }
175345  }
175346
175347  return iSegid;
175348}
175349
175350/*
175351** Discard all data currently cached in the hash-tables.
175352*/
175353static void fts5IndexDiscardData(Fts5Index *p){
175354  assert( p->pHash || p->nPendingData==0 );
175355  if( p->pHash ){
175356    sqlite3Fts5HashClear(p->pHash);
175357    p->nPendingData = 0;
175358  }
175359}
175360
175361/*
175362** Return the size of the prefix, in bytes, that buffer (nNew/pNew) shares
175363** with buffer (nOld/pOld).
175364*/
175365static int fts5PrefixCompress(
175366  int nOld, const u8 *pOld,
175367  int nNew, const u8 *pNew
175368){
175369  int i;
175370  assert( fts5BlobCompare(pOld, nOld, pNew, nNew)<0 );
175371  for(i=0; i<nOld; i++){
175372    if( pOld[i]!=pNew[i] ) break;
175373  }
175374  return i;
175375}
175376
175377static void fts5WriteDlidxClear(
175378  Fts5Index *p,
175379  Fts5SegWriter *pWriter,
175380  int bFlush                      /* If true, write dlidx to disk */
175381){
175382  int i;
175383  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
175384  for(i=0; i<pWriter->nDlidx; i++){
175385    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
175386    if( pDlidx->buf.n==0 ) break;
175387    if( bFlush ){
175388      assert( pDlidx->pgno!=0 );
175389      fts5DataWrite(p,
175390          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
175391          pDlidx->buf.p, pDlidx->buf.n
175392      );
175393    }
175394    sqlite3Fts5BufferZero(&pDlidx->buf);
175395    pDlidx->bPrevValid = 0;
175396  }
175397}
175398
175399/*
175400** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
175401** Any new array elements are zeroed before returning.
175402*/
175403static int fts5WriteDlidxGrow(
175404  Fts5Index *p,
175405  Fts5SegWriter *pWriter,
175406  int nLvl
175407){
175408  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
175409    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
175410        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
175411    );
175412    if( aDlidx==0 ){
175413      p->rc = SQLITE_NOMEM;
175414    }else{
175415      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
175416      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
175417      pWriter->aDlidx = aDlidx;
175418      pWriter->nDlidx = nLvl;
175419    }
175420  }
175421  return p->rc;
175422}
175423
175424/*
175425** If the current doclist-index accumulating in pWriter->aDlidx[] is large
175426** enough, flush it to disk and return 1. Otherwise discard it and return
175427** zero.
175428*/
175429static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
175430  int bFlag = 0;
175431
175432  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
175433  ** to the database, also write the doclist-index to disk.  */
175434  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
175435    bFlag = 1;
175436  }
175437  fts5WriteDlidxClear(p, pWriter, bFlag);
175438  pWriter->nEmpty = 0;
175439  return bFlag;
175440}
175441
175442/*
175443** This function is called whenever processing of the doclist for the
175444** last term on leaf page (pWriter->iBtPage) is completed.
175445**
175446** The doclist-index for that term is currently stored in-memory within the
175447** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
175448** writes it out to disk. Or, if it is too small to bother with, discards
175449** it.
175450**
175451** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
175452*/
175453static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
175454  int bFlag;
175455
175456  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
175457  if( pWriter->iBtPage==0 ) return;
175458  bFlag = fts5WriteFlushDlidx(p, pWriter);
175459
175460  if( p->rc==SQLITE_OK ){
175461    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
175462    /* The following was already done in fts5WriteInit(): */
175463    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
175464    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
175465    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
175466    sqlite3_step(p->pIdxWriter);
175467    p->rc = sqlite3_reset(p->pIdxWriter);
175468  }
175469  pWriter->iBtPage = 0;
175470}
175471
175472/*
175473** This is called once for each leaf page except the first that contains
175474** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
175475** is larger than all terms written to earlier leaves, and equal to or
175476** smaller than the first term on the new leaf.
175477**
175478** If an error occurs, an error code is left in Fts5Index.rc. If an error
175479** has already occurred when this function is called, it is a no-op.
175480*/
175481static void fts5WriteBtreeTerm(
175482  Fts5Index *p,                   /* FTS5 backend object */
175483  Fts5SegWriter *pWriter,         /* Writer object */
175484  int nTerm, const u8 *pTerm      /* First term on new page */
175485){
175486  fts5WriteFlushBtree(p, pWriter);
175487  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
175488  pWriter->iBtPage = pWriter->writer.pgno;
175489}
175490
175491/*
175492** This function is called when flushing a leaf page that contains no
175493** terms at all to disk.
175494*/
175495static void fts5WriteBtreeNoTerm(
175496  Fts5Index *p,                   /* FTS5 backend object */
175497  Fts5SegWriter *pWriter          /* Writer object */
175498){
175499  /* If there were no rowids on the leaf page either and the doclist-index
175500  ** has already been started, append an 0x00 byte to it.  */
175501  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
175502    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
175503    assert( pDlidx->bPrevValid );
175504    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
175505  }
175506
175507  /* Increment the "number of sequential leaves without a term" counter. */
175508  pWriter->nEmpty++;
175509}
175510
175511static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
175512  i64 iRowid;
175513  int iOff;
175514
175515  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
175516  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
175517  return iRowid;
175518}
175519
175520/*
175521** Rowid iRowid has just been appended to the current leaf page. It is the
175522** first on the page. This function appends an appropriate entry to the current
175523** doclist-index.
175524*/
175525static void fts5WriteDlidxAppend(
175526  Fts5Index *p,
175527  Fts5SegWriter *pWriter,
175528  i64 iRowid
175529){
175530  int i;
175531  int bDone = 0;
175532
175533  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
175534    i64 iVal;
175535    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
175536
175537    if( pDlidx->buf.n>=p->pConfig->pgsz ){
175538      /* The current doclist-index page is full. Write it to disk and push
175539      ** a copy of iRowid (which will become the first rowid on the next
175540      ** doclist-index leaf page) up into the next level of the b-tree
175541      ** hierarchy. If the node being flushed is currently the root node,
175542      ** also push its first rowid upwards. */
175543      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
175544      fts5DataWrite(p,
175545          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
175546          pDlidx->buf.p, pDlidx->buf.n
175547      );
175548      fts5WriteDlidxGrow(p, pWriter, i+2);
175549      pDlidx = &pWriter->aDlidx[i];
175550      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
175551        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
175552
175553        /* This was the root node. Push its first rowid up to the new root. */
175554        pDlidx[1].pgno = pDlidx->pgno;
175555        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
175556        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
175557        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
175558        pDlidx[1].bPrevValid = 1;
175559        pDlidx[1].iPrev = iFirst;
175560      }
175561
175562      sqlite3Fts5BufferZero(&pDlidx->buf);
175563      pDlidx->bPrevValid = 0;
175564      pDlidx->pgno++;
175565    }else{
175566      bDone = 1;
175567    }
175568
175569    if( pDlidx->bPrevValid ){
175570      iVal = iRowid - pDlidx->iPrev;
175571    }else{
175572      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
175573      assert( pDlidx->buf.n==0 );
175574      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
175575      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
175576      iVal = iRowid;
175577    }
175578
175579    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
175580    pDlidx->bPrevValid = 1;
175581    pDlidx->iPrev = iRowid;
175582  }
175583}
175584
175585static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
175586  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
175587  Fts5PageWriter *pPage = &pWriter->writer;
175588  i64 iRowid;
175589
175590  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
175591
175592  /* Set the szLeaf header field. */
175593  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
175594  fts5PutU16(&pPage->buf.p[2], pPage->buf.n);
175595
175596  if( pWriter->bFirstTermInPage ){
175597    /* No term was written to this page. */
175598    assert( pPage->pgidx.n==0 );
175599    fts5WriteBtreeNoTerm(p, pWriter);
175600  }else{
175601    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
175602    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
175603  }
175604
175605  /* Write the page out to disk */
175606  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
175607  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
175608
175609  /* Initialize the next page. */
175610  fts5BufferZero(&pPage->buf);
175611  fts5BufferZero(&pPage->pgidx);
175612  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
175613  pPage->iPrevPgidx = 0;
175614  pPage->pgno++;
175615
175616  /* Increase the leaves written counter */
175617  pWriter->nLeafWritten++;
175618
175619  /* The new leaf holds no terms or rowids */
175620  pWriter->bFirstTermInPage = 1;
175621  pWriter->bFirstRowidInPage = 1;
175622}
175623
175624/*
175625** Append term pTerm/nTerm to the segment being written by the writer passed
175626** as the second argument.
175627**
175628** If an error occurs, set the Fts5Index.rc error code. If an error has
175629** already occurred, this function is a no-op.
175630*/
175631static void fts5WriteAppendTerm(
175632  Fts5Index *p,
175633  Fts5SegWriter *pWriter,
175634  int nTerm, const u8 *pTerm
175635){
175636  int nPrefix;                    /* Bytes of prefix compression for term */
175637  Fts5PageWriter *pPage = &pWriter->writer;
175638  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
175639
175640  assert( p->rc==SQLITE_OK );
175641  assert( pPage->buf.n>=4 );
175642  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
175643
175644  /* If the current leaf page is full, flush it to disk. */
175645  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
175646    if( pPage->buf.n>4 ){
175647      fts5WriteFlushLeaf(p, pWriter);
175648    }
175649    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
175650  }
175651
175652  /* TODO1: Updating pgidx here. */
175653  pPgidx->n += sqlite3Fts5PutVarint(
175654      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
175655  );
175656  pPage->iPrevPgidx = pPage->buf.n;
175657#if 0
175658  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
175659  pPgidx->n += 2;
175660#endif
175661
175662  if( pWriter->bFirstTermInPage ){
175663    nPrefix = 0;
175664    if( pPage->pgno!=1 ){
175665      /* This is the first term on a leaf that is not the leftmost leaf in
175666      ** the segment b-tree. In this case it is necessary to add a term to
175667      ** the b-tree hierarchy that is (a) larger than the largest term
175668      ** already written to the segment and (b) smaller than or equal to
175669      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
175670      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
175671      ** previous term.
175672      **
175673      ** Usually, the previous term is available in pPage->term. The exception
175674      ** is if this is the first term written in an incremental-merge step.
175675      ** In this case the previous term is not available, so just write a
175676      ** copy of (pTerm/nTerm) into the parent node. This is slightly
175677      ** inefficient, but still correct.  */
175678      int n = nTerm;
175679      if( pPage->term.n ){
175680        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
175681      }
175682      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
175683      pPage = &pWriter->writer;
175684    }
175685  }else{
175686    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
175687    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
175688  }
175689
175690  /* Append the number of bytes of new data, then the term data itself
175691  ** to the page. */
175692  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
175693  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
175694
175695  /* Update the Fts5PageWriter.term field. */
175696  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
175697  pWriter->bFirstTermInPage = 0;
175698
175699  pWriter->bFirstRowidInPage = 0;
175700  pWriter->bFirstRowidInDoclist = 1;
175701
175702  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
175703  pWriter->aDlidx[0].pgno = pPage->pgno;
175704}
175705
175706/*
175707** Append a rowid and position-list size field to the writers output.
175708*/
175709static void fts5WriteAppendRowid(
175710  Fts5Index *p,
175711  Fts5SegWriter *pWriter,
175712  i64 iRowid,
175713  int nPos
175714){
175715  if( p->rc==SQLITE_OK ){
175716    Fts5PageWriter *pPage = &pWriter->writer;
175717
175718    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
175719      fts5WriteFlushLeaf(p, pWriter);
175720    }
175721
175722    /* If this is to be the first rowid written to the page, set the
175723    ** rowid-pointer in the page-header. Also append a value to the dlidx
175724    ** buffer, in case a doclist-index is required.  */
175725    if( pWriter->bFirstRowidInPage ){
175726      fts5PutU16(pPage->buf.p, pPage->buf.n);
175727      fts5WriteDlidxAppend(p, pWriter, iRowid);
175728    }
175729
175730    /* Write the rowid. */
175731    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
175732      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
175733    }else{
175734      assert( p->rc || iRowid>pWriter->iPrevRowid );
175735      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
175736    }
175737    pWriter->iPrevRowid = iRowid;
175738    pWriter->bFirstRowidInDoclist = 0;
175739    pWriter->bFirstRowidInPage = 0;
175740
175741    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPos);
175742  }
175743}
175744
175745static void fts5WriteAppendPoslistData(
175746  Fts5Index *p,
175747  Fts5SegWriter *pWriter,
175748  const u8 *aData,
175749  int nData
175750){
175751  Fts5PageWriter *pPage = &pWriter->writer;
175752  const u8 *a = aData;
175753  int n = nData;
175754
175755  assert( p->pConfig->pgsz>0 );
175756  while( p->rc==SQLITE_OK
175757     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
175758  ){
175759    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
175760    int nCopy = 0;
175761    while( nCopy<nReq ){
175762      i64 dummy;
175763      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
175764    }
175765    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
175766    a += nCopy;
175767    n -= nCopy;
175768    fts5WriteFlushLeaf(p, pWriter);
175769  }
175770  if( n>0 ){
175771    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
175772  }
175773}
175774
175775/*
175776** Flush any data cached by the writer object to the database. Free any
175777** allocations associated with the writer.
175778*/
175779static void fts5WriteFinish(
175780  Fts5Index *p,
175781  Fts5SegWriter *pWriter,         /* Writer object */
175782  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
175783){
175784  int i;
175785  Fts5PageWriter *pLeaf = &pWriter->writer;
175786  if( p->rc==SQLITE_OK ){
175787    assert( pLeaf->pgno>=1 );
175788    if( pLeaf->buf.n>4 ){
175789      fts5WriteFlushLeaf(p, pWriter);
175790    }
175791    *pnLeaf = pLeaf->pgno-1;
175792    fts5WriteFlushBtree(p, pWriter);
175793  }
175794  fts5BufferFree(&pLeaf->term);
175795  fts5BufferFree(&pLeaf->buf);
175796  fts5BufferFree(&pLeaf->pgidx);
175797  fts5BufferFree(&pWriter->btterm);
175798
175799  for(i=0; i<pWriter->nDlidx; i++){
175800    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
175801  }
175802  sqlite3_free(pWriter->aDlidx);
175803}
175804
175805static void fts5WriteInit(
175806  Fts5Index *p,
175807  Fts5SegWriter *pWriter,
175808  int iSegid
175809){
175810  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
175811
175812  memset(pWriter, 0, sizeof(Fts5SegWriter));
175813  pWriter->iSegid = iSegid;
175814
175815  fts5WriteDlidxGrow(p, pWriter, 1);
175816  pWriter->writer.pgno = 1;
175817  pWriter->bFirstTermInPage = 1;
175818  pWriter->iBtPage = 1;
175819
175820  /* Grow the two buffers to pgsz + padding bytes in size. */
175821  fts5BufferGrow(&p->rc, &pWriter->writer.pgidx, nBuffer);
175822  fts5BufferGrow(&p->rc, &pWriter->writer.buf, nBuffer);
175823
175824  if( p->pIdxWriter==0 ){
175825    Fts5Config *pConfig = p->pConfig;
175826    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
175827          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
175828          pConfig->zDb, pConfig->zName
175829    ));
175830  }
175831
175832  if( p->rc==SQLITE_OK ){
175833    /* Initialize the 4-byte leaf-page header to 0x00. */
175834    memset(pWriter->writer.buf.p, 0, 4);
175835    pWriter->writer.buf.n = 4;
175836
175837    /* Bind the current output segment id to the index-writer. This is an
175838    ** optimization over binding the same value over and over as rows are
175839    ** inserted into %_idx by the current writer.  */
175840    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
175841  }
175842}
175843
175844/*
175845** Iterator pIter was used to iterate through the input segments of on an
175846** incremental merge operation. This function is called if the incremental
175847** merge step has finished but the input has not been completely exhausted.
175848*/
175849static void fts5TrimSegments(Fts5Index *p, Fts5IndexIter *pIter){
175850  int i;
175851  Fts5Buffer buf;
175852  memset(&buf, 0, sizeof(Fts5Buffer));
175853  for(i=0; i<pIter->nSeg; i++){
175854    Fts5SegIter *pSeg = &pIter->aSeg[i];
175855    if( pSeg->pSeg==0 ){
175856      /* no-op */
175857    }else if( pSeg->pLeaf==0 ){
175858      /* All keys from this input segment have been transfered to the output.
175859      ** Set both the first and last page-numbers to 0 to indicate that the
175860      ** segment is now empty. */
175861      pSeg->pSeg->pgnoLast = 0;
175862      pSeg->pSeg->pgnoFirst = 0;
175863    }else{
175864      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
175865      i64 iLeafRowid;
175866      Fts5Data *pData;
175867      int iId = pSeg->pSeg->iSegid;
175868      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
175869
175870      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
175871      pData = fts5DataRead(p, iLeafRowid);
175872      if( pData ){
175873        fts5BufferZero(&buf);
175874        fts5BufferGrow(&p->rc, &buf, pData->nn);
175875        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
175876        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
175877        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
175878        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
175879        if( p->rc==SQLITE_OK ){
175880          /* Set the szLeaf field */
175881          fts5PutU16(&buf.p[2], buf.n);
175882        }
175883
175884        /* Set up the new page-index array */
175885        fts5BufferAppendVarint(&p->rc, &buf, 4);
175886        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
175887         && pSeg->iEndofDoclist<pData->szLeaf
175888        ){
175889          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
175890          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
175891          fts5BufferAppendBlob(&p->rc, &buf,
175892              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
175893          );
175894        }
175895
175896        fts5DataRelease(pData);
175897        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
175898        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
175899        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
175900      }
175901    }
175902  }
175903  fts5BufferFree(&buf);
175904}
175905
175906static void fts5MergeChunkCallback(
175907  Fts5Index *p,
175908  void *pCtx,
175909  const u8 *pChunk, int nChunk
175910){
175911  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
175912  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
175913}
175914
175915/*
175916**
175917*/
175918static void fts5IndexMergeLevel(
175919  Fts5Index *p,                   /* FTS5 backend object */
175920  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
175921  int iLvl,                       /* Level to read input from */
175922  int *pnRem                      /* Write up to this many output leaves */
175923){
175924  Fts5Structure *pStruct = *ppStruct;
175925  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
175926  Fts5StructureLevel *pLvlOut;
175927  Fts5IndexIter *pIter = 0;       /* Iterator to read input data */
175928  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
175929  int nInput;                     /* Number of input segments */
175930  Fts5SegWriter writer;           /* Writer object */
175931  Fts5StructureSegment *pSeg;     /* Output segment */
175932  Fts5Buffer term;
175933  int bOldest;                    /* True if the output segment is the oldest */
175934
175935  assert( iLvl<pStruct->nLevel );
175936  assert( pLvl->nMerge<=pLvl->nSeg );
175937
175938  memset(&writer, 0, sizeof(Fts5SegWriter));
175939  memset(&term, 0, sizeof(Fts5Buffer));
175940  if( pLvl->nMerge ){
175941    pLvlOut = &pStruct->aLevel[iLvl+1];
175942    assert( pLvlOut->nSeg>0 );
175943    nInput = pLvl->nMerge;
175944    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
175945
175946    fts5WriteInit(p, &writer, pSeg->iSegid);
175947    writer.writer.pgno = pSeg->pgnoLast+1;
175948    writer.iBtPage = 0;
175949  }else{
175950    int iSegid = fts5AllocateSegid(p, pStruct);
175951
175952    /* Extend the Fts5Structure object as required to ensure the output
175953    ** segment exists. */
175954    if( iLvl==pStruct->nLevel-1 ){
175955      fts5StructureAddLevel(&p->rc, ppStruct);
175956      pStruct = *ppStruct;
175957    }
175958    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
175959    if( p->rc ) return;
175960    pLvl = &pStruct->aLevel[iLvl];
175961    pLvlOut = &pStruct->aLevel[iLvl+1];
175962
175963    fts5WriteInit(p, &writer, iSegid);
175964
175965    /* Add the new segment to the output level */
175966    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
175967    pLvlOut->nSeg++;
175968    pSeg->pgnoFirst = 1;
175969    pSeg->iSegid = iSegid;
175970    pStruct->nSegment++;
175971
175972    /* Read input from all segments in the input level */
175973    nInput = pLvl->nSeg;
175974  }
175975  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
175976
175977  assert( iLvl>=0 );
175978  for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, iLvl, nInput, &pIter);
175979      fts5MultiIterEof(p, pIter)==0;
175980      fts5MultiIterNext(p, pIter, 0, 0)
175981  ){
175982    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
175983    int nPos;                     /* position-list size field value */
175984    int nTerm;
175985    const u8 *pTerm;
175986
175987    /* Check for key annihilation. */
175988    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
175989
175990    pTerm = fts5MultiIterTerm(pIter, &nTerm);
175991    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
175992      if( pnRem && writer.nLeafWritten>nRem ){
175993        break;
175994      }
175995
175996      /* This is a new term. Append a term to the output segment. */
175997      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
175998      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
175999    }
176000
176001    /* Append the rowid to the output */
176002    /* WRITEPOSLISTSIZE */
176003    nPos = pSegIter->nPos*2 + pSegIter->bDel;
176004    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter), nPos);
176005
176006    /* Append the position-list data to the output */
176007    fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
176008  }
176009
176010  /* Flush the last leaf page to disk. Set the output segment b-tree height
176011  ** and last leaf page number at the same time.  */
176012  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
176013
176014  if( fts5MultiIterEof(p, pIter) ){
176015    int i;
176016
176017    /* Remove the redundant segments from the %_data table */
176018    for(i=0; i<nInput; i++){
176019      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
176020    }
176021
176022    /* Remove the redundant segments from the input level */
176023    if( pLvl->nSeg!=nInput ){
176024      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
176025      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
176026    }
176027    pStruct->nSegment -= nInput;
176028    pLvl->nSeg -= nInput;
176029    pLvl->nMerge = 0;
176030    if( pSeg->pgnoLast==0 ){
176031      pLvlOut->nSeg--;
176032      pStruct->nSegment--;
176033    }
176034  }else{
176035    assert( pSeg->pgnoLast>0 );
176036    fts5TrimSegments(p, pIter);
176037    pLvl->nMerge = nInput;
176038  }
176039
176040  fts5MultiIterFree(p, pIter);
176041  fts5BufferFree(&term);
176042  if( pnRem ) *pnRem -= writer.nLeafWritten;
176043}
176044
176045/*
176046** Do up to nPg pages of automerge work on the index.
176047*/
176048static void fts5IndexMerge(
176049  Fts5Index *p,                   /* FTS5 backend object */
176050  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
176051  int nPg                         /* Pages of work to do */
176052){
176053  int nRem = nPg;
176054  Fts5Structure *pStruct = *ppStruct;
176055  while( nRem>0 && p->rc==SQLITE_OK ){
176056    int iLvl;                   /* To iterate through levels */
176057    int iBestLvl = 0;           /* Level offering the most input segments */
176058    int nBest = 0;              /* Number of input segments on best level */
176059
176060    /* Set iBestLvl to the level to read input segments from. */
176061    assert( pStruct->nLevel>0 );
176062    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
176063      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
176064      if( pLvl->nMerge ){
176065        if( pLvl->nMerge>nBest ){
176066          iBestLvl = iLvl;
176067          nBest = pLvl->nMerge;
176068        }
176069        break;
176070      }
176071      if( pLvl->nSeg>nBest ){
176072        nBest = pLvl->nSeg;
176073        iBestLvl = iLvl;
176074      }
176075    }
176076
176077    /* If nBest is still 0, then the index must be empty. */
176078#ifdef SQLITE_DEBUG
176079    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
176080      assert( pStruct->aLevel[iLvl].nSeg==0 );
176081    }
176082#endif
176083
176084    if( nBest<p->pConfig->nAutomerge
176085        && pStruct->aLevel[iBestLvl].nMerge==0
176086      ){
176087      break;
176088    }
176089    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
176090    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
176091      fts5StructurePromote(p, iBestLvl+1, pStruct);
176092    }
176093  }
176094  *ppStruct = pStruct;
176095}
176096
176097/*
176098** A total of nLeaf leaf pages of data has just been flushed to a level-0
176099** segment. This function updates the write-counter accordingly and, if
176100** necessary, performs incremental merge work.
176101**
176102** If an error occurs, set the Fts5Index.rc error code. If an error has
176103** already occurred, this function is a no-op.
176104*/
176105static void fts5IndexAutomerge(
176106  Fts5Index *p,                   /* FTS5 backend object */
176107  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
176108  int nLeaf                       /* Number of output leaves just written */
176109){
176110  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
176111    Fts5Structure *pStruct = *ppStruct;
176112    u64 nWrite;                   /* Initial value of write-counter */
176113    int nWork;                    /* Number of work-quanta to perform */
176114    int nRem;                     /* Number of leaf pages left to write */
176115
176116    /* Update the write-counter. While doing so, set nWork. */
176117    nWrite = pStruct->nWriteCounter;
176118    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
176119    pStruct->nWriteCounter += nLeaf;
176120    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
176121
176122    fts5IndexMerge(p, ppStruct, nRem);
176123  }
176124}
176125
176126static void fts5IndexCrisismerge(
176127  Fts5Index *p,                   /* FTS5 backend object */
176128  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
176129){
176130  const int nCrisis = p->pConfig->nCrisisMerge;
176131  Fts5Structure *pStruct = *ppStruct;
176132  int iLvl = 0;
176133
176134  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
176135  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
176136    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
176137    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
176138    fts5StructurePromote(p, iLvl+1, pStruct);
176139    iLvl++;
176140  }
176141  *ppStruct = pStruct;
176142}
176143
176144static int fts5IndexReturn(Fts5Index *p){
176145  int rc = p->rc;
176146  p->rc = SQLITE_OK;
176147  return rc;
176148}
176149
176150typedef struct Fts5FlushCtx Fts5FlushCtx;
176151struct Fts5FlushCtx {
176152  Fts5Index *pIdx;
176153  Fts5SegWriter writer;
176154};
176155
176156/*
176157** Buffer aBuf[] contains a list of varints, all small enough to fit
176158** in a 32-bit integer. Return the size of the largest prefix of this
176159** list nMax bytes or less in size.
176160*/
176161static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
176162  int ret;
176163  u32 dummy;
176164  ret = fts5GetVarint32(aBuf, dummy);
176165  if( ret<nMax ){
176166    while( 1 ){
176167      int i = fts5GetVarint32(&aBuf[ret], dummy);
176168      if( (ret + i) > nMax ) break;
176169      ret += i;
176170    }
176171  }
176172  return ret;
176173}
176174
176175#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
176176  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
176177  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
176178  (pBuf)->n += nBlob;                                      \
176179}
176180
176181#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
176182  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
176183  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
176184}
176185
176186/*
176187** Flush the contents of in-memory hash table iHash to a new level-0
176188** segment on disk. Also update the corresponding structure record.
176189**
176190** If an error occurs, set the Fts5Index.rc error code. If an error has
176191** already occurred, this function is a no-op.
176192*/
176193static void fts5FlushOneHash(Fts5Index *p){
176194  Fts5Hash *pHash = p->pHash;
176195  Fts5Structure *pStruct;
176196  int iSegid;
176197  int pgnoLast = 0;                 /* Last leaf page number in segment */
176198
176199  /* Obtain a reference to the index structure and allocate a new segment-id
176200  ** for the new level-0 segment.  */
176201  pStruct = fts5StructureRead(p);
176202  iSegid = fts5AllocateSegid(p, pStruct);
176203
176204  if( iSegid ){
176205    const int pgsz = p->pConfig->pgsz;
176206
176207    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
176208    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
176209    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
176210
176211    Fts5SegWriter writer;
176212    fts5WriteInit(p, &writer, iSegid);
176213
176214    pBuf = &writer.writer.buf;
176215    pPgidx = &writer.writer.pgidx;
176216
176217    /* fts5WriteInit() should have initialized the buffers to (most likely)
176218    ** the maximum space required. */
176219    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
176220    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
176221
176222    /* Begin scanning through hash table entries. This loop runs once for each
176223    ** term/doclist currently stored within the hash table. */
176224    if( p->rc==SQLITE_OK ){
176225      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
176226    }
176227    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
176228      const char *zTerm;          /* Buffer containing term */
176229      const u8 *pDoclist;         /* Pointer to doclist for this term */
176230      int nDoclist;               /* Size of doclist in bytes */
176231
176232      /* Write the term for this entry to disk. */
176233      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
176234      fts5WriteAppendTerm(p, &writer, strlen(zTerm), (const u8*)zTerm);
176235
176236      assert( writer.bFirstRowidInPage==0 );
176237      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
176238        /* The entire doclist will fit on the current leaf. */
176239        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
176240      }else{
176241        i64 iRowid = 0;
176242        i64 iDelta = 0;
176243        int iOff = 0;
176244
176245        /* The entire doclist will not fit on this leaf. The following
176246        ** loop iterates through the poslists that make up the current
176247        ** doclist.  */
176248        while( p->rc==SQLITE_OK && iOff<nDoclist ){
176249          int nPos;
176250          int nCopy;
176251          int bDummy;
176252          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
176253          nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
176254          nCopy += nPos;
176255          iRowid += iDelta;
176256
176257          if( writer.bFirstRowidInPage ){
176258            fts5PutU16(&pBuf->p[0], pBuf->n);   /* first rowid on page */
176259            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
176260            writer.bFirstRowidInPage = 0;
176261            fts5WriteDlidxAppend(p, &writer, iRowid);
176262          }else{
176263            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
176264          }
176265          assert( pBuf->n<=pBuf->nSpace );
176266
176267          if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
176268            /* The entire poslist will fit on the current leaf. So copy
176269            ** it in one go. */
176270            fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
176271          }else{
176272            /* The entire poslist will not fit on this leaf. So it needs
176273            ** to be broken into sections. The only qualification being
176274            ** that each varint must be stored contiguously.  */
176275            const u8 *pPoslist = &pDoclist[iOff];
176276            int iPos = 0;
176277            while( p->rc==SQLITE_OK ){
176278              int nSpace = pgsz - pBuf->n - pPgidx->n;
176279              int n = 0;
176280              if( (nCopy - iPos)<=nSpace ){
176281                n = nCopy - iPos;
176282              }else{
176283                n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
176284              }
176285              assert( n>0 );
176286              fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
176287              iPos += n;
176288              if( (pBuf->n + pPgidx->n)>=pgsz ){
176289                fts5WriteFlushLeaf(p, &writer);
176290              }
176291              if( iPos>=nCopy ) break;
176292            }
176293          }
176294          iOff += nCopy;
176295        }
176296      }
176297
176298      /* TODO2: Doclist terminator written here. */
176299      /* pBuf->p[pBuf->n++] = '\0'; */
176300      assert( pBuf->n<=pBuf->nSpace );
176301      sqlite3Fts5HashScanNext(pHash);
176302    }
176303    sqlite3Fts5HashClear(pHash);
176304    fts5WriteFinish(p, &writer, &pgnoLast);
176305
176306    /* Update the Fts5Structure. It is written back to the database by the
176307    ** fts5StructureRelease() call below.  */
176308    if( pStruct->nLevel==0 ){
176309      fts5StructureAddLevel(&p->rc, &pStruct);
176310    }
176311    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
176312    if( p->rc==SQLITE_OK ){
176313      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
176314      pSeg->iSegid = iSegid;
176315      pSeg->pgnoFirst = 1;
176316      pSeg->pgnoLast = pgnoLast;
176317      pStruct->nSegment++;
176318    }
176319    fts5StructurePromote(p, 0, pStruct);
176320  }
176321
176322  fts5IndexAutomerge(p, &pStruct, pgnoLast);
176323  fts5IndexCrisismerge(p, &pStruct);
176324  fts5StructureWrite(p, pStruct);
176325  fts5StructureRelease(pStruct);
176326}
176327
176328/*
176329** Flush any data stored in the in-memory hash tables to the database.
176330*/
176331static void fts5IndexFlush(Fts5Index *p){
176332  /* Unless it is empty, flush the hash table to disk */
176333  if( p->nPendingData ){
176334    assert( p->pHash );
176335    p->nPendingData = 0;
176336    fts5FlushOneHash(p);
176337  }
176338}
176339
176340
176341static int sqlite3Fts5IndexOptimize(Fts5Index *p){
176342  Fts5Structure *pStruct;
176343  Fts5Structure *pNew = 0;
176344  int nSeg = 0;
176345
176346  assert( p->rc==SQLITE_OK );
176347  fts5IndexFlush(p);
176348  pStruct = fts5StructureRead(p);
176349
176350  if( pStruct ){
176351    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
176352    nSeg = pStruct->nSegment;
176353    if( nSeg>1 ){
176354      int nByte = sizeof(Fts5Structure);
176355      nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
176356      pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
176357    }
176358  }
176359  if( pNew ){
176360    Fts5StructureLevel *pLvl;
176361    int nByte = nSeg * sizeof(Fts5StructureSegment);
176362    pNew->nLevel = pStruct->nLevel+1;
176363    pNew->nRef = 1;
176364    pNew->nWriteCounter = pStruct->nWriteCounter;
176365    pLvl = &pNew->aLevel[pStruct->nLevel];
176366    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
176367    if( pLvl->aSeg ){
176368      int iLvl, iSeg;
176369      int iSegOut = 0;
176370      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
176371        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
176372          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
176373          iSegOut++;
176374        }
176375      }
176376      pNew->nSegment = pLvl->nSeg = nSeg;
176377    }else{
176378      sqlite3_free(pNew);
176379      pNew = 0;
176380    }
176381  }
176382
176383  if( pNew ){
176384    int iLvl = pNew->nLevel-1;
176385    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
176386      int nRem = FTS5_OPT_WORK_UNIT;
176387      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
176388    }
176389
176390    fts5StructureWrite(p, pNew);
176391    fts5StructureRelease(pNew);
176392  }
176393
176394  fts5StructureRelease(pStruct);
176395  return fts5IndexReturn(p);
176396}
176397
176398static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
176399  Fts5Structure *pStruct;
176400
176401  pStruct = fts5StructureRead(p);
176402  if( pStruct && pStruct->nLevel ){
176403    fts5IndexMerge(p, &pStruct, nMerge);
176404    fts5StructureWrite(p, pStruct);
176405  }
176406  fts5StructureRelease(pStruct);
176407
176408  return fts5IndexReturn(p);
176409}
176410
176411static void fts5PoslistCallback(
176412  Fts5Index *p,
176413  void *pContext,
176414  const u8 *pChunk, int nChunk
176415){
176416  assert_nc( nChunk>=0 );
176417  if( nChunk>0 ){
176418    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
176419  }
176420}
176421
176422typedef struct PoslistCallbackCtx PoslistCallbackCtx;
176423struct PoslistCallbackCtx {
176424  Fts5Buffer *pBuf;               /* Append to this buffer */
176425  Fts5Colset *pColset;            /* Restrict matches to this column */
176426  int eState;                     /* See above */
176427};
176428
176429/*
176430** TODO: Make this more efficient!
176431*/
176432static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
176433  int i;
176434  for(i=0; i<pColset->nCol; i++){
176435    if( pColset->aiCol[i]==iCol ) return 1;
176436  }
176437  return 0;
176438}
176439
176440static void fts5PoslistFilterCallback(
176441  Fts5Index *p,
176442  void *pContext,
176443  const u8 *pChunk, int nChunk
176444){
176445  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
176446  assert_nc( nChunk>=0 );
176447  if( nChunk>0 ){
176448    /* Search through to find the first varint with value 1. This is the
176449    ** start of the next columns hits. */
176450    int i = 0;
176451    int iStart = 0;
176452
176453    if( pCtx->eState==2 ){
176454      int iCol;
176455      fts5FastGetVarint32(pChunk, i, iCol);
176456      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
176457        pCtx->eState = 1;
176458        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
176459      }else{
176460        pCtx->eState = 0;
176461      }
176462    }
176463
176464    do {
176465      while( i<nChunk && pChunk[i]!=0x01 ){
176466        while( pChunk[i] & 0x80 ) i++;
176467        i++;
176468      }
176469      if( pCtx->eState ){
176470        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
176471      }
176472      if( i<nChunk ){
176473        int iCol;
176474        iStart = i;
176475        i++;
176476        if( i>=nChunk ){
176477          pCtx->eState = 2;
176478        }else{
176479          fts5FastGetVarint32(pChunk, i, iCol);
176480          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
176481          if( pCtx->eState ){
176482            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
176483            iStart = i;
176484          }
176485        }
176486      }
176487    }while( i<nChunk );
176488  }
176489}
176490
176491/*
176492** Iterator pIter currently points to a valid entry (not EOF). This
176493** function appends the position list data for the current entry to
176494** buffer pBuf. It does not make a copy of the position-list size
176495** field.
176496*/
176497static void fts5SegiterPoslist(
176498  Fts5Index *p,
176499  Fts5SegIter *pSeg,
176500  Fts5Colset *pColset,
176501  Fts5Buffer *pBuf
176502){
176503  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
176504    if( pColset==0 ){
176505      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
176506    }else{
176507      PoslistCallbackCtx sCtx;
176508      sCtx.pBuf = pBuf;
176509      sCtx.pColset = pColset;
176510      sCtx.eState = pColset ? fts5IndexColsetTest(pColset, 0) : 1;
176511      assert( sCtx.eState==0 || sCtx.eState==1 );
176512      fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
176513    }
176514  }
176515}
176516
176517/*
176518** IN/OUT parameter (*pa) points to a position list n bytes in size. If
176519** the position list contains entries for column iCol, then (*pa) is set
176520** to point to the sub-position-list for that column and the number of
176521** bytes in it returned. Or, if the argument position list does not
176522** contain any entries for column iCol, return 0.
176523*/
176524static int fts5IndexExtractCol(
176525  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
176526  int n,                          /* IN: Size of poslist in bytes */
176527  int iCol                        /* Column to extract from poslist */
176528){
176529  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
176530  const u8 *p = *pa;
176531  const u8 *pEnd = &p[n];         /* One byte past end of position list */
176532  u8 prev = 0;
176533
176534  while( iCol!=iCurrent ){
176535    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
176536    ** not part of a varint */
176537    while( (prev & 0x80) || *p!=0x01 ){
176538      prev = *p++;
176539      if( p==pEnd ) return 0;
176540    }
176541    *pa = p++;
176542    p += fts5GetVarint32(p, iCurrent);
176543  }
176544
176545  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
176546  ** not part of a varint */
176547  assert( (prev & 0x80)==0 );
176548  while( p<pEnd && ((prev & 0x80) || *p!=0x01) ){
176549    prev = *p++;
176550  }
176551  return p - (*pa);
176552}
176553
176554
176555/*
176556** Iterator pMulti currently points to a valid entry (not EOF). This
176557** function appends the following to buffer pBuf:
176558**
176559**   * The varint iDelta, and
176560**   * the position list that currently points to, including the size field.
176561**
176562** If argument pColset is NULL, then the position list is filtered according
176563** to pColset before being appended to the buffer. If this means there are
176564** no entries in the position list, nothing is appended to the buffer (not
176565** even iDelta).
176566**
176567** If an error occurs, an error code is left in p->rc.
176568*/
176569static int fts5AppendPoslist(
176570  Fts5Index *p,
176571  i64 iDelta,
176572  Fts5IndexIter *pMulti,
176573  Fts5Colset *pColset,
176574  Fts5Buffer *pBuf
176575){
176576  if( p->rc==SQLITE_OK ){
176577    Fts5SegIter *pSeg = &pMulti->aSeg[ pMulti->aFirst[1].iFirst ];
176578    assert( fts5MultiIterEof(p, pMulti)==0 );
176579    assert( pSeg->nPos>0 );
176580    if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+9+9) ){
176581      int iSv1;
176582      int iSv2;
176583      int iData;
176584
176585      /* Append iDelta */
176586      iSv1 = pBuf->n;
176587      fts5BufferSafeAppendVarint(pBuf, iDelta);
176588
176589      /* WRITEPOSLISTSIZE */
176590      iSv2 = pBuf->n;
176591      fts5BufferSafeAppendVarint(pBuf, pSeg->nPos*2);
176592      iData = pBuf->n;
176593
176594      if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf
176595       && (pColset==0 || pColset->nCol==1)
176596      ){
176597        const u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
176598        int nPos;
176599        if( pColset ){
176600          nPos = fts5IndexExtractCol(&pPos, pSeg->nPos, pColset->aiCol[0]);
176601        }else{
176602          nPos = pSeg->nPos;
176603        }
176604        fts5BufferSafeAppendBlob(pBuf, pPos, nPos);
176605      }else{
176606        fts5SegiterPoslist(p, pSeg, pColset, pBuf);
176607      }
176608
176609      if( pColset ){
176610        int nActual = pBuf->n - iData;
176611        if( nActual!=pSeg->nPos ){
176612          if( nActual==0 ){
176613            pBuf->n = iSv1;
176614            return 1;
176615          }else{
176616            int nReq = sqlite3Fts5GetVarintLen((u32)(nActual*2));
176617            while( iSv2<(iData-nReq) ){ pBuf->p[iSv2++] = 0x80; }
176618            sqlite3Fts5PutVarint(&pBuf->p[iSv2], nActual*2);
176619          }
176620        }
176621      }
176622    }
176623  }
176624
176625  return 0;
176626}
176627
176628static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
176629  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
176630
176631  assert( pIter->aPoslist );
176632  if( p>=pIter->aEof ){
176633    pIter->aPoslist = 0;
176634  }else{
176635    i64 iDelta;
176636
176637    p += fts5GetVarint(p, (u64*)&iDelta);
176638    pIter->iRowid += iDelta;
176639
176640    /* Read position list size */
176641    if( p[0] & 0x80 ){
176642      int nPos;
176643      pIter->nSize = fts5GetVarint32(p, nPos);
176644      pIter->nPoslist = (nPos>>1);
176645    }else{
176646      pIter->nPoslist = ((int)(p[0])) >> 1;
176647      pIter->nSize = 1;
176648    }
176649
176650    pIter->aPoslist = p;
176651  }
176652}
176653
176654static void fts5DoclistIterInit(
176655  Fts5Buffer *pBuf,
176656  Fts5DoclistIter *pIter
176657){
176658  memset(pIter, 0, sizeof(*pIter));
176659  pIter->aPoslist = pBuf->p;
176660  pIter->aEof = &pBuf->p[pBuf->n];
176661  fts5DoclistIterNext(pIter);
176662}
176663
176664#if 0
176665/*
176666** Append a doclist to buffer pBuf.
176667**
176668** This function assumes that space within the buffer has already been
176669** allocated.
176670*/
176671static void fts5MergeAppendDocid(
176672  Fts5Buffer *pBuf,               /* Buffer to write to */
176673  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
176674  i64 iRowid                      /* Rowid to append */
176675){
176676  assert( pBuf->n!=0 || (*piLastRowid)==0 );
176677  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
176678  *piLastRowid = iRowid;
176679}
176680#endif
176681
176682#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
176683  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
176684  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
176685  (iLastRowid) = (iRowid);                                     \
176686}
176687
176688/*
176689** Buffers p1 and p2 contain doclists. This function merges the content
176690** of the two doclists together and sets buffer p1 to the result before
176691** returning.
176692**
176693** If an error occurs, an error code is left in p->rc. If an error has
176694** already occurred, this function is a no-op.
176695*/
176696static void fts5MergePrefixLists(
176697  Fts5Index *p,                   /* FTS5 backend object */
176698  Fts5Buffer *p1,                 /* First list to merge */
176699  Fts5Buffer *p2                  /* Second list to merge */
176700){
176701  if( p2->n ){
176702    i64 iLastRowid = 0;
176703    Fts5DoclistIter i1;
176704    Fts5DoclistIter i2;
176705    Fts5Buffer out;
176706    Fts5Buffer tmp;
176707    memset(&out, 0, sizeof(out));
176708    memset(&tmp, 0, sizeof(tmp));
176709
176710    sqlite3Fts5BufferGrow(&p->rc, &out, p1->n + p2->n);
176711    fts5DoclistIterInit(p1, &i1);
176712    fts5DoclistIterInit(p2, &i2);
176713    while( p->rc==SQLITE_OK && (i1.aPoslist!=0 || i2.aPoslist!=0) ){
176714      if( i2.aPoslist==0 || (i1.aPoslist && i1.iRowid<i2.iRowid) ){
176715        /* Copy entry from i1 */
176716        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
176717        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
176718        fts5DoclistIterNext(&i1);
176719      }
176720      else if( i1.aPoslist==0 || i2.iRowid!=i1.iRowid ){
176721        /* Copy entry from i2 */
176722        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
176723        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
176724        fts5DoclistIterNext(&i2);
176725      }
176726      else{
176727        i64 iPos1 = 0;
176728        i64 iPos2 = 0;
176729        int iOff1 = 0;
176730        int iOff2 = 0;
176731        u8 *a1 = &i1.aPoslist[i1.nSize];
176732        u8 *a2 = &i2.aPoslist[i2.nSize];
176733
176734        Fts5PoslistWriter writer;
176735        memset(&writer, 0, sizeof(writer));
176736
176737        /* Merge the two position lists. */
176738        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
176739        fts5BufferZero(&tmp);
176740
176741        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
176742        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
176743
176744        while( p->rc==SQLITE_OK && (iPos1>=0 || iPos2>=0) ){
176745          i64 iNew;
176746          if( iPos2<0 || (iPos1>=0 && iPos1<iPos2) ){
176747            iNew = iPos1;
176748            sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
176749          }else{
176750            iNew = iPos2;
176751            sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
176752            if( iPos1==iPos2 ){
176753              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1,&iPos1);
176754            }
176755          }
176756          p->rc = sqlite3Fts5PoslistWriterAppend(&tmp, &writer, iNew);
176757        }
176758
176759        /* WRITEPOSLISTSIZE */
176760        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
176761        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
176762        fts5DoclistIterNext(&i1);
176763        fts5DoclistIterNext(&i2);
176764      }
176765    }
176766
176767    fts5BufferSet(&p->rc, p1, out.n, out.p);
176768    fts5BufferFree(&tmp);
176769    fts5BufferFree(&out);
176770  }
176771}
176772
176773static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
176774  Fts5Buffer tmp = *p1;
176775  *p1 = *p2;
176776  *p2 = tmp;
176777}
176778
176779static void fts5SetupPrefixIter(
176780  Fts5Index *p,                   /* Index to read from */
176781  int bDesc,                      /* True for "ORDER BY rowid DESC" */
176782  const u8 *pToken,               /* Buffer containing prefix to match */
176783  int nToken,                     /* Size of buffer pToken in bytes */
176784  Fts5Colset *pColset,            /* Restrict matches to these columns */
176785  Fts5IndexIter **ppIter          /* OUT: New iterator */
176786){
176787  Fts5Structure *pStruct;
176788  Fts5Buffer *aBuf;
176789  const int nBuf = 32;
176790
176791  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
176792  pStruct = fts5StructureRead(p);
176793
176794  if( aBuf && pStruct ){
176795    const int flags = FTS5INDEX_QUERY_SCAN;
176796    int i;
176797    i64 iLastRowid = 0;
176798    Fts5IndexIter *p1 = 0;     /* Iterator used to gather data from index */
176799    Fts5Data *pData;
176800    Fts5Buffer doclist;
176801
176802    memset(&doclist, 0, sizeof(doclist));
176803    for(fts5MultiIterNew(p, pStruct, 1, flags, pToken, nToken, -1, 0, &p1);
176804        fts5MultiIterEof(p, p1)==0;
176805        fts5MultiIterNext(p, p1, 0, 0)
176806    ){
176807      i64 iRowid = fts5MultiIterRowid(p1);
176808      int nTerm;
176809      const u8 *pTerm = fts5MultiIterTerm(p1, &nTerm);
176810      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
176811      if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
176812
176813      if( doclist.n>0 && iRowid<=iLastRowid ){
176814        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
176815          assert( i<nBuf );
176816          if( aBuf[i].n==0 ){
176817            fts5BufferSwap(&doclist, &aBuf[i]);
176818            fts5BufferZero(&doclist);
176819          }else{
176820            fts5MergePrefixLists(p, &doclist, &aBuf[i]);
176821            fts5BufferZero(&aBuf[i]);
176822          }
176823        }
176824        iLastRowid = 0;
176825      }
176826
176827      if( !fts5AppendPoslist(p, iRowid-iLastRowid, p1, pColset, &doclist) ){
176828        iLastRowid = iRowid;
176829      }
176830    }
176831
176832    for(i=0; i<nBuf; i++){
176833      if( p->rc==SQLITE_OK ){
176834        fts5MergePrefixLists(p, &doclist, &aBuf[i]);
176835      }
176836      fts5BufferFree(&aBuf[i]);
176837    }
176838    fts5MultiIterFree(p, p1);
176839
176840    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
176841    if( pData ){
176842      pData->p = (u8*)&pData[1];
176843      pData->nn = pData->szLeaf = doclist.n;
176844      memcpy(pData->p, doclist.p, doclist.n);
176845      fts5MultiIterNew2(p, pData, bDesc, ppIter);
176846    }
176847    fts5BufferFree(&doclist);
176848  }
176849
176850  fts5StructureRelease(pStruct);
176851  sqlite3_free(aBuf);
176852}
176853
176854
176855/*
176856** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
176857** to the document with rowid iRowid.
176858*/
176859static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
176860  assert( p->rc==SQLITE_OK );
176861
176862  /* Allocate the hash table if it has not already been allocated */
176863  if( p->pHash==0 ){
176864    p->rc = sqlite3Fts5HashNew(&p->pHash, &p->nPendingData);
176865  }
176866
176867  /* Flush the hash table to disk if required */
176868  if( iRowid<p->iWriteRowid
176869   || (iRowid==p->iWriteRowid && p->bDelete==0)
176870   || (p->nPendingData > p->nMaxPendingData)
176871  ){
176872    fts5IndexFlush(p);
176873  }
176874
176875  p->iWriteRowid = iRowid;
176876  p->bDelete = bDelete;
176877  return fts5IndexReturn(p);
176878}
176879
176880/*
176881** Commit data to disk.
176882*/
176883static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
176884  assert( p->rc==SQLITE_OK );
176885  fts5IndexFlush(p);
176886  if( bCommit ) fts5CloseReader(p);
176887  return fts5IndexReturn(p);
176888}
176889
176890/*
176891** Discard any data stored in the in-memory hash tables. Do not write it
176892** to the database. Additionally, assume that the contents of the %_data
176893** table may have changed on disk. So any in-memory caches of %_data
176894** records must be invalidated.
176895*/
176896static int sqlite3Fts5IndexRollback(Fts5Index *p){
176897  fts5CloseReader(p);
176898  fts5IndexDiscardData(p);
176899  assert( p->rc==SQLITE_OK );
176900  return SQLITE_OK;
176901}
176902
176903/*
176904** The %_data table is completely empty when this function is called. This
176905** function populates it with the initial structure objects for each index,
176906** and the initial version of the "averages" record (a zero-byte blob).
176907*/
176908static int sqlite3Fts5IndexReinit(Fts5Index *p){
176909  Fts5Structure s;
176910  memset(&s, 0, sizeof(Fts5Structure));
176911  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
176912  fts5StructureWrite(p, &s);
176913  return fts5IndexReturn(p);
176914}
176915
176916/*
176917** Open a new Fts5Index handle. If the bCreate argument is true, create
176918** and initialize the underlying %_data table.
176919**
176920** If successful, set *pp to point to the new object and return SQLITE_OK.
176921** Otherwise, set *pp to NULL and return an SQLite error code.
176922*/
176923static int sqlite3Fts5IndexOpen(
176924  Fts5Config *pConfig,
176925  int bCreate,
176926  Fts5Index **pp,
176927  char **pzErr
176928){
176929  int rc = SQLITE_OK;
176930  Fts5Index *p;                   /* New object */
176931
176932  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
176933  if( rc==SQLITE_OK ){
176934    p->pConfig = pConfig;
176935    p->nWorkUnit = FTS5_WORK_UNIT;
176936    p->nMaxPendingData = 1024*1024;
176937    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
176938    if( p->zDataTbl && bCreate ){
176939      rc = sqlite3Fts5CreateTable(
176940          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
176941      );
176942      if( rc==SQLITE_OK ){
176943        rc = sqlite3Fts5CreateTable(pConfig, "idx",
176944            "segid, term, pgno, PRIMARY KEY(segid, term)",
176945            1, pzErr
176946        );
176947      }
176948      if( rc==SQLITE_OK ){
176949        rc = sqlite3Fts5IndexReinit(p);
176950      }
176951    }
176952  }
176953
176954  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
176955  if( rc ){
176956    sqlite3Fts5IndexClose(p);
176957    *pp = 0;
176958  }
176959  return rc;
176960}
176961
176962/*
176963** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
176964*/
176965static int sqlite3Fts5IndexClose(Fts5Index *p){
176966  int rc = SQLITE_OK;
176967  if( p ){
176968    assert( p->pReader==0 );
176969    sqlite3_finalize(p->pWriter);
176970    sqlite3_finalize(p->pDeleter);
176971    sqlite3_finalize(p->pIdxWriter);
176972    sqlite3_finalize(p->pIdxDeleter);
176973    sqlite3_finalize(p->pIdxSelect);
176974    sqlite3Fts5HashFree(p->pHash);
176975    sqlite3_free(p->zDataTbl);
176976    sqlite3_free(p);
176977  }
176978  return rc;
176979}
176980
176981/*
176982** Argument p points to a buffer containing utf-8 text that is n bytes in
176983** size. Return the number of bytes in the nChar character prefix of the
176984** buffer, or 0 if there are less than nChar characters in total.
176985*/
176986static int fts5IndexCharlenToBytelen(const char *p, int nByte, int nChar){
176987  int n = 0;
176988  int i;
176989  for(i=0; i<nChar; i++){
176990    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
176991    if( (unsigned char)p[n++]>=0xc0 ){
176992      while( (p[n] & 0xc0)==0x80 ) n++;
176993    }
176994  }
176995  return n;
176996}
176997
176998/*
176999** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
177000** unicode characters in the string.
177001*/
177002static int fts5IndexCharlen(const char *pIn, int nIn){
177003  int nChar = 0;
177004  int i = 0;
177005  while( i<nIn ){
177006    if( (unsigned char)pIn[i++]>=0xc0 ){
177007      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
177008    }
177009    nChar++;
177010  }
177011  return nChar;
177012}
177013
177014/*
177015** Insert or remove data to or from the index. Each time a document is
177016** added to or removed from the index, this function is called one or more
177017** times.
177018**
177019** For an insert, it must be called once for each token in the new document.
177020** If the operation is a delete, it must be called (at least) once for each
177021** unique token in the document with an iCol value less than zero. The iPos
177022** argument is ignored for a delete.
177023*/
177024static int sqlite3Fts5IndexWrite(
177025  Fts5Index *p,                   /* Index to write to */
177026  int iCol,                       /* Column token appears in (-ve -> delete) */
177027  int iPos,                       /* Position of token within column */
177028  const char *pToken, int nToken  /* Token to add or remove to or from index */
177029){
177030  int i;                          /* Used to iterate through indexes */
177031  int rc = SQLITE_OK;             /* Return code */
177032  Fts5Config *pConfig = p->pConfig;
177033
177034  assert( p->rc==SQLITE_OK );
177035  assert( (iCol<0)==p->bDelete );
177036
177037  /* Add the entry to the main terms index. */
177038  rc = sqlite3Fts5HashWrite(
177039      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
177040  );
177041
177042  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
177043    int nByte = fts5IndexCharlenToBytelen(pToken, nToken, pConfig->aPrefix[i]);
177044    if( nByte ){
177045      rc = sqlite3Fts5HashWrite(p->pHash,
177046          p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX+i+1, pToken, nByte
177047      );
177048    }
177049  }
177050
177051  return rc;
177052}
177053
177054/*
177055** Open a new iterator to iterate though all rowid that match the
177056** specified token or token prefix.
177057*/
177058static int sqlite3Fts5IndexQuery(
177059  Fts5Index *p,                   /* FTS index to query */
177060  const char *pToken, int nToken, /* Token (or prefix) to query for */
177061  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
177062  Fts5Colset *pColset,            /* Match these columns only */
177063  Fts5IndexIter **ppIter          /* OUT: New iterator object */
177064){
177065  Fts5Config *pConfig = p->pConfig;
177066  Fts5IndexIter *pRet = 0;
177067  int iIdx = 0;
177068  Fts5Buffer buf = {0, 0, 0};
177069
177070  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
177071  assert( (flags & FTS5INDEX_QUERY_SCAN)==0
177072       || (flags & FTS5INDEX_QUERY_SCAN)==FTS5INDEX_QUERY_SCAN
177073  );
177074
177075  if( sqlite3Fts5BufferGrow(&p->rc, &buf, nToken+1)==0 ){
177076    memcpy(&buf.p[1], pToken, nToken);
177077
177078#ifdef SQLITE_DEBUG
177079    /* If the QUERY_TEST_NOIDX flag was specified, then this must be a
177080    ** prefix-query. Instead of using a prefix-index (if one exists),
177081    ** evaluate the prefix query using the main FTS index. This is used
177082    ** for internal sanity checking by the integrity-check in debug
177083    ** mode only.  */
177084    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
177085      assert( flags & FTS5INDEX_QUERY_PREFIX );
177086      iIdx = 1+pConfig->nPrefix;
177087    }else
177088#endif
177089    if( flags & FTS5INDEX_QUERY_PREFIX ){
177090      int nChar = fts5IndexCharlen(pToken, nToken);
177091      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
177092        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
177093      }
177094    }
177095
177096    if( iIdx<=pConfig->nPrefix ){
177097      Fts5Structure *pStruct = fts5StructureRead(p);
177098      buf.p[0] = FTS5_MAIN_PREFIX + iIdx;
177099      if( pStruct ){
177100        fts5MultiIterNew(p, pStruct, 1, flags, buf.p, nToken+1, -1, 0, &pRet);
177101        fts5StructureRelease(pStruct);
177102      }
177103    }else{
177104      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
177105      buf.p[0] = FTS5_MAIN_PREFIX;
177106      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
177107    }
177108
177109    if( p->rc ){
177110      sqlite3Fts5IterClose(pRet);
177111      pRet = 0;
177112      fts5CloseReader(p);
177113    }
177114    *ppIter = pRet;
177115    sqlite3Fts5BufferFree(&buf);
177116  }
177117  return fts5IndexReturn(p);
177118}
177119
177120/*
177121** Return true if the iterator passed as the only argument is at EOF.
177122*/
177123static int sqlite3Fts5IterEof(Fts5IndexIter *pIter){
177124  assert( pIter->pIndex->rc==SQLITE_OK );
177125  return pIter->bEof;
177126}
177127
177128/*
177129** Move to the next matching rowid.
177130*/
177131static int sqlite3Fts5IterNext(Fts5IndexIter *pIter){
177132  assert( pIter->pIndex->rc==SQLITE_OK );
177133  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
177134  return fts5IndexReturn(pIter->pIndex);
177135}
177136
177137/*
177138** Move to the next matching term/rowid. Used by the fts5vocab module.
177139*/
177140static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIter){
177141  Fts5Index *p = pIter->pIndex;
177142
177143  assert( pIter->pIndex->rc==SQLITE_OK );
177144
177145  fts5MultiIterNext(p, pIter, 0, 0);
177146  if( p->rc==SQLITE_OK ){
177147    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177148    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
177149      fts5DataRelease(pSeg->pLeaf);
177150      pSeg->pLeaf = 0;
177151      pIter->bEof = 1;
177152    }
177153  }
177154
177155  return fts5IndexReturn(pIter->pIndex);
177156}
177157
177158/*
177159** Move to the next matching rowid that occurs at or after iMatch. The
177160** definition of "at or after" depends on whether this iterator iterates
177161** in ascending or descending rowid order.
177162*/
177163static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIter, i64 iMatch){
177164  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
177165  return fts5IndexReturn(pIter->pIndex);
177166}
177167
177168/*
177169** Return the current rowid.
177170*/
177171static i64 sqlite3Fts5IterRowid(Fts5IndexIter *pIter){
177172  return fts5MultiIterRowid(pIter);
177173}
177174
177175/*
177176** Return the current term.
177177*/
177178static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIter, int *pn){
177179  int n;
177180  const char *z = (const char*)fts5MultiIterTerm(pIter, &n);
177181  *pn = n-1;
177182  return &z[1];
177183}
177184
177185
177186static int fts5IndexExtractColset (
177187  Fts5Colset *pColset,            /* Colset to filter on */
177188  const u8 *pPos, int nPos,       /* Position list */
177189  Fts5Buffer *pBuf                /* Output buffer */
177190){
177191  int rc = SQLITE_OK;
177192  int i;
177193
177194  fts5BufferZero(pBuf);
177195  for(i=0; i<pColset->nCol; i++){
177196    const u8 *pSub = pPos;
177197    int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
177198    if( nSub ){
177199      fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
177200    }
177201  }
177202  return rc;
177203}
177204
177205
177206/*
177207** Return a pointer to a buffer containing a copy of the position list for
177208** the current entry. Output variable *pn is set to the size of the buffer
177209** in bytes before returning.
177210**
177211** The returned position list does not include the "number of bytes" varint
177212** field that starts the position list on disk.
177213*/
177214static int sqlite3Fts5IterPoslist(
177215  Fts5IndexIter *pIter,
177216  Fts5Colset *pColset,            /* Column filter (or NULL) */
177217  const u8 **pp,                  /* OUT: Pointer to position-list data */
177218  int *pn,                        /* OUT: Size of position-list in bytes */
177219  i64 *piRowid                    /* OUT: Current rowid */
177220){
177221  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177222  assert( pIter->pIndex->rc==SQLITE_OK );
177223  *piRowid = pSeg->iRowid;
177224  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
177225    u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
177226    if( pColset==0 || pIter->bFiltered ){
177227      *pn = pSeg->nPos;
177228      *pp = pPos;
177229    }else if( pColset->nCol==1 ){
177230      *pp = pPos;
177231      *pn = fts5IndexExtractCol(pp, pSeg->nPos, pColset->aiCol[0]);
177232    }else{
177233      fts5BufferZero(&pIter->poslist);
177234      fts5IndexExtractColset(pColset, pPos, pSeg->nPos, &pIter->poslist);
177235      *pp = pIter->poslist.p;
177236      *pn = pIter->poslist.n;
177237    }
177238  }else{
177239    fts5BufferZero(&pIter->poslist);
177240    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
177241    *pp = pIter->poslist.p;
177242    *pn = pIter->poslist.n;
177243  }
177244  return fts5IndexReturn(pIter->pIndex);
177245}
177246
177247/*
177248** This function is similar to sqlite3Fts5IterPoslist(), except that it
177249** copies the position list into the buffer supplied as the second
177250** argument.
177251*/
177252static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf){
177253  Fts5Index *p = pIter->pIndex;
177254  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177255  assert( p->rc==SQLITE_OK );
177256  fts5BufferZero(pBuf);
177257  fts5SegiterPoslist(p, pSeg, 0, pBuf);
177258  return fts5IndexReturn(p);
177259}
177260
177261/*
177262** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
177263*/
177264static void sqlite3Fts5IterClose(Fts5IndexIter *pIter){
177265  if( pIter ){
177266    Fts5Index *pIndex = pIter->pIndex;
177267    fts5MultiIterFree(pIter->pIndex, pIter);
177268    fts5CloseReader(pIndex);
177269  }
177270}
177271
177272/*
177273** Read and decode the "averages" record from the database.
177274**
177275** Parameter anSize must point to an array of size nCol, where nCol is
177276** the number of user defined columns in the FTS table.
177277*/
177278static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
177279  int nCol = p->pConfig->nCol;
177280  Fts5Data *pData;
177281
177282  *pnRow = 0;
177283  memset(anSize, 0, sizeof(i64) * nCol);
177284  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
177285  if( p->rc==SQLITE_OK && pData->nn ){
177286    int i = 0;
177287    int iCol;
177288    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
177289    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
177290      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
177291    }
177292  }
177293
177294  fts5DataRelease(pData);
177295  return fts5IndexReturn(p);
177296}
177297
177298/*
177299** Replace the current "averages" record with the contents of the buffer
177300** supplied as the second argument.
177301*/
177302static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
177303  assert( p->rc==SQLITE_OK );
177304  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
177305  return fts5IndexReturn(p);
177306}
177307
177308/*
177309** Return the total number of blocks this module has read from the %_data
177310** table since it was created.
177311*/
177312static int sqlite3Fts5IndexReads(Fts5Index *p){
177313  return p->nRead;
177314}
177315
177316/*
177317** Set the 32-bit cookie value stored at the start of all structure
177318** records to the value passed as the second argument.
177319**
177320** Return SQLITE_OK if successful, or an SQLite error code if an error
177321** occurs.
177322*/
177323static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
177324  int rc;                              /* Return code */
177325  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
177326  u8 aCookie[4];                       /* Binary representation of iNew */
177327  sqlite3_blob *pBlob = 0;
177328
177329  assert( p->rc==SQLITE_OK );
177330  sqlite3Fts5Put32(aCookie, iNew);
177331
177332  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
177333      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
177334  );
177335  if( rc==SQLITE_OK ){
177336    sqlite3_blob_write(pBlob, aCookie, 4, 0);
177337    rc = sqlite3_blob_close(pBlob);
177338  }
177339
177340  return rc;
177341}
177342
177343static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
177344  Fts5Structure *pStruct;
177345  pStruct = fts5StructureRead(p);
177346  fts5StructureRelease(pStruct);
177347  return fts5IndexReturn(p);
177348}
177349
177350
177351/*************************************************************************
177352**************************************************************************
177353** Below this point is the implementation of the integrity-check
177354** functionality.
177355*/
177356
177357/*
177358** Return a simple checksum value based on the arguments.
177359*/
177360static u64 fts5IndexEntryCksum(
177361  i64 iRowid,
177362  int iCol,
177363  int iPos,
177364  int iIdx,
177365  const char *pTerm,
177366  int nTerm
177367){
177368  int i;
177369  u64 ret = iRowid;
177370  ret += (ret<<3) + iCol;
177371  ret += (ret<<3) + iPos;
177372  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
177373  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
177374  return ret;
177375}
177376
177377#ifdef SQLITE_DEBUG
177378/*
177379** This function is purely an internal test. It does not contribute to
177380** FTS functionality, or even the integrity-check, in any way.
177381**
177382** Instead, it tests that the same set of pgno/rowid combinations are
177383** visited regardless of whether the doclist-index identified by parameters
177384** iSegid/iLeaf is iterated in forwards or reverse order.
177385*/
177386static void fts5TestDlidxReverse(
177387  Fts5Index *p,
177388  int iSegid,                     /* Segment id to load from */
177389  int iLeaf                       /* Load doclist-index for this leaf */
177390){
177391  Fts5DlidxIter *pDlidx = 0;
177392  u64 cksum1 = 13;
177393  u64 cksum2 = 13;
177394
177395  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
177396      fts5DlidxIterEof(p, pDlidx)==0;
177397      fts5DlidxIterNext(p, pDlidx)
177398  ){
177399    i64 iRowid = fts5DlidxIterRowid(pDlidx);
177400    int pgno = fts5DlidxIterPgno(pDlidx);
177401    assert( pgno>iLeaf );
177402    cksum1 += iRowid + ((i64)pgno<<32);
177403  }
177404  fts5DlidxIterFree(pDlidx);
177405  pDlidx = 0;
177406
177407  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
177408      fts5DlidxIterEof(p, pDlidx)==0;
177409      fts5DlidxIterPrev(p, pDlidx)
177410  ){
177411    i64 iRowid = fts5DlidxIterRowid(pDlidx);
177412    int pgno = fts5DlidxIterPgno(pDlidx);
177413    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
177414    cksum2 += iRowid + ((i64)pgno<<32);
177415  }
177416  fts5DlidxIterFree(pDlidx);
177417  pDlidx = 0;
177418
177419  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
177420}
177421
177422static int fts5QueryCksum(
177423  Fts5Index *p,                   /* Fts5 index object */
177424  int iIdx,
177425  const char *z,                  /* Index key to query for */
177426  int n,                          /* Size of index key in bytes */
177427  int flags,                      /* Flags for Fts5IndexQuery */
177428  u64 *pCksum                     /* IN/OUT: Checksum value */
177429){
177430  u64 cksum = *pCksum;
177431  Fts5IndexIter *pIdxIter = 0;
177432  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIdxIter);
177433
177434  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIdxIter) ){
177435    i64 dummy;
177436    const u8 *pPos;
177437    int nPos;
177438    i64 rowid = sqlite3Fts5IterRowid(pIdxIter);
177439    rc = sqlite3Fts5IterPoslist(pIdxIter, 0, &pPos, &nPos, &dummy);
177440    if( rc==SQLITE_OK ){
177441      Fts5PoslistReader sReader;
177442      for(sqlite3Fts5PoslistReaderInit(pPos, nPos, &sReader);
177443          sReader.bEof==0;
177444          sqlite3Fts5PoslistReaderNext(&sReader)
177445      ){
177446        int iCol = FTS5_POS2COLUMN(sReader.iPos);
177447        int iOff = FTS5_POS2OFFSET(sReader.iPos);
177448        cksum ^= fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
177449      }
177450      rc = sqlite3Fts5IterNext(pIdxIter);
177451    }
177452  }
177453  sqlite3Fts5IterClose(pIdxIter);
177454
177455  *pCksum = cksum;
177456  return rc;
177457}
177458
177459
177460/*
177461** This function is also purely an internal test. It does not contribute to
177462** FTS functionality, or even the integrity-check, in any way.
177463*/
177464static void fts5TestTerm(
177465  Fts5Index *p,
177466  Fts5Buffer *pPrev,              /* Previous term */
177467  const char *z, int n,           /* Possibly new term to test */
177468  u64 expected,
177469  u64 *pCksum
177470){
177471  int rc = p->rc;
177472  if( pPrev->n==0 ){
177473    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
177474  }else
177475  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
177476    u64 cksum3 = *pCksum;
177477    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
177478    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
177479    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
177480    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
177481    u64 ck1 = 0;
177482    u64 ck2 = 0;
177483
177484    /* Check that the results returned for ASC and DESC queries are
177485    ** the same. If not, call this corruption.  */
177486    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
177487    if( rc==SQLITE_OK ){
177488      int f = flags|FTS5INDEX_QUERY_DESC;
177489      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177490    }
177491    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177492
177493    /* If this is a prefix query, check that the results returned if the
177494    ** the index is disabled are the same. In both ASC and DESC order.
177495    **
177496    ** This check may only be performed if the hash table is empty. This
177497    ** is because the hash table only supports a single scan query at
177498    ** a time, and the multi-iter loop from which this function is called
177499    ** is already performing such a scan. */
177500    if( p->nPendingData==0 ){
177501      if( iIdx>0 && rc==SQLITE_OK ){
177502        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
177503        ck2 = 0;
177504        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177505        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177506      }
177507      if( iIdx>0 && rc==SQLITE_OK ){
177508        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
177509        ck2 = 0;
177510        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177511        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177512      }
177513    }
177514
177515    cksum3 ^= ck1;
177516    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
177517
177518    if( rc==SQLITE_OK && cksum3!=expected ){
177519      rc = FTS5_CORRUPT;
177520    }
177521    *pCksum = cksum3;
177522  }
177523  p->rc = rc;
177524}
177525
177526#else
177527# define fts5TestDlidxReverse(x,y,z)
177528# define fts5TestTerm(u,v,w,x,y,z)
177529#endif
177530
177531/*
177532** Check that:
177533**
177534**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
177535**      contain zero terms.
177536**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
177537**      contain zero rowids.
177538*/
177539static void fts5IndexIntegrityCheckEmpty(
177540  Fts5Index *p,
177541  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
177542  int iFirst,
177543  int iNoRowid,
177544  int iLast
177545){
177546  int i;
177547
177548  /* Now check that the iter.nEmpty leaves following the current leaf
177549  ** (a) exist and (b) contain no terms. */
177550  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
177551    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
177552    if( pLeaf ){
177553      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
177554      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
177555    }
177556    fts5DataRelease(pLeaf);
177557  }
177558}
177559
177560static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
177561  int iTermOff = 0;
177562  int ii;
177563
177564  Fts5Buffer buf1 = {0,0,0};
177565  Fts5Buffer buf2 = {0,0,0};
177566
177567  ii = pLeaf->szLeaf;
177568  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
177569    int res;
177570    int iOff;
177571    int nIncr;
177572
177573    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
177574    iTermOff += nIncr;
177575    iOff = iTermOff;
177576
177577    if( iOff>=pLeaf->szLeaf ){
177578      p->rc = FTS5_CORRUPT;
177579    }else if( iTermOff==nIncr ){
177580      int nByte;
177581      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
177582      if( (iOff+nByte)>pLeaf->szLeaf ){
177583        p->rc = FTS5_CORRUPT;
177584      }else{
177585        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
177586      }
177587    }else{
177588      int nKeep, nByte;
177589      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
177590      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
177591      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
177592        p->rc = FTS5_CORRUPT;
177593      }else{
177594        buf1.n = nKeep;
177595        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
177596      }
177597
177598      if( p->rc==SQLITE_OK ){
177599        res = fts5BufferCompare(&buf1, &buf2);
177600        if( res<=0 ) p->rc = FTS5_CORRUPT;
177601      }
177602    }
177603    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
177604  }
177605
177606  fts5BufferFree(&buf1);
177607  fts5BufferFree(&buf2);
177608}
177609
177610static void fts5IndexIntegrityCheckSegment(
177611  Fts5Index *p,                   /* FTS5 backend object */
177612  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
177613){
177614  Fts5Config *pConfig = p->pConfig;
177615  sqlite3_stmt *pStmt = 0;
177616  int rc2;
177617  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
177618  int iDlidxPrevLeaf = pSeg->pgnoLast;
177619
177620  if( pSeg->pgnoFirst==0 ) return;
177621
177622  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
177623      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
177624      pConfig->zDb, pConfig->zName, pSeg->iSegid
177625  ));
177626
177627  /* Iterate through the b-tree hierarchy.  */
177628  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
177629    i64 iRow;                     /* Rowid for this leaf */
177630    Fts5Data *pLeaf;              /* Data for this leaf */
177631
177632    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
177633    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
177634    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
177635    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
177636
177637    /* If the leaf in question has already been trimmed from the segment,
177638    ** ignore this b-tree entry. Otherwise, load it into memory. */
177639    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
177640    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
177641    pLeaf = fts5DataRead(p, iRow);
177642    if( pLeaf==0 ) break;
177643
177644    /* Check that the leaf contains at least one term, and that it is equal
177645    ** to or larger than the split-key in zIdxTerm.  Also check that if there
177646    ** is also a rowid pointer within the leaf page header, it points to a
177647    ** location before the term.  */
177648    if( pLeaf->nn<=pLeaf->szLeaf ){
177649      p->rc = FTS5_CORRUPT;
177650    }else{
177651      int iOff;                   /* Offset of first term on leaf */
177652      int iRowidOff;              /* Offset of first rowid on leaf */
177653      int nTerm;                  /* Size of term on leaf in bytes */
177654      int res;                    /* Comparison of term and split-key */
177655
177656      iOff = fts5LeafFirstTermOff(pLeaf);
177657      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
177658      if( iRowidOff>=iOff ){
177659        p->rc = FTS5_CORRUPT;
177660      }else{
177661        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
177662        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
177663        if( res==0 ) res = nTerm - nIdxTerm;
177664        if( res<0 ) p->rc = FTS5_CORRUPT;
177665      }
177666
177667      fts5IntegrityCheckPgidx(p, pLeaf);
177668    }
177669    fts5DataRelease(pLeaf);
177670    if( p->rc ) break;
177671
177672
177673    /* Now check that the iter.nEmpty leaves following the current leaf
177674    ** (a) exist and (b) contain no terms. */
177675    fts5IndexIntegrityCheckEmpty(
177676        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
177677    );
177678    if( p->rc ) break;
177679
177680    /* If there is a doclist-index, check that it looks right. */
177681    if( bIdxDlidx ){
177682      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
177683      int iPrevLeaf = iIdxLeaf;
177684      int iSegid = pSeg->iSegid;
177685      int iPg = 0;
177686      i64 iKey;
177687
177688      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
177689          fts5DlidxIterEof(p, pDlidx)==0;
177690          fts5DlidxIterNext(p, pDlidx)
177691      ){
177692
177693        /* Check any rowid-less pages that occur before the current leaf. */
177694        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
177695          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
177696          pLeaf = fts5DataRead(p, iKey);
177697          if( pLeaf ){
177698            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
177699            fts5DataRelease(pLeaf);
177700          }
177701        }
177702        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
177703
177704        /* Check that the leaf page indicated by the iterator really does
177705        ** contain the rowid suggested by the same. */
177706        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
177707        pLeaf = fts5DataRead(p, iKey);
177708        if( pLeaf ){
177709          i64 iRowid;
177710          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
177711          ASSERT_SZLEAF_OK(pLeaf);
177712          if( iRowidOff>=pLeaf->szLeaf ){
177713            p->rc = FTS5_CORRUPT;
177714          }else{
177715            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
177716            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
177717          }
177718          fts5DataRelease(pLeaf);
177719        }
177720      }
177721
177722      iDlidxPrevLeaf = iPg;
177723      fts5DlidxIterFree(pDlidx);
177724      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
177725    }else{
177726      iDlidxPrevLeaf = pSeg->pgnoLast;
177727      /* TODO: Check there is no doclist index */
177728    }
177729
177730    iIdxPrevLeaf = iIdxLeaf;
177731  }
177732
177733  rc2 = sqlite3_finalize(pStmt);
177734  if( p->rc==SQLITE_OK ) p->rc = rc2;
177735
177736  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
177737#if 0
177738  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
177739    p->rc = FTS5_CORRUPT;
177740  }
177741#endif
177742}
177743
177744
177745/*
177746** Run internal checks to ensure that the FTS index (a) is internally
177747** consistent and (b) contains entries for which the XOR of the checksums
177748** as calculated by fts5IndexEntryCksum() is cksum.
177749**
177750** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
177751** checksum does not match. Return SQLITE_OK if all checks pass without
177752** error, or some other SQLite error code if another error (e.g. OOM)
177753** occurs.
177754*/
177755static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
177756  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
177757  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
177758  Fts5IndexIter *pIter;           /* Used to iterate through entire index */
177759  Fts5Structure *pStruct;         /* Index structure */
177760
177761  /* Used by extra internal tests only run if NDEBUG is not defined */
177762  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
177763  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
177764
177765  /* Load the FTS index structure */
177766  pStruct = fts5StructureRead(p);
177767
177768  /* Check that the internal nodes of each segment match the leaves */
177769  if( pStruct ){
177770    int iLvl, iSeg;
177771    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
177772      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
177773        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
177774        fts5IndexIntegrityCheckSegment(p, pSeg);
177775      }
177776    }
177777  }
177778
177779  /* The cksum argument passed to this function is a checksum calculated
177780  ** based on all expected entries in the FTS index (including prefix index
177781  ** entries). This block checks that a checksum calculated based on the
177782  ** actual contents of FTS index is identical.
177783  **
177784  ** Two versions of the same checksum are calculated. The first (stack
177785  ** variable cksum2) based on entries extracted from the full-text index
177786  ** while doing a linear scan of each individual index in turn.
177787  **
177788  ** As each term visited by the linear scans, a separate query for the
177789  ** same term is performed. cksum3 is calculated based on the entries
177790  ** extracted by these queries.
177791  */
177792  for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, -1, 0, &pIter);
177793      fts5MultiIterEof(p, pIter)==0;
177794      fts5MultiIterNext(p, pIter, 0, 0)
177795  ){
177796    int n;                      /* Size of term in bytes */
177797    i64 iPos = 0;               /* Position read from poslist */
177798    int iOff = 0;               /* Offset within poslist */
177799    i64 iRowid = fts5MultiIterRowid(pIter);
177800    char *z = (char*)fts5MultiIterTerm(pIter, &n);
177801
177802    /* If this is a new term, query for it. Update cksum3 with the results. */
177803    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
177804
177805    poslist.n = 0;
177806    fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst] , 0, &poslist);
177807    while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
177808      int iCol = FTS5_POS2COLUMN(iPos);
177809      int iTokOff = FTS5_POS2OFFSET(iPos);
177810      cksum2 ^= fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
177811    }
177812  }
177813  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
177814
177815  fts5MultiIterFree(p, pIter);
177816  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
177817
177818  fts5StructureRelease(pStruct);
177819  fts5BufferFree(&term);
177820  fts5BufferFree(&poslist);
177821  return fts5IndexReturn(p);
177822}
177823
177824
177825/*
177826** Calculate and return a checksum that is the XOR of the index entry
177827** checksum of all entries that would be generated by the token specified
177828** by the final 5 arguments.
177829*/
177830static u64 sqlite3Fts5IndexCksum(
177831  Fts5Config *pConfig,            /* Configuration object */
177832  i64 iRowid,                     /* Document term appears in */
177833  int iCol,                       /* Column term appears in */
177834  int iPos,                       /* Position term appears in */
177835  const char *pTerm, int nTerm    /* Term at iPos */
177836){
177837  u64 ret = 0;                    /* Return value */
177838  int iIdx;                       /* For iterating through indexes */
177839
177840  ret = fts5IndexEntryCksum(iRowid, iCol, iPos, 0, pTerm, nTerm);
177841
177842  for(iIdx=0; iIdx<pConfig->nPrefix; iIdx++){
177843    int nByte = fts5IndexCharlenToBytelen(pTerm, nTerm, pConfig->aPrefix[iIdx]);
177844    if( nByte ){
177845      ret ^= fts5IndexEntryCksum(iRowid, iCol, iPos, iIdx+1, pTerm, nByte);
177846    }
177847  }
177848
177849  return ret;
177850}
177851
177852/*************************************************************************
177853**************************************************************************
177854** Below this point is the implementation of the fts5_decode() scalar
177855** function only.
177856*/
177857
177858/*
177859** Decode a segment-data rowid from the %_data table. This function is
177860** the opposite of macro FTS5_SEGMENT_ROWID().
177861*/
177862static void fts5DecodeRowid(
177863  i64 iRowid,                     /* Rowid from %_data table */
177864  int *piSegid,                   /* OUT: Segment id */
177865  int *pbDlidx,                   /* OUT: Dlidx flag */
177866  int *piHeight,                  /* OUT: Height */
177867  int *piPgno                     /* OUT: Page number */
177868){
177869  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
177870  iRowid >>= FTS5_DATA_PAGE_B;
177871
177872  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
177873  iRowid >>= FTS5_DATA_HEIGHT_B;
177874
177875  *pbDlidx = (int)(iRowid & 0x0001);
177876  iRowid >>= FTS5_DATA_DLI_B;
177877
177878  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
177879}
177880
177881static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
177882  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
177883  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
177884
177885  if( iSegid==0 ){
177886    if( iKey==FTS5_AVERAGES_ROWID ){
177887      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
177888    }else{
177889      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
177890    }
177891  }
177892  else{
177893    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
177894        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
177895    );
177896  }
177897}
177898
177899static void fts5DebugStructure(
177900  int *pRc,                       /* IN/OUT: error code */
177901  Fts5Buffer *pBuf,
177902  Fts5Structure *p
177903){
177904  int iLvl, iSeg;                 /* Iterate through levels, segments */
177905
177906  for(iLvl=0; iLvl<p->nLevel; iLvl++){
177907    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
177908    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
177909        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
177910    );
177911    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
177912      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
177913      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
177914          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
177915      );
177916    }
177917    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
177918  }
177919}
177920
177921/*
177922** This is part of the fts5_decode() debugging aid.
177923**
177924** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
177925** function appends a human-readable representation of the same object
177926** to the buffer passed as the second argument.
177927*/
177928static void fts5DecodeStructure(
177929  int *pRc,                       /* IN/OUT: error code */
177930  Fts5Buffer *pBuf,
177931  const u8 *pBlob, int nBlob
177932){
177933  int rc;                         /* Return code */
177934  Fts5Structure *p = 0;           /* Decoded structure object */
177935
177936  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
177937  if( rc!=SQLITE_OK ){
177938    *pRc = rc;
177939    return;
177940  }
177941
177942  fts5DebugStructure(pRc, pBuf, p);
177943  fts5StructureRelease(p);
177944}
177945
177946/*
177947** This is part of the fts5_decode() debugging aid.
177948**
177949** Arguments pBlob/nBlob contain an "averages" record. This function
177950** appends a human-readable representation of record to the buffer passed
177951** as the second argument.
177952*/
177953static void fts5DecodeAverages(
177954  int *pRc,                       /* IN/OUT: error code */
177955  Fts5Buffer *pBuf,
177956  const u8 *pBlob, int nBlob
177957){
177958  int i = 0;
177959  const char *zSpace = "";
177960
177961  while( i<nBlob ){
177962    u64 iVal;
177963    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
177964    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
177965    zSpace = " ";
177966  }
177967}
177968
177969/*
177970** Buffer (a/n) is assumed to contain a list of serialized varints. Read
177971** each varint and append its string representation to buffer pBuf. Return
177972** after either the input buffer is exhausted or a 0 value is read.
177973**
177974** The return value is the number of bytes read from the input buffer.
177975*/
177976static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
177977  int iOff = 0;
177978  while( iOff<n ){
177979    int iVal;
177980    iOff += fts5GetVarint32(&a[iOff], iVal);
177981    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
177982  }
177983  return iOff;
177984}
177985
177986/*
177987** The start of buffer (a/n) contains the start of a doclist. The doclist
177988** may or may not finish within the buffer. This function appends a text
177989** representation of the part of the doclist that is present to buffer
177990** pBuf.
177991**
177992** The return value is the number of bytes read from the input buffer.
177993*/
177994static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
177995  i64 iDocid = 0;
177996  int iOff = 0;
177997
177998  if( n>0 ){
177999    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
178000    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
178001  }
178002  while( iOff<n ){
178003    int nPos;
178004    int bDummy;
178005    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
178006    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
178007    if( iOff<n ){
178008      i64 iDelta;
178009      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
178010      iDocid += iDelta;
178011      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
178012    }
178013  }
178014
178015  return iOff;
178016}
178017
178018/*
178019** The implementation of user-defined scalar function fts5_decode().
178020*/
178021static void fts5DecodeFunction(
178022  sqlite3_context *pCtx,          /* Function call context */
178023  int nArg,                       /* Number of args (always 2) */
178024  sqlite3_value **apVal           /* Function arguments */
178025){
178026  i64 iRowid;                     /* Rowid for record being decoded */
178027  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
178028  const u8 *aBlob; int n;         /* Record to decode */
178029  u8 *a = 0;
178030  Fts5Buffer s;                   /* Build up text to return here */
178031  int rc = SQLITE_OK;             /* Return code */
178032  int nSpace = 0;
178033
178034  assert( nArg==2 );
178035  memset(&s, 0, sizeof(Fts5Buffer));
178036  iRowid = sqlite3_value_int64(apVal[0]);
178037
178038  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
178039  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
178040  ** buffer overreads even if the record is corrupt.  */
178041  n = sqlite3_value_bytes(apVal[1]);
178042  aBlob = sqlite3_value_blob(apVal[1]);
178043  nSpace = n + FTS5_DATA_ZERO_PADDING;
178044  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
178045  if( a==0 ) goto decode_out;
178046  memcpy(a, aBlob, n);
178047
178048
178049  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
178050
178051  fts5DebugRowid(&rc, &s, iRowid);
178052  if( bDlidx ){
178053    Fts5Data dlidx;
178054    Fts5DlidxLvl lvl;
178055
178056    dlidx.p = a;
178057    dlidx.nn = n;
178058
178059    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
178060    lvl.pData = &dlidx;
178061    lvl.iLeafPgno = iPgno;
178062
178063    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
178064      sqlite3Fts5BufferAppendPrintf(&rc, &s,
178065          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
178066      );
178067    }
178068  }else if( iSegid==0 ){
178069    if( iRowid==FTS5_AVERAGES_ROWID ){
178070      fts5DecodeAverages(&rc, &s, a, n);
178071    }else{
178072      fts5DecodeStructure(&rc, &s, a, n);
178073    }
178074  }else{
178075    Fts5Buffer term;              /* Current term read from page */
178076    int szLeaf;                   /* Offset of pgidx in a[] */
178077    int iPgidxOff;
178078    int iPgidxPrev = 0;           /* Previous value read from pgidx */
178079    int iTermOff = 0;
178080    int iRowidOff = 0;
178081    int iOff;
178082    int nDoclist;
178083
178084    memset(&term, 0, sizeof(Fts5Buffer));
178085
178086    if( n<4 ){
178087      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
178088      goto decode_out;
178089    }else{
178090      iRowidOff = fts5GetU16(&a[0]);
178091      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
178092      if( iPgidxOff<n ){
178093        fts5GetVarint32(&a[iPgidxOff], iTermOff);
178094      }
178095    }
178096
178097    /* Decode the position list tail at the start of the page */
178098    if( iRowidOff!=0 ){
178099      iOff = iRowidOff;
178100    }else if( iTermOff!=0 ){
178101      iOff = iTermOff;
178102    }else{
178103      iOff = szLeaf;
178104    }
178105    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
178106
178107    /* Decode any more doclist data that appears on the page before the
178108    ** first term. */
178109    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
178110    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
178111
178112    while( iPgidxOff<n ){
178113      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
178114      int nByte;                            /* Bytes of data */
178115      int iEnd;
178116
178117      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
178118      iPgidxPrev += nByte;
178119      iOff = iPgidxPrev;
178120
178121      if( iPgidxOff<n ){
178122        fts5GetVarint32(&a[iPgidxOff], nByte);
178123        iEnd = iPgidxPrev + nByte;
178124      }else{
178125        iEnd = szLeaf;
178126      }
178127
178128      if( bFirst==0 ){
178129        iOff += fts5GetVarint32(&a[iOff], nByte);
178130        term.n = nByte;
178131      }
178132      iOff += fts5GetVarint32(&a[iOff], nByte);
178133      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
178134      iOff += nByte;
178135
178136      sqlite3Fts5BufferAppendPrintf(
178137          &rc, &s, " term=%.*s", term.n, (const char*)term.p
178138      );
178139      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
178140    }
178141
178142    fts5BufferFree(&term);
178143  }
178144
178145 decode_out:
178146  sqlite3_free(a);
178147  if( rc==SQLITE_OK ){
178148    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
178149  }else{
178150    sqlite3_result_error_code(pCtx, rc);
178151  }
178152  fts5BufferFree(&s);
178153}
178154
178155/*
178156** The implementation of user-defined scalar function fts5_rowid().
178157*/
178158static void fts5RowidFunction(
178159  sqlite3_context *pCtx,          /* Function call context */
178160  int nArg,                       /* Number of args (always 2) */
178161  sqlite3_value **apVal           /* Function arguments */
178162){
178163  const char *zArg;
178164  if( nArg==0 ){
178165    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
178166  }else{
178167    zArg = (const char*)sqlite3_value_text(apVal[0]);
178168    if( 0==sqlite3_stricmp(zArg, "segment") ){
178169      i64 iRowid;
178170      int segid, pgno;
178171      if( nArg!=3 ){
178172        sqlite3_result_error(pCtx,
178173            "should be: fts5_rowid('segment', segid, pgno))", -1
178174        );
178175      }else{
178176        segid = sqlite3_value_int(apVal[1]);
178177        pgno = sqlite3_value_int(apVal[2]);
178178        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
178179        sqlite3_result_int64(pCtx, iRowid);
178180      }
178181    }else{
178182      sqlite3_result_error(pCtx,
178183        "first arg to fts5_rowid() must be 'segment'" , -1
178184      );
178185    }
178186  }
178187}
178188
178189/*
178190** This is called as part of registering the FTS5 module with database
178191** connection db. It registers several user-defined scalar functions useful
178192** with FTS5.
178193**
178194** If successful, SQLITE_OK is returned. If an error occurs, some other
178195** SQLite error code is returned instead.
178196*/
178197static int sqlite3Fts5IndexInit(sqlite3 *db){
178198  int rc = sqlite3_create_function(
178199      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
178200  );
178201  if( rc==SQLITE_OK ){
178202    rc = sqlite3_create_function(
178203        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
178204    );
178205  }
178206  return rc;
178207}
178208
178209
178210/*
178211** 2014 Jun 09
178212**
178213** The author disclaims copyright to this source code.  In place of
178214** a legal notice, here is a blessing:
178215**
178216**    May you do good and not evil.
178217**    May you find forgiveness for yourself and forgive others.
178218**    May you share freely, never taking more than you give.
178219**
178220******************************************************************************
178221**
178222** This is an SQLite module implementing full-text search.
178223*/
178224
178225
178226
178227/*
178228** This variable is set to false when running tests for which the on disk
178229** structures should not be corrupt. Otherwise, true. If it is false, extra
178230** assert() conditions in the fts5 code are activated - conditions that are
178231** only true if it is guaranteed that the fts5 database is not corrupt.
178232*/
178233SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
178234
178235
178236typedef struct Fts5Auxdata Fts5Auxdata;
178237typedef struct Fts5Auxiliary Fts5Auxiliary;
178238typedef struct Fts5Cursor Fts5Cursor;
178239typedef struct Fts5Sorter Fts5Sorter;
178240typedef struct Fts5Table Fts5Table;
178241typedef struct Fts5TokenizerModule Fts5TokenizerModule;
178242
178243/*
178244** NOTES ON TRANSACTIONS:
178245**
178246** SQLite invokes the following virtual table methods as transactions are
178247** opened and closed by the user:
178248**
178249**     xBegin():    Start of a new transaction.
178250**     xSync():     Initial part of two-phase commit.
178251**     xCommit():   Final part of two-phase commit.
178252**     xRollback(): Rollback the transaction.
178253**
178254** Anything that is required as part of a commit that may fail is performed
178255** in the xSync() callback. Current versions of SQLite ignore any errors
178256** returned by xCommit().
178257**
178258** And as sub-transactions are opened/closed:
178259**
178260**     xSavepoint(int S):  Open savepoint S.
178261**     xRelease(int S):    Commit and close savepoint S.
178262**     xRollbackTo(int S): Rollback to start of savepoint S.
178263**
178264** During a write-transaction the fts5_index.c module may cache some data
178265** in-memory. It is flushed to disk whenever xSync(), xRelease() or
178266** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
178267** is called.
178268**
178269** Additionally, if SQLITE_DEBUG is defined, an instance of the following
178270** structure is used to record the current transaction state. This information
178271** is not required, but it is used in the assert() statements executed by
178272** function fts5CheckTransactionState() (see below).
178273*/
178274struct Fts5TransactionState {
178275  int eState;                     /* 0==closed, 1==open, 2==synced */
178276  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
178277};
178278
178279/*
178280** A single object of this type is allocated when the FTS5 module is
178281** registered with a database handle. It is used to store pointers to
178282** all registered FTS5 extensions - tokenizers and auxiliary functions.
178283*/
178284struct Fts5Global {
178285  fts5_api api;                   /* User visible part of object (see fts5.h) */
178286  sqlite3 *db;                    /* Associated database connection */
178287  i64 iNextId;                    /* Used to allocate unique cursor ids */
178288  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
178289  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
178290  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
178291  Fts5Cursor *pCsr;               /* First in list of all open cursors */
178292};
178293
178294/*
178295** Each auxiliary function registered with the FTS5 module is represented
178296** by an object of the following type. All such objects are stored as part
178297** of the Fts5Global.pAux list.
178298*/
178299struct Fts5Auxiliary {
178300  Fts5Global *pGlobal;            /* Global context for this function */
178301  char *zFunc;                    /* Function name (nul-terminated) */
178302  void *pUserData;                /* User-data pointer */
178303  fts5_extension_function xFunc;  /* Callback function */
178304  void (*xDestroy)(void*);        /* Destructor function */
178305  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
178306};
178307
178308/*
178309** Each tokenizer module registered with the FTS5 module is represented
178310** by an object of the following type. All such objects are stored as part
178311** of the Fts5Global.pTok list.
178312*/
178313struct Fts5TokenizerModule {
178314  char *zName;                    /* Name of tokenizer */
178315  void *pUserData;                /* User pointer passed to xCreate() */
178316  fts5_tokenizer x;               /* Tokenizer functions */
178317  void (*xDestroy)(void*);        /* Destructor function */
178318  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
178319};
178320
178321/*
178322** Virtual-table object.
178323*/
178324struct Fts5Table {
178325  sqlite3_vtab base;              /* Base class used by SQLite core */
178326  Fts5Config *pConfig;            /* Virtual table configuration */
178327  Fts5Index *pIndex;              /* Full-text index */
178328  Fts5Storage *pStorage;          /* Document store */
178329  Fts5Global *pGlobal;            /* Global (connection wide) data */
178330  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
178331#ifdef SQLITE_DEBUG
178332  struct Fts5TransactionState ts;
178333#endif
178334};
178335
178336struct Fts5MatchPhrase {
178337  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
178338  int nTerm;                      /* Size of phrase in terms */
178339};
178340
178341/*
178342** pStmt:
178343**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
178344**
178345** aIdx[]:
178346**   There is one entry in the aIdx[] array for each phrase in the query,
178347**   the value of which is the offset within aPoslist[] following the last
178348**   byte of the position list for the corresponding phrase.
178349*/
178350struct Fts5Sorter {
178351  sqlite3_stmt *pStmt;
178352  i64 iRowid;                     /* Current rowid */
178353  const u8 *aPoslist;             /* Position lists for current row */
178354  int nIdx;                       /* Number of entries in aIdx[] */
178355  int aIdx[1];                    /* Offsets into aPoslist for current row */
178356};
178357
178358
178359/*
178360** Virtual-table cursor object.
178361**
178362** iSpecial:
178363**   If this is a 'special' query (refer to function fts5SpecialMatch()),
178364**   then this variable contains the result of the query.
178365**
178366** iFirstRowid, iLastRowid:
178367**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
178368**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
178369**   limit of rowids to return, and iLastRowid the upper. In other words, the
178370**   WHERE clause in the user's query might have been:
178371**
178372**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
178373**
178374**   If the cursor iterates in descending order of rowid, iFirstRowid
178375**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
178376**   the lower.
178377*/
178378struct Fts5Cursor {
178379  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
178380  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
178381  int *aColumnSize;               /* Values for xColumnSize() */
178382  i64 iCsrId;                     /* Cursor id */
178383
178384  /* Zero from this point onwards on cursor reset */
178385  int ePlan;                      /* FTS5_PLAN_XXX value */
178386  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
178387  i64 iFirstRowid;                /* Return no rowids earlier than this */
178388  i64 iLastRowid;                 /* Return no rowids later than this */
178389  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
178390  Fts5Expr *pExpr;                /* Expression for MATCH queries */
178391  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
178392  int csrflags;                   /* Mask of cursor flags (see below) */
178393  i64 iSpecial;                   /* Result of special query */
178394
178395  /* "rank" function. Populated on demand from vtab.xColumn(). */
178396  char *zRank;                    /* Custom rank function */
178397  char *zRankArgs;                /* Custom rank function args */
178398  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
178399  int nRankArg;                   /* Number of trailing arguments for rank() */
178400  sqlite3_value **apRankArg;      /* Array of trailing arguments */
178401  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
178402
178403  /* Auxiliary data storage */
178404  Fts5Auxiliary *pAux;            /* Currently executing extension function */
178405  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
178406
178407  /* Cache used by auxiliary functions xInst() and xInstCount() */
178408  Fts5PoslistReader *aInstIter;   /* One for each phrase */
178409  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
178410  int nInstCount;                 /* Number of phrase instances */
178411  int *aInst;                     /* 3 integers per phrase instance */
178412};
178413
178414/*
178415** Bits that make up the "idxNum" parameter passed indirectly by
178416** xBestIndex() to xFilter().
178417*/
178418#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
178419#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
178420#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
178421#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
178422#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
178423
178424#define FTS5_BI_ORDER_RANK   0x0020
178425#define FTS5_BI_ORDER_ROWID  0x0040
178426#define FTS5_BI_ORDER_DESC   0x0080
178427
178428/*
178429** Values for Fts5Cursor.csrflags
178430*/
178431#define FTS5CSR_REQUIRE_CONTENT   0x01
178432#define FTS5CSR_REQUIRE_DOCSIZE   0x02
178433#define FTS5CSR_REQUIRE_INST      0x04
178434#define FTS5CSR_EOF               0x08
178435#define FTS5CSR_FREE_ZRANK        0x10
178436#define FTS5CSR_REQUIRE_RESEEK    0x20
178437
178438#define BitFlagAllTest(x,y) (((x) & (y))==(y))
178439#define BitFlagTest(x,y)    (((x) & (y))!=0)
178440
178441
178442/*
178443** Macros to Set(), Clear() and Test() cursor flags.
178444*/
178445#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
178446#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
178447#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
178448
178449struct Fts5Auxdata {
178450  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
178451  void *pPtr;                     /* Pointer value */
178452  void(*xDelete)(void*);          /* Destructor */
178453  Fts5Auxdata *pNext;             /* Next object in linked list */
178454};
178455
178456#ifdef SQLITE_DEBUG
178457#define FTS5_BEGIN      1
178458#define FTS5_SYNC       2
178459#define FTS5_COMMIT     3
178460#define FTS5_ROLLBACK   4
178461#define FTS5_SAVEPOINT  5
178462#define FTS5_RELEASE    6
178463#define FTS5_ROLLBACKTO 7
178464static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
178465  switch( op ){
178466    case FTS5_BEGIN:
178467      assert( p->ts.eState==0 );
178468      p->ts.eState = 1;
178469      p->ts.iSavepoint = -1;
178470      break;
178471
178472    case FTS5_SYNC:
178473      assert( p->ts.eState==1 );
178474      p->ts.eState = 2;
178475      break;
178476
178477    case FTS5_COMMIT:
178478      assert( p->ts.eState==2 );
178479      p->ts.eState = 0;
178480      break;
178481
178482    case FTS5_ROLLBACK:
178483      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
178484      p->ts.eState = 0;
178485      break;
178486
178487    case FTS5_SAVEPOINT:
178488      assert( p->ts.eState==1 );
178489      assert( iSavepoint>=0 );
178490      assert( iSavepoint>p->ts.iSavepoint );
178491      p->ts.iSavepoint = iSavepoint;
178492      break;
178493
178494    case FTS5_RELEASE:
178495      assert( p->ts.eState==1 );
178496      assert( iSavepoint>=0 );
178497      assert( iSavepoint<=p->ts.iSavepoint );
178498      p->ts.iSavepoint = iSavepoint-1;
178499      break;
178500
178501    case FTS5_ROLLBACKTO:
178502      assert( p->ts.eState==1 );
178503      assert( iSavepoint>=0 );
178504      assert( iSavepoint<=p->ts.iSavepoint );
178505      p->ts.iSavepoint = iSavepoint;
178506      break;
178507  }
178508}
178509#else
178510# define fts5CheckTransactionState(x,y,z)
178511#endif
178512
178513/*
178514** Return true if pTab is a contentless table.
178515*/
178516static int fts5IsContentless(Fts5Table *pTab){
178517  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
178518}
178519
178520/*
178521** Delete a virtual table handle allocated by fts5InitVtab().
178522*/
178523static void fts5FreeVtab(Fts5Table *pTab){
178524  if( pTab ){
178525    sqlite3Fts5IndexClose(pTab->pIndex);
178526    sqlite3Fts5StorageClose(pTab->pStorage);
178527    sqlite3Fts5ConfigFree(pTab->pConfig);
178528    sqlite3_free(pTab);
178529  }
178530}
178531
178532/*
178533** The xDisconnect() virtual table method.
178534*/
178535static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
178536  fts5FreeVtab((Fts5Table*)pVtab);
178537  return SQLITE_OK;
178538}
178539
178540/*
178541** The xDestroy() virtual table method.
178542*/
178543static int fts5DestroyMethod(sqlite3_vtab *pVtab){
178544  Fts5Table *pTab = (Fts5Table*)pVtab;
178545  int rc = sqlite3Fts5DropAll(pTab->pConfig);
178546  if( rc==SQLITE_OK ){
178547    fts5FreeVtab((Fts5Table*)pVtab);
178548  }
178549  return rc;
178550}
178551
178552/*
178553** This function is the implementation of both the xConnect and xCreate
178554** methods of the FTS3 virtual table.
178555**
178556** The argv[] array contains the following:
178557**
178558**   argv[0]   -> module name  ("fts5")
178559**   argv[1]   -> database name
178560**   argv[2]   -> table name
178561**   argv[...] -> "column name" and other module argument fields.
178562*/
178563static int fts5InitVtab(
178564  int bCreate,                    /* True for xCreate, false for xConnect */
178565  sqlite3 *db,                    /* The SQLite database connection */
178566  void *pAux,                     /* Hash table containing tokenizers */
178567  int argc,                       /* Number of elements in argv array */
178568  const char * const *argv,       /* xCreate/xConnect argument array */
178569  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
178570  char **pzErr                    /* Write any error message here */
178571){
178572  Fts5Global *pGlobal = (Fts5Global*)pAux;
178573  const char **azConfig = (const char**)argv;
178574  int rc = SQLITE_OK;             /* Return code */
178575  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
178576  Fts5Table *pTab = 0;            /* New virtual table object */
178577
178578  /* Allocate the new vtab object and parse the configuration */
178579  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
178580  if( rc==SQLITE_OK ){
178581    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
178582    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
178583  }
178584  if( rc==SQLITE_OK ){
178585    pTab->pConfig = pConfig;
178586    pTab->pGlobal = pGlobal;
178587  }
178588
178589  /* Open the index sub-system */
178590  if( rc==SQLITE_OK ){
178591    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
178592  }
178593
178594  /* Open the storage sub-system */
178595  if( rc==SQLITE_OK ){
178596    rc = sqlite3Fts5StorageOpen(
178597        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
178598    );
178599  }
178600
178601  /* Call sqlite3_declare_vtab() */
178602  if( rc==SQLITE_OK ){
178603    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
178604  }
178605
178606  if( rc!=SQLITE_OK ){
178607    fts5FreeVtab(pTab);
178608    pTab = 0;
178609  }else if( bCreate ){
178610    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
178611  }
178612  *ppVTab = (sqlite3_vtab*)pTab;
178613  return rc;
178614}
178615
178616/*
178617** The xConnect() and xCreate() methods for the virtual table. All the
178618** work is done in function fts5InitVtab().
178619*/
178620static int fts5ConnectMethod(
178621  sqlite3 *db,                    /* Database connection */
178622  void *pAux,                     /* Pointer to tokenizer hash table */
178623  int argc,                       /* Number of elements in argv array */
178624  const char * const *argv,       /* xCreate/xConnect argument array */
178625  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
178626  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
178627){
178628  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
178629}
178630static int fts5CreateMethod(
178631  sqlite3 *db,                    /* Database connection */
178632  void *pAux,                     /* Pointer to tokenizer hash table */
178633  int argc,                       /* Number of elements in argv array */
178634  const char * const *argv,       /* xCreate/xConnect argument array */
178635  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
178636  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
178637){
178638  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
178639}
178640
178641/*
178642** The different query plans.
178643*/
178644#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
178645#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
178646#define FTS5_PLAN_SPECIAL        3       /* An internal query */
178647#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
178648#define FTS5_PLAN_SCAN           5       /* No usable constraint */
178649#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
178650
178651/*
178652** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
178653** extension is currently being used by a version of SQLite too old to
178654** support index-info flags. In that case this function is a no-op.
178655*/
178656static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
178657#if SQLITE_VERSION_NUMBER>=3008012
178658  if( sqlite3_libversion_number()>=3008012 ){
178659    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
178660  }
178661#endif
178662}
178663
178664/*
178665** Implementation of the xBestIndex method for FTS5 tables. Within the
178666** WHERE constraint, it searches for the following:
178667**
178668**   1. A MATCH constraint against the special column.
178669**   2. A MATCH constraint against the "rank" column.
178670**   3. An == constraint against the rowid column.
178671**   4. A < or <= constraint against the rowid column.
178672**   5. A > or >= constraint against the rowid column.
178673**
178674** Within the ORDER BY, either:
178675**
178676**   5. ORDER BY rank [ASC|DESC]
178677**   6. ORDER BY rowid [ASC|DESC]
178678**
178679** Costs are assigned as follows:
178680**
178681**  a) If an unusable MATCH operator is present in the WHERE clause, the
178682**     cost is unconditionally set to 1e50 (a really big number).
178683**
178684**  a) If a MATCH operator is present, the cost depends on the other
178685**     constraints also present. As follows:
178686**
178687**       * No other constraints:         cost=1000.0
178688**       * One rowid range constraint:   cost=750.0
178689**       * Both rowid range constraints: cost=500.0
178690**       * An == rowid constraint:       cost=100.0
178691**
178692**  b) Otherwise, if there is no MATCH:
178693**
178694**       * No other constraints:         cost=1000000.0
178695**       * One rowid range constraint:   cost=750000.0
178696**       * Both rowid range constraints: cost=250000.0
178697**       * An == rowid constraint:       cost=10.0
178698**
178699** Costs are not modified by the ORDER BY clause.
178700*/
178701static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
178702  Fts5Table *pTab = (Fts5Table*)pVTab;
178703  Fts5Config *pConfig = pTab->pConfig;
178704  int idxFlags = 0;               /* Parameter passed through to xFilter() */
178705  int bHasMatch;
178706  int iNext;
178707  int i;
178708
178709  struct Constraint {
178710    int op;                       /* Mask against sqlite3_index_constraint.op */
178711    int fts5op;                   /* FTS5 mask for idxFlags */
178712    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
178713    int omit;                     /* True to omit this if found */
178714    int iConsIndex;               /* Index in pInfo->aConstraint[] */
178715  } aConstraint[] = {
178716    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
178717                                    FTS5_BI_MATCH,    1, 1, -1},
178718    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
178719                                    FTS5_BI_RANK,     2, 1, -1},
178720    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
178721    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
178722                                    FTS5_BI_ROWID_LE, 0, 0, -1},
178723    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
178724                                    FTS5_BI_ROWID_GE, 0, 0, -1},
178725  };
178726
178727  int aColMap[3];
178728  aColMap[0] = -1;
178729  aColMap[1] = pConfig->nCol;
178730  aColMap[2] = pConfig->nCol+1;
178731
178732  /* Set idxFlags flags for all WHERE clause terms that will be used. */
178733  for(i=0; i<pInfo->nConstraint; i++){
178734    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
178735    int j;
178736    for(j=0; j<sizeof(aConstraint)/sizeof(aConstraint[0]); j++){
178737      struct Constraint *pC = &aConstraint[j];
178738      if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
178739        if( p->usable ){
178740          pC->iConsIndex = i;
178741          idxFlags |= pC->fts5op;
178742        }else if( j==0 ){
178743          /* As there exists an unusable MATCH constraint this is an
178744          ** unusable plan. Set a prohibitively high cost. */
178745          pInfo->estimatedCost = 1e50;
178746          return SQLITE_OK;
178747        }
178748      }
178749    }
178750  }
178751
178752  /* Set idxFlags flags for the ORDER BY clause */
178753  if( pInfo->nOrderBy==1 ){
178754    int iSort = pInfo->aOrderBy[0].iColumn;
178755    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
178756      idxFlags |= FTS5_BI_ORDER_RANK;
178757    }else if( iSort==-1 ){
178758      idxFlags |= FTS5_BI_ORDER_ROWID;
178759    }
178760    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
178761      pInfo->orderByConsumed = 1;
178762      if( pInfo->aOrderBy[0].desc ){
178763        idxFlags |= FTS5_BI_ORDER_DESC;
178764      }
178765    }
178766  }
178767
178768  /* Calculate the estimated cost based on the flags set in idxFlags. */
178769  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
178770  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
178771    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
178772    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
178773  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
178774    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
178775  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
178776    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
178777  }else{
178778    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
178779  }
178780
178781  /* Assign argvIndex values to each constraint in use. */
178782  iNext = 1;
178783  for(i=0; i<sizeof(aConstraint)/sizeof(aConstraint[0]); i++){
178784    struct Constraint *pC = &aConstraint[i];
178785    if( pC->iConsIndex>=0 ){
178786      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
178787      pInfo->aConstraintUsage[pC->iConsIndex].omit = pC->omit;
178788    }
178789  }
178790
178791  pInfo->idxNum = idxFlags;
178792  return SQLITE_OK;
178793}
178794
178795/*
178796** Implementation of xOpen method.
178797*/
178798static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
178799  Fts5Table *pTab = (Fts5Table*)pVTab;
178800  Fts5Config *pConfig = pTab->pConfig;
178801  Fts5Cursor *pCsr;               /* New cursor object */
178802  int nByte;                      /* Bytes of space to allocate */
178803  int rc = SQLITE_OK;             /* Return code */
178804
178805  nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
178806  pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
178807  if( pCsr ){
178808    Fts5Global *pGlobal = pTab->pGlobal;
178809    memset(pCsr, 0, nByte);
178810    pCsr->aColumnSize = (int*)&pCsr[1];
178811    pCsr->pNext = pGlobal->pCsr;
178812    pGlobal->pCsr = pCsr;
178813    pCsr->iCsrId = ++pGlobal->iNextId;
178814  }else{
178815    rc = SQLITE_NOMEM;
178816  }
178817  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
178818  return rc;
178819}
178820
178821static int fts5StmtType(Fts5Cursor *pCsr){
178822  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
178823    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
178824  }
178825  return FTS5_STMT_LOOKUP;
178826}
178827
178828/*
178829** This function is called after the cursor passed as the only argument
178830** is moved to point at a different row. It clears all cached data
178831** specific to the previous row stored by the cursor object.
178832*/
178833static void fts5CsrNewrow(Fts5Cursor *pCsr){
178834  CsrFlagSet(pCsr,
178835      FTS5CSR_REQUIRE_CONTENT
178836    | FTS5CSR_REQUIRE_DOCSIZE
178837    | FTS5CSR_REQUIRE_INST
178838  );
178839}
178840
178841static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
178842  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
178843  Fts5Auxdata *pData;
178844  Fts5Auxdata *pNext;
178845
178846  sqlite3_free(pCsr->aInstIter);
178847  sqlite3_free(pCsr->aInst);
178848  if( pCsr->pStmt ){
178849    int eStmt = fts5StmtType(pCsr);
178850    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
178851  }
178852  if( pCsr->pSorter ){
178853    Fts5Sorter *pSorter = pCsr->pSorter;
178854    sqlite3_finalize(pSorter->pStmt);
178855    sqlite3_free(pSorter);
178856  }
178857
178858  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
178859    sqlite3Fts5ExprFree(pCsr->pExpr);
178860  }
178861
178862  for(pData=pCsr->pAuxdata; pData; pData=pNext){
178863    pNext = pData->pNext;
178864    if( pData->xDelete ) pData->xDelete(pData->pPtr);
178865    sqlite3_free(pData);
178866  }
178867
178868  sqlite3_finalize(pCsr->pRankArgStmt);
178869  sqlite3_free(pCsr->apRankArg);
178870
178871  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
178872    sqlite3_free(pCsr->zRank);
178873    sqlite3_free(pCsr->zRankArgs);
178874  }
178875
178876  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
178877}
178878
178879
178880/*
178881** Close the cursor.  For additional information see the documentation
178882** on the xClose method of the virtual table interface.
178883*/
178884static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
178885  if( pCursor ){
178886    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
178887    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
178888    Fts5Cursor **pp;
178889
178890    fts5FreeCursorComponents(pCsr);
178891    /* Remove the cursor from the Fts5Global.pCsr list */
178892    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
178893    *pp = pCsr->pNext;
178894
178895    sqlite3_free(pCsr);
178896  }
178897  return SQLITE_OK;
178898}
178899
178900static int fts5SorterNext(Fts5Cursor *pCsr){
178901  Fts5Sorter *pSorter = pCsr->pSorter;
178902  int rc;
178903
178904  rc = sqlite3_step(pSorter->pStmt);
178905  if( rc==SQLITE_DONE ){
178906    rc = SQLITE_OK;
178907    CsrFlagSet(pCsr, FTS5CSR_EOF);
178908  }else if( rc==SQLITE_ROW ){
178909    const u8 *a;
178910    const u8 *aBlob;
178911    int nBlob;
178912    int i;
178913    int iOff = 0;
178914    rc = SQLITE_OK;
178915
178916    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
178917    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
178918    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
178919
178920    for(i=0; i<(pSorter->nIdx-1); i++){
178921      int iVal;
178922      a += fts5GetVarint32(a, iVal);
178923      iOff += iVal;
178924      pSorter->aIdx[i] = iOff;
178925    }
178926    pSorter->aIdx[i] = &aBlob[nBlob] - a;
178927
178928    pSorter->aPoslist = a;
178929    fts5CsrNewrow(pCsr);
178930  }
178931
178932  return rc;
178933}
178934
178935
178936/*
178937** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
178938** open on table pTab.
178939*/
178940static void fts5TripCursors(Fts5Table *pTab){
178941  Fts5Cursor *pCsr;
178942  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
178943    if( pCsr->ePlan==FTS5_PLAN_MATCH
178944     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
178945    ){
178946      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
178947    }
178948  }
178949}
178950
178951/*
178952** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
178953** argument, close and reopen all Fts5IndexIter iterators that the cursor
178954** is using. Then attempt to move the cursor to a rowid equal to or laster
178955** (in the cursors sort order - ASC or DESC) than the current rowid.
178956**
178957** If the new rowid is not equal to the old, set output parameter *pbSkip
178958** to 1 before returning. Otherwise, leave it unchanged.
178959**
178960** Return SQLITE_OK if successful or if no reseek was required, or an
178961** error code if an error occurred.
178962*/
178963static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
178964  int rc = SQLITE_OK;
178965  assert( *pbSkip==0 );
178966  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
178967    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
178968    int bDesc = pCsr->bDesc;
178969    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
178970
178971    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
178972    if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
178973      *pbSkip = 1;
178974    }
178975
178976    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
178977    fts5CsrNewrow(pCsr);
178978    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
178979      CsrFlagSet(pCsr, FTS5CSR_EOF);
178980    }
178981  }
178982  return rc;
178983}
178984
178985
178986/*
178987** Advance the cursor to the next row in the table that matches the
178988** search criteria.
178989**
178990** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
178991** even if we reach end-of-file.  The fts5EofMethod() will be called
178992** subsequently to determine whether or not an EOF was hit.
178993*/
178994static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
178995  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
178996  int rc = SQLITE_OK;
178997
178998  assert( (pCsr->ePlan<3)==
178999          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
179000  );
179001
179002  if( pCsr->ePlan<3 ){
179003    int bSkip = 0;
179004    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
179005    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
179006    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
179007      CsrFlagSet(pCsr, FTS5CSR_EOF);
179008    }
179009    fts5CsrNewrow(pCsr);
179010  }else{
179011    switch( pCsr->ePlan ){
179012      case FTS5_PLAN_SPECIAL: {
179013        CsrFlagSet(pCsr, FTS5CSR_EOF);
179014        break;
179015      }
179016
179017      case FTS5_PLAN_SORTED_MATCH: {
179018        rc = fts5SorterNext(pCsr);
179019        break;
179020      }
179021
179022      default:
179023        rc = sqlite3_step(pCsr->pStmt);
179024        if( rc!=SQLITE_ROW ){
179025          CsrFlagSet(pCsr, FTS5CSR_EOF);
179026          rc = sqlite3_reset(pCsr->pStmt);
179027        }else{
179028          rc = SQLITE_OK;
179029        }
179030        break;
179031    }
179032  }
179033
179034  return rc;
179035}
179036
179037static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
179038  Fts5Config *pConfig = pTab->pConfig;
179039  Fts5Sorter *pSorter;
179040  int nPhrase;
179041  int nByte;
179042  int rc = SQLITE_OK;
179043  char *zSql;
179044  const char *zRank = pCsr->zRank;
179045  const char *zRankArgs = pCsr->zRankArgs;
179046
179047  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179048  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
179049  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
179050  if( pSorter==0 ) return SQLITE_NOMEM;
179051  memset(pSorter, 0, nByte);
179052  pSorter->nIdx = nPhrase;
179053
179054  /* TODO: It would be better to have some system for reusing statement
179055  ** handles here, rather than preparing a new one for each query. But that
179056  ** is not possible as SQLite reference counts the virtual table objects.
179057  ** And since the statement required here reads from this very virtual
179058  ** table, saving it creates a circular reference.
179059  **
179060  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
179061  zSql = sqlite3Fts5Mprintf(&rc,
179062      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
179063      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
179064      (zRankArgs ? ", " : ""),
179065      (zRankArgs ? zRankArgs : ""),
179066      bDesc ? "DESC" : "ASC"
179067  );
179068  if( zSql ){
179069    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pSorter->pStmt, 0);
179070    sqlite3_free(zSql);
179071  }
179072
179073  pCsr->pSorter = pSorter;
179074  if( rc==SQLITE_OK ){
179075    assert( pTab->pSortCsr==0 );
179076    pTab->pSortCsr = pCsr;
179077    rc = fts5SorterNext(pCsr);
179078    pTab->pSortCsr = 0;
179079  }
179080
179081  if( rc!=SQLITE_OK ){
179082    sqlite3_finalize(pSorter->pStmt);
179083    sqlite3_free(pSorter);
179084    pCsr->pSorter = 0;
179085  }
179086
179087  return rc;
179088}
179089
179090static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
179091  int rc;
179092  Fts5Expr *pExpr = pCsr->pExpr;
179093  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
179094  if( sqlite3Fts5ExprEof(pExpr) ){
179095    CsrFlagSet(pCsr, FTS5CSR_EOF);
179096  }
179097  fts5CsrNewrow(pCsr);
179098  return rc;
179099}
179100
179101/*
179102** Process a "special" query. A special query is identified as one with a
179103** MATCH expression that begins with a '*' character. The remainder of
179104** the text passed to the MATCH operator are used as  the special query
179105** parameters.
179106*/
179107static int fts5SpecialMatch(
179108  Fts5Table *pTab,
179109  Fts5Cursor *pCsr,
179110  const char *zQuery
179111){
179112  int rc = SQLITE_OK;             /* Return code */
179113  const char *z = zQuery;         /* Special query text */
179114  int n;                          /* Number of bytes in text at z */
179115
179116  while( z[0]==' ' ) z++;
179117  for(n=0; z[n] && z[n]!=' '; n++);
179118
179119  assert( pTab->base.zErrMsg==0 );
179120  pCsr->ePlan = FTS5_PLAN_SPECIAL;
179121
179122  if( 0==sqlite3_strnicmp("reads", z, n) ){
179123    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
179124  }
179125  else if( 0==sqlite3_strnicmp("id", z, n) ){
179126    pCsr->iSpecial = pCsr->iCsrId;
179127  }
179128  else{
179129    /* An unrecognized directive. Return an error message. */
179130    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
179131    rc = SQLITE_ERROR;
179132  }
179133
179134  return rc;
179135}
179136
179137/*
179138** Search for an auxiliary function named zName that can be used with table
179139** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
179140** structure. Otherwise, if no such function exists, return NULL.
179141*/
179142static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
179143  Fts5Auxiliary *pAux;
179144
179145  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
179146    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
179147  }
179148
179149  /* No function of the specified name was found. Return 0. */
179150  return 0;
179151}
179152
179153
179154static int fts5FindRankFunction(Fts5Cursor *pCsr){
179155  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179156  Fts5Config *pConfig = pTab->pConfig;
179157  int rc = SQLITE_OK;
179158  Fts5Auxiliary *pAux = 0;
179159  const char *zRank = pCsr->zRank;
179160  const char *zRankArgs = pCsr->zRankArgs;
179161
179162  if( zRankArgs ){
179163    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
179164    if( zSql ){
179165      sqlite3_stmt *pStmt = 0;
179166      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
179167      sqlite3_free(zSql);
179168      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
179169      if( rc==SQLITE_OK ){
179170        if( SQLITE_ROW==sqlite3_step(pStmt) ){
179171          int nByte;
179172          pCsr->nRankArg = sqlite3_column_count(pStmt);
179173          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
179174          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
179175          if( rc==SQLITE_OK ){
179176            int i;
179177            for(i=0; i<pCsr->nRankArg; i++){
179178              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
179179            }
179180          }
179181          pCsr->pRankArgStmt = pStmt;
179182        }else{
179183          rc = sqlite3_finalize(pStmt);
179184          assert( rc!=SQLITE_OK );
179185        }
179186      }
179187    }
179188  }
179189
179190  if( rc==SQLITE_OK ){
179191    pAux = fts5FindAuxiliary(pTab, zRank);
179192    if( pAux==0 ){
179193      assert( pTab->base.zErrMsg==0 );
179194      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
179195      rc = SQLITE_ERROR;
179196    }
179197  }
179198
179199  pCsr->pRank = pAux;
179200  return rc;
179201}
179202
179203
179204static int fts5CursorParseRank(
179205  Fts5Config *pConfig,
179206  Fts5Cursor *pCsr,
179207  sqlite3_value *pRank
179208){
179209  int rc = SQLITE_OK;
179210  if( pRank ){
179211    const char *z = (const char*)sqlite3_value_text(pRank);
179212    char *zRank = 0;
179213    char *zRankArgs = 0;
179214
179215    if( z==0 ){
179216      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
179217    }else{
179218      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
179219    }
179220    if( rc==SQLITE_OK ){
179221      pCsr->zRank = zRank;
179222      pCsr->zRankArgs = zRankArgs;
179223      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
179224    }else if( rc==SQLITE_ERROR ){
179225      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
179226          "parse error in rank function: %s", z
179227      );
179228    }
179229  }else{
179230    if( pConfig->zRank ){
179231      pCsr->zRank = (char*)pConfig->zRank;
179232      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
179233    }else{
179234      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
179235      pCsr->zRankArgs = 0;
179236    }
179237  }
179238  return rc;
179239}
179240
179241static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
179242  if( pVal ){
179243    int eType = sqlite3_value_numeric_type(pVal);
179244    if( eType==SQLITE_INTEGER ){
179245      return sqlite3_value_int64(pVal);
179246    }
179247  }
179248  return iDefault;
179249}
179250
179251/*
179252** This is the xFilter interface for the virtual table.  See
179253** the virtual table xFilter method documentation for additional
179254** information.
179255**
179256** There are three possible query strategies:
179257**
179258**   1. Full-text search using a MATCH operator.
179259**   2. A by-rowid lookup.
179260**   3. A full-table scan.
179261*/
179262static int fts5FilterMethod(
179263  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
179264  int idxNum,                     /* Strategy index */
179265  const char *idxStr,             /* Unused */
179266  int nVal,                       /* Number of elements in apVal */
179267  sqlite3_value **apVal           /* Arguments for the indexing scheme */
179268){
179269  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
179270  Fts5Config *pConfig = pTab->pConfig;
179271  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179272  int rc = SQLITE_OK;             /* Error code */
179273  int iVal = 0;                   /* Counter for apVal[] */
179274  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
179275  int bOrderByRank;               /* True if ORDER BY rank */
179276  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
179277  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
179278  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
179279  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
179280  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
179281  char **pzErrmsg = pConfig->pzErrmsg;
179282
179283  if( pCsr->ePlan ){
179284    fts5FreeCursorComponents(pCsr);
179285    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
179286  }
179287
179288  assert( pCsr->pStmt==0 );
179289  assert( pCsr->pExpr==0 );
179290  assert( pCsr->csrflags==0 );
179291  assert( pCsr->pRank==0 );
179292  assert( pCsr->zRank==0 );
179293  assert( pCsr->zRankArgs==0 );
179294
179295  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
179296  pConfig->pzErrmsg = &pTab->base.zErrMsg;
179297
179298  /* Decode the arguments passed through to this function.
179299  **
179300  ** Note: The following set of if(...) statements must be in the same
179301  ** order as the corresponding entries in the struct at the top of
179302  ** fts5BestIndexMethod().  */
179303  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
179304  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
179305  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
179306  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
179307  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
179308  assert( iVal==nVal );
179309  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
179310  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
179311
179312  /* Set the cursor upper and lower rowid limits. Only some strategies
179313  ** actually use them. This is ok, as the xBestIndex() method leaves the
179314  ** sqlite3_index_constraint.omit flag clear for range constraints
179315  ** on the rowid field.  */
179316  if( pRowidEq ){
179317    pRowidLe = pRowidGe = pRowidEq;
179318  }
179319  if( bDesc ){
179320    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
179321    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
179322  }else{
179323    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
179324    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
179325  }
179326
179327  if( pTab->pSortCsr ){
179328    /* If pSortCsr is non-NULL, then this call is being made as part of
179329    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
179330    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
179331    ** return results to the user for this query. The current cursor
179332    ** (pCursor) is used to execute the query issued by function
179333    ** fts5CursorFirstSorted() above.  */
179334    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
179335    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
179336    assert( pCsr->iLastRowid==LARGEST_INT64 );
179337    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
179338    pCsr->ePlan = FTS5_PLAN_SOURCE;
179339    pCsr->pExpr = pTab->pSortCsr->pExpr;
179340    rc = fts5CursorFirst(pTab, pCsr, bDesc);
179341  }else if( pMatch ){
179342    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
179343    if( zExpr==0 ) zExpr = "";
179344
179345    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
179346    if( rc==SQLITE_OK ){
179347      if( zExpr[0]=='*' ){
179348        /* The user has issued a query of the form "MATCH '*...'". This
179349        ** indicates that the MATCH expression is not a full text query,
179350        ** but a request for an internal parameter.  */
179351        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
179352      }else{
179353        char **pzErr = &pTab->base.zErrMsg;
179354        rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
179355        if( rc==SQLITE_OK ){
179356          if( bOrderByRank ){
179357            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
179358            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
179359          }else{
179360            pCsr->ePlan = FTS5_PLAN_MATCH;
179361            rc = fts5CursorFirst(pTab, pCsr, bDesc);
179362          }
179363        }
179364      }
179365    }
179366  }else if( pConfig->zContent==0 ){
179367    *pConfig->pzErrmsg = sqlite3_mprintf(
179368        "%s: table does not support scanning", pConfig->zName
179369    );
179370    rc = SQLITE_ERROR;
179371  }else{
179372    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
179373    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
179374    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
179375    rc = sqlite3Fts5StorageStmt(
179376        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
179377    );
179378    if( rc==SQLITE_OK ){
179379      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
179380        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
179381      }else{
179382        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
179383        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
179384      }
179385      rc = fts5NextMethod(pCursor);
179386    }
179387  }
179388
179389  pConfig->pzErrmsg = pzErrmsg;
179390  return rc;
179391}
179392
179393/*
179394** This is the xEof method of the virtual table. SQLite calls this
179395** routine to find out if it has reached the end of a result set.
179396*/
179397static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
179398  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179399  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
179400}
179401
179402/*
179403** Return the rowid that the cursor currently points to.
179404*/
179405static i64 fts5CursorRowid(Fts5Cursor *pCsr){
179406  assert( pCsr->ePlan==FTS5_PLAN_MATCH
179407       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
179408       || pCsr->ePlan==FTS5_PLAN_SOURCE
179409  );
179410  if( pCsr->pSorter ){
179411    return pCsr->pSorter->iRowid;
179412  }else{
179413    return sqlite3Fts5ExprRowid(pCsr->pExpr);
179414  }
179415}
179416
179417/*
179418** This is the xRowid method. The SQLite core calls this routine to
179419** retrieve the rowid for the current row of the result set. fts5
179420** exposes %_content.rowid as the rowid for the virtual table. The
179421** rowid should be written to *pRowid.
179422*/
179423static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
179424  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179425  int ePlan = pCsr->ePlan;
179426
179427  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
179428  switch( ePlan ){
179429    case FTS5_PLAN_SPECIAL:
179430      *pRowid = 0;
179431      break;
179432
179433    case FTS5_PLAN_SOURCE:
179434    case FTS5_PLAN_MATCH:
179435    case FTS5_PLAN_SORTED_MATCH:
179436      *pRowid = fts5CursorRowid(pCsr);
179437      break;
179438
179439    default:
179440      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
179441      break;
179442  }
179443
179444  return SQLITE_OK;
179445}
179446
179447/*
179448** If the cursor requires seeking (bSeekRequired flag is set), seek it.
179449** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
179450**
179451** If argument bErrormsg is true and an error occurs, an error message may
179452** be left in sqlite3_vtab.zErrMsg.
179453*/
179454static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
179455  int rc = SQLITE_OK;
179456
179457  /* If the cursor does not yet have a statement handle, obtain one now. */
179458  if( pCsr->pStmt==0 ){
179459    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179460    int eStmt = fts5StmtType(pCsr);
179461    rc = sqlite3Fts5StorageStmt(
179462        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
179463    );
179464    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
179465    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
179466  }
179467
179468  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
179469    assert( pCsr->pExpr );
179470    sqlite3_reset(pCsr->pStmt);
179471    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
179472    rc = sqlite3_step(pCsr->pStmt);
179473    if( rc==SQLITE_ROW ){
179474      rc = SQLITE_OK;
179475      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
179476    }else{
179477      rc = sqlite3_reset(pCsr->pStmt);
179478      if( rc==SQLITE_OK ){
179479        rc = FTS5_CORRUPT;
179480      }
179481    }
179482  }
179483  return rc;
179484}
179485
179486static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
179487  va_list ap;                     /* ... printf arguments */
179488  va_start(ap, zFormat);
179489  assert( p->base.zErrMsg==0 );
179490  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
179491  va_end(ap);
179492}
179493
179494/*
179495** This function is called to handle an FTS INSERT command. In other words,
179496** an INSERT statement of the form:
179497**
179498**     INSERT INTO fts(fts) VALUES($pCmd)
179499**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
179500**
179501** Argument pVal is the value assigned to column "fts" by the INSERT
179502** statement. This function returns SQLITE_OK if successful, or an SQLite
179503** error code if an error occurs.
179504**
179505** The commands implemented by this function are documented in the "Special
179506** INSERT Directives" section of the documentation. It should be updated if
179507** more commands are added to this function.
179508*/
179509static int fts5SpecialInsert(
179510  Fts5Table *pTab,                /* Fts5 table object */
179511  const char *zCmd,               /* Text inserted into table-name column */
179512  sqlite3_value *pVal             /* Value inserted into rank column */
179513){
179514  Fts5Config *pConfig = pTab->pConfig;
179515  int rc = SQLITE_OK;
179516  int bError = 0;
179517
179518  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
179519    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
179520      fts5SetVtabError(pTab,
179521          "'delete-all' may only be used with a "
179522          "contentless or external content fts5 table"
179523      );
179524      rc = SQLITE_ERROR;
179525    }else{
179526      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
179527    }
179528  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
179529    if( pConfig->eContent==FTS5_CONTENT_NONE ){
179530      fts5SetVtabError(pTab,
179531          "'rebuild' may not be used with a contentless fts5 table"
179532      );
179533      rc = SQLITE_ERROR;
179534    }else{
179535      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
179536    }
179537  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
179538    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
179539  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
179540    int nMerge = sqlite3_value_int(pVal);
179541    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
179542  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
179543    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
179544#ifdef SQLITE_DEBUG
179545  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
179546    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
179547#endif
179548  }else{
179549    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
179550    if( rc==SQLITE_OK ){
179551      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
179552    }
179553    if( rc==SQLITE_OK ){
179554      if( bError ){
179555        rc = SQLITE_ERROR;
179556      }else{
179557        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
179558      }
179559    }
179560  }
179561  return rc;
179562}
179563
179564static int fts5SpecialDelete(
179565  Fts5Table *pTab,
179566  sqlite3_value **apVal,
179567  sqlite3_int64 *piRowid
179568){
179569  int rc = SQLITE_OK;
179570  int eType1 = sqlite3_value_type(apVal[1]);
179571  if( eType1==SQLITE_INTEGER ){
179572    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
179573    rc = sqlite3Fts5StorageSpecialDelete(pTab->pStorage, iDel, &apVal[2]);
179574  }
179575  return rc;
179576}
179577
179578static void fts5StorageInsert(
179579  int *pRc,
179580  Fts5Table *pTab,
179581  sqlite3_value **apVal,
179582  i64 *piRowid
179583){
179584  int rc = *pRc;
179585  if( rc==SQLITE_OK ){
179586    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
179587  }
179588  if( rc==SQLITE_OK ){
179589    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
179590  }
179591  *pRc = rc;
179592}
179593
179594/*
179595** This function is the implementation of the xUpdate callback used by
179596** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
179597** inserted, updated or deleted.
179598**
179599** A delete specifies a single argument - the rowid of the row to remove.
179600**
179601** Update and insert operations pass:
179602**
179603**   1. The "old" rowid, or NULL.
179604**   2. The "new" rowid.
179605**   3. Values for each of the nCol matchable columns.
179606**   4. Values for the two hidden columns (<tablename> and "rank").
179607*/
179608static int fts5UpdateMethod(
179609  sqlite3_vtab *pVtab,            /* Virtual table handle */
179610  int nArg,                       /* Size of argument array */
179611  sqlite3_value **apVal,          /* Array of arguments */
179612  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
179613){
179614  Fts5Table *pTab = (Fts5Table*)pVtab;
179615  Fts5Config *pConfig = pTab->pConfig;
179616  int eType0;                     /* value_type() of apVal[0] */
179617  int rc = SQLITE_OK;             /* Return code */
179618
179619  /* A transaction must be open when this is called. */
179620  assert( pTab->ts.eState==1 );
179621
179622  assert( pVtab->zErrMsg==0 );
179623  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
179624  assert( nArg==1
179625      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
179626      || sqlite3_value_type(apVal[1])==SQLITE_NULL
179627  );
179628  assert( pTab->pConfig->pzErrmsg==0 );
179629  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
179630
179631  /* Put any active cursors into REQUIRE_SEEK state. */
179632  fts5TripCursors(pTab);
179633
179634  eType0 = sqlite3_value_type(apVal[0]);
179635  if( eType0==SQLITE_NULL
179636   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
179637  ){
179638    /* A "special" INSERT op. These are handled separately. */
179639    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
179640    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
179641      && 0==sqlite3_stricmp("delete", z)
179642    ){
179643      rc = fts5SpecialDelete(pTab, apVal, pRowid);
179644    }else{
179645      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
179646    }
179647  }else{
179648    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
179649    ** any conflict on the rowid value must be detected before any
179650    ** modifications are made to the database file. There are 4 cases:
179651    **
179652    **   1) DELETE
179653    **   2) UPDATE (rowid not modified)
179654    **   3) UPDATE (rowid modified)
179655    **   4) INSERT
179656    **
179657    ** Cases 3 and 4 may violate the rowid constraint.
179658    */
179659    int eConflict = sqlite3_vtab_on_conflict(pConfig->db);
179660
179661    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
179662    assert( nArg!=1 || eType0==SQLITE_INTEGER );
179663
179664    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
179665    ** This is not suported.  */
179666    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
179667      pTab->base.zErrMsg = sqlite3_mprintf(
179668          "cannot %s contentless fts5 table: %s",
179669          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
179670      );
179671      rc = SQLITE_ERROR;
179672    }
179673
179674    /* Case 1: DELETE */
179675    else if( nArg==1 ){
179676      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
179677      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel);
179678    }
179679
179680    /* Case 2: INSERT */
179681    else if( eType0!=SQLITE_INTEGER ){
179682      /* If this is a REPLACE, first remove the current entry (if any) */
179683      if( eConflict==SQLITE_REPLACE
179684       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
179685      ){
179686        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
179687        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
179688      }
179689      fts5StorageInsert(&rc, pTab, apVal, pRowid);
179690    }
179691
179692    /* Case 2: UPDATE */
179693    else{
179694      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
179695      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
179696      if( iOld!=iNew ){
179697        if( eConflict==SQLITE_REPLACE ){
179698          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179699          if( rc==SQLITE_OK ){
179700            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
179701          }
179702          fts5StorageInsert(&rc, pTab, apVal, pRowid);
179703        }else{
179704          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
179705          if( rc==SQLITE_OK ){
179706            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179707          }
179708          if( rc==SQLITE_OK ){
179709            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
179710          }
179711        }
179712      }else{
179713        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179714        fts5StorageInsert(&rc, pTab, apVal, pRowid);
179715      }
179716    }
179717  }
179718
179719  pTab->pConfig->pzErrmsg = 0;
179720  return rc;
179721}
179722
179723/*
179724** Implementation of xSync() method.
179725*/
179726static int fts5SyncMethod(sqlite3_vtab *pVtab){
179727  int rc;
179728  Fts5Table *pTab = (Fts5Table*)pVtab;
179729  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
179730  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
179731  fts5TripCursors(pTab);
179732  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
179733  pTab->pConfig->pzErrmsg = 0;
179734  return rc;
179735}
179736
179737/*
179738** Implementation of xBegin() method.
179739*/
179740static int fts5BeginMethod(sqlite3_vtab *pVtab){
179741  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
179742  return SQLITE_OK;
179743}
179744
179745/*
179746** Implementation of xCommit() method. This is a no-op. The contents of
179747** the pending-terms hash-table have already been flushed into the database
179748** by fts5SyncMethod().
179749*/
179750static int fts5CommitMethod(sqlite3_vtab *pVtab){
179751  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
179752  return SQLITE_OK;
179753}
179754
179755/*
179756** Implementation of xRollback(). Discard the contents of the pending-terms
179757** hash-table. Any changes made to the database are reverted by SQLite.
179758*/
179759static int fts5RollbackMethod(sqlite3_vtab *pVtab){
179760  int rc;
179761  Fts5Table *pTab = (Fts5Table*)pVtab;
179762  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
179763  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
179764  return rc;
179765}
179766
179767static void *fts5ApiUserData(Fts5Context *pCtx){
179768  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179769  return pCsr->pAux->pUserData;
179770}
179771
179772static int fts5ApiColumnCount(Fts5Context *pCtx){
179773  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179774  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
179775}
179776
179777static int fts5ApiColumnTotalSize(
179778  Fts5Context *pCtx,
179779  int iCol,
179780  sqlite3_int64 *pnToken
179781){
179782  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179783  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179784  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
179785}
179786
179787static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
179788  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179789  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179790  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
179791}
179792
179793static int fts5ApiTokenize(
179794  Fts5Context *pCtx,
179795  const char *pText, int nText,
179796  void *pUserData,
179797  int (*xToken)(void*, int, const char*, int, int, int)
179798){
179799  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179800  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179801  return sqlite3Fts5Tokenize(
179802      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
179803  );
179804}
179805
179806static int fts5ApiPhraseCount(Fts5Context *pCtx){
179807  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179808  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179809}
179810
179811static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
179812  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179813  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
179814}
179815
179816static int fts5CsrPoslist(Fts5Cursor *pCsr, int iPhrase, const u8 **pa){
179817  int n;
179818  if( pCsr->pSorter ){
179819    Fts5Sorter *pSorter = pCsr->pSorter;
179820    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
179821    n = pSorter->aIdx[iPhrase] - i1;
179822    *pa = &pSorter->aPoslist[i1];
179823  }else{
179824    n = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
179825  }
179826  return n;
179827}
179828
179829/*
179830** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
179831** correctly for the current view. Return SQLITE_OK if successful, or an
179832** SQLite error code otherwise.
179833*/
179834static int fts5CacheInstArray(Fts5Cursor *pCsr){
179835  int rc = SQLITE_OK;
179836  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
179837  int nIter;                      /* Number of iterators/phrases */
179838
179839  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179840  if( pCsr->aInstIter==0 ){
179841    int nByte = sizeof(Fts5PoslistReader) * nIter;
179842    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
179843  }
179844  aIter = pCsr->aInstIter;
179845
179846  if( aIter ){
179847    int nInst = 0;                /* Number instances seen so far */
179848    int i;
179849
179850    /* Initialize all iterators */
179851    for(i=0; i<nIter; i++){
179852      const u8 *a;
179853      int n = fts5CsrPoslist(pCsr, i, &a);
179854      sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
179855    }
179856
179857    while( 1 ){
179858      int *aInst;
179859      int iBest = -1;
179860      for(i=0; i<nIter; i++){
179861        if( (aIter[i].bEof==0)
179862         && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
179863        ){
179864          iBest = i;
179865        }
179866      }
179867      if( iBest<0 ) break;
179868
179869      nInst++;
179870      if( nInst>=pCsr->nInstAlloc ){
179871        pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
179872        aInst = (int*)sqlite3_realloc(
179873            pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
179874        );
179875        if( aInst ){
179876          pCsr->aInst = aInst;
179877        }else{
179878          rc = SQLITE_NOMEM;
179879          break;
179880        }
179881      }
179882
179883      aInst = &pCsr->aInst[3 * (nInst-1)];
179884      aInst[0] = iBest;
179885      aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
179886      aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
179887      sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
179888    }
179889
179890    pCsr->nInstCount = nInst;
179891    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
179892  }
179893  return rc;
179894}
179895
179896static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
179897  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179898  int rc = SQLITE_OK;
179899  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
179900   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
179901    *pnInst = pCsr->nInstCount;
179902  }
179903  return rc;
179904}
179905
179906static int fts5ApiInst(
179907  Fts5Context *pCtx,
179908  int iIdx,
179909  int *piPhrase,
179910  int *piCol,
179911  int *piOff
179912){
179913  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179914  int rc = SQLITE_OK;
179915  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
179916   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
179917  ){
179918    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
179919      rc = SQLITE_RANGE;
179920    }else{
179921      *piPhrase = pCsr->aInst[iIdx*3];
179922      *piCol = pCsr->aInst[iIdx*3 + 1];
179923      *piOff = pCsr->aInst[iIdx*3 + 2];
179924    }
179925  }
179926  return rc;
179927}
179928
179929static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
179930  return fts5CursorRowid((Fts5Cursor*)pCtx);
179931}
179932
179933static int fts5ApiColumnText(
179934  Fts5Context *pCtx,
179935  int iCol,
179936  const char **pz,
179937  int *pn
179938){
179939  int rc = SQLITE_OK;
179940  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179941  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
179942    *pz = 0;
179943    *pn = 0;
179944  }else{
179945    rc = fts5SeekCursor(pCsr, 0);
179946    if( rc==SQLITE_OK ){
179947      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
179948      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
179949    }
179950  }
179951  return rc;
179952}
179953
179954static int fts5ColumnSizeCb(
179955  void *pContext,                 /* Pointer to int */
179956  int tflags,
179957  const char *pToken,             /* Buffer containing token */
179958  int nToken,                     /* Size of token in bytes */
179959  int iStart,                     /* Start offset of token */
179960  int iEnd                        /* End offset of token */
179961){
179962  int *pCnt = (int*)pContext;
179963  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
179964    (*pCnt)++;
179965  }
179966  return SQLITE_OK;
179967}
179968
179969static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
179970  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179971  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179972  Fts5Config *pConfig = pTab->pConfig;
179973  int rc = SQLITE_OK;
179974
179975  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
179976    if( pConfig->bColumnsize ){
179977      i64 iRowid = fts5CursorRowid(pCsr);
179978      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
179979    }else if( pConfig->zContent==0 ){
179980      int i;
179981      for(i=0; i<pConfig->nCol; i++){
179982        if( pConfig->abUnindexed[i]==0 ){
179983          pCsr->aColumnSize[i] = -1;
179984        }
179985      }
179986    }else{
179987      int i;
179988      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
179989        if( pConfig->abUnindexed[i]==0 ){
179990          const char *z; int n;
179991          void *p = (void*)(&pCsr->aColumnSize[i]);
179992          pCsr->aColumnSize[i] = 0;
179993          rc = fts5ApiColumnText(pCtx, i, &z, &n);
179994          if( rc==SQLITE_OK ){
179995            rc = sqlite3Fts5Tokenize(
179996                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
179997            );
179998          }
179999        }
180000      }
180001    }
180002    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
180003  }
180004  if( iCol<0 ){
180005    int i;
180006    *pnToken = 0;
180007    for(i=0; i<pConfig->nCol; i++){
180008      *pnToken += pCsr->aColumnSize[i];
180009    }
180010  }else if( iCol<pConfig->nCol ){
180011    *pnToken = pCsr->aColumnSize[iCol];
180012  }else{
180013    *pnToken = 0;
180014    rc = SQLITE_RANGE;
180015  }
180016  return rc;
180017}
180018
180019/*
180020** Implementation of the xSetAuxdata() method.
180021*/
180022static int fts5ApiSetAuxdata(
180023  Fts5Context *pCtx,              /* Fts5 context */
180024  void *pPtr,                     /* Pointer to save as auxdata */
180025  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
180026){
180027  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180028  Fts5Auxdata *pData;
180029
180030  /* Search through the cursors list of Fts5Auxdata objects for one that
180031  ** corresponds to the currently executing auxiliary function.  */
180032  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
180033    if( pData->pAux==pCsr->pAux ) break;
180034  }
180035
180036  if( pData ){
180037    if( pData->xDelete ){
180038      pData->xDelete(pData->pPtr);
180039    }
180040  }else{
180041    int rc = SQLITE_OK;
180042    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
180043    if( pData==0 ){
180044      if( xDelete ) xDelete(pPtr);
180045      return rc;
180046    }
180047    pData->pAux = pCsr->pAux;
180048    pData->pNext = pCsr->pAuxdata;
180049    pCsr->pAuxdata = pData;
180050  }
180051
180052  pData->xDelete = xDelete;
180053  pData->pPtr = pPtr;
180054  return SQLITE_OK;
180055}
180056
180057static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
180058  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180059  Fts5Auxdata *pData;
180060  void *pRet = 0;
180061
180062  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
180063    if( pData->pAux==pCsr->pAux ) break;
180064  }
180065
180066  if( pData ){
180067    pRet = pData->pPtr;
180068    if( bClear ){
180069      pData->pPtr = 0;
180070      pData->xDelete = 0;
180071    }
180072  }
180073
180074  return pRet;
180075}
180076
180077static void fts5ApiPhraseNext(
180078  Fts5Context *pCtx,
180079  Fts5PhraseIter *pIter,
180080  int *piCol, int *piOff
180081){
180082  if( pIter->a>=pIter->b ){
180083    *piCol = -1;
180084    *piOff = -1;
180085  }else{
180086    int iVal;
180087    pIter->a += fts5GetVarint32(pIter->a, iVal);
180088    if( iVal==1 ){
180089      pIter->a += fts5GetVarint32(pIter->a, iVal);
180090      *piCol = iVal;
180091      *piOff = 0;
180092      pIter->a += fts5GetVarint32(pIter->a, iVal);
180093    }
180094    *piOff += (iVal-2);
180095  }
180096}
180097
180098static void fts5ApiPhraseFirst(
180099  Fts5Context *pCtx,
180100  int iPhrase,
180101  Fts5PhraseIter *pIter,
180102  int *piCol, int *piOff
180103){
180104  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180105  int n = fts5CsrPoslist(pCsr, iPhrase, &pIter->a);
180106  pIter->b = &pIter->a[n];
180107  *piCol = 0;
180108  *piOff = 0;
180109  fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
180110}
180111
180112static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
180113    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
180114);
180115
180116static const Fts5ExtensionApi sFts5Api = {
180117  2,                            /* iVersion */
180118  fts5ApiUserData,
180119  fts5ApiColumnCount,
180120  fts5ApiRowCount,
180121  fts5ApiColumnTotalSize,
180122  fts5ApiTokenize,
180123  fts5ApiPhraseCount,
180124  fts5ApiPhraseSize,
180125  fts5ApiInstCount,
180126  fts5ApiInst,
180127  fts5ApiRowid,
180128  fts5ApiColumnText,
180129  fts5ApiColumnSize,
180130  fts5ApiQueryPhrase,
180131  fts5ApiSetAuxdata,
180132  fts5ApiGetAuxdata,
180133  fts5ApiPhraseFirst,
180134  fts5ApiPhraseNext,
180135};
180136
180137
180138/*
180139** Implementation of API function xQueryPhrase().
180140*/
180141static int fts5ApiQueryPhrase(
180142  Fts5Context *pCtx,
180143  int iPhrase,
180144  void *pUserData,
180145  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
180146){
180147  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180148  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
180149  int rc;
180150  Fts5Cursor *pNew = 0;
180151
180152  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
180153  if( rc==SQLITE_OK ){
180154    Fts5Config *pConf = pTab->pConfig;
180155    pNew->ePlan = FTS5_PLAN_MATCH;
180156    pNew->iFirstRowid = SMALLEST_INT64;
180157    pNew->iLastRowid = LARGEST_INT64;
180158    pNew->base.pVtab = (sqlite3_vtab*)pTab;
180159    rc = sqlite3Fts5ExprClonePhrase(pConf, pCsr->pExpr, iPhrase, &pNew->pExpr);
180160  }
180161
180162  if( rc==SQLITE_OK ){
180163    for(rc = fts5CursorFirst(pTab, pNew, 0);
180164        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
180165        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
180166    ){
180167      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
180168      if( rc!=SQLITE_OK ){
180169        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
180170        break;
180171      }
180172    }
180173  }
180174
180175  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
180176  return rc;
180177}
180178
180179static void fts5ApiInvoke(
180180  Fts5Auxiliary *pAux,
180181  Fts5Cursor *pCsr,
180182  sqlite3_context *context,
180183  int argc,
180184  sqlite3_value **argv
180185){
180186  assert( pCsr->pAux==0 );
180187  pCsr->pAux = pAux;
180188  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
180189  pCsr->pAux = 0;
180190}
180191
180192static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
180193  Fts5Cursor *pCsr;
180194  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
180195    if( pCsr->iCsrId==iCsrId ) break;
180196  }
180197  return pCsr;
180198}
180199
180200static void fts5ApiCallback(
180201  sqlite3_context *context,
180202  int argc,
180203  sqlite3_value **argv
180204){
180205
180206  Fts5Auxiliary *pAux;
180207  Fts5Cursor *pCsr;
180208  i64 iCsrId;
180209
180210  assert( argc>=1 );
180211  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
180212  iCsrId = sqlite3_value_int64(argv[0]);
180213
180214  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
180215  if( pCsr==0 ){
180216    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
180217    sqlite3_result_error(context, zErr, -1);
180218    sqlite3_free(zErr);
180219  }else{
180220    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
180221  }
180222}
180223
180224
180225/*
180226** Given cursor id iId, return a pointer to the corresponding Fts5Index
180227** object. Or NULL If the cursor id does not exist.
180228**
180229** If successful, set *pnCol to the number of indexed columns in the
180230** table before returning.
180231*/
180232static Fts5Index *sqlite3Fts5IndexFromCsrid(
180233  Fts5Global *pGlobal,
180234  i64 iCsrId,
180235  int *pnCol
180236){
180237  Fts5Cursor *pCsr;
180238  Fts5Table *pTab;
180239
180240  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
180241  pTab = (Fts5Table*)pCsr->base.pVtab;
180242  *pnCol = pTab->pConfig->nCol;
180243
180244  return pTab->pIndex;
180245}
180246
180247/*
180248** Return a "position-list blob" corresponding to the current position of
180249** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
180250** the current position-list for each phrase in the query associated with
180251** cursor pCsr.
180252**
180253** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
180254** the number of phrases in the query. Following the varints are the
180255** concatenated position lists for each phrase, in order.
180256**
180257** The first varint (if it exists) contains the size of the position list
180258** for phrase 0. The second (same disclaimer) contains the size of position
180259** list 1. And so on. There is no size field for the final position list,
180260** as it can be derived from the total size of the blob.
180261*/
180262static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
180263  int i;
180264  int rc = SQLITE_OK;
180265  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
180266  Fts5Buffer val;
180267
180268  memset(&val, 0, sizeof(Fts5Buffer));
180269
180270  /* Append the varints */
180271  for(i=0; i<(nPhrase-1); i++){
180272    const u8 *dummy;
180273    int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
180274    sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
180275  }
180276
180277  /* Append the position lists */
180278  for(i=0; i<nPhrase; i++){
180279    const u8 *pPoslist;
180280    int nPoslist;
180281    nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
180282    sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
180283  }
180284
180285  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
180286  return rc;
180287}
180288
180289/*
180290** This is the xColumn method, called by SQLite to request a value from
180291** the row that the supplied cursor currently points to.
180292*/
180293static int fts5ColumnMethod(
180294  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
180295  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
180296  int iCol                        /* Index of column to read value from */
180297){
180298  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
180299  Fts5Config *pConfig = pTab->pConfig;
180300  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
180301  int rc = SQLITE_OK;
180302
180303  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
180304
180305  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
180306    if( iCol==pConfig->nCol ){
180307      sqlite3_result_int64(pCtx, pCsr->iSpecial);
180308    }
180309  }else
180310
180311  if( iCol==pConfig->nCol ){
180312    /* User is requesting the value of the special column with the same name
180313    ** as the table. Return the cursor integer id number. This value is only
180314    ** useful in that it may be passed as the first argument to an FTS5
180315    ** auxiliary function.  */
180316    sqlite3_result_int64(pCtx, pCsr->iCsrId);
180317  }else if( iCol==pConfig->nCol+1 ){
180318
180319    /* The value of the "rank" column. */
180320    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
180321      fts5PoslistBlob(pCtx, pCsr);
180322    }else if(
180323        pCsr->ePlan==FTS5_PLAN_MATCH
180324     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
180325    ){
180326      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
180327        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
180328      }
180329    }
180330  }else if( !fts5IsContentless(pTab) ){
180331    rc = fts5SeekCursor(pCsr, 1);
180332    if( rc==SQLITE_OK ){
180333      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
180334    }
180335  }
180336  return rc;
180337}
180338
180339
180340/*
180341** This routine implements the xFindFunction method for the FTS3
180342** virtual table.
180343*/
180344static int fts5FindFunctionMethod(
180345  sqlite3_vtab *pVtab,            /* Virtual table handle */
180346  int nArg,                       /* Number of SQL function arguments */
180347  const char *zName,              /* Name of SQL function */
180348  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
180349  void **ppArg                    /* OUT: User data for *pxFunc */
180350){
180351  Fts5Table *pTab = (Fts5Table*)pVtab;
180352  Fts5Auxiliary *pAux;
180353
180354  pAux = fts5FindAuxiliary(pTab, zName);
180355  if( pAux ){
180356    *pxFunc = fts5ApiCallback;
180357    *ppArg = (void*)pAux;
180358    return 1;
180359  }
180360
180361  /* No function of the specified name was found. Return 0. */
180362  return 0;
180363}
180364
180365/*
180366** Implementation of FTS5 xRename method. Rename an fts5 table.
180367*/
180368static int fts5RenameMethod(
180369  sqlite3_vtab *pVtab,            /* Virtual table handle */
180370  const char *zName               /* New name of table */
180371){
180372  Fts5Table *pTab = (Fts5Table*)pVtab;
180373  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
180374}
180375
180376/*
180377** The xSavepoint() method.
180378**
180379** Flush the contents of the pending-terms table to disk.
180380*/
180381static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
180382  Fts5Table *pTab = (Fts5Table*)pVtab;
180383  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
180384  fts5TripCursors(pTab);
180385  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
180386}
180387
180388/*
180389** The xRelease() method.
180390**
180391** This is a no-op.
180392*/
180393static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
180394  Fts5Table *pTab = (Fts5Table*)pVtab;
180395  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
180396  fts5TripCursors(pTab);
180397  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
180398}
180399
180400/*
180401** The xRollbackTo() method.
180402**
180403** Discard the contents of the pending terms table.
180404*/
180405static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
180406  Fts5Table *pTab = (Fts5Table*)pVtab;
180407  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
180408  fts5TripCursors(pTab);
180409  return sqlite3Fts5StorageRollback(pTab->pStorage);
180410}
180411
180412/*
180413** Register a new auxiliary function with global context pGlobal.
180414*/
180415static int fts5CreateAux(
180416  fts5_api *pApi,                 /* Global context (one per db handle) */
180417  const char *zName,              /* Name of new function */
180418  void *pUserData,                /* User data for aux. function */
180419  fts5_extension_function xFunc,  /* Aux. function implementation */
180420  void(*xDestroy)(void*)          /* Destructor for pUserData */
180421){
180422  Fts5Global *pGlobal = (Fts5Global*)pApi;
180423  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
180424  if( rc==SQLITE_OK ){
180425    Fts5Auxiliary *pAux;
180426    int nName;                      /* Size of zName in bytes, including \0 */
180427    int nByte;                      /* Bytes of space to allocate */
180428
180429    nName = (int)strlen(zName) + 1;
180430    nByte = sizeof(Fts5Auxiliary) + nName;
180431    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
180432    if( pAux ){
180433      memset(pAux, 0, nByte);
180434      pAux->zFunc = (char*)&pAux[1];
180435      memcpy(pAux->zFunc, zName, nName);
180436      pAux->pGlobal = pGlobal;
180437      pAux->pUserData = pUserData;
180438      pAux->xFunc = xFunc;
180439      pAux->xDestroy = xDestroy;
180440      pAux->pNext = pGlobal->pAux;
180441      pGlobal->pAux = pAux;
180442    }else{
180443      rc = SQLITE_NOMEM;
180444    }
180445  }
180446
180447  return rc;
180448}
180449
180450/*
180451** Register a new tokenizer. This is the implementation of the
180452** fts5_api.xCreateTokenizer() method.
180453*/
180454static int fts5CreateTokenizer(
180455  fts5_api *pApi,                 /* Global context (one per db handle) */
180456  const char *zName,              /* Name of new function */
180457  void *pUserData,                /* User data for aux. function */
180458  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
180459  void(*xDestroy)(void*)          /* Destructor for pUserData */
180460){
180461  Fts5Global *pGlobal = (Fts5Global*)pApi;
180462  Fts5TokenizerModule *pNew;
180463  int nName;                      /* Size of zName and its \0 terminator */
180464  int nByte;                      /* Bytes of space to allocate */
180465  int rc = SQLITE_OK;
180466
180467  nName = (int)strlen(zName) + 1;
180468  nByte = sizeof(Fts5TokenizerModule) + nName;
180469  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
180470  if( pNew ){
180471    memset(pNew, 0, nByte);
180472    pNew->zName = (char*)&pNew[1];
180473    memcpy(pNew->zName, zName, nName);
180474    pNew->pUserData = pUserData;
180475    pNew->x = *pTokenizer;
180476    pNew->xDestroy = xDestroy;
180477    pNew->pNext = pGlobal->pTok;
180478    pGlobal->pTok = pNew;
180479    if( pNew->pNext==0 ){
180480      pGlobal->pDfltTok = pNew;
180481    }
180482  }else{
180483    rc = SQLITE_NOMEM;
180484  }
180485
180486  return rc;
180487}
180488
180489static Fts5TokenizerModule *fts5LocateTokenizer(
180490  Fts5Global *pGlobal,
180491  const char *zName
180492){
180493  Fts5TokenizerModule *pMod = 0;
180494
180495  if( zName==0 ){
180496    pMod = pGlobal->pDfltTok;
180497  }else{
180498    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
180499      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
180500    }
180501  }
180502
180503  return pMod;
180504}
180505
180506/*
180507** Find a tokenizer. This is the implementation of the
180508** fts5_api.xFindTokenizer() method.
180509*/
180510static int fts5FindTokenizer(
180511  fts5_api *pApi,                 /* Global context (one per db handle) */
180512  const char *zName,              /* Name of new function */
180513  void **ppUserData,
180514  fts5_tokenizer *pTokenizer      /* Populate this object */
180515){
180516  int rc = SQLITE_OK;
180517  Fts5TokenizerModule *pMod;
180518
180519  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
180520  if( pMod ){
180521    *pTokenizer = pMod->x;
180522    *ppUserData = pMod->pUserData;
180523  }else{
180524    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
180525    rc = SQLITE_ERROR;
180526  }
180527
180528  return rc;
180529}
180530
180531static int sqlite3Fts5GetTokenizer(
180532  Fts5Global *pGlobal,
180533  const char **azArg,
180534  int nArg,
180535  Fts5Tokenizer **ppTok,
180536  fts5_tokenizer **ppTokApi,
180537  char **pzErr
180538){
180539  Fts5TokenizerModule *pMod;
180540  int rc = SQLITE_OK;
180541
180542  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
180543  if( pMod==0 ){
180544    assert( nArg>0 );
180545    rc = SQLITE_ERROR;
180546    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
180547  }else{
180548    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
180549    *ppTokApi = &pMod->x;
180550    if( rc!=SQLITE_OK && pzErr ){
180551      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
180552    }
180553  }
180554
180555  if( rc!=SQLITE_OK ){
180556    *ppTokApi = 0;
180557    *ppTok = 0;
180558  }
180559
180560  return rc;
180561}
180562
180563static void fts5ModuleDestroy(void *pCtx){
180564  Fts5TokenizerModule *pTok, *pNextTok;
180565  Fts5Auxiliary *pAux, *pNextAux;
180566  Fts5Global *pGlobal = (Fts5Global*)pCtx;
180567
180568  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
180569    pNextAux = pAux->pNext;
180570    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
180571    sqlite3_free(pAux);
180572  }
180573
180574  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
180575    pNextTok = pTok->pNext;
180576    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
180577    sqlite3_free(pTok);
180578  }
180579
180580  sqlite3_free(pGlobal);
180581}
180582
180583static void fts5Fts5Func(
180584  sqlite3_context *pCtx,          /* Function call context */
180585  int nArg,                       /* Number of args */
180586  sqlite3_value **apVal           /* Function arguments */
180587){
180588  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
180589  char buf[8];
180590  assert( nArg==0 );
180591  assert( sizeof(buf)>=sizeof(pGlobal) );
180592  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
180593  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
180594}
180595
180596/*
180597** Implementation of fts5_source_id() function.
180598*/
180599static void fts5SourceIdFunc(
180600  sqlite3_context *pCtx,          /* Function call context */
180601  int nArg,                       /* Number of args */
180602  sqlite3_value **apVal           /* Function arguments */
180603){
180604  assert( nArg==0 );
180605  sqlite3_result_text(pCtx, "fts5: 2015-11-02 18:31:45 bda77dda9697c463c3d0704014d51627fceee328", -1, SQLITE_TRANSIENT);
180606}
180607
180608static int fts5Init(sqlite3 *db){
180609  static const sqlite3_module fts5Mod = {
180610    /* iVersion      */ 2,
180611    /* xCreate       */ fts5CreateMethod,
180612    /* xConnect      */ fts5ConnectMethod,
180613    /* xBestIndex    */ fts5BestIndexMethod,
180614    /* xDisconnect   */ fts5DisconnectMethod,
180615    /* xDestroy      */ fts5DestroyMethod,
180616    /* xOpen         */ fts5OpenMethod,
180617    /* xClose        */ fts5CloseMethod,
180618    /* xFilter       */ fts5FilterMethod,
180619    /* xNext         */ fts5NextMethod,
180620    /* xEof          */ fts5EofMethod,
180621    /* xColumn       */ fts5ColumnMethod,
180622    /* xRowid        */ fts5RowidMethod,
180623    /* xUpdate       */ fts5UpdateMethod,
180624    /* xBegin        */ fts5BeginMethod,
180625    /* xSync         */ fts5SyncMethod,
180626    /* xCommit       */ fts5CommitMethod,
180627    /* xRollback     */ fts5RollbackMethod,
180628    /* xFindFunction */ fts5FindFunctionMethod,
180629    /* xRename       */ fts5RenameMethod,
180630    /* xSavepoint    */ fts5SavepointMethod,
180631    /* xRelease      */ fts5ReleaseMethod,
180632    /* xRollbackTo   */ fts5RollbackToMethod,
180633  };
180634
180635  int rc;
180636  Fts5Global *pGlobal = 0;
180637
180638  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
180639  if( pGlobal==0 ){
180640    rc = SQLITE_NOMEM;
180641  }else{
180642    void *p = (void*)pGlobal;
180643    memset(pGlobal, 0, sizeof(Fts5Global));
180644    pGlobal->db = db;
180645    pGlobal->api.iVersion = 2;
180646    pGlobal->api.xCreateFunction = fts5CreateAux;
180647    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
180648    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
180649    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
180650    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
180651    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
180652    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
180653    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
180654    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
180655    if( rc==SQLITE_OK ){
180656      rc = sqlite3_create_function(
180657          db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
180658      );
180659    }
180660    if( rc==SQLITE_OK ){
180661      rc = sqlite3_create_function(
180662          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
180663      );
180664    }
180665  }
180666  return rc;
180667}
180668
180669/*
180670** The following functions are used to register the module with SQLite. If
180671** this module is being built as part of the SQLite core (SQLITE_CORE is
180672** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
180673**
180674** Or, if this module is being built as a loadable extension,
180675** sqlite3Fts5Init() is omitted and the two standard entry points
180676** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
180677*/
180678#ifndef SQLITE_CORE
180679#ifdef _WIN32
180680__declspec(dllexport)
180681#endif
180682SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
180683  sqlite3 *db,
180684  char **pzErrMsg,
180685  const sqlite3_api_routines *pApi
180686){
180687  SQLITE_EXTENSION_INIT2(pApi);
180688  (void)pzErrMsg;  /* Unused parameter */
180689  return fts5Init(db);
180690}
180691
180692#ifdef _WIN32
180693__declspec(dllexport)
180694#endif
180695SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
180696  sqlite3 *db,
180697  char **pzErrMsg,
180698  const sqlite3_api_routines *pApi
180699){
180700  SQLITE_EXTENSION_INIT2(pApi);
180701  (void)pzErrMsg;  /* Unused parameter */
180702  return fts5Init(db);
180703}
180704#else
180705SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
180706  return fts5Init(db);
180707}
180708#endif
180709
180710/*
180711** 2014 May 31
180712**
180713** The author disclaims copyright to this source code.  In place of
180714** a legal notice, here is a blessing:
180715**
180716**    May you do good and not evil.
180717**    May you find forgiveness for yourself and forgive others.
180718**    May you share freely, never taking more than you give.
180719**
180720******************************************************************************
180721**
180722*/
180723
180724
180725
180726
180727struct Fts5Storage {
180728  Fts5Config *pConfig;
180729  Fts5Index *pIndex;
180730  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
180731  i64 nTotalRow;                  /* Total number of rows in FTS table */
180732  i64 *aTotalSize;                /* Total sizes of each column */
180733  sqlite3_stmt *aStmt[11];
180734};
180735
180736
180737#if FTS5_STMT_SCAN_ASC!=0
180738# error "FTS5_STMT_SCAN_ASC mismatch"
180739#endif
180740#if FTS5_STMT_SCAN_DESC!=1
180741# error "FTS5_STMT_SCAN_DESC mismatch"
180742#endif
180743#if FTS5_STMT_LOOKUP!=2
180744# error "FTS5_STMT_LOOKUP mismatch"
180745#endif
180746
180747#define FTS5_STMT_INSERT_CONTENT  3
180748#define FTS5_STMT_REPLACE_CONTENT 4
180749#define FTS5_STMT_DELETE_CONTENT  5
180750#define FTS5_STMT_REPLACE_DOCSIZE  6
180751#define FTS5_STMT_DELETE_DOCSIZE  7
180752#define FTS5_STMT_LOOKUP_DOCSIZE  8
180753#define FTS5_STMT_REPLACE_CONFIG 9
180754#define FTS5_STMT_SCAN 10
180755
180756/*
180757** Prepare the two insert statements - Fts5Storage.pInsertContent and
180758** Fts5Storage.pInsertDocsize - if they have not already been prepared.
180759** Return SQLITE_OK if successful, or an SQLite error code if an error
180760** occurs.
180761*/
180762static int fts5StorageGetStmt(
180763  Fts5Storage *p,                 /* Storage handle */
180764  int eStmt,                      /* FTS5_STMT_XXX constant */
180765  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
180766  char **pzErrMsg                 /* OUT: Error message (if any) */
180767){
180768  int rc = SQLITE_OK;
180769
180770  /* If there is no %_docsize table, there should be no requests for
180771  ** statements to operate on it.  */
180772  assert( p->pConfig->bColumnsize || (
180773        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
180774     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
180775     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
180776  ));
180777
180778  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
180779  if( p->aStmt[eStmt]==0 ){
180780    const char *azStmt[] = {
180781      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
180782      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
180783      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
180784
180785      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
180786      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
180787      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
180788      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
180789      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
180790
180791      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
180792
180793      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
180794      "SELECT %s FROM %s AS T",                         /* SCAN */
180795    };
180796    Fts5Config *pC = p->pConfig;
180797    char *zSql = 0;
180798
180799    switch( eStmt ){
180800      case FTS5_STMT_SCAN:
180801        zSql = sqlite3_mprintf(azStmt[eStmt],
180802            pC->zContentExprlist, pC->zContent
180803        );
180804        break;
180805
180806      case FTS5_STMT_SCAN_ASC:
180807      case FTS5_STMT_SCAN_DESC:
180808        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
180809            pC->zContent, pC->zContentRowid, pC->zContentRowid,
180810            pC->zContentRowid
180811        );
180812        break;
180813
180814      case FTS5_STMT_LOOKUP:
180815        zSql = sqlite3_mprintf(azStmt[eStmt],
180816            pC->zContentExprlist, pC->zContent, pC->zContentRowid
180817        );
180818        break;
180819
180820      case FTS5_STMT_INSERT_CONTENT:
180821      case FTS5_STMT_REPLACE_CONTENT: {
180822        int nCol = pC->nCol + 1;
180823        char *zBind;
180824        int i;
180825
180826        zBind = sqlite3_malloc(1 + nCol*2);
180827        if( zBind ){
180828          for(i=0; i<nCol; i++){
180829            zBind[i*2] = '?';
180830            zBind[i*2 + 1] = ',';
180831          }
180832          zBind[i*2-1] = '\0';
180833          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
180834          sqlite3_free(zBind);
180835        }
180836        break;
180837      }
180838
180839      default:
180840        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
180841        break;
180842    }
180843
180844    if( zSql==0 ){
180845      rc = SQLITE_NOMEM;
180846    }else{
180847      rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
180848      sqlite3_free(zSql);
180849      if( rc!=SQLITE_OK && pzErrMsg ){
180850        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
180851      }
180852    }
180853  }
180854
180855  *ppStmt = p->aStmt[eStmt];
180856  return rc;
180857}
180858
180859
180860static int fts5ExecPrintf(
180861  sqlite3 *db,
180862  char **pzErr,
180863  const char *zFormat,
180864  ...
180865){
180866  int rc;
180867  va_list ap;                     /* ... printf arguments */
180868  char *zSql;
180869
180870  va_start(ap, zFormat);
180871  zSql = sqlite3_vmprintf(zFormat, ap);
180872
180873  if( zSql==0 ){
180874    rc = SQLITE_NOMEM;
180875  }else{
180876    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
180877    sqlite3_free(zSql);
180878  }
180879
180880  va_end(ap);
180881  return rc;
180882}
180883
180884/*
180885** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
180886** code otherwise.
180887*/
180888static int sqlite3Fts5DropAll(Fts5Config *pConfig){
180889  int rc = fts5ExecPrintf(pConfig->db, 0,
180890      "DROP TABLE IF EXISTS %Q.'%q_data';"
180891      "DROP TABLE IF EXISTS %Q.'%q_idx';"
180892      "DROP TABLE IF EXISTS %Q.'%q_config';",
180893      pConfig->zDb, pConfig->zName,
180894      pConfig->zDb, pConfig->zName,
180895      pConfig->zDb, pConfig->zName
180896  );
180897  if( rc==SQLITE_OK && pConfig->bColumnsize ){
180898    rc = fts5ExecPrintf(pConfig->db, 0,
180899        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
180900        pConfig->zDb, pConfig->zName
180901    );
180902  }
180903  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
180904    rc = fts5ExecPrintf(pConfig->db, 0,
180905        "DROP TABLE IF EXISTS %Q.'%q_content';",
180906        pConfig->zDb, pConfig->zName
180907    );
180908  }
180909  return rc;
180910}
180911
180912static void fts5StorageRenameOne(
180913  Fts5Config *pConfig,            /* Current FTS5 configuration */
180914  int *pRc,                       /* IN/OUT: Error code */
180915  const char *zTail,              /* Tail of table name e.g. "data", "config" */
180916  const char *zName               /* New name of FTS5 table */
180917){
180918  if( *pRc==SQLITE_OK ){
180919    *pRc = fts5ExecPrintf(pConfig->db, 0,
180920        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
180921        pConfig->zDb, pConfig->zName, zTail, zName, zTail
180922    );
180923  }
180924}
180925
180926static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
180927  Fts5Config *pConfig = pStorage->pConfig;
180928  int rc = sqlite3Fts5StorageSync(pStorage, 1);
180929
180930  fts5StorageRenameOne(pConfig, &rc, "data", zName);
180931  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
180932  fts5StorageRenameOne(pConfig, &rc, "config", zName);
180933  if( pConfig->bColumnsize ){
180934    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
180935  }
180936  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
180937    fts5StorageRenameOne(pConfig, &rc, "content", zName);
180938  }
180939  return rc;
180940}
180941
180942/*
180943** Create the shadow table named zPost, with definition zDefn. Return
180944** SQLITE_OK if successful, or an SQLite error code otherwise.
180945*/
180946static int sqlite3Fts5CreateTable(
180947  Fts5Config *pConfig,            /* FTS5 configuration */
180948  const char *zPost,              /* Shadow table to create (e.g. "content") */
180949  const char *zDefn,              /* Columns etc. for shadow table */
180950  int bWithout,                   /* True for without rowid */
180951  char **pzErr                    /* OUT: Error message */
180952){
180953  int rc;
180954  char *zErr = 0;
180955
180956  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
180957      pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
180958  );
180959  if( zErr ){
180960    *pzErr = sqlite3_mprintf(
180961        "fts5: error creating shadow table %q_%s: %s",
180962        pConfig->zName, zPost, zErr
180963    );
180964    sqlite3_free(zErr);
180965  }
180966
180967  return rc;
180968}
180969
180970/*
180971** Open a new Fts5Index handle. If the bCreate argument is true, create
180972** and initialize the underlying tables
180973**
180974** If successful, set *pp to point to the new object and return SQLITE_OK.
180975** Otherwise, set *pp to NULL and return an SQLite error code.
180976*/
180977static int sqlite3Fts5StorageOpen(
180978  Fts5Config *pConfig,
180979  Fts5Index *pIndex,
180980  int bCreate,
180981  Fts5Storage **pp,
180982  char **pzErr                    /* OUT: Error message */
180983){
180984  int rc = SQLITE_OK;
180985  Fts5Storage *p;                 /* New object */
180986  int nByte;                      /* Bytes of space to allocate */
180987
180988  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
180989        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
180990  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
180991  if( !p ) return SQLITE_NOMEM;
180992
180993  memset(p, 0, nByte);
180994  p->aTotalSize = (i64*)&p[1];
180995  p->pConfig = pConfig;
180996  p->pIndex = pIndex;
180997
180998  if( bCreate ){
180999    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
181000      int nDefn = 32 + pConfig->nCol*10;
181001      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
181002      if( zDefn==0 ){
181003        rc = SQLITE_NOMEM;
181004      }else{
181005        int i;
181006        int iOff;
181007        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
181008        iOff = strlen(zDefn);
181009        for(i=0; i<pConfig->nCol; i++){
181010          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
181011          iOff += strlen(&zDefn[iOff]);
181012        }
181013        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
181014      }
181015      sqlite3_free(zDefn);
181016    }
181017
181018    if( rc==SQLITE_OK && pConfig->bColumnsize ){
181019      rc = sqlite3Fts5CreateTable(
181020          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
181021      );
181022    }
181023    if( rc==SQLITE_OK ){
181024      rc = sqlite3Fts5CreateTable(
181025          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
181026      );
181027    }
181028    if( rc==SQLITE_OK ){
181029      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
181030    }
181031  }
181032
181033  if( rc ){
181034    sqlite3Fts5StorageClose(p);
181035    *pp = 0;
181036  }
181037  return rc;
181038}
181039
181040/*
181041** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
181042*/
181043static int sqlite3Fts5StorageClose(Fts5Storage *p){
181044  int rc = SQLITE_OK;
181045  if( p ){
181046    int i;
181047
181048    /* Finalize all SQL statements */
181049    for(i=0; i<ArraySize(p->aStmt); i++){
181050      sqlite3_finalize(p->aStmt[i]);
181051    }
181052
181053    sqlite3_free(p);
181054  }
181055  return rc;
181056}
181057
181058typedef struct Fts5InsertCtx Fts5InsertCtx;
181059struct Fts5InsertCtx {
181060  Fts5Storage *pStorage;
181061  int iCol;
181062  int szCol;                      /* Size of column value in tokens */
181063};
181064
181065/*
181066** Tokenization callback used when inserting tokens into the FTS index.
181067*/
181068static int fts5StorageInsertCallback(
181069  void *pContext,                 /* Pointer to Fts5InsertCtx object */
181070  int tflags,
181071  const char *pToken,             /* Buffer containing token */
181072  int nToken,                     /* Size of token in bytes */
181073  int iStart,                     /* Start offset of token */
181074  int iEnd                        /* End offset of token */
181075){
181076  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
181077  Fts5Index *pIdx = pCtx->pStorage->pIndex;
181078  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
181079    pCtx->szCol++;
181080  }
181081  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
181082}
181083
181084/*
181085** If a row with rowid iDel is present in the %_content table, add the
181086** delete-markers to the FTS index necessary to delete it. Do not actually
181087** remove the %_content row at this time though.
181088*/
181089static int fts5StorageDeleteFromIndex(Fts5Storage *p, i64 iDel){
181090  Fts5Config *pConfig = p->pConfig;
181091  sqlite3_stmt *pSeek;            /* SELECT to read row iDel from %_data */
181092  int rc;                         /* Return code */
181093
181094  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
181095  if( rc==SQLITE_OK ){
181096    int rc2;
181097    sqlite3_bind_int64(pSeek, 1, iDel);
181098    if( sqlite3_step(pSeek)==SQLITE_ROW ){
181099      int iCol;
181100      Fts5InsertCtx ctx;
181101      ctx.pStorage = p;
181102      ctx.iCol = -1;
181103      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
181104      for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
181105        if( pConfig->abUnindexed[iCol-1] ) continue;
181106        ctx.szCol = 0;
181107        rc = sqlite3Fts5Tokenize(pConfig,
181108            FTS5_TOKENIZE_DOCUMENT,
181109            (const char*)sqlite3_column_text(pSeek, iCol),
181110            sqlite3_column_bytes(pSeek, iCol),
181111            (void*)&ctx,
181112            fts5StorageInsertCallback
181113        );
181114        p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
181115      }
181116      p->nTotalRow--;
181117    }
181118    rc2 = sqlite3_reset(pSeek);
181119    if( rc==SQLITE_OK ) rc = rc2;
181120  }
181121
181122  return rc;
181123}
181124
181125
181126/*
181127** Insert a record into the %_docsize table. Specifically, do:
181128**
181129**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
181130**
181131** If there is no %_docsize table (as happens if the columnsize=0 option
181132** is specified when the FTS5 table is created), this function is a no-op.
181133*/
181134static int fts5StorageInsertDocsize(
181135  Fts5Storage *p,                 /* Storage module to write to */
181136  i64 iRowid,                     /* id value */
181137  Fts5Buffer *pBuf                /* sz value */
181138){
181139  int rc = SQLITE_OK;
181140  if( p->pConfig->bColumnsize ){
181141    sqlite3_stmt *pReplace = 0;
181142    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
181143    if( rc==SQLITE_OK ){
181144      sqlite3_bind_int64(pReplace, 1, iRowid);
181145      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
181146      sqlite3_step(pReplace);
181147      rc = sqlite3_reset(pReplace);
181148    }
181149  }
181150  return rc;
181151}
181152
181153/*
181154** Load the contents of the "averages" record from disk into the
181155** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
181156** argument bCache is true, set the p->bTotalsValid flag to indicate
181157** that the contents of aTotalSize[] and nTotalRow are valid until
181158** further notice.
181159**
181160** Return SQLITE_OK if successful, or an SQLite error code if an error
181161** occurs.
181162*/
181163static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
181164  int rc = SQLITE_OK;
181165  if( p->bTotalsValid==0 ){
181166    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
181167    p->bTotalsValid = bCache;
181168  }
181169  return rc;
181170}
181171
181172/*
181173** Store the current contents of the p->nTotalRow and p->aTotalSize[]
181174** variables in the "averages" record on disk.
181175**
181176** Return SQLITE_OK if successful, or an SQLite error code if an error
181177** occurs.
181178*/
181179static int fts5StorageSaveTotals(Fts5Storage *p){
181180  int nCol = p->pConfig->nCol;
181181  int i;
181182  Fts5Buffer buf;
181183  int rc = SQLITE_OK;
181184  memset(&buf, 0, sizeof(buf));
181185
181186  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
181187  for(i=0; i<nCol; i++){
181188    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
181189  }
181190  if( rc==SQLITE_OK ){
181191    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
181192  }
181193  sqlite3_free(buf.p);
181194
181195  return rc;
181196}
181197
181198/*
181199** Remove a row from the FTS table.
181200*/
181201static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel){
181202  Fts5Config *pConfig = p->pConfig;
181203  int rc;
181204  sqlite3_stmt *pDel = 0;
181205
181206  rc = fts5StorageLoadTotals(p, 1);
181207
181208  /* Delete the index records */
181209  if( rc==SQLITE_OK ){
181210    rc = fts5StorageDeleteFromIndex(p, iDel);
181211  }
181212
181213  /* Delete the %_docsize record */
181214  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181215    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
181216    if( rc==SQLITE_OK ){
181217      sqlite3_bind_int64(pDel, 1, iDel);
181218      sqlite3_step(pDel);
181219      rc = sqlite3_reset(pDel);
181220    }
181221  }
181222
181223  /* Delete the %_content record */
181224  if( rc==SQLITE_OK ){
181225    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
181226  }
181227  if( rc==SQLITE_OK ){
181228    sqlite3_bind_int64(pDel, 1, iDel);
181229    sqlite3_step(pDel);
181230    rc = sqlite3_reset(pDel);
181231  }
181232
181233  /* Write the averages record */
181234  if( rc==SQLITE_OK ){
181235    rc = fts5StorageSaveTotals(p);
181236  }
181237
181238  return rc;
181239}
181240
181241static int sqlite3Fts5StorageSpecialDelete(
181242  Fts5Storage *p,
181243  i64 iDel,
181244  sqlite3_value **apVal
181245){
181246  Fts5Config *pConfig = p->pConfig;
181247  int rc;
181248  sqlite3_stmt *pDel = 0;
181249
181250  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL );
181251  rc = fts5StorageLoadTotals(p, 1);
181252
181253  /* Delete the index records */
181254  if( rc==SQLITE_OK ){
181255    int iCol;
181256    Fts5InsertCtx ctx;
181257    ctx.pStorage = p;
181258    ctx.iCol = -1;
181259
181260    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
181261    for(iCol=0; rc==SQLITE_OK && iCol<pConfig->nCol; iCol++){
181262      if( pConfig->abUnindexed[iCol] ) continue;
181263      ctx.szCol = 0;
181264      rc = sqlite3Fts5Tokenize(pConfig,
181265        FTS5_TOKENIZE_DOCUMENT,
181266        (const char*)sqlite3_value_text(apVal[iCol]),
181267        sqlite3_value_bytes(apVal[iCol]),
181268        (void*)&ctx,
181269        fts5StorageInsertCallback
181270      );
181271      p->aTotalSize[iCol] -= (i64)ctx.szCol;
181272    }
181273    p->nTotalRow--;
181274  }
181275
181276  /* Delete the %_docsize record */
181277  if( pConfig->bColumnsize ){
181278    if( rc==SQLITE_OK ){
181279      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
181280    }
181281    if( rc==SQLITE_OK ){
181282      sqlite3_bind_int64(pDel, 1, iDel);
181283      sqlite3_step(pDel);
181284      rc = sqlite3_reset(pDel);
181285    }
181286  }
181287
181288  /* Write the averages record */
181289  if( rc==SQLITE_OK ){
181290    rc = fts5StorageSaveTotals(p);
181291  }
181292
181293  return rc;
181294}
181295
181296/*
181297** Delete all entries in the FTS5 index.
181298*/
181299static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
181300  Fts5Config *pConfig = p->pConfig;
181301  int rc;
181302
181303  /* Delete the contents of the %_data and %_docsize tables. */
181304  rc = fts5ExecPrintf(pConfig->db, 0,
181305      "DELETE FROM %Q.'%q_data';"
181306      "DELETE FROM %Q.'%q_idx';",
181307      pConfig->zDb, pConfig->zName,
181308      pConfig->zDb, pConfig->zName
181309  );
181310  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181311    rc = fts5ExecPrintf(pConfig->db, 0,
181312        "DELETE FROM %Q.'%q_docsize';",
181313        pConfig->zDb, pConfig->zName
181314    );
181315  }
181316
181317  /* Reinitialize the %_data table. This call creates the initial structure
181318  ** and averages records.  */
181319  if( rc==SQLITE_OK ){
181320    rc = sqlite3Fts5IndexReinit(p->pIndex);
181321  }
181322  if( rc==SQLITE_OK ){
181323    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
181324  }
181325  return rc;
181326}
181327
181328static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
181329  Fts5Buffer buf = {0,0,0};
181330  Fts5Config *pConfig = p->pConfig;
181331  sqlite3_stmt *pScan = 0;
181332  Fts5InsertCtx ctx;
181333  int rc;
181334
181335  memset(&ctx, 0, sizeof(Fts5InsertCtx));
181336  ctx.pStorage = p;
181337  rc = sqlite3Fts5StorageDeleteAll(p);
181338  if( rc==SQLITE_OK ){
181339    rc = fts5StorageLoadTotals(p, 1);
181340  }
181341
181342  if( rc==SQLITE_OK ){
181343    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
181344  }
181345
181346  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
181347    i64 iRowid = sqlite3_column_int64(pScan, 0);
181348
181349    sqlite3Fts5BufferZero(&buf);
181350    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
181351    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
181352      ctx.szCol = 0;
181353      if( pConfig->abUnindexed[ctx.iCol]==0 ){
181354        rc = sqlite3Fts5Tokenize(pConfig,
181355            FTS5_TOKENIZE_DOCUMENT,
181356            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
181357            sqlite3_column_bytes(pScan, ctx.iCol+1),
181358            (void*)&ctx,
181359            fts5StorageInsertCallback
181360        );
181361      }
181362      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
181363      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
181364    }
181365    p->nTotalRow++;
181366
181367    if( rc==SQLITE_OK ){
181368      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
181369    }
181370  }
181371  sqlite3_free(buf.p);
181372
181373  /* Write the averages record */
181374  if( rc==SQLITE_OK ){
181375    rc = fts5StorageSaveTotals(p);
181376  }
181377  return rc;
181378}
181379
181380static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
181381  return sqlite3Fts5IndexOptimize(p->pIndex);
181382}
181383
181384static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
181385  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
181386}
181387
181388/*
181389** Allocate a new rowid. This is used for "external content" tables when
181390** a NULL value is inserted into the rowid column. The new rowid is allocated
181391** by inserting a dummy row into the %_docsize table. The dummy will be
181392** overwritten later.
181393**
181394** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
181395** this case the user is required to provide a rowid explicitly.
181396*/
181397static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
181398  int rc = SQLITE_MISMATCH;
181399  if( p->pConfig->bColumnsize ){
181400    sqlite3_stmt *pReplace = 0;
181401    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
181402    if( rc==SQLITE_OK ){
181403      sqlite3_bind_null(pReplace, 1);
181404      sqlite3_bind_null(pReplace, 2);
181405      sqlite3_step(pReplace);
181406      rc = sqlite3_reset(pReplace);
181407    }
181408    if( rc==SQLITE_OK ){
181409      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
181410    }
181411  }
181412  return rc;
181413}
181414
181415/*
181416** Insert a new row into the FTS content table.
181417*/
181418static int sqlite3Fts5StorageContentInsert(
181419  Fts5Storage *p,
181420  sqlite3_value **apVal,
181421  i64 *piRowid
181422){
181423  Fts5Config *pConfig = p->pConfig;
181424  int rc = SQLITE_OK;
181425
181426  /* Insert the new row into the %_content table. */
181427  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
181428    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
181429      *piRowid = sqlite3_value_int64(apVal[1]);
181430    }else{
181431      rc = fts5StorageNewRowid(p, piRowid);
181432    }
181433  }else{
181434    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
181435    int i;                        /* Counter variable */
181436#if 0
181437    if( eConflict==SQLITE_REPLACE ){
181438      eStmt = FTS5_STMT_REPLACE_CONTENT;
181439      rc = fts5StorageDeleteFromIndex(p, sqlite3_value_int64(apVal[1]));
181440    }else{
181441      eStmt = FTS5_STMT_INSERT_CONTENT;
181442    }
181443#endif
181444    if( rc==SQLITE_OK ){
181445      rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
181446    }
181447    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
181448      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
181449    }
181450    if( rc==SQLITE_OK ){
181451      sqlite3_step(pInsert);
181452      rc = sqlite3_reset(pInsert);
181453    }
181454    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
181455  }
181456
181457  return rc;
181458}
181459
181460/*
181461** Insert new entries into the FTS index and %_docsize table.
181462*/
181463static int sqlite3Fts5StorageIndexInsert(
181464  Fts5Storage *p,
181465  sqlite3_value **apVal,
181466  i64 iRowid
181467){
181468  Fts5Config *pConfig = p->pConfig;
181469  int rc = SQLITE_OK;             /* Return code */
181470  Fts5InsertCtx ctx;              /* Tokenization callback context object */
181471  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
181472
181473  memset(&buf, 0, sizeof(Fts5Buffer));
181474  ctx.pStorage = p;
181475  rc = fts5StorageLoadTotals(p, 1);
181476
181477  if( rc==SQLITE_OK ){
181478    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
181479  }
181480  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
181481    ctx.szCol = 0;
181482    if( pConfig->abUnindexed[ctx.iCol]==0 ){
181483      rc = sqlite3Fts5Tokenize(pConfig,
181484          FTS5_TOKENIZE_DOCUMENT,
181485          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
181486          sqlite3_value_bytes(apVal[ctx.iCol+2]),
181487          (void*)&ctx,
181488          fts5StorageInsertCallback
181489      );
181490    }
181491    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
181492    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
181493  }
181494  p->nTotalRow++;
181495
181496  /* Write the %_docsize record */
181497  if( rc==SQLITE_OK ){
181498    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
181499  }
181500  sqlite3_free(buf.p);
181501
181502  /* Write the averages record */
181503  if( rc==SQLITE_OK ){
181504    rc = fts5StorageSaveTotals(p);
181505  }
181506
181507  return rc;
181508}
181509
181510static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
181511  Fts5Config *pConfig = p->pConfig;
181512  char *zSql;
181513  int rc;
181514
181515  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
181516      pConfig->zDb, pConfig->zName, zSuffix
181517  );
181518  if( zSql==0 ){
181519    rc = SQLITE_NOMEM;
181520  }else{
181521    sqlite3_stmt *pCnt = 0;
181522    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
181523    if( rc==SQLITE_OK ){
181524      if( SQLITE_ROW==sqlite3_step(pCnt) ){
181525        *pnRow = sqlite3_column_int64(pCnt, 0);
181526      }
181527      rc = sqlite3_finalize(pCnt);
181528    }
181529  }
181530
181531  sqlite3_free(zSql);
181532  return rc;
181533}
181534
181535/*
181536** Context object used by sqlite3Fts5StorageIntegrity().
181537*/
181538typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
181539struct Fts5IntegrityCtx {
181540  i64 iRowid;
181541  int iCol;
181542  int szCol;
181543  u64 cksum;
181544  Fts5Config *pConfig;
181545};
181546
181547/*
181548** Tokenization callback used by integrity check.
181549*/
181550static int fts5StorageIntegrityCallback(
181551  void *pContext,                 /* Pointer to Fts5InsertCtx object */
181552  int tflags,
181553  const char *pToken,             /* Buffer containing token */
181554  int nToken,                     /* Size of token in bytes */
181555  int iStart,                     /* Start offset of token */
181556  int iEnd                        /* End offset of token */
181557){
181558  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
181559  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
181560    pCtx->szCol++;
181561  }
181562  pCtx->cksum ^= sqlite3Fts5IndexCksum(
181563      pCtx->pConfig, pCtx->iRowid, pCtx->iCol, pCtx->szCol-1, pToken, nToken
181564  );
181565  return SQLITE_OK;
181566}
181567
181568/*
181569** Check that the contents of the FTS index match that of the %_content
181570** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
181571** some other SQLite error code if an error occurs while attempting to
181572** determine this.
181573*/
181574static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
181575  Fts5Config *pConfig = p->pConfig;
181576  int rc;                         /* Return code */
181577  int *aColSize;                  /* Array of size pConfig->nCol */
181578  i64 *aTotalSize;                /* Array of size pConfig->nCol */
181579  Fts5IntegrityCtx ctx;
181580  sqlite3_stmt *pScan;
181581
181582  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
181583  ctx.pConfig = p->pConfig;
181584  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
181585  if( !aTotalSize ) return SQLITE_NOMEM;
181586  aColSize = (int*)&aTotalSize[pConfig->nCol];
181587  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
181588
181589  /* Generate the expected index checksum based on the contents of the
181590  ** %_content table. This block stores the checksum in ctx.cksum. */
181591  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
181592  if( rc==SQLITE_OK ){
181593    int rc2;
181594    while( SQLITE_ROW==sqlite3_step(pScan) ){
181595      int i;
181596      ctx.iRowid = sqlite3_column_int64(pScan, 0);
181597      ctx.szCol = 0;
181598      if( pConfig->bColumnsize ){
181599        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
181600      }
181601      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
181602        if( pConfig->abUnindexed[i] ) continue;
181603        ctx.iCol = i;
181604        ctx.szCol = 0;
181605        rc = sqlite3Fts5Tokenize(pConfig,
181606            FTS5_TOKENIZE_DOCUMENT,
181607            (const char*)sqlite3_column_text(pScan, i+1),
181608            sqlite3_column_bytes(pScan, i+1),
181609            (void*)&ctx,
181610            fts5StorageIntegrityCallback
181611        );
181612        if( pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
181613          rc = FTS5_CORRUPT;
181614        }
181615        aTotalSize[i] += ctx.szCol;
181616      }
181617      if( rc!=SQLITE_OK ) break;
181618    }
181619    rc2 = sqlite3_reset(pScan);
181620    if( rc==SQLITE_OK ) rc = rc2;
181621  }
181622
181623  /* Test that the "totals" (sometimes called "averages") record looks Ok */
181624  if( rc==SQLITE_OK ){
181625    int i;
181626    rc = fts5StorageLoadTotals(p, 0);
181627    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
181628      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
181629    }
181630  }
181631
181632  /* Check that the %_docsize and %_content tables contain the expected
181633  ** number of rows.  */
181634  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
181635    i64 nRow;
181636    rc = fts5StorageCount(p, "content", &nRow);
181637    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
181638  }
181639  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181640    i64 nRow;
181641    rc = fts5StorageCount(p, "docsize", &nRow);
181642    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
181643  }
181644
181645  /* Pass the expected checksum down to the FTS index module. It will
181646  ** verify, amongst other things, that it matches the checksum generated by
181647  ** inspecting the index itself.  */
181648  if( rc==SQLITE_OK ){
181649    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
181650  }
181651
181652  sqlite3_free(aTotalSize);
181653  return rc;
181654}
181655
181656/*
181657** Obtain an SQLite statement handle that may be used to read data from the
181658** %_content table.
181659*/
181660static int sqlite3Fts5StorageStmt(
181661  Fts5Storage *p,
181662  int eStmt,
181663  sqlite3_stmt **pp,
181664  char **pzErrMsg
181665){
181666  int rc;
181667  assert( eStmt==FTS5_STMT_SCAN_ASC
181668       || eStmt==FTS5_STMT_SCAN_DESC
181669       || eStmt==FTS5_STMT_LOOKUP
181670  );
181671  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
181672  if( rc==SQLITE_OK ){
181673    assert( p->aStmt[eStmt]==*pp );
181674    p->aStmt[eStmt] = 0;
181675  }
181676  return rc;
181677}
181678
181679/*
181680** Release an SQLite statement handle obtained via an earlier call to
181681** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
181682** must match that passed to the sqlite3Fts5StorageStmt() call.
181683*/
181684static void sqlite3Fts5StorageStmtRelease(
181685  Fts5Storage *p,
181686  int eStmt,
181687  sqlite3_stmt *pStmt
181688){
181689  assert( eStmt==FTS5_STMT_SCAN_ASC
181690       || eStmt==FTS5_STMT_SCAN_DESC
181691       || eStmt==FTS5_STMT_LOOKUP
181692  );
181693  if( p->aStmt[eStmt]==0 ){
181694    sqlite3_reset(pStmt);
181695    p->aStmt[eStmt] = pStmt;
181696  }else{
181697    sqlite3_finalize(pStmt);
181698  }
181699}
181700
181701static int fts5StorageDecodeSizeArray(
181702  int *aCol, int nCol,            /* Array to populate */
181703  const u8 *aBlob, int nBlob      /* Record to read varints from */
181704){
181705  int i;
181706  int iOff = 0;
181707  for(i=0; i<nCol; i++){
181708    if( iOff>=nBlob ) return 1;
181709    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
181710  }
181711  return (iOff!=nBlob);
181712}
181713
181714/*
181715** Argument aCol points to an array of integers containing one entry for
181716** each table column. This function reads the %_docsize record for the
181717** specified rowid and populates aCol[] with the results.
181718**
181719** An SQLite error code is returned if an error occurs, or SQLITE_OK
181720** otherwise.
181721*/
181722static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
181723  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
181724  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
181725  int rc;                         /* Return Code */
181726
181727  assert( p->pConfig->bColumnsize );
181728  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
181729  if( rc==SQLITE_OK ){
181730    int bCorrupt = 1;
181731    sqlite3_bind_int64(pLookup, 1, iRowid);
181732    if( SQLITE_ROW==sqlite3_step(pLookup) ){
181733      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
181734      int nBlob = sqlite3_column_bytes(pLookup, 0);
181735      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
181736        bCorrupt = 0;
181737      }
181738    }
181739    rc = sqlite3_reset(pLookup);
181740    if( bCorrupt && rc==SQLITE_OK ){
181741      rc = FTS5_CORRUPT;
181742    }
181743  }
181744
181745  return rc;
181746}
181747
181748static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
181749  int rc = fts5StorageLoadTotals(p, 0);
181750  if( rc==SQLITE_OK ){
181751    *pnToken = 0;
181752    if( iCol<0 ){
181753      int i;
181754      for(i=0; i<p->pConfig->nCol; i++){
181755        *pnToken += p->aTotalSize[i];
181756      }
181757    }else if( iCol<p->pConfig->nCol ){
181758      *pnToken = p->aTotalSize[iCol];
181759    }else{
181760      rc = SQLITE_RANGE;
181761    }
181762  }
181763  return rc;
181764}
181765
181766static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
181767  int rc = fts5StorageLoadTotals(p, 0);
181768  if( rc==SQLITE_OK ){
181769    *pnRow = p->nTotalRow;
181770  }
181771  return rc;
181772}
181773
181774/*
181775** Flush any data currently held in-memory to disk.
181776*/
181777static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
181778  if( bCommit && p->bTotalsValid ){
181779    int rc = fts5StorageSaveTotals(p);
181780    p->bTotalsValid = 0;
181781    if( rc!=SQLITE_OK ) return rc;
181782  }
181783  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
181784}
181785
181786static int sqlite3Fts5StorageRollback(Fts5Storage *p){
181787  p->bTotalsValid = 0;
181788  return sqlite3Fts5IndexRollback(p->pIndex);
181789}
181790
181791static int sqlite3Fts5StorageConfigValue(
181792  Fts5Storage *p,
181793  const char *z,
181794  sqlite3_value *pVal,
181795  int iVal
181796){
181797  sqlite3_stmt *pReplace = 0;
181798  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
181799  if( rc==SQLITE_OK ){
181800    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
181801    if( pVal ){
181802      sqlite3_bind_value(pReplace, 2, pVal);
181803    }else{
181804      sqlite3_bind_int(pReplace, 2, iVal);
181805    }
181806    sqlite3_step(pReplace);
181807    rc = sqlite3_reset(pReplace);
181808  }
181809  if( rc==SQLITE_OK && pVal ){
181810    int iNew = p->pConfig->iCookie + 1;
181811    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
181812    if( rc==SQLITE_OK ){
181813      p->pConfig->iCookie = iNew;
181814    }
181815  }
181816  return rc;
181817}
181818
181819
181820
181821/*
181822** 2014 May 31
181823**
181824** The author disclaims copyright to this source code.  In place of
181825** a legal notice, here is a blessing:
181826**
181827**    May you do good and not evil.
181828**    May you find forgiveness for yourself and forgive others.
181829**    May you share freely, never taking more than you give.
181830**
181831******************************************************************************
181832*/
181833
181834
181835
181836/**************************************************************************
181837** Start of ascii tokenizer implementation.
181838*/
181839
181840/*
181841** For tokenizers with no "unicode" modifier, the set of token characters
181842** is the same as the set of ASCII range alphanumeric characters.
181843*/
181844static unsigned char aAsciiTokenChar[128] = {
181845  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
181846  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
181847  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
181848  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
181849  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
181850  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
181851  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
181852  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
181853};
181854
181855typedef struct AsciiTokenizer AsciiTokenizer;
181856struct AsciiTokenizer {
181857  unsigned char aTokenChar[128];
181858};
181859
181860static void fts5AsciiAddExceptions(
181861  AsciiTokenizer *p,
181862  const char *zArg,
181863  int bTokenChars
181864){
181865  int i;
181866  for(i=0; zArg[i]; i++){
181867    if( (zArg[i] & 0x80)==0 ){
181868      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
181869    }
181870  }
181871}
181872
181873/*
181874** Delete a "ascii" tokenizer.
181875*/
181876static void fts5AsciiDelete(Fts5Tokenizer *p){
181877  sqlite3_free(p);
181878}
181879
181880/*
181881** Create an "ascii" tokenizer.
181882*/
181883static int fts5AsciiCreate(
181884  void *pCtx,
181885  const char **azArg, int nArg,
181886  Fts5Tokenizer **ppOut
181887){
181888  int rc = SQLITE_OK;
181889  AsciiTokenizer *p = 0;
181890  if( nArg%2 ){
181891    rc = SQLITE_ERROR;
181892  }else{
181893    p = sqlite3_malloc(sizeof(AsciiTokenizer));
181894    if( p==0 ){
181895      rc = SQLITE_NOMEM;
181896    }else{
181897      int i;
181898      memset(p, 0, sizeof(AsciiTokenizer));
181899      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
181900      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
181901        const char *zArg = azArg[i+1];
181902        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
181903          fts5AsciiAddExceptions(p, zArg, 1);
181904        }else
181905        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
181906          fts5AsciiAddExceptions(p, zArg, 0);
181907        }else{
181908          rc = SQLITE_ERROR;
181909        }
181910      }
181911      if( rc!=SQLITE_OK ){
181912        fts5AsciiDelete((Fts5Tokenizer*)p);
181913        p = 0;
181914      }
181915    }
181916  }
181917
181918  *ppOut = (Fts5Tokenizer*)p;
181919  return rc;
181920}
181921
181922
181923static void asciiFold(char *aOut, const char *aIn, int nByte){
181924  int i;
181925  for(i=0; i<nByte; i++){
181926    char c = aIn[i];
181927    if( c>='A' && c<='Z' ) c += 32;
181928    aOut[i] = c;
181929  }
181930}
181931
181932/*
181933** Tokenize some text using the ascii tokenizer.
181934*/
181935static int fts5AsciiTokenize(
181936  Fts5Tokenizer *pTokenizer,
181937  void *pCtx,
181938  int flags,
181939  const char *pText, int nText,
181940  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
181941){
181942  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
181943  int rc = SQLITE_OK;
181944  int ie;
181945  int is = 0;
181946
181947  char aFold[64];
181948  int nFold = sizeof(aFold);
181949  char *pFold = aFold;
181950  unsigned char *a = p->aTokenChar;
181951
181952  while( is<nText && rc==SQLITE_OK ){
181953    int nByte;
181954
181955    /* Skip any leading divider characters. */
181956    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
181957      is++;
181958    }
181959    if( is==nText ) break;
181960
181961    /* Count the token characters */
181962    ie = is+1;
181963    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
181964      ie++;
181965    }
181966
181967    /* Fold to lower case */
181968    nByte = ie-is;
181969    if( nByte>nFold ){
181970      if( pFold!=aFold ) sqlite3_free(pFold);
181971      pFold = sqlite3_malloc(nByte*2);
181972      if( pFold==0 ){
181973        rc = SQLITE_NOMEM;
181974        break;
181975      }
181976      nFold = nByte*2;
181977    }
181978    asciiFold(pFold, &pText[is], nByte);
181979
181980    /* Invoke the token callback */
181981    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
181982    is = ie+1;
181983  }
181984
181985  if( pFold!=aFold ) sqlite3_free(pFold);
181986  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
181987  return rc;
181988}
181989
181990/**************************************************************************
181991** Start of unicode61 tokenizer implementation.
181992*/
181993
181994
181995/*
181996** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
181997** from the sqlite3 source file utf.c. If this file is compiled as part
181998** of the amalgamation, they are not required.
181999*/
182000#ifndef SQLITE_AMALGAMATION
182001
182002static const unsigned char sqlite3Utf8Trans1[] = {
182003  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182004  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182005  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
182006  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
182007  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182008  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182009  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182010  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
182011};
182012
182013#define READ_UTF8(zIn, zTerm, c)                           \
182014  c = *(zIn++);                                            \
182015  if( c>=0xc0 ){                                           \
182016    c = sqlite3Utf8Trans1[c-0xc0];                         \
182017    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
182018      c = (c<<6) + (0x3f & *(zIn++));                      \
182019    }                                                      \
182020    if( c<0x80                                             \
182021        || (c&0xFFFFF800)==0xD800                          \
182022        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
182023  }
182024
182025
182026#define WRITE_UTF8(zOut, c) {                          \
182027  if( c<0x00080 ){                                     \
182028    *zOut++ = (unsigned char)(c&0xFF);                 \
182029  }                                                    \
182030  else if( c<0x00800 ){                                \
182031    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
182032    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182033  }                                                    \
182034  else if( c<0x10000 ){                                \
182035    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
182036    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
182037    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182038  }else{                                               \
182039    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
182040    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
182041    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
182042    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182043  }                                                    \
182044}
182045
182046#endif /* ifndef SQLITE_AMALGAMATION */
182047
182048typedef struct Unicode61Tokenizer Unicode61Tokenizer;
182049struct Unicode61Tokenizer {
182050  unsigned char aTokenChar[128];  /* ASCII range token characters */
182051  char *aFold;                    /* Buffer to fold text into */
182052  int nFold;                      /* Size of aFold[] in bytes */
182053  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
182054  int nException;
182055  int *aiException;
182056};
182057
182058static int fts5UnicodeAddExceptions(
182059  Unicode61Tokenizer *p,          /* Tokenizer object */
182060  const char *z,                  /* Characters to treat as exceptions */
182061  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
182062){
182063  int rc = SQLITE_OK;
182064  int n = strlen(z);
182065  int *aNew;
182066
182067  if( n>0 ){
182068    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
182069    if( aNew ){
182070      int nNew = p->nException;
182071      const unsigned char *zCsr = (const unsigned char*)z;
182072      const unsigned char *zTerm = (const unsigned char*)&z[n];
182073      while( zCsr<zTerm ){
182074        int iCode;
182075        int bToken;
182076        READ_UTF8(zCsr, zTerm, iCode);
182077        if( iCode<128 ){
182078          p->aTokenChar[iCode] = bTokenChars;
182079        }else{
182080          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
182081          assert( (bToken==0 || bToken==1) );
182082          assert( (bTokenChars==0 || bTokenChars==1) );
182083          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
182084            int i;
182085            for(i=0; i<nNew; i++){
182086              if( aNew[i]>iCode ) break;
182087            }
182088            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
182089            aNew[i] = iCode;
182090            nNew++;
182091          }
182092        }
182093      }
182094      p->aiException = aNew;
182095      p->nException = nNew;
182096    }else{
182097      rc = SQLITE_NOMEM;
182098    }
182099  }
182100
182101  return rc;
182102}
182103
182104/*
182105** Return true if the p->aiException[] array contains the value iCode.
182106*/
182107static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
182108  if( p->nException>0 ){
182109    int *a = p->aiException;
182110    int iLo = 0;
182111    int iHi = p->nException-1;
182112
182113    while( iHi>=iLo ){
182114      int iTest = (iHi + iLo) / 2;
182115      if( iCode==a[iTest] ){
182116        return 1;
182117      }else if( iCode>a[iTest] ){
182118        iLo = iTest+1;
182119      }else{
182120        iHi = iTest-1;
182121      }
182122    }
182123  }
182124
182125  return 0;
182126}
182127
182128/*
182129** Delete a "unicode61" tokenizer.
182130*/
182131static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
182132  if( pTok ){
182133    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
182134    sqlite3_free(p->aiException);
182135    sqlite3_free(p->aFold);
182136    sqlite3_free(p);
182137  }
182138  return;
182139}
182140
182141/*
182142** Create a "unicode61" tokenizer.
182143*/
182144static int fts5UnicodeCreate(
182145  void *pCtx,
182146  const char **azArg, int nArg,
182147  Fts5Tokenizer **ppOut
182148){
182149  int rc = SQLITE_OK;             /* Return code */
182150  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
182151
182152  if( nArg%2 ){
182153    rc = SQLITE_ERROR;
182154  }else{
182155    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
182156    if( p ){
182157      int i;
182158      memset(p, 0, sizeof(Unicode61Tokenizer));
182159      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
182160      p->bRemoveDiacritic = 1;
182161      p->nFold = 64;
182162      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
182163      if( p->aFold==0 ){
182164        rc = SQLITE_NOMEM;
182165      }
182166      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
182167        const char *zArg = azArg[i+1];
182168        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
182169          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
182170            rc = SQLITE_ERROR;
182171          }
182172          p->bRemoveDiacritic = (zArg[0]=='1');
182173        }else
182174        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
182175          rc = fts5UnicodeAddExceptions(p, zArg, 1);
182176        }else
182177        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
182178          rc = fts5UnicodeAddExceptions(p, zArg, 0);
182179        }else{
182180          rc = SQLITE_ERROR;
182181        }
182182      }
182183    }else{
182184      rc = SQLITE_NOMEM;
182185    }
182186    if( rc!=SQLITE_OK ){
182187      fts5UnicodeDelete((Fts5Tokenizer*)p);
182188      p = 0;
182189    }
182190    *ppOut = (Fts5Tokenizer*)p;
182191  }
182192  return rc;
182193}
182194
182195/*
182196** Return true if, for the purposes of tokenizing with the tokenizer
182197** passed as the first argument, codepoint iCode is considered a token
182198** character (not a separator).
182199*/
182200static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
182201  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
182202  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
182203}
182204
182205static int fts5UnicodeTokenize(
182206  Fts5Tokenizer *pTokenizer,
182207  void *pCtx,
182208  int flags,
182209  const char *pText, int nText,
182210  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
182211){
182212  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
182213  int rc = SQLITE_OK;
182214  unsigned char *a = p->aTokenChar;
182215
182216  unsigned char *zTerm = (unsigned char*)&pText[nText];
182217  unsigned char *zCsr = (unsigned char *)pText;
182218
182219  /* Output buffer */
182220  char *aFold = p->aFold;
182221  int nFold = p->nFold;
182222  const char *pEnd = &aFold[nFold-6];
182223
182224  /* Each iteration of this loop gobbles up a contiguous run of separators,
182225  ** then the next token.  */
182226  while( rc==SQLITE_OK ){
182227    int iCode;                    /* non-ASCII codepoint read from input */
182228    char *zOut = aFold;
182229    int is;
182230    int ie;
182231
182232    /* Skip any separator characters. */
182233    while( 1 ){
182234      if( zCsr>=zTerm ) goto tokenize_done;
182235      if( *zCsr & 0x80 ) {
182236        /* A character outside of the ascii range. Skip past it if it is
182237        ** a separator character. Or break out of the loop if it is not. */
182238        is = zCsr - (unsigned char*)pText;
182239        READ_UTF8(zCsr, zTerm, iCode);
182240        if( fts5UnicodeIsAlnum(p, iCode) ){
182241          goto non_ascii_tokenchar;
182242        }
182243      }else{
182244        if( a[*zCsr] ){
182245          is = zCsr - (unsigned char*)pText;
182246          goto ascii_tokenchar;
182247        }
182248        zCsr++;
182249      }
182250    }
182251
182252    /* Run through the tokenchars. Fold them into the output buffer along
182253    ** the way.  */
182254    while( zCsr<zTerm ){
182255
182256      /* Grow the output buffer so that there is sufficient space to fit the
182257      ** largest possible utf-8 character.  */
182258      if( zOut>pEnd ){
182259        aFold = sqlite3_malloc(nFold*2);
182260        if( aFold==0 ){
182261          rc = SQLITE_NOMEM;
182262          goto tokenize_done;
182263        }
182264        zOut = &aFold[zOut - p->aFold];
182265        memcpy(aFold, p->aFold, nFold);
182266        sqlite3_free(p->aFold);
182267        p->aFold = aFold;
182268        p->nFold = nFold = nFold*2;
182269        pEnd = &aFold[nFold-6];
182270      }
182271
182272      if( *zCsr & 0x80 ){
182273        /* An non-ascii-range character. Fold it into the output buffer if
182274        ** it is a token character, or break out of the loop if it is not. */
182275        READ_UTF8(zCsr, zTerm, iCode);
182276        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
182277 non_ascii_tokenchar:
182278          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
182279          if( iCode ) WRITE_UTF8(zOut, iCode);
182280        }else{
182281          break;
182282        }
182283      }else if( a[*zCsr]==0 ){
182284        /* An ascii-range separator character. End of token. */
182285        break;
182286      }else{
182287 ascii_tokenchar:
182288        if( *zCsr>='A' && *zCsr<='Z' ){
182289          *zOut++ = *zCsr + 32;
182290        }else{
182291          *zOut++ = *zCsr;
182292        }
182293        zCsr++;
182294      }
182295      ie = zCsr - (unsigned char*)pText;
182296    }
182297
182298    /* Invoke the token callback */
182299    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
182300  }
182301
182302 tokenize_done:
182303  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
182304  return rc;
182305}
182306
182307/**************************************************************************
182308** Start of porter stemmer implementation.
182309*/
182310
182311/* Any tokens larger than this (in bytes) are passed through without
182312** stemming. */
182313#define FTS5_PORTER_MAX_TOKEN 64
182314
182315typedef struct PorterTokenizer PorterTokenizer;
182316struct PorterTokenizer {
182317  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
182318  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
182319  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
182320};
182321
182322/*
182323** Delete a "porter" tokenizer.
182324*/
182325static void fts5PorterDelete(Fts5Tokenizer *pTok){
182326  if( pTok ){
182327    PorterTokenizer *p = (PorterTokenizer*)pTok;
182328    if( p->pTokenizer ){
182329      p->tokenizer.xDelete(p->pTokenizer);
182330    }
182331    sqlite3_free(p);
182332  }
182333}
182334
182335/*
182336** Create a "porter" tokenizer.
182337*/
182338static int fts5PorterCreate(
182339  void *pCtx,
182340  const char **azArg, int nArg,
182341  Fts5Tokenizer **ppOut
182342){
182343  fts5_api *pApi = (fts5_api*)pCtx;
182344  int rc = SQLITE_OK;
182345  PorterTokenizer *pRet;
182346  void *pUserdata = 0;
182347  const char *zBase = "unicode61";
182348
182349  if( nArg>0 ){
182350    zBase = azArg[0];
182351  }
182352
182353  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
182354  if( pRet ){
182355    memset(pRet, 0, sizeof(PorterTokenizer));
182356    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
182357  }else{
182358    rc = SQLITE_NOMEM;
182359  }
182360  if( rc==SQLITE_OK ){
182361    int nArg2 = (nArg>0 ? nArg-1 : 0);
182362    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
182363    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
182364  }
182365
182366  if( rc!=SQLITE_OK ){
182367    fts5PorterDelete((Fts5Tokenizer*)pRet);
182368    pRet = 0;
182369  }
182370  *ppOut = (Fts5Tokenizer*)pRet;
182371  return rc;
182372}
182373
182374typedef struct PorterContext PorterContext;
182375struct PorterContext {
182376  void *pCtx;
182377  int (*xToken)(void*, int, const char*, int, int, int);
182378  char *aBuf;
182379};
182380
182381typedef struct PorterRule PorterRule;
182382struct PorterRule {
182383  const char *zSuffix;
182384  int nSuffix;
182385  int (*xCond)(char *zStem, int nStem);
182386  const char *zOutput;
182387  int nOutput;
182388};
182389
182390#if 0
182391static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
182392  int ret = -1;
182393  int nBuf = *pnBuf;
182394  PorterRule *p;
182395
182396  for(p=aRule; p->zSuffix; p++){
182397    assert( strlen(p->zSuffix)==p->nSuffix );
182398    assert( strlen(p->zOutput)==p->nOutput );
182399    if( nBuf<p->nSuffix ) continue;
182400    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
182401  }
182402
182403  if( p->zSuffix ){
182404    int nStem = nBuf - p->nSuffix;
182405    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
182406      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
182407      *pnBuf = nStem + p->nOutput;
182408      ret = p - aRule;
182409    }
182410  }
182411
182412  return ret;
182413}
182414#endif
182415
182416static int fts5PorterIsVowel(char c, int bYIsVowel){
182417  return (
182418      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
182419  );
182420}
182421
182422static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
182423  int i;
182424  int bCons = bPrevCons;
182425
182426  /* Scan for a vowel */
182427  for(i=0; i<nStem; i++){
182428    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
182429  }
182430
182431  /* Scan for a consonent */
182432  for(i++; i<nStem; i++){
182433    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
182434  }
182435  return 0;
182436}
182437
182438/* porter rule condition: (m > 0) */
182439static int fts5Porter_MGt0(char *zStem, int nStem){
182440  return !!fts5PorterGobbleVC(zStem, nStem, 0);
182441}
182442
182443/* porter rule condition: (m > 1) */
182444static int fts5Porter_MGt1(char *zStem, int nStem){
182445  int n;
182446  n = fts5PorterGobbleVC(zStem, nStem, 0);
182447  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
182448    return 1;
182449  }
182450  return 0;
182451}
182452
182453/* porter rule condition: (m = 1) */
182454static int fts5Porter_MEq1(char *zStem, int nStem){
182455  int n;
182456  n = fts5PorterGobbleVC(zStem, nStem, 0);
182457  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
182458    return 1;
182459  }
182460  return 0;
182461}
182462
182463/* porter rule condition: (*o) */
182464static int fts5Porter_Ostar(char *zStem, int nStem){
182465  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
182466    return 0;
182467  }else{
182468    int i;
182469    int mask = 0;
182470    int bCons = 0;
182471    for(i=0; i<nStem; i++){
182472      bCons = !fts5PorterIsVowel(zStem[i], bCons);
182473      assert( bCons==0 || bCons==1 );
182474      mask = (mask << 1) + bCons;
182475    }
182476    return ((mask & 0x0007)==0x0005);
182477  }
182478}
182479
182480/* porter rule condition: (m > 1 and (*S or *T)) */
182481static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
182482  assert( nStem>0 );
182483  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
182484      && fts5Porter_MGt1(zStem, nStem);
182485}
182486
182487/* porter rule condition: (*v*) */
182488static int fts5Porter_Vowel(char *zStem, int nStem){
182489  int i;
182490  for(i=0; i<nStem; i++){
182491    if( fts5PorterIsVowel(zStem[i], i>0) ){
182492      return 1;
182493    }
182494  }
182495  return 0;
182496}
182497
182498
182499/**************************************************************************
182500***************************************************************************
182501** GENERATED CODE STARTS HERE (mkportersteps.tcl)
182502*/
182503
182504static int fts5PorterStep4(char *aBuf, int *pnBuf){
182505  int ret = 0;
182506  int nBuf = *pnBuf;
182507  switch( aBuf[nBuf-2] ){
182508
182509    case 'a':
182510      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
182511        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182512          *pnBuf = nBuf - 2;
182513        }
182514      }
182515      break;
182516
182517    case 'c':
182518      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
182519        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182520          *pnBuf = nBuf - 4;
182521        }
182522      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
182523        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182524          *pnBuf = nBuf - 4;
182525        }
182526      }
182527      break;
182528
182529    case 'e':
182530      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
182531        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182532          *pnBuf = nBuf - 2;
182533        }
182534      }
182535      break;
182536
182537    case 'i':
182538      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
182539        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182540          *pnBuf = nBuf - 2;
182541        }
182542      }
182543      break;
182544
182545    case 'l':
182546      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
182547        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182548          *pnBuf = nBuf - 4;
182549        }
182550      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
182551        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182552          *pnBuf = nBuf - 4;
182553        }
182554      }
182555      break;
182556
182557    case 'n':
182558      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
182559        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182560          *pnBuf = nBuf - 3;
182561        }
182562      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
182563        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
182564          *pnBuf = nBuf - 5;
182565        }
182566      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
182567        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182568          *pnBuf = nBuf - 4;
182569        }
182570      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
182571        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182572          *pnBuf = nBuf - 3;
182573        }
182574      }
182575      break;
182576
182577    case 'o':
182578      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
182579        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
182580          *pnBuf = nBuf - 3;
182581        }
182582      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
182583        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182584          *pnBuf = nBuf - 2;
182585        }
182586      }
182587      break;
182588
182589    case 's':
182590      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
182591        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182592          *pnBuf = nBuf - 3;
182593        }
182594      }
182595      break;
182596
182597    case 't':
182598      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
182599        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182600          *pnBuf = nBuf - 3;
182601        }
182602      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
182603        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182604          *pnBuf = nBuf - 3;
182605        }
182606      }
182607      break;
182608
182609    case 'u':
182610      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
182611        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182612          *pnBuf = nBuf - 3;
182613        }
182614      }
182615      break;
182616
182617    case 'v':
182618      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
182619        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182620          *pnBuf = nBuf - 3;
182621        }
182622      }
182623      break;
182624
182625    case 'z':
182626      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
182627        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182628          *pnBuf = nBuf - 3;
182629        }
182630      }
182631      break;
182632
182633  }
182634  return ret;
182635}
182636
182637
182638static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
182639  int ret = 0;
182640  int nBuf = *pnBuf;
182641  switch( aBuf[nBuf-2] ){
182642
182643    case 'a':
182644      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
182645        memcpy(&aBuf[nBuf-2], "ate", 3);
182646        *pnBuf = nBuf - 2 + 3;
182647        ret = 1;
182648      }
182649      break;
182650
182651    case 'b':
182652      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
182653        memcpy(&aBuf[nBuf-2], "ble", 3);
182654        *pnBuf = nBuf - 2 + 3;
182655        ret = 1;
182656      }
182657      break;
182658
182659    case 'i':
182660      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
182661        memcpy(&aBuf[nBuf-2], "ize", 3);
182662        *pnBuf = nBuf - 2 + 3;
182663        ret = 1;
182664      }
182665      break;
182666
182667  }
182668  return ret;
182669}
182670
182671
182672static int fts5PorterStep2(char *aBuf, int *pnBuf){
182673  int ret = 0;
182674  int nBuf = *pnBuf;
182675  switch( aBuf[nBuf-2] ){
182676
182677    case 'a':
182678      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
182679        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182680          memcpy(&aBuf[nBuf-7], "ate", 3);
182681          *pnBuf = nBuf - 7 + 3;
182682        }
182683      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
182684        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
182685          memcpy(&aBuf[nBuf-6], "tion", 4);
182686          *pnBuf = nBuf - 6 + 4;
182687        }
182688      }
182689      break;
182690
182691    case 'c':
182692      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
182693        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182694          memcpy(&aBuf[nBuf-4], "ence", 4);
182695          *pnBuf = nBuf - 4 + 4;
182696        }
182697      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
182698        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182699          memcpy(&aBuf[nBuf-4], "ance", 4);
182700          *pnBuf = nBuf - 4 + 4;
182701        }
182702      }
182703      break;
182704
182705    case 'e':
182706      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
182707        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182708          memcpy(&aBuf[nBuf-4], "ize", 3);
182709          *pnBuf = nBuf - 4 + 3;
182710        }
182711      }
182712      break;
182713
182714    case 'g':
182715      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
182716        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182717          memcpy(&aBuf[nBuf-4], "log", 3);
182718          *pnBuf = nBuf - 4 + 3;
182719        }
182720      }
182721      break;
182722
182723    case 'l':
182724      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
182725        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182726          memcpy(&aBuf[nBuf-3], "ble", 3);
182727          *pnBuf = nBuf - 3 + 3;
182728        }
182729      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
182730        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182731          memcpy(&aBuf[nBuf-4], "al", 2);
182732          *pnBuf = nBuf - 4 + 2;
182733        }
182734      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
182735        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182736          memcpy(&aBuf[nBuf-5], "ent", 3);
182737          *pnBuf = nBuf - 5 + 3;
182738        }
182739      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
182740        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182741          memcpy(&aBuf[nBuf-3], "e", 1);
182742          *pnBuf = nBuf - 3 + 1;
182743        }
182744      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
182745        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182746          memcpy(&aBuf[nBuf-5], "ous", 3);
182747          *pnBuf = nBuf - 5 + 3;
182748        }
182749      }
182750      break;
182751
182752    case 'o':
182753      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
182754        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182755          memcpy(&aBuf[nBuf-7], "ize", 3);
182756          *pnBuf = nBuf - 7 + 3;
182757        }
182758      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
182759        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182760          memcpy(&aBuf[nBuf-5], "ate", 3);
182761          *pnBuf = nBuf - 5 + 3;
182762        }
182763      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
182764        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182765          memcpy(&aBuf[nBuf-4], "ate", 3);
182766          *pnBuf = nBuf - 4 + 3;
182767        }
182768      }
182769      break;
182770
182771    case 's':
182772      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
182773        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182774          memcpy(&aBuf[nBuf-5], "al", 2);
182775          *pnBuf = nBuf - 5 + 2;
182776        }
182777      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
182778        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182779          memcpy(&aBuf[nBuf-7], "ive", 3);
182780          *pnBuf = nBuf - 7 + 3;
182781        }
182782      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
182783        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182784          memcpy(&aBuf[nBuf-7], "ful", 3);
182785          *pnBuf = nBuf - 7 + 3;
182786        }
182787      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
182788        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182789          memcpy(&aBuf[nBuf-7], "ous", 3);
182790          *pnBuf = nBuf - 7 + 3;
182791        }
182792      }
182793      break;
182794
182795    case 't':
182796      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
182797        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182798          memcpy(&aBuf[nBuf-5], "al", 2);
182799          *pnBuf = nBuf - 5 + 2;
182800        }
182801      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
182802        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182803          memcpy(&aBuf[nBuf-5], "ive", 3);
182804          *pnBuf = nBuf - 5 + 3;
182805        }
182806      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
182807        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
182808          memcpy(&aBuf[nBuf-6], "ble", 3);
182809          *pnBuf = nBuf - 6 + 3;
182810        }
182811      }
182812      break;
182813
182814  }
182815  return ret;
182816}
182817
182818
182819static int fts5PorterStep3(char *aBuf, int *pnBuf){
182820  int ret = 0;
182821  int nBuf = *pnBuf;
182822  switch( aBuf[nBuf-2] ){
182823
182824    case 'a':
182825      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
182826        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182827          memcpy(&aBuf[nBuf-4], "ic", 2);
182828          *pnBuf = nBuf - 4 + 2;
182829        }
182830      }
182831      break;
182832
182833    case 's':
182834      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
182835        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182836          *pnBuf = nBuf - 4;
182837        }
182838      }
182839      break;
182840
182841    case 't':
182842      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
182843        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182844          memcpy(&aBuf[nBuf-5], "ic", 2);
182845          *pnBuf = nBuf - 5 + 2;
182846        }
182847      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
182848        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182849          memcpy(&aBuf[nBuf-5], "ic", 2);
182850          *pnBuf = nBuf - 5 + 2;
182851        }
182852      }
182853      break;
182854
182855    case 'u':
182856      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
182857        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182858          *pnBuf = nBuf - 3;
182859        }
182860      }
182861      break;
182862
182863    case 'v':
182864      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
182865        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182866          *pnBuf = nBuf - 5;
182867        }
182868      }
182869      break;
182870
182871    case 'z':
182872      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
182873        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182874          memcpy(&aBuf[nBuf-5], "al", 2);
182875          *pnBuf = nBuf - 5 + 2;
182876        }
182877      }
182878      break;
182879
182880  }
182881  return ret;
182882}
182883
182884
182885static int fts5PorterStep1B(char *aBuf, int *pnBuf){
182886  int ret = 0;
182887  int nBuf = *pnBuf;
182888  switch( aBuf[nBuf-2] ){
182889
182890    case 'e':
182891      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
182892        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182893          memcpy(&aBuf[nBuf-3], "ee", 2);
182894          *pnBuf = nBuf - 3 + 2;
182895        }
182896      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
182897        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
182898          *pnBuf = nBuf - 2;
182899          ret = 1;
182900        }
182901      }
182902      break;
182903
182904    case 'n':
182905      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
182906        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
182907          *pnBuf = nBuf - 3;
182908          ret = 1;
182909        }
182910      }
182911      break;
182912
182913  }
182914  return ret;
182915}
182916
182917/*
182918** GENERATED CODE ENDS HERE (mkportersteps.tcl)
182919***************************************************************************
182920**************************************************************************/
182921
182922static void fts5PorterStep1A(char *aBuf, int *pnBuf){
182923  int nBuf = *pnBuf;
182924  if( aBuf[nBuf-1]=='s' ){
182925    if( aBuf[nBuf-2]=='e' ){
182926      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
182927       || (nBuf>3 && aBuf[nBuf-3]=='i' )
182928      ){
182929        *pnBuf = nBuf-2;
182930      }else{
182931        *pnBuf = nBuf-1;
182932      }
182933    }
182934    else if( aBuf[nBuf-2]!='s' ){
182935      *pnBuf = nBuf-1;
182936    }
182937  }
182938}
182939
182940static int fts5PorterCb(
182941  void *pCtx,
182942  int tflags,
182943  const char *pToken,
182944  int nToken,
182945  int iStart,
182946  int iEnd
182947){
182948  PorterContext *p = (PorterContext*)pCtx;
182949
182950  char *aBuf;
182951  int nBuf;
182952
182953  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
182954  aBuf = p->aBuf;
182955  nBuf = nToken;
182956  memcpy(aBuf, pToken, nBuf);
182957
182958  /* Step 1. */
182959  fts5PorterStep1A(aBuf, &nBuf);
182960  if( fts5PorterStep1B(aBuf, &nBuf) ){
182961    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
182962      char c = aBuf[nBuf-1];
182963      if( fts5PorterIsVowel(c, 0)==0
182964       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
182965      ){
182966        nBuf--;
182967      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
182968        aBuf[nBuf++] = 'e';
182969      }
182970    }
182971  }
182972
182973  /* Step 1C. */
182974  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
182975    aBuf[nBuf-1] = 'i';
182976  }
182977
182978  /* Steps 2 through 4. */
182979  fts5PorterStep2(aBuf, &nBuf);
182980  fts5PorterStep3(aBuf, &nBuf);
182981  fts5PorterStep4(aBuf, &nBuf);
182982
182983  /* Step 5a. */
182984  assert( nBuf>0 );
182985  if( aBuf[nBuf-1]=='e' ){
182986    if( fts5Porter_MGt1(aBuf, nBuf-1)
182987     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
182988    ){
182989      nBuf--;
182990    }
182991  }
182992
182993  /* Step 5b. */
182994  if( nBuf>1 && aBuf[nBuf-1]=='l'
182995   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
182996  ){
182997    nBuf--;
182998  }
182999
183000  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
183001
183002 pass_through:
183003  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
183004}
183005
183006/*
183007** Tokenize using the porter tokenizer.
183008*/
183009static int fts5PorterTokenize(
183010  Fts5Tokenizer *pTokenizer,
183011  void *pCtx,
183012  int flags,
183013  const char *pText, int nText,
183014  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
183015){
183016  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
183017  PorterContext sCtx;
183018  sCtx.xToken = xToken;
183019  sCtx.pCtx = pCtx;
183020  sCtx.aBuf = p->aBuf;
183021  return p->tokenizer.xTokenize(
183022      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
183023  );
183024}
183025
183026/*
183027** Register all built-in tokenizers with FTS5.
183028*/
183029static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
183030  struct BuiltinTokenizer {
183031    const char *zName;
183032    fts5_tokenizer x;
183033  } aBuiltin[] = {
183034    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
183035    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
183036    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
183037  };
183038
183039  int rc = SQLITE_OK;             /* Return code */
183040  int i;                          /* To iterate through builtin functions */
183041
183042  for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
183043    rc = pApi->xCreateTokenizer(pApi,
183044        aBuiltin[i].zName,
183045        (void*)pApi,
183046        &aBuiltin[i].x,
183047        0
183048    );
183049  }
183050
183051  return rc;
183052}
183053
183054
183055
183056/*
183057** 2012 May 25
183058**
183059** The author disclaims copyright to this source code.  In place of
183060** a legal notice, here is a blessing:
183061**
183062**    May you do good and not evil.
183063**    May you find forgiveness for yourself and forgive others.
183064**    May you share freely, never taking more than you give.
183065**
183066******************************************************************************
183067*/
183068
183069/*
183070** DO NOT EDIT THIS MACHINE GENERATED FILE.
183071*/
183072
183073
183074/* #include <assert.h> */
183075
183076/*
183077** Return true if the argument corresponds to a unicode codepoint
183078** classified as either a letter or a number. Otherwise false.
183079**
183080** The results are undefined if the value passed to this function
183081** is less than zero.
183082*/
183083static int sqlite3Fts5UnicodeIsalnum(int c){
183084  /* Each unsigned integer in the following array corresponds to a contiguous
183085  ** range of unicode codepoints that are not either letters or numbers (i.e.
183086  ** codepoints for which this function should return 0).
183087  **
183088  ** The most significant 22 bits in each 32-bit value contain the first
183089  ** codepoint in the range. The least significant 10 bits are used to store
183090  ** the size of the range (always at least 1). In other words, the value
183091  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
183092  ** C. It is not possible to represent a range larger than 1023 codepoints
183093  ** using this format.
183094  */
183095  static const unsigned int aEntry[] = {
183096    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
183097    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
183098    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
183099    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
183100    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
183101    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
183102    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
183103    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
183104    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
183105    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
183106    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
183107    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
183108    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
183109    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
183110    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
183111    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
183112    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
183113    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
183114    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
183115    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
183116    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
183117    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
183118    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
183119    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
183120    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
183121    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
183122    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
183123    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
183124    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
183125    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
183126    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
183127    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
183128    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
183129    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
183130    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
183131    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
183132    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
183133    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
183134    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
183135    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
183136    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
183137    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
183138    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
183139    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
183140    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
183141    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
183142    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
183143    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
183144    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
183145    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
183146    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
183147    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
183148    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
183149    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
183150    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
183151    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
183152    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
183153    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
183154    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
183155    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
183156    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
183157    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
183158    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
183159    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
183160    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
183161    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
183162    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
183163    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
183164    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
183165    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
183166    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
183167    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
183168    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
183169    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
183170    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
183171    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
183172    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
183173    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
183174    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
183175    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
183176    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
183177    0x380400F0,
183178  };
183179  static const unsigned int aAscii[4] = {
183180    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
183181  };
183182
183183  if( c<128 ){
183184    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
183185  }else if( c<(1<<22) ){
183186    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
183187    int iRes = 0;
183188    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183189    int iLo = 0;
183190    while( iHi>=iLo ){
183191      int iTest = (iHi + iLo) / 2;
183192      if( key >= aEntry[iTest] ){
183193        iRes = iTest;
183194        iLo = iTest+1;
183195      }else{
183196        iHi = iTest-1;
183197      }
183198    }
183199    assert( aEntry[0]<key );
183200    assert( key>=aEntry[iRes] );
183201    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
183202  }
183203  return 1;
183204}
183205
183206
183207/*
183208** If the argument is a codepoint corresponding to a lowercase letter
183209** in the ASCII range with a diacritic added, return the codepoint
183210** of the ASCII letter only. For example, if passed 235 - "LATIN
183211** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
183212** E"). The resuls of passing a codepoint that corresponds to an
183213** uppercase letter are undefined.
183214*/
183215static int fts5_remove_diacritic(int c){
183216  unsigned short aDia[] = {
183217        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
183218     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
183219     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
183220     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
183221     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
183222     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
183223     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
183224     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
183225    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
183226    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
183227    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
183228    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
183229    62924, 63050, 63082, 63274, 63390,
183230  };
183231  char aChar[] = {
183232    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
183233    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
183234    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
183235    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
183236    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
183237    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
183238    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
183239    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
183240    'e',  'i',  'o',  'u',  'y',
183241  };
183242
183243  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
183244  int iRes = 0;
183245  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
183246  int iLo = 0;
183247  while( iHi>=iLo ){
183248    int iTest = (iHi + iLo) / 2;
183249    if( key >= aDia[iTest] ){
183250      iRes = iTest;
183251      iLo = iTest+1;
183252    }else{
183253      iHi = iTest-1;
183254    }
183255  }
183256  assert( key>=aDia[iRes] );
183257  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
183258}
183259
183260
183261/*
183262** Return true if the argument interpreted as a unicode codepoint
183263** is a diacritical modifier character.
183264*/
183265static int sqlite3Fts5UnicodeIsdiacritic(int c){
183266  unsigned int mask0 = 0x08029FDF;
183267  unsigned int mask1 = 0x000361F8;
183268  if( c<768 || c>817 ) return 0;
183269  return (c < 768+32) ?
183270      (mask0 & (1 << (c-768))) :
183271      (mask1 & (1 << (c-768-32)));
183272}
183273
183274
183275/*
183276** Interpret the argument as a unicode codepoint. If the codepoint
183277** is an upper case character that has a lower case equivalent,
183278** return the codepoint corresponding to the lower case version.
183279** Otherwise, return a copy of the argument.
183280**
183281** The results are undefined if the value passed to this function
183282** is less than zero.
183283*/
183284static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
183285  /* Each entry in the following array defines a rule for folding a range
183286  ** of codepoints to lower case. The rule applies to a range of nRange
183287  ** codepoints starting at codepoint iCode.
183288  **
183289  ** If the least significant bit in flags is clear, then the rule applies
183290  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
183291  ** need to be folded). Or, if it is set, then the rule only applies to
183292  ** every second codepoint in the range, starting with codepoint C.
183293  **
183294  ** The 7 most significant bits in flags are an index into the aiOff[]
183295  ** array. If a specific codepoint C does require folding, then its lower
183296  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
183297  **
183298  ** The contents of this array are generated by parsing the CaseFolding.txt
183299  ** file distributed as part of the "Unicode Character Database". See
183300  ** http://www.unicode.org for details.
183301  */
183302  static const struct TableEntry {
183303    unsigned short iCode;
183304    unsigned char flags;
183305    unsigned char nRange;
183306  } aEntry[] = {
183307    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
183308    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
183309    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
183310    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
183311    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
183312    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
183313    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
183314    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
183315    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
183316    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
183317    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
183318    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
183319    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
183320    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
183321    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
183322    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
183323    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
183324    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
183325    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
183326    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
183327    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
183328    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
183329    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
183330    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
183331    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
183332    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
183333    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
183334    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
183335    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
183336    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
183337    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
183338    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
183339    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
183340    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
183341    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
183342    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
183343    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
183344    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
183345    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
183346    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
183347    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
183348    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
183349    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
183350    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
183351    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
183352    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
183353    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
183354    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
183355    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
183356    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
183357    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
183358    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
183359    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
183360    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
183361    {65313, 14, 26},
183362  };
183363  static const unsigned short aiOff[] = {
183364   1,     2,     8,     15,    16,    26,    28,    32,
183365   37,    38,    40,    48,    63,    64,    69,    71,
183366   79,    80,    116,   202,   203,   205,   206,   207,
183367   209,   210,   211,   213,   214,   217,   218,   219,
183368   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
183369   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
183370   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
183371   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
183372   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
183373   65514, 65521, 65527, 65528, 65529,
183374  };
183375
183376  int ret = c;
183377
183378  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
183379
183380  if( c<128 ){
183381    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
183382  }else if( c<65536 ){
183383    const struct TableEntry *p;
183384    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183385    int iLo = 0;
183386    int iRes = -1;
183387
183388    assert( c>aEntry[0].iCode );
183389    while( iHi>=iLo ){
183390      int iTest = (iHi + iLo) / 2;
183391      int cmp = (c - aEntry[iTest].iCode);
183392      if( cmp>=0 ){
183393        iRes = iTest;
183394        iLo = iTest+1;
183395      }else{
183396        iHi = iTest-1;
183397      }
183398    }
183399
183400    assert( iRes>=0 && c>=aEntry[iRes].iCode );
183401    p = &aEntry[iRes];
183402    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
183403      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
183404      assert( ret>0 );
183405    }
183406
183407    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
183408  }
183409
183410  else if( c>=66560 && c<66600 ){
183411    ret = c + 40;
183412  }
183413
183414  return ret;
183415}
183416
183417/*
183418** 2015 May 30
183419**
183420** The author disclaims copyright to this source code.  In place of
183421** a legal notice, here is a blessing:
183422**
183423**    May you do good and not evil.
183424**    May you find forgiveness for yourself and forgive others.
183425**    May you share freely, never taking more than you give.
183426**
183427******************************************************************************
183428**
183429** Routines for varint serialization and deserialization.
183430*/
183431
183432
183433
183434/*
183435** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
183436** Except, this version does handle the single byte case that the core
183437** version depends on being handled before its function is called.
183438*/
183439static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
183440  u32 a,b;
183441
183442  /* The 1-byte case. Overwhelmingly the most common. */
183443  a = *p;
183444  /* a: p0 (unmasked) */
183445  if (!(a&0x80))
183446  {
183447    /* Values between 0 and 127 */
183448    *v = a;
183449    return 1;
183450  }
183451
183452  /* The 2-byte case */
183453  p++;
183454  b = *p;
183455  /* b: p1 (unmasked) */
183456  if (!(b&0x80))
183457  {
183458    /* Values between 128 and 16383 */
183459    a &= 0x7f;
183460    a = a<<7;
183461    *v = a | b;
183462    return 2;
183463  }
183464
183465  /* The 3-byte case */
183466  p++;
183467  a = a<<14;
183468  a |= *p;
183469  /* a: p0<<14 | p2 (unmasked) */
183470  if (!(a&0x80))
183471  {
183472    /* Values between 16384 and 2097151 */
183473    a &= (0x7f<<14)|(0x7f);
183474    b &= 0x7f;
183475    b = b<<7;
183476    *v = a | b;
183477    return 3;
183478  }
183479
183480  /* A 32-bit varint is used to store size information in btrees.
183481  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
183482  ** A 3-byte varint is sufficient, for example, to record the size
183483  ** of a 1048569-byte BLOB or string.
183484  **
183485  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
183486  ** rare larger cases can be handled by the slower 64-bit varint
183487  ** routine.
183488  */
183489  {
183490    u64 v64;
183491    u8 n;
183492    p -= 2;
183493    n = sqlite3Fts5GetVarint(p, &v64);
183494    *v = (u32)v64;
183495    assert( n>3 && n<=9 );
183496    return n;
183497  }
183498}
183499
183500
183501/*
183502** Bitmasks used by sqlite3GetVarint().  These precomputed constants
183503** are defined here rather than simply putting the constant expressions
183504** inline in order to work around bugs in the RVT compiler.
183505**
183506** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
183507**
183508** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
183509*/
183510#define SLOT_2_0     0x001fc07f
183511#define SLOT_4_2_0   0xf01fc07f
183512
183513/*
183514** Read a 64-bit variable-length integer from memory starting at p[0].
183515** Return the number of bytes read.  The value is stored in *v.
183516*/
183517static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
183518  u32 a,b,s;
183519
183520  a = *p;
183521  /* a: p0 (unmasked) */
183522  if (!(a&0x80))
183523  {
183524    *v = a;
183525    return 1;
183526  }
183527
183528  p++;
183529  b = *p;
183530  /* b: p1 (unmasked) */
183531  if (!(b&0x80))
183532  {
183533    a &= 0x7f;
183534    a = a<<7;
183535    a |= b;
183536    *v = a;
183537    return 2;
183538  }
183539
183540  /* Verify that constants are precomputed correctly */
183541  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
183542  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
183543
183544  p++;
183545  a = a<<14;
183546  a |= *p;
183547  /* a: p0<<14 | p2 (unmasked) */
183548  if (!(a&0x80))
183549  {
183550    a &= SLOT_2_0;
183551    b &= 0x7f;
183552    b = b<<7;
183553    a |= b;
183554    *v = a;
183555    return 3;
183556  }
183557
183558  /* CSE1 from below */
183559  a &= SLOT_2_0;
183560  p++;
183561  b = b<<14;
183562  b |= *p;
183563  /* b: p1<<14 | p3 (unmasked) */
183564  if (!(b&0x80))
183565  {
183566    b &= SLOT_2_0;
183567    /* moved CSE1 up */
183568    /* a &= (0x7f<<14)|(0x7f); */
183569    a = a<<7;
183570    a |= b;
183571    *v = a;
183572    return 4;
183573  }
183574
183575  /* a: p0<<14 | p2 (masked) */
183576  /* b: p1<<14 | p3 (unmasked) */
183577  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183578  /* moved CSE1 up */
183579  /* a &= (0x7f<<14)|(0x7f); */
183580  b &= SLOT_2_0;
183581  s = a;
183582  /* s: p0<<14 | p2 (masked) */
183583
183584  p++;
183585  a = a<<14;
183586  a |= *p;
183587  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
183588  if (!(a&0x80))
183589  {
183590    /* we can skip these cause they were (effectively) done above in calc'ing s */
183591    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
183592    /* b &= (0x7f<<14)|(0x7f); */
183593    b = b<<7;
183594    a |= b;
183595    s = s>>18;
183596    *v = ((u64)s)<<32 | a;
183597    return 5;
183598  }
183599
183600  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183601  s = s<<7;
183602  s |= b;
183603  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183604
183605  p++;
183606  b = b<<14;
183607  b |= *p;
183608  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
183609  if (!(b&0x80))
183610  {
183611    /* we can skip this cause it was (effectively) done above in calc'ing s */
183612    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
183613    a &= SLOT_2_0;
183614    a = a<<7;
183615    a |= b;
183616    s = s>>18;
183617    *v = ((u64)s)<<32 | a;
183618    return 6;
183619  }
183620
183621  p++;
183622  a = a<<14;
183623  a |= *p;
183624  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
183625  if (!(a&0x80))
183626  {
183627    a &= SLOT_4_2_0;
183628    b &= SLOT_2_0;
183629    b = b<<7;
183630    a |= b;
183631    s = s>>11;
183632    *v = ((u64)s)<<32 | a;
183633    return 7;
183634  }
183635
183636  /* CSE2 from below */
183637  a &= SLOT_2_0;
183638  p++;
183639  b = b<<14;
183640  b |= *p;
183641  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
183642  if (!(b&0x80))
183643  {
183644    b &= SLOT_4_2_0;
183645    /* moved CSE2 up */
183646    /* a &= (0x7f<<14)|(0x7f); */
183647    a = a<<7;
183648    a |= b;
183649    s = s>>4;
183650    *v = ((u64)s)<<32 | a;
183651    return 8;
183652  }
183653
183654  p++;
183655  a = a<<15;
183656  a |= *p;
183657  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
183658
183659  /* moved CSE2 up */
183660  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
183661  b &= SLOT_2_0;
183662  b = b<<8;
183663  a |= b;
183664
183665  s = s<<4;
183666  b = p[-4];
183667  b &= 0x7f;
183668  b = b>>3;
183669  s |= b;
183670
183671  *v = ((u64)s)<<32 | a;
183672
183673  return 9;
183674}
183675
183676/*
183677** The variable-length integer encoding is as follows:
183678**
183679** KEY:
183680**         A = 0xxxxxxx    7 bits of data and one flag bit
183681**         B = 1xxxxxxx    7 bits of data and one flag bit
183682**         C = xxxxxxxx    8 bits of data
183683**
183684**  7 bits - A
183685** 14 bits - BA
183686** 21 bits - BBA
183687** 28 bits - BBBA
183688** 35 bits - BBBBA
183689** 42 bits - BBBBBA
183690** 49 bits - BBBBBBA
183691** 56 bits - BBBBBBBA
183692** 64 bits - BBBBBBBBC
183693*/
183694
183695#ifdef SQLITE_NOINLINE
183696# define FTS5_NOINLINE SQLITE_NOINLINE
183697#else
183698# define FTS5_NOINLINE
183699#endif
183700
183701/*
183702** Write a 64-bit variable-length integer to memory starting at p[0].
183703** The length of data write will be between 1 and 9 bytes.  The number
183704** of bytes written is returned.
183705**
183706** A variable-length integer consists of the lower 7 bits of each byte
183707** for all bytes that have the 8th bit set and one byte with the 8th
183708** bit clear.  Except, if we get to the 9th byte, it stores the full
183709** 8 bits and is the last byte.
183710*/
183711static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
183712  int i, j, n;
183713  u8 buf[10];
183714  if( v & (((u64)0xff000000)<<32) ){
183715    p[8] = (u8)v;
183716    v >>= 8;
183717    for(i=7; i>=0; i--){
183718      p[i] = (u8)((v & 0x7f) | 0x80);
183719      v >>= 7;
183720    }
183721    return 9;
183722  }
183723  n = 0;
183724  do{
183725    buf[n++] = (u8)((v & 0x7f) | 0x80);
183726    v >>= 7;
183727  }while( v!=0 );
183728  buf[0] &= 0x7f;
183729  assert( n<=9 );
183730  for(i=0, j=n-1; j>=0; j--, i++){
183731    p[i] = buf[j];
183732  }
183733  return n;
183734}
183735
183736static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
183737  if( v<=0x7f ){
183738    p[0] = v&0x7f;
183739    return 1;
183740  }
183741  if( v<=0x3fff ){
183742    p[0] = ((v>>7)&0x7f)|0x80;
183743    p[1] = v&0x7f;
183744    return 2;
183745  }
183746  return fts5PutVarint64(p,v);
183747}
183748
183749
183750static int sqlite3Fts5GetVarintLen(u32 iVal){
183751  if( iVal<(1 << 7 ) ) return 1;
183752  if( iVal<(1 << 14) ) return 2;
183753  if( iVal<(1 << 21) ) return 3;
183754  if( iVal<(1 << 28) ) return 4;
183755  return 5;
183756}
183757
183758
183759/*
183760** 2015 May 08
183761**
183762** The author disclaims copyright to this source code.  In place of
183763** a legal notice, here is a blessing:
183764**
183765**    May you do good and not evil.
183766**    May you find forgiveness for yourself and forgive others.
183767**    May you share freely, never taking more than you give.
183768**
183769******************************************************************************
183770**
183771** This is an SQLite virtual table module implementing direct access to an
183772** existing FTS5 index. The module may create several different types of
183773** tables:
183774**
183775** col:
183776**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
183777**
183778**   One row for each term/column combination. The value of $doc is set to
183779**   the number of fts5 rows that contain at least one instance of term
183780**   $term within column $col. Field $cnt is set to the total number of
183781**   instances of term $term in column $col (in any row of the fts5 table).
183782**
183783** row:
183784**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
183785**
183786**   One row for each term in the database. The value of $doc is set to
183787**   the number of fts5 rows that contain at least one instance of term
183788**   $term. Field $cnt is set to the total number of instances of term
183789**   $term in the database.
183790*/
183791
183792
183793
183794
183795typedef struct Fts5VocabTable Fts5VocabTable;
183796typedef struct Fts5VocabCursor Fts5VocabCursor;
183797
183798struct Fts5VocabTable {
183799  sqlite3_vtab base;
183800  char *zFts5Tbl;                 /* Name of fts5 table */
183801  char *zFts5Db;                  /* Db containing fts5 table */
183802  sqlite3 *db;                    /* Database handle */
183803  Fts5Global *pGlobal;            /* FTS5 global object for this database */
183804  int eType;                      /* FTS5_VOCAB_COL or ROW */
183805};
183806
183807struct Fts5VocabCursor {
183808  sqlite3_vtab_cursor base;
183809  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
183810  Fts5Index *pIndex;              /* Associated FTS5 index */
183811
183812  int bEof;                       /* True if this cursor is at EOF */
183813  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
183814
183815  /* These are used by 'col' tables only */
183816  int nCol;
183817  int iCol;
183818  i64 *aCnt;
183819  i64 *aDoc;
183820
183821  /* Output values */
183822  i64 rowid;                      /* This table's current rowid value */
183823  Fts5Buffer term;                /* Current value of 'term' column */
183824  i64 aVal[3];                    /* Up to three columns left of 'term' */
183825};
183826
183827#define FTS5_VOCAB_COL    0
183828#define FTS5_VOCAB_ROW    1
183829
183830#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
183831#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
183832
183833/*
183834** Translate a string containing an fts5vocab table type to an
183835** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
183836** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
183837** and return SQLITE_ERROR.
183838*/
183839static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
183840  int rc = SQLITE_OK;
183841  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
183842  if( rc==SQLITE_OK ){
183843    sqlite3Fts5Dequote(zCopy);
183844    if( sqlite3_stricmp(zCopy, "col")==0 ){
183845      *peType = FTS5_VOCAB_COL;
183846    }else
183847
183848    if( sqlite3_stricmp(zCopy, "row")==0 ){
183849      *peType = FTS5_VOCAB_ROW;
183850    }else
183851    {
183852      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
183853      rc = SQLITE_ERROR;
183854    }
183855    sqlite3_free(zCopy);
183856  }
183857
183858  return rc;
183859}
183860
183861
183862/*
183863** The xDisconnect() virtual table method.
183864*/
183865static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
183866  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
183867  sqlite3_free(pTab);
183868  return SQLITE_OK;
183869}
183870
183871/*
183872** The xDestroy() virtual table method.
183873*/
183874static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
183875  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
183876  sqlite3_free(pTab);
183877  return SQLITE_OK;
183878}
183879
183880/*
183881** This function is the implementation of both the xConnect and xCreate
183882** methods of the FTS3 virtual table.
183883**
183884** The argv[] array contains the following:
183885**
183886**   argv[0]   -> module name  ("fts5vocab")
183887**   argv[1]   -> database name
183888**   argv[2]   -> table name
183889**
183890** then:
183891**
183892**   argv[3]   -> name of fts5 table
183893**   argv[4]   -> type of fts5vocab table
183894**
183895** or, for tables in the TEMP schema only.
183896**
183897**   argv[3]   -> name of fts5 tables database
183898**   argv[4]   -> name of fts5 table
183899**   argv[5]   -> type of fts5vocab table
183900*/
183901static int fts5VocabInitVtab(
183902  sqlite3 *db,                    /* The SQLite database connection */
183903  void *pAux,                     /* Pointer to Fts5Global object */
183904  int argc,                       /* Number of elements in argv array */
183905  const char * const *argv,       /* xCreate/xConnect argument array */
183906  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
183907  char **pzErr                    /* Write any error message here */
183908){
183909  const char *azSchema[] = {
183910    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
183911    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
183912  };
183913
183914  Fts5VocabTable *pRet = 0;
183915  int rc = SQLITE_OK;             /* Return code */
183916  int bDb;
183917
183918  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
183919
183920  if( argc!=5 && bDb==0 ){
183921    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
183922    rc = SQLITE_ERROR;
183923  }else{
183924    int nByte;                      /* Bytes of space to allocate */
183925    const char *zDb = bDb ? argv[3] : argv[1];
183926    const char *zTab = bDb ? argv[4] : argv[3];
183927    const char *zType = bDb ? argv[5] : argv[4];
183928    int nDb = strlen(zDb)+1;
183929    int nTab = strlen(zTab)+1;
183930    int eType;
183931
183932    rc = fts5VocabTableType(zType, pzErr, &eType);
183933    if( rc==SQLITE_OK ){
183934      assert( eType>=0 && eType<sizeof(azSchema)/sizeof(azSchema[0]) );
183935      rc = sqlite3_declare_vtab(db, azSchema[eType]);
183936    }
183937
183938    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
183939    pRet = sqlite3Fts5MallocZero(&rc, nByte);
183940    if( pRet ){
183941      pRet->pGlobal = (Fts5Global*)pAux;
183942      pRet->eType = eType;
183943      pRet->db = db;
183944      pRet->zFts5Tbl = (char*)&pRet[1];
183945      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
183946      memcpy(pRet->zFts5Tbl, zTab, nTab);
183947      memcpy(pRet->zFts5Db, zDb, nDb);
183948      sqlite3Fts5Dequote(pRet->zFts5Tbl);
183949      sqlite3Fts5Dequote(pRet->zFts5Db);
183950    }
183951  }
183952
183953  *ppVTab = (sqlite3_vtab*)pRet;
183954  return rc;
183955}
183956
183957
183958/*
183959** The xConnect() and xCreate() methods for the virtual table. All the
183960** work is done in function fts5VocabInitVtab().
183961*/
183962static int fts5VocabConnectMethod(
183963  sqlite3 *db,                    /* Database connection */
183964  void *pAux,                     /* Pointer to tokenizer hash table */
183965  int argc,                       /* Number of elements in argv array */
183966  const char * const *argv,       /* xCreate/xConnect argument array */
183967  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
183968  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
183969){
183970  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
183971}
183972static int fts5VocabCreateMethod(
183973  sqlite3 *db,                    /* Database connection */
183974  void *pAux,                     /* Pointer to tokenizer hash table */
183975  int argc,                       /* Number of elements in argv array */
183976  const char * const *argv,       /* xCreate/xConnect argument array */
183977  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
183978  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
183979){
183980  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
183981}
183982
183983/*
183984** Implementation of the xBestIndex method.
183985*/
183986static int fts5VocabBestIndexMethod(
183987  sqlite3_vtab *pVTab,
183988  sqlite3_index_info *pInfo
183989){
183990  return SQLITE_OK;
183991}
183992
183993/*
183994** Implementation of xOpen method.
183995*/
183996static int fts5VocabOpenMethod(
183997  sqlite3_vtab *pVTab,
183998  sqlite3_vtab_cursor **ppCsr
183999){
184000  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
184001  Fts5Index *pIndex = 0;
184002  int nCol = 0;
184003  Fts5VocabCursor *pCsr = 0;
184004  int rc = SQLITE_OK;
184005  sqlite3_stmt *pStmt = 0;
184006  char *zSql = 0;
184007  int nByte;
184008
184009  zSql = sqlite3Fts5Mprintf(&rc,
184010      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
184011      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
184012  );
184013  if( zSql ){
184014    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
184015  }
184016  sqlite3_free(zSql);
184017  assert( rc==SQLITE_OK || pStmt==0 );
184018  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
184019
184020  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
184021    i64 iId = sqlite3_column_int64(pStmt, 0);
184022    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &nCol);
184023  }
184024
184025  if( rc==SQLITE_OK && pIndex==0 ){
184026    rc = sqlite3_finalize(pStmt);
184027    pStmt = 0;
184028    if( rc==SQLITE_OK ){
184029      pVTab->zErrMsg = sqlite3_mprintf(
184030          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
184031      );
184032      rc = SQLITE_ERROR;
184033    }
184034  }
184035
184036  nByte = nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
184037  pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
184038  if( pCsr ){
184039    pCsr->pIndex = pIndex;
184040    pCsr->pStmt = pStmt;
184041    pCsr->nCol = nCol;
184042    pCsr->aCnt = (i64*)&pCsr[1];
184043    pCsr->aDoc = &pCsr->aCnt[nCol];
184044  }else{
184045    sqlite3_finalize(pStmt);
184046  }
184047
184048  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
184049  return rc;
184050}
184051
184052static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
184053  pCsr->rowid = 0;
184054  sqlite3Fts5IterClose(pCsr->pIter);
184055  pCsr->pIter = 0;
184056}
184057
184058/*
184059** Close the cursor.  For additional information see the documentation
184060** on the xClose method of the virtual table interface.
184061*/
184062static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
184063  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184064  fts5VocabResetCursor(pCsr);
184065  sqlite3Fts5BufferFree(&pCsr->term);
184066  sqlite3_finalize(pCsr->pStmt);
184067  sqlite3_free(pCsr);
184068  return SQLITE_OK;
184069}
184070
184071
184072/*
184073** Advance the cursor to the next row in the table.
184074*/
184075static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
184076  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184077  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
184078  int rc = SQLITE_OK;
184079
184080  pCsr->rowid++;
184081
184082  if( pTab->eType==FTS5_VOCAB_COL ){
184083    for(pCsr->iCol++; pCsr->iCol<pCsr->nCol; pCsr->iCol++){
184084      if( pCsr->aCnt[pCsr->iCol] ) break;
184085    }
184086  }
184087
184088  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=pCsr->nCol ){
184089    if( sqlite3Fts5IterEof(pCsr->pIter) ){
184090      pCsr->bEof = 1;
184091    }else{
184092      const char *zTerm;
184093      int nTerm;
184094
184095      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
184096      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
184097      memset(pCsr->aVal, 0, sizeof(pCsr->aVal));
184098      memset(pCsr->aCnt, 0, pCsr->nCol * sizeof(i64));
184099      memset(pCsr->aDoc, 0, pCsr->nCol * sizeof(i64));
184100      pCsr->iCol = 0;
184101
184102      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
184103      while( rc==SQLITE_OK ){
184104        i64 dummy;
184105        const u8 *pPos; int nPos;   /* Position list */
184106        i64 iPos = 0;               /* 64-bit position read from poslist */
184107        int iOff = 0;               /* Current offset within position list */
184108
184109        rc = sqlite3Fts5IterPoslist(pCsr->pIter, 0, &pPos, &nPos, &dummy);
184110        if( rc==SQLITE_OK ){
184111          if( pTab->eType==FTS5_VOCAB_ROW ){
184112            while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
184113              pCsr->aVal[1]++;
184114            }
184115            pCsr->aVal[0]++;
184116          }else{
184117            int iCol = -1;
184118            while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
184119              int ii = FTS5_POS2COLUMN(iPos);
184120              pCsr->aCnt[ii]++;
184121              if( iCol!=ii ){
184122                pCsr->aDoc[ii]++;
184123                iCol = ii;
184124              }
184125            }
184126          }
184127          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
184128        }
184129        if( rc==SQLITE_OK ){
184130          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
184131          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ) break;
184132          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
184133        }
184134      }
184135    }
184136  }
184137
184138  if( pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
184139    while( pCsr->aCnt[pCsr->iCol]==0 ) pCsr->iCol++;
184140    pCsr->aVal[0] = pCsr->iCol;
184141    pCsr->aVal[1] = pCsr->aDoc[pCsr->iCol];
184142    pCsr->aVal[2] = pCsr->aCnt[pCsr->iCol];
184143  }
184144  return rc;
184145}
184146
184147/*
184148** This is the xFilter implementation for the virtual table.
184149*/
184150static int fts5VocabFilterMethod(
184151  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
184152  int idxNum,                     /* Strategy index */
184153  const char *idxStr,             /* Unused */
184154  int nVal,                       /* Number of elements in apVal */
184155  sqlite3_value **apVal           /* Arguments for the indexing scheme */
184156){
184157  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184158  int rc;
184159  const int flags = FTS5INDEX_QUERY_SCAN;
184160
184161  fts5VocabResetCursor(pCsr);
184162  rc = sqlite3Fts5IndexQuery(pCsr->pIndex, 0, 0, flags, 0, &pCsr->pIter);
184163  if( rc==SQLITE_OK ){
184164    rc = fts5VocabNextMethod(pCursor);
184165  }
184166
184167  return rc;
184168}
184169
184170/*
184171** This is the xEof method of the virtual table. SQLite calls this
184172** routine to find out if it has reached the end of a result set.
184173*/
184174static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
184175  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184176  return pCsr->bEof;
184177}
184178
184179static int fts5VocabColumnMethod(
184180  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
184181  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
184182  int iCol                        /* Index of column to read value from */
184183){
184184  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184185  switch( iCol ){
184186    case 0: /* term */
184187      sqlite3_result_text(
184188          pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
184189      );
184190      break;
184191
184192    default:
184193      assert( iCol<4 && iCol>0 );
184194      sqlite3_result_int64(pCtx, pCsr->aVal[iCol-1]);
184195      break;
184196  }
184197  return SQLITE_OK;
184198}
184199
184200/*
184201** This is the xRowid method. The SQLite core calls this routine to
184202** retrieve the rowid for the current row of the result set. The
184203** rowid should be written to *pRowid.
184204*/
184205static int fts5VocabRowidMethod(
184206  sqlite3_vtab_cursor *pCursor,
184207  sqlite_int64 *pRowid
184208){
184209  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184210  *pRowid = pCsr->rowid;
184211  return SQLITE_OK;
184212}
184213
184214static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
184215  static const sqlite3_module fts5Vocab = {
184216    /* iVersion      */ 2,
184217    /* xCreate       */ fts5VocabCreateMethod,
184218    /* xConnect      */ fts5VocabConnectMethod,
184219    /* xBestIndex    */ fts5VocabBestIndexMethod,
184220    /* xDisconnect   */ fts5VocabDisconnectMethod,
184221    /* xDestroy      */ fts5VocabDestroyMethod,
184222    /* xOpen         */ fts5VocabOpenMethod,
184223    /* xClose        */ fts5VocabCloseMethod,
184224    /* xFilter       */ fts5VocabFilterMethod,
184225    /* xNext         */ fts5VocabNextMethod,
184226    /* xEof          */ fts5VocabEofMethod,
184227    /* xColumn       */ fts5VocabColumnMethod,
184228    /* xRowid        */ fts5VocabRowidMethod,
184229    /* xUpdate       */ 0,
184230    /* xBegin        */ 0,
184231    /* xSync         */ 0,
184232    /* xCommit       */ 0,
184233    /* xRollback     */ 0,
184234    /* xFindFunction */ 0,
184235    /* xRename       */ 0,
184236    /* xSavepoint    */ 0,
184237    /* xRelease      */ 0,
184238    /* xRollbackTo   */ 0,
184239  };
184240  void *p = (void*)pGlobal;
184241
184242  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
184243}
184244
184245
184246
184247
184248
184249#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
184250
184251/************** End of fts5.c ************************************************/
184252